repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
grancier/linux-3.14.3-c720 | tools/perf/util/symbol-minimal.c | 359 | 6509 | #include "symbol.h"
#include "util.h"
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <byteswap.h>
#include <sys/stat.h>
static bool check_need_swap(int file_endian)
{
const int data = 1;
u8 *check = (u8 *)&data;
int host_endian;
if (check[0] == 1)
host_endian = ELFDATA2LSB;
else
host_endian = ELFDATA2MSB;
return host_endian != file_endian;
}
#define NOTE_ALIGN(sz) (((sz) + 3) & ~3)
#define NT_GNU_BUILD_ID 3
static int read_build_id(void *note_data, size_t note_len, void *bf,
size_t size, bool need_swap)
{
struct {
u32 n_namesz;
u32 n_descsz;
u32 n_type;
} *nhdr;
void *ptr;
ptr = note_data;
while (ptr < (note_data + note_len)) {
const char *name;
size_t namesz, descsz;
nhdr = ptr;
if (need_swap) {
nhdr->n_namesz = bswap_32(nhdr->n_namesz);
nhdr->n_descsz = bswap_32(nhdr->n_descsz);
nhdr->n_type = bswap_32(nhdr->n_type);
}
namesz = NOTE_ALIGN(nhdr->n_namesz);
descsz = NOTE_ALIGN(nhdr->n_descsz);
ptr += sizeof(*nhdr);
name = ptr;
ptr += namesz;
if (nhdr->n_type == NT_GNU_BUILD_ID &&
nhdr->n_namesz == sizeof("GNU")) {
if (memcmp(name, "GNU", sizeof("GNU")) == 0) {
size_t sz = min(size, descsz);
memcpy(bf, ptr, sz);
memset(bf + sz, 0, size - sz);
return 0;
}
}
ptr += descsz;
}
return -1;
}
int filename__read_debuglink(const char *filename __maybe_unused,
char *debuglink __maybe_unused,
size_t size __maybe_unused)
{
return -1;
}
/*
* Just try PT_NOTE header otherwise fails
*/
int filename__read_build_id(const char *filename, void *bf, size_t size)
{
FILE *fp;
int ret = -1;
bool need_swap = false;
u8 e_ident[EI_NIDENT];
size_t buf_size;
void *buf;
int i;
fp = fopen(filename, "r");
if (fp == NULL)
return -1;
if (fread(e_ident, sizeof(e_ident), 1, fp) != 1)
goto out;
if (memcmp(e_ident, ELFMAG, SELFMAG) ||
e_ident[EI_VERSION] != EV_CURRENT)
goto out;
need_swap = check_need_swap(e_ident[EI_DATA]);
/* for simplicity */
fseek(fp, 0, SEEK_SET);
if (e_ident[EI_CLASS] == ELFCLASS32) {
Elf32_Ehdr ehdr;
Elf32_Phdr *phdr;
if (fread(&ehdr, sizeof(ehdr), 1, fp) != 1)
goto out;
if (need_swap) {
ehdr.e_phoff = bswap_32(ehdr.e_phoff);
ehdr.e_phentsize = bswap_16(ehdr.e_phentsize);
ehdr.e_phnum = bswap_16(ehdr.e_phnum);
}
buf_size = ehdr.e_phentsize * ehdr.e_phnum;
buf = malloc(buf_size);
if (buf == NULL)
goto out;
fseek(fp, ehdr.e_phoff, SEEK_SET);
if (fread(buf, buf_size, 1, fp) != 1)
goto out_free;
for (i = 0, phdr = buf; i < ehdr.e_phnum; i++, phdr++) {
void *tmp;
if (need_swap) {
phdr->p_type = bswap_32(phdr->p_type);
phdr->p_offset = bswap_32(phdr->p_offset);
phdr->p_filesz = bswap_32(phdr->p_filesz);
}
if (phdr->p_type != PT_NOTE)
continue;
buf_size = phdr->p_filesz;
tmp = realloc(buf, buf_size);
if (tmp == NULL)
goto out_free;
buf = tmp;
fseek(fp, phdr->p_offset, SEEK_SET);
if (fread(buf, buf_size, 1, fp) != 1)
goto out_free;
ret = read_build_id(buf, buf_size, bf, size, need_swap);
if (ret == 0)
ret = size;
break;
}
} else {
Elf64_Ehdr ehdr;
Elf64_Phdr *phdr;
if (fread(&ehdr, sizeof(ehdr), 1, fp) != 1)
goto out;
if (need_swap) {
ehdr.e_phoff = bswap_64(ehdr.e_phoff);
ehdr.e_phentsize = bswap_16(ehdr.e_phentsize);
ehdr.e_phnum = bswap_16(ehdr.e_phnum);
}
buf_size = ehdr.e_phentsize * ehdr.e_phnum;
buf = malloc(buf_size);
if (buf == NULL)
goto out;
fseek(fp, ehdr.e_phoff, SEEK_SET);
if (fread(buf, buf_size, 1, fp) != 1)
goto out_free;
for (i = 0, phdr = buf; i < ehdr.e_phnum; i++, phdr++) {
void *tmp;
if (need_swap) {
phdr->p_type = bswap_32(phdr->p_type);
phdr->p_offset = bswap_64(phdr->p_offset);
phdr->p_filesz = bswap_64(phdr->p_filesz);
}
if (phdr->p_type != PT_NOTE)
continue;
buf_size = phdr->p_filesz;
tmp = realloc(buf, buf_size);
if (tmp == NULL)
goto out_free;
buf = tmp;
fseek(fp, phdr->p_offset, SEEK_SET);
if (fread(buf, buf_size, 1, fp) != 1)
goto out_free;
ret = read_build_id(buf, buf_size, bf, size, need_swap);
if (ret == 0)
ret = size;
break;
}
}
out_free:
free(buf);
out:
fclose(fp);
return ret;
}
int sysfs__read_build_id(const char *filename, void *build_id, size_t size)
{
int fd;
int ret = -1;
struct stat stbuf;
size_t buf_size;
void *buf;
fd = open(filename, O_RDONLY);
if (fd < 0)
return -1;
if (fstat(fd, &stbuf) < 0)
goto out;
buf_size = stbuf.st_size;
buf = malloc(buf_size);
if (buf == NULL)
goto out;
if (read(fd, buf, buf_size) != (ssize_t) buf_size)
goto out_free;
ret = read_build_id(buf, buf_size, build_id, size, false);
out_free:
free(buf);
out:
close(fd);
return ret;
}
int symsrc__init(struct symsrc *ss, struct dso *dso __maybe_unused,
const char *name,
enum dso_binary_type type)
{
int fd = open(name, O_RDONLY);
if (fd < 0)
return -1;
ss->name = strdup(name);
if (!ss->name)
goto out_close;
ss->fd = fd;
ss->type = type;
return 0;
out_close:
close(fd);
return -1;
}
bool symsrc__possibly_runtime(struct symsrc *ss __maybe_unused)
{
/* Assume all sym sources could be a runtime image. */
return true;
}
bool symsrc__has_symtab(struct symsrc *ss __maybe_unused)
{
return false;
}
void symsrc__destroy(struct symsrc *ss)
{
zfree(&ss->name);
close(ss->fd);
}
int dso__synthesize_plt_symbols(struct dso *dso __maybe_unused,
struct symsrc *ss __maybe_unused,
struct map *map __maybe_unused,
symbol_filter_t filter __maybe_unused)
{
return 0;
}
int dso__load_sym(struct dso *dso, struct map *map __maybe_unused,
struct symsrc *ss,
struct symsrc *runtime_ss __maybe_unused,
symbol_filter_t filter __maybe_unused,
int kmodule __maybe_unused)
{
unsigned char *build_id[BUILD_ID_SIZE];
if (filename__read_build_id(ss->name, build_id, BUILD_ID_SIZE) > 0) {
dso__set_build_id(dso, build_id);
return 1;
}
return 0;
}
int file__read_maps(int fd __maybe_unused, bool exe __maybe_unused,
mapfn_t mapfn __maybe_unused, void *data __maybe_unused,
bool *is_64_bit __maybe_unused)
{
return -1;
}
int kcore_extract__create(struct kcore_extract *kce __maybe_unused)
{
return -1;
}
void kcore_extract__delete(struct kcore_extract *kce __maybe_unused)
{
}
int kcore_copy(const char *from_dir __maybe_unused,
const char *to_dir __maybe_unused)
{
return -1;
}
void symbol__elf_init(void)
{
}
| gpl-2.0 |
metredigm/linux | drivers/mtd/ubi/vtbl.c | 359 | 24531 | /*
* Copyright (c) International Business Machines Corp., 2006
* Copyright (c) Nokia Corporation, 2006, 2007
*
* 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
*
* Author: Artem Bityutskiy (Битюцкий Артём)
*/
/*
* This file includes volume table manipulation code. The volume table is an
* on-flash table containing volume meta-data like name, number of reserved
* physical eraseblocks, type, etc. The volume table is stored in the so-called
* "layout volume".
*
* The layout volume is an internal volume which is organized as follows. It
* consists of two logical eraseblocks - LEB 0 and LEB 1. Each logical
* eraseblock stores one volume table copy, i.e. LEB 0 and LEB 1 duplicate each
* other. This redundancy guarantees robustness to unclean reboots. The volume
* table is basically an array of volume table records. Each record contains
* full information about the volume and protected by a CRC checksum. Note,
* nowadays we use the atomic LEB change operation when updating the volume
* table, so we do not really need 2 LEBs anymore, but we preserve the older
* design for the backward compatibility reasons.
*
* When the volume table is changed, it is first changed in RAM. Then LEB 0 is
* erased, and the updated volume table is written back to LEB 0. Then same for
* LEB 1. This scheme guarantees recoverability from unclean reboots.
*
* In this UBI implementation the on-flash volume table does not contain any
* information about how much data static volumes contain.
*
* But it would still be beneficial to store this information in the volume
* table. For example, suppose we have a static volume X, and all its physical
* eraseblocks became bad for some reasons. Suppose we are attaching the
* corresponding MTD device, for some reason we find no logical eraseblocks
* corresponding to the volume X. According to the volume table volume X does
* exist. So we don't know whether it is just empty or all its physical
* eraseblocks went bad. So we cannot alarm the user properly.
*
* The volume table also stores so-called "update marker", which is used for
* volume updates. Before updating the volume, the update marker is set, and
* after the update operation is finished, the update marker is cleared. So if
* the update operation was interrupted (e.g. by an unclean reboot) - the
* update marker is still there and we know that the volume's contents is
* damaged.
*/
#include <linux/crc32.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <asm/div64.h>
#include "ubi.h"
static void self_vtbl_check(const struct ubi_device *ubi);
/* Empty volume table record */
static struct ubi_vtbl_record empty_vtbl_record;
/**
* ubi_update_layout_vol - helper for updatting layout volumes on flash
* @ubi: UBI device description object
*/
static int ubi_update_layout_vol(struct ubi_device *ubi)
{
struct ubi_volume *layout_vol;
int i, err;
layout_vol = ubi->volumes[vol_id2idx(ubi, UBI_LAYOUT_VOLUME_ID)];
for (i = 0; i < UBI_LAYOUT_VOLUME_EBS; i++) {
err = ubi_eba_atomic_leb_change(ubi, layout_vol, i, ubi->vtbl,
ubi->vtbl_size);
if (err)
return err;
}
return 0;
}
/**
* ubi_change_vtbl_record - change volume table record.
* @ubi: UBI device description object
* @idx: table index to change
* @vtbl_rec: new volume table record
*
* This function changes volume table record @idx. If @vtbl_rec is %NULL, empty
* volume table record is written. The caller does not have to calculate CRC of
* the record as it is done by this function. Returns zero in case of success
* and a negative error code in case of failure.
*/
int ubi_change_vtbl_record(struct ubi_device *ubi, int idx,
struct ubi_vtbl_record *vtbl_rec)
{
int err;
uint32_t crc;
ubi_assert(idx >= 0 && idx < ubi->vtbl_slots);
if (!vtbl_rec)
vtbl_rec = &empty_vtbl_record;
else {
crc = crc32(UBI_CRC32_INIT, vtbl_rec, UBI_VTBL_RECORD_SIZE_CRC);
vtbl_rec->crc = cpu_to_be32(crc);
}
memcpy(&ubi->vtbl[idx], vtbl_rec, sizeof(struct ubi_vtbl_record));
err = ubi_update_layout_vol(ubi);
self_vtbl_check(ubi);
return err ? err : 0;
}
/**
* ubi_vtbl_rename_volumes - rename UBI volumes in the volume table.
* @ubi: UBI device description object
* @rename_list: list of &struct ubi_rename_entry objects
*
* This function re-names multiple volumes specified in @req in the volume
* table. Returns zero in case of success and a negative error code in case of
* failure.
*/
int ubi_vtbl_rename_volumes(struct ubi_device *ubi,
struct list_head *rename_list)
{
struct ubi_rename_entry *re;
list_for_each_entry(re, rename_list, list) {
uint32_t crc;
struct ubi_volume *vol = re->desc->vol;
struct ubi_vtbl_record *vtbl_rec = &ubi->vtbl[vol->vol_id];
if (re->remove) {
memcpy(vtbl_rec, &empty_vtbl_record,
sizeof(struct ubi_vtbl_record));
continue;
}
vtbl_rec->name_len = cpu_to_be16(re->new_name_len);
memcpy(vtbl_rec->name, re->new_name, re->new_name_len);
memset(vtbl_rec->name + re->new_name_len, 0,
UBI_VOL_NAME_MAX + 1 - re->new_name_len);
crc = crc32(UBI_CRC32_INIT, vtbl_rec,
UBI_VTBL_RECORD_SIZE_CRC);
vtbl_rec->crc = cpu_to_be32(crc);
}
return ubi_update_layout_vol(ubi);
}
/**
* vtbl_check - check if volume table is not corrupted and sensible.
* @ubi: UBI device description object
* @vtbl: volume table
*
* This function returns zero if @vtbl is all right, %1 if CRC is incorrect,
* and %-EINVAL if it contains inconsistent data.
*/
static int vtbl_check(const struct ubi_device *ubi,
const struct ubi_vtbl_record *vtbl)
{
int i, n, reserved_pebs, alignment, data_pad, vol_type, name_len;
int upd_marker, err;
uint32_t crc;
const char *name;
for (i = 0; i < ubi->vtbl_slots; i++) {
cond_resched();
reserved_pebs = be32_to_cpu(vtbl[i].reserved_pebs);
alignment = be32_to_cpu(vtbl[i].alignment);
data_pad = be32_to_cpu(vtbl[i].data_pad);
upd_marker = vtbl[i].upd_marker;
vol_type = vtbl[i].vol_type;
name_len = be16_to_cpu(vtbl[i].name_len);
name = &vtbl[i].name[0];
crc = crc32(UBI_CRC32_INIT, &vtbl[i], UBI_VTBL_RECORD_SIZE_CRC);
if (be32_to_cpu(vtbl[i].crc) != crc) {
ubi_err(ubi, "bad CRC at record %u: %#08x, not %#08x",
i, crc, be32_to_cpu(vtbl[i].crc));
ubi_dump_vtbl_record(&vtbl[i], i);
return 1;
}
if (reserved_pebs == 0) {
if (memcmp(&vtbl[i], &empty_vtbl_record,
UBI_VTBL_RECORD_SIZE)) {
err = 2;
goto bad;
}
continue;
}
if (reserved_pebs < 0 || alignment < 0 || data_pad < 0 ||
name_len < 0) {
err = 3;
goto bad;
}
if (alignment > ubi->leb_size || alignment == 0) {
err = 4;
goto bad;
}
n = alignment & (ubi->min_io_size - 1);
if (alignment != 1 && n) {
err = 5;
goto bad;
}
n = ubi->leb_size % alignment;
if (data_pad != n) {
ubi_err(ubi, "bad data_pad, has to be %d", n);
err = 6;
goto bad;
}
if (vol_type != UBI_VID_DYNAMIC && vol_type != UBI_VID_STATIC) {
err = 7;
goto bad;
}
if (upd_marker != 0 && upd_marker != 1) {
err = 8;
goto bad;
}
if (reserved_pebs > ubi->good_peb_count) {
ubi_err(ubi, "too large reserved_pebs %d, good PEBs %d",
reserved_pebs, ubi->good_peb_count);
err = 9;
goto bad;
}
if (name_len > UBI_VOL_NAME_MAX) {
err = 10;
goto bad;
}
if (name[0] == '\0') {
err = 11;
goto bad;
}
if (name_len != strnlen(name, name_len + 1)) {
err = 12;
goto bad;
}
}
/* Checks that all names are unique */
for (i = 0; i < ubi->vtbl_slots - 1; i++) {
for (n = i + 1; n < ubi->vtbl_slots; n++) {
int len1 = be16_to_cpu(vtbl[i].name_len);
int len2 = be16_to_cpu(vtbl[n].name_len);
if (len1 > 0 && len1 == len2 &&
!strncmp(vtbl[i].name, vtbl[n].name, len1)) {
ubi_err(ubi, "volumes %d and %d have the same name \"%s\"",
i, n, vtbl[i].name);
ubi_dump_vtbl_record(&vtbl[i], i);
ubi_dump_vtbl_record(&vtbl[n], n);
return -EINVAL;
}
}
}
return 0;
bad:
ubi_err(ubi, "volume table check failed: record %d, error %d", i, err);
ubi_dump_vtbl_record(&vtbl[i], i);
return -EINVAL;
}
/**
* create_vtbl - create a copy of volume table.
* @ubi: UBI device description object
* @ai: attaching information
* @copy: number of the volume table copy
* @vtbl: contents of the volume table
*
* This function returns zero in case of success and a negative error code in
* case of failure.
*/
static int create_vtbl(struct ubi_device *ubi, struct ubi_attach_info *ai,
int copy, void *vtbl)
{
int err, tries = 0;
struct ubi_vid_hdr *vid_hdr;
struct ubi_ainf_peb *new_aeb;
dbg_gen("create volume table (copy #%d)", copy + 1);
vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_KERNEL);
if (!vid_hdr)
return -ENOMEM;
retry:
new_aeb = ubi_early_get_peb(ubi, ai);
if (IS_ERR(new_aeb)) {
err = PTR_ERR(new_aeb);
goto out_free;
}
vid_hdr->vol_type = UBI_LAYOUT_VOLUME_TYPE;
vid_hdr->vol_id = cpu_to_be32(UBI_LAYOUT_VOLUME_ID);
vid_hdr->compat = UBI_LAYOUT_VOLUME_COMPAT;
vid_hdr->data_size = vid_hdr->used_ebs =
vid_hdr->data_pad = cpu_to_be32(0);
vid_hdr->lnum = cpu_to_be32(copy);
vid_hdr->sqnum = cpu_to_be64(++ai->max_sqnum);
/* The EC header is already there, write the VID header */
err = ubi_io_write_vid_hdr(ubi, new_aeb->pnum, vid_hdr);
if (err)
goto write_error;
/* Write the layout volume contents */
err = ubi_io_write_data(ubi, vtbl, new_aeb->pnum, 0, ubi->vtbl_size);
if (err)
goto write_error;
/*
* And add it to the attaching information. Don't delete the old version
* of this LEB as it will be deleted and freed in 'ubi_add_to_av()'.
*/
err = ubi_add_to_av(ubi, ai, new_aeb->pnum, new_aeb->ec, vid_hdr, 0);
kmem_cache_free(ai->aeb_slab_cache, new_aeb);
ubi_free_vid_hdr(ubi, vid_hdr);
return err;
write_error:
if (err == -EIO && ++tries <= 5) {
/*
* Probably this physical eraseblock went bad, try to pick
* another one.
*/
list_add(&new_aeb->u.list, &ai->erase);
goto retry;
}
kmem_cache_free(ai->aeb_slab_cache, new_aeb);
out_free:
ubi_free_vid_hdr(ubi, vid_hdr);
return err;
}
/**
* process_lvol - process the layout volume.
* @ubi: UBI device description object
* @ai: attaching information
* @av: layout volume attaching information
*
* This function is responsible for reading the layout volume, ensuring it is
* not corrupted, and recovering from corruptions if needed. Returns volume
* table in case of success and a negative error code in case of failure.
*/
static struct ubi_vtbl_record *process_lvol(struct ubi_device *ubi,
struct ubi_attach_info *ai,
struct ubi_ainf_volume *av)
{
int err;
struct rb_node *rb;
struct ubi_ainf_peb *aeb;
struct ubi_vtbl_record *leb[UBI_LAYOUT_VOLUME_EBS] = { NULL, NULL };
int leb_corrupted[UBI_LAYOUT_VOLUME_EBS] = {1, 1};
/*
* UBI goes through the following steps when it changes the layout
* volume:
* a. erase LEB 0;
* b. write new data to LEB 0;
* c. erase LEB 1;
* d. write new data to LEB 1.
*
* Before the change, both LEBs contain the same data.
*
* Due to unclean reboots, the contents of LEB 0 may be lost, but there
* should LEB 1. So it is OK if LEB 0 is corrupted while LEB 1 is not.
* Similarly, LEB 1 may be lost, but there should be LEB 0. And
* finally, unclean reboots may result in a situation when neither LEB
* 0 nor LEB 1 are corrupted, but they are different. In this case, LEB
* 0 contains more recent information.
*
* So the plan is to first check LEB 0. Then
* a. if LEB 0 is OK, it must be containing the most recent data; then
* we compare it with LEB 1, and if they are different, we copy LEB
* 0 to LEB 1;
* b. if LEB 0 is corrupted, but LEB 1 has to be OK, and we copy LEB 1
* to LEB 0.
*/
dbg_gen("check layout volume");
/* Read both LEB 0 and LEB 1 into memory */
ubi_rb_for_each_entry(rb, aeb, &av->root, u.rb) {
leb[aeb->lnum] = vzalloc(ubi->vtbl_size);
if (!leb[aeb->lnum]) {
err = -ENOMEM;
goto out_free;
}
err = ubi_io_read_data(ubi, leb[aeb->lnum], aeb->pnum, 0,
ubi->vtbl_size);
if (err == UBI_IO_BITFLIPS || mtd_is_eccerr(err))
/*
* Scrub the PEB later. Note, -EBADMSG indicates an
* uncorrectable ECC error, but we have our own CRC and
* the data will be checked later. If the data is OK,
* the PEB will be scrubbed (because we set
* aeb->scrub). If the data is not OK, the contents of
* the PEB will be recovered from the second copy, and
* aeb->scrub will be cleared in
* 'ubi_add_to_av()'.
*/
aeb->scrub = 1;
else if (err)
goto out_free;
}
err = -EINVAL;
if (leb[0]) {
leb_corrupted[0] = vtbl_check(ubi, leb[0]);
if (leb_corrupted[0] < 0)
goto out_free;
}
if (!leb_corrupted[0]) {
/* LEB 0 is OK */
if (leb[1])
leb_corrupted[1] = memcmp(leb[0], leb[1],
ubi->vtbl_size);
if (leb_corrupted[1]) {
ubi_warn(ubi, "volume table copy #2 is corrupted");
err = create_vtbl(ubi, ai, 1, leb[0]);
if (err)
goto out_free;
ubi_msg(ubi, "volume table was restored");
}
/* Both LEB 1 and LEB 2 are OK and consistent */
vfree(leb[1]);
return leb[0];
} else {
/* LEB 0 is corrupted or does not exist */
if (leb[1]) {
leb_corrupted[1] = vtbl_check(ubi, leb[1]);
if (leb_corrupted[1] < 0)
goto out_free;
}
if (leb_corrupted[1]) {
/* Both LEB 0 and LEB 1 are corrupted */
ubi_err(ubi, "both volume tables are corrupted");
goto out_free;
}
ubi_warn(ubi, "volume table copy #1 is corrupted");
err = create_vtbl(ubi, ai, 0, leb[1]);
if (err)
goto out_free;
ubi_msg(ubi, "volume table was restored");
vfree(leb[0]);
return leb[1];
}
out_free:
vfree(leb[0]);
vfree(leb[1]);
return ERR_PTR(err);
}
/**
* create_empty_lvol - create empty layout volume.
* @ubi: UBI device description object
* @ai: attaching information
*
* This function returns volume table contents in case of success and a
* negative error code in case of failure.
*/
static struct ubi_vtbl_record *create_empty_lvol(struct ubi_device *ubi,
struct ubi_attach_info *ai)
{
int i;
struct ubi_vtbl_record *vtbl;
vtbl = vzalloc(ubi->vtbl_size);
if (!vtbl)
return ERR_PTR(-ENOMEM);
for (i = 0; i < ubi->vtbl_slots; i++)
memcpy(&vtbl[i], &empty_vtbl_record, UBI_VTBL_RECORD_SIZE);
for (i = 0; i < UBI_LAYOUT_VOLUME_EBS; i++) {
int err;
err = create_vtbl(ubi, ai, i, vtbl);
if (err) {
vfree(vtbl);
return ERR_PTR(err);
}
}
return vtbl;
}
/**
* init_volumes - initialize volume information for existing volumes.
* @ubi: UBI device description object
* @ai: scanning information
* @vtbl: volume table
*
* This function allocates volume description objects for existing volumes.
* Returns zero in case of success and a negative error code in case of
* failure.
*/
static int init_volumes(struct ubi_device *ubi,
const struct ubi_attach_info *ai,
const struct ubi_vtbl_record *vtbl)
{
int i, reserved_pebs = 0;
struct ubi_ainf_volume *av;
struct ubi_volume *vol;
for (i = 0; i < ubi->vtbl_slots; i++) {
cond_resched();
if (be32_to_cpu(vtbl[i].reserved_pebs) == 0)
continue; /* Empty record */
vol = kzalloc(sizeof(struct ubi_volume), GFP_KERNEL);
if (!vol)
return -ENOMEM;
vol->reserved_pebs = be32_to_cpu(vtbl[i].reserved_pebs);
vol->alignment = be32_to_cpu(vtbl[i].alignment);
vol->data_pad = be32_to_cpu(vtbl[i].data_pad);
vol->upd_marker = vtbl[i].upd_marker;
vol->vol_type = vtbl[i].vol_type == UBI_VID_DYNAMIC ?
UBI_DYNAMIC_VOLUME : UBI_STATIC_VOLUME;
vol->name_len = be16_to_cpu(vtbl[i].name_len);
vol->usable_leb_size = ubi->leb_size - vol->data_pad;
memcpy(vol->name, vtbl[i].name, vol->name_len);
vol->name[vol->name_len] = '\0';
vol->vol_id = i;
if (vtbl[i].flags & UBI_VTBL_AUTORESIZE_FLG) {
/* Auto re-size flag may be set only for one volume */
if (ubi->autoresize_vol_id != -1) {
ubi_err(ubi, "more than one auto-resize volume (%d and %d)",
ubi->autoresize_vol_id, i);
kfree(vol);
return -EINVAL;
}
ubi->autoresize_vol_id = i;
}
ubi_assert(!ubi->volumes[i]);
ubi->volumes[i] = vol;
ubi->vol_count += 1;
vol->ubi = ubi;
reserved_pebs += vol->reserved_pebs;
/*
* In case of dynamic volume UBI knows nothing about how many
* data is stored there. So assume the whole volume is used.
*/
if (vol->vol_type == UBI_DYNAMIC_VOLUME) {
vol->used_ebs = vol->reserved_pebs;
vol->last_eb_bytes = vol->usable_leb_size;
vol->used_bytes =
(long long)vol->used_ebs * vol->usable_leb_size;
continue;
}
/* Static volumes only */
av = ubi_find_av(ai, i);
if (!av || !av->leb_count) {
/*
* No eraseblocks belonging to this volume found. We
* don't actually know whether this static volume is
* completely corrupted or just contains no data. And
* we cannot know this as long as data size is not
* stored on flash. So we just assume the volume is
* empty. FIXME: this should be handled.
*/
continue;
}
if (av->leb_count != av->used_ebs) {
/*
* We found a static volume which misses several
* eraseblocks. Treat it as corrupted.
*/
ubi_warn(ubi, "static volume %d misses %d LEBs - corrupted",
av->vol_id, av->used_ebs - av->leb_count);
vol->corrupted = 1;
continue;
}
vol->used_ebs = av->used_ebs;
vol->used_bytes =
(long long)(vol->used_ebs - 1) * vol->usable_leb_size;
vol->used_bytes += av->last_data_size;
vol->last_eb_bytes = av->last_data_size;
}
/* And add the layout volume */
vol = kzalloc(sizeof(struct ubi_volume), GFP_KERNEL);
if (!vol)
return -ENOMEM;
vol->reserved_pebs = UBI_LAYOUT_VOLUME_EBS;
vol->alignment = UBI_LAYOUT_VOLUME_ALIGN;
vol->vol_type = UBI_DYNAMIC_VOLUME;
vol->name_len = sizeof(UBI_LAYOUT_VOLUME_NAME) - 1;
memcpy(vol->name, UBI_LAYOUT_VOLUME_NAME, vol->name_len + 1);
vol->usable_leb_size = ubi->leb_size;
vol->used_ebs = vol->reserved_pebs;
vol->last_eb_bytes = vol->reserved_pebs;
vol->used_bytes =
(long long)vol->used_ebs * (ubi->leb_size - vol->data_pad);
vol->vol_id = UBI_LAYOUT_VOLUME_ID;
vol->ref_count = 1;
ubi_assert(!ubi->volumes[i]);
ubi->volumes[vol_id2idx(ubi, vol->vol_id)] = vol;
reserved_pebs += vol->reserved_pebs;
ubi->vol_count += 1;
vol->ubi = ubi;
if (reserved_pebs > ubi->avail_pebs) {
ubi_err(ubi, "not enough PEBs, required %d, available %d",
reserved_pebs, ubi->avail_pebs);
if (ubi->corr_peb_count)
ubi_err(ubi, "%d PEBs are corrupted and not used",
ubi->corr_peb_count);
}
ubi->rsvd_pebs += reserved_pebs;
ubi->avail_pebs -= reserved_pebs;
return 0;
}
/**
* check_av - check volume attaching information.
* @vol: UBI volume description object
* @av: volume attaching information
*
* This function returns zero if the volume attaching information is consistent
* to the data read from the volume tabla, and %-EINVAL if not.
*/
static int check_av(const struct ubi_volume *vol,
const struct ubi_ainf_volume *av)
{
int err;
if (av->highest_lnum >= vol->reserved_pebs) {
err = 1;
goto bad;
}
if (av->leb_count > vol->reserved_pebs) {
err = 2;
goto bad;
}
if (av->vol_type != vol->vol_type) {
err = 3;
goto bad;
}
if (av->used_ebs > vol->reserved_pebs) {
err = 4;
goto bad;
}
if (av->data_pad != vol->data_pad) {
err = 5;
goto bad;
}
return 0;
bad:
ubi_err(vol->ubi, "bad attaching information, error %d", err);
ubi_dump_av(av);
ubi_dump_vol_info(vol);
return -EINVAL;
}
/**
* check_attaching_info - check that attaching information.
* @ubi: UBI device description object
* @ai: attaching information
*
* Even though we protect on-flash data by CRC checksums, we still don't trust
* the media. This function ensures that attaching information is consistent to
* the information read from the volume table. Returns zero if the attaching
* information is OK and %-EINVAL if it is not.
*/
static int check_attaching_info(const struct ubi_device *ubi,
struct ubi_attach_info *ai)
{
int err, i;
struct ubi_ainf_volume *av;
struct ubi_volume *vol;
if (ai->vols_found > UBI_INT_VOL_COUNT + ubi->vtbl_slots) {
ubi_err(ubi, "found %d volumes while attaching, maximum is %d + %d",
ai->vols_found, UBI_INT_VOL_COUNT, ubi->vtbl_slots);
return -EINVAL;
}
if (ai->highest_vol_id >= ubi->vtbl_slots + UBI_INT_VOL_COUNT &&
ai->highest_vol_id < UBI_INTERNAL_VOL_START) {
ubi_err(ubi, "too large volume ID %d found",
ai->highest_vol_id);
return -EINVAL;
}
for (i = 0; i < ubi->vtbl_slots + UBI_INT_VOL_COUNT; i++) {
cond_resched();
av = ubi_find_av(ai, i);
vol = ubi->volumes[i];
if (!vol) {
if (av)
ubi_remove_av(ai, av);
continue;
}
if (vol->reserved_pebs == 0) {
ubi_assert(i < ubi->vtbl_slots);
if (!av)
continue;
/*
* During attaching we found a volume which does not
* exist according to the information in the volume
* table. This must have happened due to an unclean
* reboot while the volume was being removed. Discard
* these eraseblocks.
*/
ubi_msg(ubi, "finish volume %d removal", av->vol_id);
ubi_remove_av(ai, av);
} else if (av) {
err = check_av(vol, av);
if (err)
return err;
}
}
return 0;
}
/**
* ubi_read_volume_table - read the volume table.
* @ubi: UBI device description object
* @ai: attaching information
*
* This function reads volume table, checks it, recover from errors if needed,
* or creates it if needed. Returns zero in case of success and a negative
* error code in case of failure.
*/
int ubi_read_volume_table(struct ubi_device *ubi, struct ubi_attach_info *ai)
{
int i, err;
struct ubi_ainf_volume *av;
empty_vtbl_record.crc = cpu_to_be32(0xf116c36b);
/*
* The number of supported volumes is limited by the eraseblock size
* and by the UBI_MAX_VOLUMES constant.
*/
ubi->vtbl_slots = ubi->leb_size / UBI_VTBL_RECORD_SIZE;
if (ubi->vtbl_slots > UBI_MAX_VOLUMES)
ubi->vtbl_slots = UBI_MAX_VOLUMES;
ubi->vtbl_size = ubi->vtbl_slots * UBI_VTBL_RECORD_SIZE;
ubi->vtbl_size = ALIGN(ubi->vtbl_size, ubi->min_io_size);
av = ubi_find_av(ai, UBI_LAYOUT_VOLUME_ID);
if (!av) {
/*
* No logical eraseblocks belonging to the layout volume were
* found. This could mean that the flash is just empty. In
* this case we create empty layout volume.
*
* But if flash is not empty this must be a corruption or the
* MTD device just contains garbage.
*/
if (ai->is_empty) {
ubi->vtbl = create_empty_lvol(ubi, ai);
if (IS_ERR(ubi->vtbl))
return PTR_ERR(ubi->vtbl);
} else {
ubi_err(ubi, "the layout volume was not found");
return -EINVAL;
}
} else {
if (av->leb_count > UBI_LAYOUT_VOLUME_EBS) {
/* This must not happen with proper UBI images */
ubi_err(ubi, "too many LEBs (%d) in layout volume",
av->leb_count);
return -EINVAL;
}
ubi->vtbl = process_lvol(ubi, ai, av);
if (IS_ERR(ubi->vtbl))
return PTR_ERR(ubi->vtbl);
}
ubi->avail_pebs = ubi->good_peb_count - ubi->corr_peb_count;
/*
* The layout volume is OK, initialize the corresponding in-RAM data
* structures.
*/
err = init_volumes(ubi, ai, ubi->vtbl);
if (err)
goto out_free;
/*
* Make sure that the attaching information is consistent to the
* information stored in the volume table.
*/
err = check_attaching_info(ubi, ai);
if (err)
goto out_free;
return 0;
out_free:
vfree(ubi->vtbl);
for (i = 0; i < ubi->vtbl_slots + UBI_INT_VOL_COUNT; i++) {
kfree(ubi->volumes[i]);
ubi->volumes[i] = NULL;
}
return err;
}
/**
* self_vtbl_check - check volume table.
* @ubi: UBI device description object
*/
static void self_vtbl_check(const struct ubi_device *ubi)
{
if (!ubi_dbg_chk_gen(ubi))
return;
if (vtbl_check(ubi, ubi->vtbl)) {
ubi_err(ubi, "self-check failed");
BUG();
}
}
| gpl-2.0 |
kaiaixi/RP2_MPTCP | drivers/net/wireless/iwlwifi/iwl-2000.c | 615 | 7136 | /******************************************************************************
*
* Copyright(c) 2008 - 2014 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
*****************************************************************************/
#include <linux/module.h>
#include <linux/stringify.h>
#include "iwl-config.h"
#include "iwl-agn-hw.h"
#include "dvm/commands.h" /* needed for BT for now */
/* Highest firmware API version supported */
#define IWL2030_UCODE_API_MAX 6
#define IWL2000_UCODE_API_MAX 6
#define IWL105_UCODE_API_MAX 6
#define IWL135_UCODE_API_MAX 6
/* Oldest version we won't warn about */
#define IWL2030_UCODE_API_OK 6
#define IWL2000_UCODE_API_OK 6
#define IWL105_UCODE_API_OK 6
#define IWL135_UCODE_API_OK 6
/* Lowest firmware API version supported */
#define IWL2030_UCODE_API_MIN 5
#define IWL2000_UCODE_API_MIN 5
#define IWL105_UCODE_API_MIN 5
#define IWL135_UCODE_API_MIN 5
/* EEPROM version */
#define EEPROM_2000_TX_POWER_VERSION (6)
#define EEPROM_2000_EEPROM_VERSION (0x805)
#define IWL2030_FW_PRE "iwlwifi-2030-"
#define IWL2030_MODULE_FIRMWARE(api) IWL2030_FW_PRE __stringify(api) ".ucode"
#define IWL2000_FW_PRE "iwlwifi-2000-"
#define IWL2000_MODULE_FIRMWARE(api) IWL2000_FW_PRE __stringify(api) ".ucode"
#define IWL105_FW_PRE "iwlwifi-105-"
#define IWL105_MODULE_FIRMWARE(api) IWL105_FW_PRE __stringify(api) ".ucode"
#define IWL135_FW_PRE "iwlwifi-135-"
#define IWL135_MODULE_FIRMWARE(api) IWL135_FW_PRE __stringify(api) ".ucode"
static const struct iwl_base_params iwl2000_base_params = {
.eeprom_size = OTP_LOW_IMAGE_SIZE,
.num_of_queues = IWLAGN_NUM_QUEUES,
.pll_cfg_val = 0,
.max_ll_items = OTP_MAX_LL_ITEMS_2x00,
.shadow_ram_support = true,
.led_compensation = 51,
.wd_timeout = IWL_DEF_WD_TIMEOUT,
.max_event_log_size = 512,
.shadow_reg_enable = false, /* TODO: fix bugs using this feature */
.scd_chain_ext_wa = true,
};
static const struct iwl_base_params iwl2030_base_params = {
.eeprom_size = OTP_LOW_IMAGE_SIZE,
.num_of_queues = IWLAGN_NUM_QUEUES,
.pll_cfg_val = 0,
.max_ll_items = OTP_MAX_LL_ITEMS_2x00,
.shadow_ram_support = true,
.led_compensation = 57,
.wd_timeout = IWL_LONG_WD_TIMEOUT,
.max_event_log_size = 512,
.shadow_reg_enable = false, /* TODO: fix bugs using this feature */
.scd_chain_ext_wa = true,
};
static const struct iwl_ht_params iwl2000_ht_params = {
.ht_greenfield_support = true,
.use_rts_for_aggregation = true, /* use rts/cts protection */
.ht40_bands = BIT(IEEE80211_BAND_2GHZ),
};
static const struct iwl_eeprom_params iwl20x0_eeprom_params = {
.regulatory_bands = {
EEPROM_REG_BAND_1_CHANNELS,
EEPROM_REG_BAND_2_CHANNELS,
EEPROM_REG_BAND_3_CHANNELS,
EEPROM_REG_BAND_4_CHANNELS,
EEPROM_REG_BAND_5_CHANNELS,
EEPROM_6000_REG_BAND_24_HT40_CHANNELS,
EEPROM_REGULATORY_BAND_NO_HT40,
},
.enhanced_txpower = true,
};
#define IWL_DEVICE_2000 \
.fw_name_pre = IWL2000_FW_PRE, \
.ucode_api_max = IWL2000_UCODE_API_MAX, \
.ucode_api_ok = IWL2000_UCODE_API_OK, \
.ucode_api_min = IWL2000_UCODE_API_MIN, \
.device_family = IWL_DEVICE_FAMILY_2000, \
.max_inst_size = IWL60_RTC_INST_SIZE, \
.max_data_size = IWL60_RTC_DATA_SIZE, \
.nvm_ver = EEPROM_2000_EEPROM_VERSION, \
.nvm_calib_ver = EEPROM_2000_TX_POWER_VERSION, \
.base_params = &iwl2000_base_params, \
.eeprom_params = &iwl20x0_eeprom_params, \
.led_mode = IWL_LED_RF_STATE
const struct iwl_cfg iwl2000_2bgn_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N 2200 BGN",
IWL_DEVICE_2000,
.ht_params = &iwl2000_ht_params,
};
const struct iwl_cfg iwl2000_2bgn_d_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N 2200D BGN",
IWL_DEVICE_2000,
.ht_params = &iwl2000_ht_params,
};
#define IWL_DEVICE_2030 \
.fw_name_pre = IWL2030_FW_PRE, \
.ucode_api_max = IWL2030_UCODE_API_MAX, \
.ucode_api_ok = IWL2030_UCODE_API_OK, \
.ucode_api_min = IWL2030_UCODE_API_MIN, \
.device_family = IWL_DEVICE_FAMILY_2030, \
.max_inst_size = IWL60_RTC_INST_SIZE, \
.max_data_size = IWL60_RTC_DATA_SIZE, \
.nvm_ver = EEPROM_2000_EEPROM_VERSION, \
.nvm_calib_ver = EEPROM_2000_TX_POWER_VERSION, \
.base_params = &iwl2030_base_params, \
.eeprom_params = &iwl20x0_eeprom_params, \
.led_mode = IWL_LED_RF_STATE
const struct iwl_cfg iwl2030_2bgn_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N 2230 BGN",
IWL_DEVICE_2030,
.ht_params = &iwl2000_ht_params,
};
#define IWL_DEVICE_105 \
.fw_name_pre = IWL105_FW_PRE, \
.ucode_api_max = IWL105_UCODE_API_MAX, \
.ucode_api_ok = IWL105_UCODE_API_OK, \
.ucode_api_min = IWL105_UCODE_API_MIN, \
.device_family = IWL_DEVICE_FAMILY_105, \
.max_inst_size = IWL60_RTC_INST_SIZE, \
.max_data_size = IWL60_RTC_DATA_SIZE, \
.nvm_ver = EEPROM_2000_EEPROM_VERSION, \
.nvm_calib_ver = EEPROM_2000_TX_POWER_VERSION, \
.base_params = &iwl2000_base_params, \
.eeprom_params = &iwl20x0_eeprom_params, \
.led_mode = IWL_LED_RF_STATE, \
.rx_with_siso_diversity = true
const struct iwl_cfg iwl105_bgn_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N 105 BGN",
IWL_DEVICE_105,
.ht_params = &iwl2000_ht_params,
};
const struct iwl_cfg iwl105_bgn_d_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N 105D BGN",
IWL_DEVICE_105,
.ht_params = &iwl2000_ht_params,
};
#define IWL_DEVICE_135 \
.fw_name_pre = IWL135_FW_PRE, \
.ucode_api_max = IWL135_UCODE_API_MAX, \
.ucode_api_ok = IWL135_UCODE_API_OK, \
.ucode_api_min = IWL135_UCODE_API_MIN, \
.device_family = IWL_DEVICE_FAMILY_135, \
.max_inst_size = IWL60_RTC_INST_SIZE, \
.max_data_size = IWL60_RTC_DATA_SIZE, \
.nvm_ver = EEPROM_2000_EEPROM_VERSION, \
.nvm_calib_ver = EEPROM_2000_TX_POWER_VERSION, \
.base_params = &iwl2030_base_params, \
.eeprom_params = &iwl20x0_eeprom_params, \
.led_mode = IWL_LED_RF_STATE, \
.rx_with_siso_diversity = true
const struct iwl_cfg iwl135_bgn_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N 135 BGN",
IWL_DEVICE_135,
.ht_params = &iwl2000_ht_params,
};
MODULE_FIRMWARE(IWL2000_MODULE_FIRMWARE(IWL2000_UCODE_API_OK));
MODULE_FIRMWARE(IWL2030_MODULE_FIRMWARE(IWL2030_UCODE_API_OK));
MODULE_FIRMWARE(IWL105_MODULE_FIRMWARE(IWL105_UCODE_API_OK));
MODULE_FIRMWARE(IWL135_MODULE_FIRMWARE(IWL135_UCODE_API_OK));
| gpl-2.0 |
KatsuraKKKK/linux | sound/soc/intel/common/sst-firmware.c | 615 | 29310 | /*
* Intel SST Firmware Loader
*
* Copyright (C) 2013, Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/firmware.h>
#include <linux/export.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/dmaengine.h>
#include <linux/pci.h>
#include <linux/acpi.h>
/* supported DMA engine drivers */
#include <linux/platform_data/dma-dw.h>
#include <linux/dma/dw.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include "sst-dsp.h"
#include "sst-dsp-priv.h"
#define SST_DMA_RESOURCES 2
#define SST_DSP_DMA_MAX_BURST 0x3
#define SST_HSW_BLOCK_ANY 0xffffffff
#define SST_HSW_MASK_DMA_ADDR_DSP 0xfff00000
struct sst_dma {
struct sst_dsp *sst;
struct dw_dma_chip *chip;
struct dma_async_tx_descriptor *desc;
struct dma_chan *ch;
};
static inline void sst_memcpy32(volatile void __iomem *dest, void *src, u32 bytes)
{
/* __iowrite32_copy use 32bit size values so divide by 4 */
__iowrite32_copy((void *)dest, src, bytes/4);
}
static void sst_dma_transfer_complete(void *arg)
{
struct sst_dsp *sst = (struct sst_dsp *)arg;
dev_dbg(sst->dev, "DMA: callback\n");
}
static int sst_dsp_dma_copy(struct sst_dsp *sst, dma_addr_t dest_addr,
dma_addr_t src_addr, size_t size)
{
struct dma_async_tx_descriptor *desc;
struct sst_dma *dma = sst->dma;
if (dma->ch == NULL) {
dev_err(sst->dev, "error: no DMA channel\n");
return -ENODEV;
}
dev_dbg(sst->dev, "DMA: src: 0x%lx dest 0x%lx size %zu\n",
(unsigned long)src_addr, (unsigned long)dest_addr, size);
desc = dma->ch->device->device_prep_dma_memcpy(dma->ch, dest_addr,
src_addr, size, DMA_CTRL_ACK);
if (!desc){
dev_err(sst->dev, "error: dma prep memcpy failed\n");
return -EINVAL;
}
desc->callback = sst_dma_transfer_complete;
desc->callback_param = sst;
desc->tx_submit(desc);
dma_wait_for_async_tx(desc);
return 0;
}
/* copy to DSP */
int sst_dsp_dma_copyto(struct sst_dsp *sst, dma_addr_t dest_addr,
dma_addr_t src_addr, size_t size)
{
return sst_dsp_dma_copy(sst, dest_addr | SST_HSW_MASK_DMA_ADDR_DSP,
src_addr, size);
}
EXPORT_SYMBOL_GPL(sst_dsp_dma_copyto);
/* copy from DSP */
int sst_dsp_dma_copyfrom(struct sst_dsp *sst, dma_addr_t dest_addr,
dma_addr_t src_addr, size_t size)
{
return sst_dsp_dma_copy(sst, dest_addr,
src_addr | SST_HSW_MASK_DMA_ADDR_DSP, size);
}
EXPORT_SYMBOL_GPL(sst_dsp_dma_copyfrom);
/* remove module from memory - callers hold locks */
static void block_list_remove(struct sst_dsp *dsp,
struct list_head *block_list)
{
struct sst_mem_block *block, *tmp;
int err;
/* disable each block */
list_for_each_entry(block, block_list, module_list) {
if (block->ops && block->ops->disable) {
err = block->ops->disable(block);
if (err < 0)
dev_err(dsp->dev,
"error: cant disable block %d:%d\n",
block->type, block->index);
}
}
/* mark each block as free */
list_for_each_entry_safe(block, tmp, block_list, module_list) {
list_del(&block->module_list);
list_move(&block->list, &dsp->free_block_list);
dev_dbg(dsp->dev, "block freed %d:%d at offset 0x%x\n",
block->type, block->index, block->offset);
}
}
/* prepare the memory block to receive data from host - callers hold locks */
static int block_list_prepare(struct sst_dsp *dsp,
struct list_head *block_list)
{
struct sst_mem_block *block;
int ret = 0;
/* enable each block so that's it'e ready for data */
list_for_each_entry(block, block_list, module_list) {
if (block->ops && block->ops->enable && !block->users) {
ret = block->ops->enable(block);
if (ret < 0) {
dev_err(dsp->dev,
"error: cant disable block %d:%d\n",
block->type, block->index);
goto err;
}
}
}
return ret;
err:
list_for_each_entry(block, block_list, module_list) {
if (block->ops && block->ops->disable)
block->ops->disable(block);
}
return ret;
}
static struct dw_dma_platform_data dw_pdata = {
.is_private = 1,
.chan_allocation_order = CHAN_ALLOCATION_ASCENDING,
.chan_priority = CHAN_PRIORITY_ASCENDING,
};
static struct dw_dma_chip *dw_probe(struct device *dev, struct resource *mem,
int irq)
{
struct dw_dma_chip *chip;
int err;
chip = devm_kzalloc(dev, sizeof(*chip), GFP_KERNEL);
if (!chip)
return ERR_PTR(-ENOMEM);
chip->irq = irq;
chip->regs = devm_ioremap_resource(dev, mem);
if (IS_ERR(chip->regs))
return ERR_CAST(chip->regs);
err = dma_coerce_mask_and_coherent(dev, DMA_BIT_MASK(31));
if (err)
return ERR_PTR(err);
chip->dev = dev;
err = dw_dma_probe(chip, &dw_pdata);
if (err)
return ERR_PTR(err);
return chip;
}
static void dw_remove(struct dw_dma_chip *chip)
{
dw_dma_remove(chip);
}
static bool dma_chan_filter(struct dma_chan *chan, void *param)
{
struct sst_dsp *dsp = (struct sst_dsp *)param;
return chan->device->dev == dsp->dma_dev;
}
int sst_dsp_dma_get_channel(struct sst_dsp *dsp, int chan_id)
{
struct sst_dma *dma = dsp->dma;
struct dma_slave_config slave;
dma_cap_mask_t mask;
int ret;
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
dma_cap_set(DMA_MEMCPY, mask);
dma->ch = dma_request_channel(mask, dma_chan_filter, dsp);
if (dma->ch == NULL) {
dev_err(dsp->dev, "error: DMA request channel failed\n");
return -EIO;
}
memset(&slave, 0, sizeof(slave));
slave.direction = DMA_MEM_TO_DEV;
slave.src_addr_width =
slave.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
slave.src_maxburst = slave.dst_maxburst = SST_DSP_DMA_MAX_BURST;
ret = dmaengine_slave_config(dma->ch, &slave);
if (ret) {
dev_err(dsp->dev, "error: unable to set DMA slave config %d\n",
ret);
dma_release_channel(dma->ch);
dma->ch = NULL;
}
return ret;
}
EXPORT_SYMBOL_GPL(sst_dsp_dma_get_channel);
void sst_dsp_dma_put_channel(struct sst_dsp *dsp)
{
struct sst_dma *dma = dsp->dma;
if (!dma->ch)
return;
dma_release_channel(dma->ch);
dma->ch = NULL;
}
EXPORT_SYMBOL_GPL(sst_dsp_dma_put_channel);
int sst_dma_new(struct sst_dsp *sst)
{
struct sst_pdata *sst_pdata = sst->pdata;
struct sst_dma *dma;
struct resource mem;
const char *dma_dev_name;
int ret = 0;
if (sst->pdata->resindex_dma_base == -1)
/* DMA is not used, return and squelsh error messages */
return 0;
/* configure the correct platform data for whatever DMA engine
* is attached to the ADSP IP. */
switch (sst->pdata->dma_engine) {
case SST_DMA_TYPE_DW:
dma_dev_name = "dw_dmac";
break;
default:
dev_err(sst->dev, "error: invalid DMA engine %d\n",
sst->pdata->dma_engine);
return -EINVAL;
}
dma = devm_kzalloc(sst->dev, sizeof(struct sst_dma), GFP_KERNEL);
if (!dma)
return -ENOMEM;
dma->sst = sst;
memset(&mem, 0, sizeof(mem));
mem.start = sst->addr.lpe_base + sst_pdata->dma_base;
mem.end = sst->addr.lpe_base + sst_pdata->dma_base + sst_pdata->dma_size - 1;
mem.flags = IORESOURCE_MEM;
/* now register DMA engine device */
dma->chip = dw_probe(sst->dma_dev, &mem, sst_pdata->irq);
if (IS_ERR(dma->chip)) {
dev_err(sst->dev, "error: DMA device register failed\n");
ret = PTR_ERR(dma->chip);
goto err_dma_dev;
}
sst->dma = dma;
sst->fw_use_dma = true;
return 0;
err_dma_dev:
devm_kfree(sst->dev, dma);
return ret;
}
EXPORT_SYMBOL(sst_dma_new);
void sst_dma_free(struct sst_dma *dma)
{
if (dma == NULL)
return;
if (dma->ch)
dma_release_channel(dma->ch);
if (dma->chip)
dw_remove(dma->chip);
}
EXPORT_SYMBOL(sst_dma_free);
/* create new generic firmware object */
struct sst_fw *sst_fw_new(struct sst_dsp *dsp,
const struct firmware *fw, void *private)
{
struct sst_fw *sst_fw;
int err;
if (!dsp->ops->parse_fw)
return NULL;
sst_fw = kzalloc(sizeof(*sst_fw), GFP_KERNEL);
if (sst_fw == NULL)
return NULL;
sst_fw->dsp = dsp;
sst_fw->private = private;
sst_fw->size = fw->size;
/* allocate DMA buffer to store FW data */
sst_fw->dma_buf = dma_alloc_coherent(dsp->dma_dev, sst_fw->size,
&sst_fw->dmable_fw_paddr, GFP_DMA | GFP_KERNEL);
if (!sst_fw->dma_buf) {
dev_err(dsp->dev, "error: DMA alloc failed\n");
kfree(sst_fw);
return NULL;
}
/* copy FW data to DMA-able memory */
memcpy((void *)sst_fw->dma_buf, (void *)fw->data, fw->size);
if (dsp->fw_use_dma) {
err = sst_dsp_dma_get_channel(dsp, 0);
if (err < 0)
goto chan_err;
}
/* call core specific FW paser to load FW data into DSP */
err = dsp->ops->parse_fw(sst_fw);
if (err < 0) {
dev_err(dsp->dev, "error: parse fw failed %d\n", err);
goto parse_err;
}
if (dsp->fw_use_dma)
sst_dsp_dma_put_channel(dsp);
mutex_lock(&dsp->mutex);
list_add(&sst_fw->list, &dsp->fw_list);
mutex_unlock(&dsp->mutex);
return sst_fw;
parse_err:
if (dsp->fw_use_dma)
sst_dsp_dma_put_channel(dsp);
chan_err:
dma_free_coherent(dsp->dma_dev, sst_fw->size,
sst_fw->dma_buf,
sst_fw->dmable_fw_paddr);
sst_fw->dma_buf = NULL;
kfree(sst_fw);
return NULL;
}
EXPORT_SYMBOL_GPL(sst_fw_new);
int sst_fw_reload(struct sst_fw *sst_fw)
{
struct sst_dsp *dsp = sst_fw->dsp;
int ret;
dev_dbg(dsp->dev, "reloading firmware\n");
/* call core specific FW paser to load FW data into DSP */
ret = dsp->ops->parse_fw(sst_fw);
if (ret < 0)
dev_err(dsp->dev, "error: parse fw failed %d\n", ret);
return ret;
}
EXPORT_SYMBOL_GPL(sst_fw_reload);
void sst_fw_unload(struct sst_fw *sst_fw)
{
struct sst_dsp *dsp = sst_fw->dsp;
struct sst_module *module, *mtmp;
struct sst_module_runtime *runtime, *rtmp;
dev_dbg(dsp->dev, "unloading firmware\n");
mutex_lock(&dsp->mutex);
/* check module by module */
list_for_each_entry_safe(module, mtmp, &dsp->module_list, list) {
if (module->sst_fw == sst_fw) {
/* remove runtime modules */
list_for_each_entry_safe(runtime, rtmp, &module->runtime_list, list) {
block_list_remove(dsp, &runtime->block_list);
list_del(&runtime->list);
kfree(runtime);
}
/* now remove the module */
block_list_remove(dsp, &module->block_list);
list_del(&module->list);
kfree(module);
}
}
/* remove all scratch blocks */
block_list_remove(dsp, &dsp->scratch_block_list);
mutex_unlock(&dsp->mutex);
}
EXPORT_SYMBOL_GPL(sst_fw_unload);
/* free single firmware object */
void sst_fw_free(struct sst_fw *sst_fw)
{
struct sst_dsp *dsp = sst_fw->dsp;
mutex_lock(&dsp->mutex);
list_del(&sst_fw->list);
mutex_unlock(&dsp->mutex);
if (sst_fw->dma_buf)
dma_free_coherent(dsp->dma_dev, sst_fw->size, sst_fw->dma_buf,
sst_fw->dmable_fw_paddr);
kfree(sst_fw);
}
EXPORT_SYMBOL_GPL(sst_fw_free);
/* free all firmware objects */
void sst_fw_free_all(struct sst_dsp *dsp)
{
struct sst_fw *sst_fw, *t;
mutex_lock(&dsp->mutex);
list_for_each_entry_safe(sst_fw, t, &dsp->fw_list, list) {
list_del(&sst_fw->list);
dma_free_coherent(dsp->dev, sst_fw->size, sst_fw->dma_buf,
sst_fw->dmable_fw_paddr);
kfree(sst_fw);
}
mutex_unlock(&dsp->mutex);
}
EXPORT_SYMBOL_GPL(sst_fw_free_all);
/* create a new SST generic module from FW template */
struct sst_module *sst_module_new(struct sst_fw *sst_fw,
struct sst_module_template *template, void *private)
{
struct sst_dsp *dsp = sst_fw->dsp;
struct sst_module *sst_module;
sst_module = kzalloc(sizeof(*sst_module), GFP_KERNEL);
if (sst_module == NULL)
return NULL;
sst_module->id = template->id;
sst_module->dsp = dsp;
sst_module->sst_fw = sst_fw;
sst_module->scratch_size = template->scratch_size;
sst_module->persistent_size = template->persistent_size;
sst_module->entry = template->entry;
sst_module->state = SST_MODULE_STATE_UNLOADED;
INIT_LIST_HEAD(&sst_module->block_list);
INIT_LIST_HEAD(&sst_module->runtime_list);
mutex_lock(&dsp->mutex);
list_add(&sst_module->list, &dsp->module_list);
mutex_unlock(&dsp->mutex);
return sst_module;
}
EXPORT_SYMBOL_GPL(sst_module_new);
/* free firmware module and remove from available list */
void sst_module_free(struct sst_module *sst_module)
{
struct sst_dsp *dsp = sst_module->dsp;
mutex_lock(&dsp->mutex);
list_del(&sst_module->list);
mutex_unlock(&dsp->mutex);
kfree(sst_module);
}
EXPORT_SYMBOL_GPL(sst_module_free);
struct sst_module_runtime *sst_module_runtime_new(struct sst_module *module,
int id, void *private)
{
struct sst_dsp *dsp = module->dsp;
struct sst_module_runtime *runtime;
runtime = kzalloc(sizeof(*runtime), GFP_KERNEL);
if (runtime == NULL)
return NULL;
runtime->id = id;
runtime->dsp = dsp;
runtime->module = module;
INIT_LIST_HEAD(&runtime->block_list);
mutex_lock(&dsp->mutex);
list_add(&runtime->list, &module->runtime_list);
mutex_unlock(&dsp->mutex);
return runtime;
}
EXPORT_SYMBOL_GPL(sst_module_runtime_new);
void sst_module_runtime_free(struct sst_module_runtime *runtime)
{
struct sst_dsp *dsp = runtime->dsp;
mutex_lock(&dsp->mutex);
list_del(&runtime->list);
mutex_unlock(&dsp->mutex);
kfree(runtime);
}
EXPORT_SYMBOL_GPL(sst_module_runtime_free);
static struct sst_mem_block *find_block(struct sst_dsp *dsp,
struct sst_block_allocator *ba)
{
struct sst_mem_block *block;
list_for_each_entry(block, &dsp->free_block_list, list) {
if (block->type == ba->type && block->offset == ba->offset)
return block;
}
return NULL;
}
/* Block allocator must be on block boundary */
static int block_alloc_contiguous(struct sst_dsp *dsp,
struct sst_block_allocator *ba, struct list_head *block_list)
{
struct list_head tmp = LIST_HEAD_INIT(tmp);
struct sst_mem_block *block;
u32 block_start = SST_HSW_BLOCK_ANY;
int size = ba->size, offset = ba->offset;
while (ba->size > 0) {
block = find_block(dsp, ba);
if (!block) {
list_splice(&tmp, &dsp->free_block_list);
ba->size = size;
ba->offset = offset;
return -ENOMEM;
}
list_move_tail(&block->list, &tmp);
ba->offset += block->size;
ba->size -= block->size;
}
ba->size = size;
ba->offset = offset;
list_for_each_entry(block, &tmp, list) {
if (block->offset < block_start)
block_start = block->offset;
list_add(&block->module_list, block_list);
dev_dbg(dsp->dev, "block allocated %d:%d at offset 0x%x\n",
block->type, block->index, block->offset);
}
list_splice(&tmp, &dsp->used_block_list);
return 0;
}
/* allocate first free DSP blocks for data - callers hold locks */
static int block_alloc(struct sst_dsp *dsp, struct sst_block_allocator *ba,
struct list_head *block_list)
{
struct sst_mem_block *block, *tmp;
int ret = 0;
if (ba->size == 0)
return 0;
/* find first free whole blocks that can hold module */
list_for_each_entry_safe(block, tmp, &dsp->free_block_list, list) {
/* ignore blocks with wrong type */
if (block->type != ba->type)
continue;
if (ba->size > block->size)
continue;
ba->offset = block->offset;
block->bytes_used = ba->size % block->size;
list_add(&block->module_list, block_list);
list_move(&block->list, &dsp->used_block_list);
dev_dbg(dsp->dev, "block allocated %d:%d at offset 0x%x\n",
block->type, block->index, block->offset);
return 0;
}
/* then find free multiple blocks that can hold module */
list_for_each_entry_safe(block, tmp, &dsp->free_block_list, list) {
/* ignore blocks with wrong type */
if (block->type != ba->type)
continue;
/* do we span > 1 blocks */
if (ba->size > block->size) {
/* align ba to block boundary */
ba->offset = block->offset;
ret = block_alloc_contiguous(dsp, ba, block_list);
if (ret == 0)
return ret;
}
}
/* not enough free block space */
return -ENOMEM;
}
int sst_alloc_blocks(struct sst_dsp *dsp, struct sst_block_allocator *ba,
struct list_head *block_list)
{
int ret;
dev_dbg(dsp->dev, "block request 0x%x bytes at offset 0x%x type %d\n",
ba->size, ba->offset, ba->type);
mutex_lock(&dsp->mutex);
ret = block_alloc(dsp, ba, block_list);
if (ret < 0) {
dev_err(dsp->dev, "error: can't alloc blocks %d\n", ret);
goto out;
}
/* prepare DSP blocks for module usage */
ret = block_list_prepare(dsp, block_list);
if (ret < 0)
dev_err(dsp->dev, "error: prepare failed\n");
out:
mutex_unlock(&dsp->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(sst_alloc_blocks);
int sst_free_blocks(struct sst_dsp *dsp, struct list_head *block_list)
{
mutex_lock(&dsp->mutex);
block_list_remove(dsp, block_list);
mutex_unlock(&dsp->mutex);
return 0;
}
EXPORT_SYMBOL_GPL(sst_free_blocks);
/* allocate memory blocks for static module addresses - callers hold locks */
static int block_alloc_fixed(struct sst_dsp *dsp, struct sst_block_allocator *ba,
struct list_head *block_list)
{
struct sst_mem_block *block, *tmp;
struct sst_block_allocator ba_tmp = *ba;
u32 end = ba->offset + ba->size, block_end;
int err;
/* only IRAM/DRAM blocks are managed */
if (ba->type != SST_MEM_IRAM && ba->type != SST_MEM_DRAM)
return 0;
/* are blocks already attached to this module */
list_for_each_entry_safe(block, tmp, block_list, module_list) {
/* ignore blocks with wrong type */
if (block->type != ba->type)
continue;
block_end = block->offset + block->size;
/* find block that holds section */
if (ba->offset >= block->offset && end <= block_end)
return 0;
/* does block span more than 1 section */
if (ba->offset >= block->offset && ba->offset < block_end) {
/* align ba to block boundary */
ba_tmp.size -= block_end - ba->offset;
ba_tmp.offset = block_end;
err = block_alloc_contiguous(dsp, &ba_tmp, block_list);
if (err < 0)
return -ENOMEM;
/* module already owns blocks */
return 0;
}
}
/* find first free blocks that can hold section in free list */
list_for_each_entry_safe(block, tmp, &dsp->free_block_list, list) {
block_end = block->offset + block->size;
/* ignore blocks with wrong type */
if (block->type != ba->type)
continue;
/* find block that holds section */
if (ba->offset >= block->offset && end <= block_end) {
/* add block */
list_move(&block->list, &dsp->used_block_list);
list_add(&block->module_list, block_list);
dev_dbg(dsp->dev, "block allocated %d:%d at offset 0x%x\n",
block->type, block->index, block->offset);
return 0;
}
/* does block span more than 1 section */
if (ba->offset >= block->offset && ba->offset < block_end) {
/* add block */
list_move(&block->list, &dsp->used_block_list);
list_add(&block->module_list, block_list);
/* align ba to block boundary */
ba_tmp.size -= block_end - ba->offset;
ba_tmp.offset = block_end;
err = block_alloc_contiguous(dsp, &ba_tmp, block_list);
if (err < 0)
return -ENOMEM;
return 0;
}
}
return -ENOMEM;
}
/* Load fixed module data into DSP memory blocks */
int sst_module_alloc_blocks(struct sst_module *module)
{
struct sst_dsp *dsp = module->dsp;
struct sst_fw *sst_fw = module->sst_fw;
struct sst_block_allocator ba;
int ret;
memset(&ba, 0, sizeof(ba));
ba.size = module->size;
ba.type = module->type;
ba.offset = module->offset;
dev_dbg(dsp->dev, "block request 0x%x bytes at offset 0x%x type %d\n",
ba.size, ba.offset, ba.type);
mutex_lock(&dsp->mutex);
/* alloc blocks that includes this section */
ret = block_alloc_fixed(dsp, &ba, &module->block_list);
if (ret < 0) {
dev_err(dsp->dev,
"error: no free blocks for section at offset 0x%x size 0x%x\n",
module->offset, module->size);
mutex_unlock(&dsp->mutex);
return -ENOMEM;
}
/* prepare DSP blocks for module copy */
ret = block_list_prepare(dsp, &module->block_list);
if (ret < 0) {
dev_err(dsp->dev, "error: fw module prepare failed\n");
goto err;
}
/* copy partial module data to blocks */
if (dsp->fw_use_dma) {
ret = sst_dsp_dma_copyto(dsp,
dsp->addr.lpe_base + module->offset,
sst_fw->dmable_fw_paddr + module->data_offset,
module->size);
if (ret < 0) {
dev_err(dsp->dev, "error: module copy failed\n");
goto err;
}
} else
sst_memcpy32(dsp->addr.lpe + module->offset, module->data,
module->size);
mutex_unlock(&dsp->mutex);
return ret;
err:
block_list_remove(dsp, &module->block_list);
mutex_unlock(&dsp->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(sst_module_alloc_blocks);
/* Unload entire module from DSP memory */
int sst_module_free_blocks(struct sst_module *module)
{
struct sst_dsp *dsp = module->dsp;
mutex_lock(&dsp->mutex);
block_list_remove(dsp, &module->block_list);
mutex_unlock(&dsp->mutex);
return 0;
}
EXPORT_SYMBOL_GPL(sst_module_free_blocks);
int sst_module_runtime_alloc_blocks(struct sst_module_runtime *runtime,
int offset)
{
struct sst_dsp *dsp = runtime->dsp;
struct sst_module *module = runtime->module;
struct sst_block_allocator ba;
int ret;
if (module->persistent_size == 0)
return 0;
memset(&ba, 0, sizeof(ba));
ba.size = module->persistent_size;
ba.type = SST_MEM_DRAM;
mutex_lock(&dsp->mutex);
/* do we need to allocate at a fixed address ? */
if (offset != 0) {
ba.offset = offset;
dev_dbg(dsp->dev, "persistent fixed block request 0x%x bytes type %d offset 0x%x\n",
ba.size, ba.type, ba.offset);
/* alloc blocks that includes this section */
ret = block_alloc_fixed(dsp, &ba, &runtime->block_list);
} else {
dev_dbg(dsp->dev, "persistent block request 0x%x bytes type %d\n",
ba.size, ba.type);
/* alloc blocks that includes this section */
ret = block_alloc(dsp, &ba, &runtime->block_list);
}
if (ret < 0) {
dev_err(dsp->dev,
"error: no free blocks for runtime module size 0x%x\n",
module->persistent_size);
mutex_unlock(&dsp->mutex);
return -ENOMEM;
}
runtime->persistent_offset = ba.offset;
/* prepare DSP blocks for module copy */
ret = block_list_prepare(dsp, &runtime->block_list);
if (ret < 0) {
dev_err(dsp->dev, "error: runtime block prepare failed\n");
goto err;
}
mutex_unlock(&dsp->mutex);
return ret;
err:
block_list_remove(dsp, &module->block_list);
mutex_unlock(&dsp->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(sst_module_runtime_alloc_blocks);
int sst_module_runtime_free_blocks(struct sst_module_runtime *runtime)
{
struct sst_dsp *dsp = runtime->dsp;
mutex_lock(&dsp->mutex);
block_list_remove(dsp, &runtime->block_list);
mutex_unlock(&dsp->mutex);
return 0;
}
EXPORT_SYMBOL_GPL(sst_module_runtime_free_blocks);
int sst_module_runtime_save(struct sst_module_runtime *runtime,
struct sst_module_runtime_context *context)
{
struct sst_dsp *dsp = runtime->dsp;
struct sst_module *module = runtime->module;
int ret = 0;
dev_dbg(dsp->dev, "saving runtime %d memory at 0x%x size 0x%x\n",
runtime->id, runtime->persistent_offset,
module->persistent_size);
context->buffer = dma_alloc_coherent(dsp->dma_dev,
module->persistent_size,
&context->dma_buffer, GFP_DMA | GFP_KERNEL);
if (!context->buffer) {
dev_err(dsp->dev, "error: DMA context alloc failed\n");
return -ENOMEM;
}
mutex_lock(&dsp->mutex);
if (dsp->fw_use_dma) {
ret = sst_dsp_dma_get_channel(dsp, 0);
if (ret < 0)
goto err;
ret = sst_dsp_dma_copyfrom(dsp, context->dma_buffer,
dsp->addr.lpe_base + runtime->persistent_offset,
module->persistent_size);
sst_dsp_dma_put_channel(dsp);
if (ret < 0) {
dev_err(dsp->dev, "error: context copy failed\n");
goto err;
}
} else
sst_memcpy32(context->buffer, dsp->addr.lpe +
runtime->persistent_offset,
module->persistent_size);
err:
mutex_unlock(&dsp->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(sst_module_runtime_save);
int sst_module_runtime_restore(struct sst_module_runtime *runtime,
struct sst_module_runtime_context *context)
{
struct sst_dsp *dsp = runtime->dsp;
struct sst_module *module = runtime->module;
int ret = 0;
dev_dbg(dsp->dev, "restoring runtime %d memory at 0x%x size 0x%x\n",
runtime->id, runtime->persistent_offset,
module->persistent_size);
mutex_lock(&dsp->mutex);
if (!context->buffer) {
dev_info(dsp->dev, "no context buffer need to restore!\n");
goto err;
}
if (dsp->fw_use_dma) {
ret = sst_dsp_dma_get_channel(dsp, 0);
if (ret < 0)
goto err;
ret = sst_dsp_dma_copyto(dsp,
dsp->addr.lpe_base + runtime->persistent_offset,
context->dma_buffer, module->persistent_size);
sst_dsp_dma_put_channel(dsp);
if (ret < 0) {
dev_err(dsp->dev, "error: module copy failed\n");
goto err;
}
} else
sst_memcpy32(dsp->addr.lpe + runtime->persistent_offset,
context->buffer, module->persistent_size);
dma_free_coherent(dsp->dma_dev, module->persistent_size,
context->buffer, context->dma_buffer);
context->buffer = NULL;
err:
mutex_unlock(&dsp->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(sst_module_runtime_restore);
/* register a DSP memory block for use with FW based modules */
struct sst_mem_block *sst_mem_block_register(struct sst_dsp *dsp, u32 offset,
u32 size, enum sst_mem_type type, struct sst_block_ops *ops, u32 index,
void *private)
{
struct sst_mem_block *block;
block = kzalloc(sizeof(*block), GFP_KERNEL);
if (block == NULL)
return NULL;
block->offset = offset;
block->size = size;
block->index = index;
block->type = type;
block->dsp = dsp;
block->private = private;
block->ops = ops;
mutex_lock(&dsp->mutex);
list_add(&block->list, &dsp->free_block_list);
mutex_unlock(&dsp->mutex);
return block;
}
EXPORT_SYMBOL_GPL(sst_mem_block_register);
/* unregister all DSP memory blocks */
void sst_mem_block_unregister_all(struct sst_dsp *dsp)
{
struct sst_mem_block *block, *tmp;
mutex_lock(&dsp->mutex);
/* unregister used blocks */
list_for_each_entry_safe(block, tmp, &dsp->used_block_list, list) {
list_del(&block->list);
kfree(block);
}
/* unregister free blocks */
list_for_each_entry_safe(block, tmp, &dsp->free_block_list, list) {
list_del(&block->list);
kfree(block);
}
mutex_unlock(&dsp->mutex);
}
EXPORT_SYMBOL_GPL(sst_mem_block_unregister_all);
/* allocate scratch buffer blocks */
int sst_block_alloc_scratch(struct sst_dsp *dsp)
{
struct sst_module *module;
struct sst_block_allocator ba;
int ret;
mutex_lock(&dsp->mutex);
/* calculate required scratch size */
dsp->scratch_size = 0;
list_for_each_entry(module, &dsp->module_list, list) {
dev_dbg(dsp->dev, "module %d scratch req 0x%x bytes\n",
module->id, module->scratch_size);
if (dsp->scratch_size < module->scratch_size)
dsp->scratch_size = module->scratch_size;
}
dev_dbg(dsp->dev, "scratch buffer required is 0x%x bytes\n",
dsp->scratch_size);
if (dsp->scratch_size == 0) {
dev_info(dsp->dev, "no modules need scratch buffer\n");
mutex_unlock(&dsp->mutex);
return 0;
}
/* allocate blocks for module scratch buffers */
dev_dbg(dsp->dev, "allocating scratch blocks\n");
ba.size = dsp->scratch_size;
ba.type = SST_MEM_DRAM;
/* do we need to allocate at fixed offset */
if (dsp->scratch_offset != 0) {
dev_dbg(dsp->dev, "block request 0x%x bytes type %d at 0x%x\n",
ba.size, ba.type, ba.offset);
ba.offset = dsp->scratch_offset;
/* alloc blocks that includes this section */
ret = block_alloc_fixed(dsp, &ba, &dsp->scratch_block_list);
} else {
dev_dbg(dsp->dev, "block request 0x%x bytes type %d\n",
ba.size, ba.type);
ba.offset = 0;
ret = block_alloc(dsp, &ba, &dsp->scratch_block_list);
}
if (ret < 0) {
dev_err(dsp->dev, "error: can't alloc scratch blocks\n");
mutex_unlock(&dsp->mutex);
return ret;
}
ret = block_list_prepare(dsp, &dsp->scratch_block_list);
if (ret < 0) {
dev_err(dsp->dev, "error: scratch block prepare failed\n");
mutex_unlock(&dsp->mutex);
return ret;
}
/* assign the same offset of scratch to each module */
dsp->scratch_offset = ba.offset;
mutex_unlock(&dsp->mutex);
return dsp->scratch_size;
}
EXPORT_SYMBOL_GPL(sst_block_alloc_scratch);
/* free all scratch blocks */
void sst_block_free_scratch(struct sst_dsp *dsp)
{
mutex_lock(&dsp->mutex);
block_list_remove(dsp, &dsp->scratch_block_list);
mutex_unlock(&dsp->mutex);
}
EXPORT_SYMBOL_GPL(sst_block_free_scratch);
/* get a module from it's unique ID */
struct sst_module *sst_module_get_from_id(struct sst_dsp *dsp, u32 id)
{
struct sst_module *module;
mutex_lock(&dsp->mutex);
list_for_each_entry(module, &dsp->module_list, list) {
if (module->id == id) {
mutex_unlock(&dsp->mutex);
return module;
}
}
mutex_unlock(&dsp->mutex);
return NULL;
}
EXPORT_SYMBOL_GPL(sst_module_get_from_id);
struct sst_module_runtime *sst_module_runtime_get_from_id(
struct sst_module *module, u32 id)
{
struct sst_module_runtime *runtime;
struct sst_dsp *dsp = module->dsp;
mutex_lock(&dsp->mutex);
list_for_each_entry(runtime, &module->runtime_list, list) {
if (runtime->id == id) {
mutex_unlock(&dsp->mutex);
return runtime;
}
}
mutex_unlock(&dsp->mutex);
return NULL;
}
EXPORT_SYMBOL_GPL(sst_module_runtime_get_from_id);
/* returns block address in DSP address space */
u32 sst_dsp_get_offset(struct sst_dsp *dsp, u32 offset,
enum sst_mem_type type)
{
switch (type) {
case SST_MEM_IRAM:
return offset - dsp->addr.iram_offset +
dsp->addr.dsp_iram_offset;
case SST_MEM_DRAM:
return offset - dsp->addr.dram_offset +
dsp->addr.dsp_dram_offset;
default:
return 0;
}
}
EXPORT_SYMBOL_GPL(sst_dsp_get_offset);
| gpl-2.0 |
NEKTech-Labs/wrapfs-kernel-linux-3.17 | drivers/infiniband/hw/nes/nes_hw.c | 871 | 131973 | /*
* Copyright (c) 2006 - 2011 Intel Corporation. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/if_vlan.h>
#include <linux/inet_lro.h>
#include <linux/slab.h>
#include "nes.h"
static unsigned int nes_lro_max_aggr = NES_LRO_MAX_AGGR;
module_param(nes_lro_max_aggr, uint, 0444);
MODULE_PARM_DESC(nes_lro_max_aggr, "NIC LRO max packet aggregation");
static int wide_ppm_offset;
module_param(wide_ppm_offset, int, 0644);
MODULE_PARM_DESC(wide_ppm_offset, "Increase CX4 interface clock ppm offset, 0=100ppm (default), 1=300ppm");
static u32 crit_err_count;
u32 int_mod_timer_init;
u32 int_mod_cq_depth_256;
u32 int_mod_cq_depth_128;
u32 int_mod_cq_depth_32;
u32 int_mod_cq_depth_24;
u32 int_mod_cq_depth_16;
u32 int_mod_cq_depth_4;
u32 int_mod_cq_depth_1;
static const u8 nes_max_critical_error_count = 100;
#include "nes_cm.h"
static void nes_cqp_ce_handler(struct nes_device *nesdev, struct nes_hw_cq *cq);
static void nes_init_csr_ne020(struct nes_device *nesdev, u8 hw_rev, u8 port_count);
static int nes_init_serdes(struct nes_device *nesdev, u8 hw_rev, u8 port_count,
struct nes_adapter *nesadapter, u8 OneG_Mode);
static void nes_nic_napi_ce_handler(struct nes_device *nesdev, struct nes_hw_nic_cq *cq);
static void nes_process_aeq(struct nes_device *nesdev, struct nes_hw_aeq *aeq);
static void nes_process_ceq(struct nes_device *nesdev, struct nes_hw_ceq *ceq);
static void nes_process_iwarp_aeqe(struct nes_device *nesdev,
struct nes_hw_aeqe *aeqe);
static void process_critical_error(struct nes_device *nesdev);
static void nes_process_mac_intr(struct nes_device *nesdev, u32 mac_number);
static unsigned int nes_reset_adapter_ne020(struct nes_device *nesdev, u8 *OneG_Mode);
static void nes_terminate_start_timer(struct nes_qp *nesqp);
#ifdef CONFIG_INFINIBAND_NES_DEBUG
static unsigned char *nes_iwarp_state_str[] = {
"Non-Existent",
"Idle",
"RTS",
"Closing",
"RSVD1",
"Terminate",
"Error",
"RSVD2",
};
static unsigned char *nes_tcp_state_str[] = {
"Non-Existent",
"Closed",
"Listen",
"SYN Sent",
"SYN Rcvd",
"Established",
"Close Wait",
"FIN Wait 1",
"Closing",
"Last Ack",
"FIN Wait 2",
"Time Wait",
"RSVD1",
"RSVD2",
"RSVD3",
"RSVD4",
};
#endif
static inline void print_ip(struct nes_cm_node *cm_node)
{
unsigned char *rem_addr;
if (cm_node) {
rem_addr = (unsigned char *)&cm_node->rem_addr;
printk(KERN_ERR PFX "Remote IP addr: %pI4\n", rem_addr);
}
}
/**
* nes_nic_init_timer_defaults
*/
void nes_nic_init_timer_defaults(struct nes_device *nesdev, u8 jumbomode)
{
unsigned long flags;
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_hw_tune_timer *shared_timer = &nesadapter->tune_timer;
spin_lock_irqsave(&nesadapter->periodic_timer_lock, flags);
shared_timer->timer_in_use_min = NES_NIC_FAST_TIMER_LOW;
shared_timer->timer_in_use_max = NES_NIC_FAST_TIMER_HIGH;
if (jumbomode) {
shared_timer->threshold_low = DEFAULT_JUMBO_NES_QL_LOW;
shared_timer->threshold_target = DEFAULT_JUMBO_NES_QL_TARGET;
shared_timer->threshold_high = DEFAULT_JUMBO_NES_QL_HIGH;
} else {
shared_timer->threshold_low = DEFAULT_NES_QL_LOW;
shared_timer->threshold_target = DEFAULT_NES_QL_TARGET;
shared_timer->threshold_high = DEFAULT_NES_QL_HIGH;
}
/* todo use netdev->mtu to set thresholds */
spin_unlock_irqrestore(&nesadapter->periodic_timer_lock, flags);
}
/**
* nes_nic_init_timer
*/
static void nes_nic_init_timer(struct nes_device *nesdev)
{
unsigned long flags;
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_hw_tune_timer *shared_timer = &nesadapter->tune_timer;
spin_lock_irqsave(&nesadapter->periodic_timer_lock, flags);
if (shared_timer->timer_in_use_old == 0) {
nesdev->deepcq_count = 0;
shared_timer->timer_direction_upward = 0;
shared_timer->timer_direction_downward = 0;
shared_timer->timer_in_use = NES_NIC_FAST_TIMER;
shared_timer->timer_in_use_old = 0;
}
if (shared_timer->timer_in_use != shared_timer->timer_in_use_old) {
shared_timer->timer_in_use_old = shared_timer->timer_in_use;
nes_write32(nesdev->regs+NES_PERIODIC_CONTROL,
0x80000000 | ((u32)(shared_timer->timer_in_use*8)));
}
/* todo use netdev->mtu to set thresholds */
spin_unlock_irqrestore(&nesadapter->periodic_timer_lock, flags);
}
/**
* nes_nic_tune_timer
*/
static void nes_nic_tune_timer(struct nes_device *nesdev)
{
unsigned long flags;
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_hw_tune_timer *shared_timer = &nesadapter->tune_timer;
u16 cq_count = nesdev->currcq_count;
spin_lock_irqsave(&nesadapter->periodic_timer_lock, flags);
if (shared_timer->cq_count_old <= cq_count)
shared_timer->cq_direction_downward = 0;
else
shared_timer->cq_direction_downward++;
shared_timer->cq_count_old = cq_count;
if (shared_timer->cq_direction_downward > NES_NIC_CQ_DOWNWARD_TREND) {
if (cq_count <= shared_timer->threshold_low &&
shared_timer->threshold_low > 4) {
shared_timer->threshold_low = shared_timer->threshold_low/2;
shared_timer->cq_direction_downward=0;
nesdev->currcq_count = 0;
spin_unlock_irqrestore(&nesadapter->periodic_timer_lock, flags);
return;
}
}
if (cq_count > 1) {
nesdev->deepcq_count += cq_count;
if (cq_count <= shared_timer->threshold_low) { /* increase timer gently */
shared_timer->timer_direction_upward++;
shared_timer->timer_direction_downward = 0;
} else if (cq_count <= shared_timer->threshold_target) { /* balanced */
shared_timer->timer_direction_upward = 0;
shared_timer->timer_direction_downward = 0;
} else if (cq_count <= shared_timer->threshold_high) { /* decrease timer gently */
shared_timer->timer_direction_downward++;
shared_timer->timer_direction_upward = 0;
} else if (cq_count <= (shared_timer->threshold_high) * 2) {
shared_timer->timer_in_use -= 2;
shared_timer->timer_direction_upward = 0;
shared_timer->timer_direction_downward++;
} else {
shared_timer->timer_in_use -= 4;
shared_timer->timer_direction_upward = 0;
shared_timer->timer_direction_downward++;
}
if (shared_timer->timer_direction_upward > 3 ) { /* using history */
shared_timer->timer_in_use += 3;
shared_timer->timer_direction_upward = 0;
shared_timer->timer_direction_downward = 0;
}
if (shared_timer->timer_direction_downward > 5) { /* using history */
shared_timer->timer_in_use -= 4 ;
shared_timer->timer_direction_downward = 0;
shared_timer->timer_direction_upward = 0;
}
}
/* boundary checking */
if (shared_timer->timer_in_use > shared_timer->threshold_high)
shared_timer->timer_in_use = shared_timer->threshold_high;
else if (shared_timer->timer_in_use < shared_timer->threshold_low)
shared_timer->timer_in_use = shared_timer->threshold_low;
nesdev->currcq_count = 0;
spin_unlock_irqrestore(&nesadapter->periodic_timer_lock, flags);
}
/**
* nes_init_adapter - initialize adapter
*/
struct nes_adapter *nes_init_adapter(struct nes_device *nesdev, u8 hw_rev) {
struct nes_adapter *nesadapter = NULL;
unsigned long num_pds;
u32 u32temp;
u32 port_count;
u16 max_rq_wrs;
u16 max_sq_wrs;
u32 max_mr;
u32 max_256pbl;
u32 max_4kpbl;
u32 max_qp;
u32 max_irrq;
u32 max_cq;
u32 hte_index_mask;
u32 adapter_size;
u32 arp_table_size;
u16 vendor_id;
u16 device_id;
u8 OneG_Mode;
u8 func_index;
/* search the list of existing adapters */
list_for_each_entry(nesadapter, &nes_adapter_list, list) {
nes_debug(NES_DBG_INIT, "Searching Adapter list for PCI devfn = 0x%X,"
" adapter PCI slot/bus = %u/%u, pci devices PCI slot/bus = %u/%u, .\n",
nesdev->pcidev->devfn,
PCI_SLOT(nesadapter->devfn),
nesadapter->bus_number,
PCI_SLOT(nesdev->pcidev->devfn),
nesdev->pcidev->bus->number );
if ((PCI_SLOT(nesadapter->devfn) == PCI_SLOT(nesdev->pcidev->devfn)) &&
(nesadapter->bus_number == nesdev->pcidev->bus->number)) {
nesadapter->ref_count++;
return nesadapter;
}
}
/* no adapter found */
num_pds = pci_resource_len(nesdev->pcidev, BAR_1) >> PAGE_SHIFT;
if ((hw_rev != NE020_REV) && (hw_rev != NE020_REV1)) {
nes_debug(NES_DBG_INIT, "NE020 driver detected unknown hardware revision 0x%x\n",
hw_rev);
return NULL;
}
nes_debug(NES_DBG_INIT, "Determine Soft Reset, QP_control=0x%x, CPU0=0x%x, CPU1=0x%x, CPU2=0x%x\n",
nes_read_indexed(nesdev, NES_IDX_QP_CONTROL + PCI_FUNC(nesdev->pcidev->devfn) * 8),
nes_read_indexed(nesdev, NES_IDX_INT_CPU_STATUS),
nes_read_indexed(nesdev, NES_IDX_INT_CPU_STATUS + 4),
nes_read_indexed(nesdev, NES_IDX_INT_CPU_STATUS + 8));
nes_debug(NES_DBG_INIT, "Reset and init NE020\n");
if ((port_count = nes_reset_adapter_ne020(nesdev, &OneG_Mode)) == 0)
return NULL;
max_qp = nes_read_indexed(nesdev, NES_IDX_QP_CTX_SIZE);
nes_debug(NES_DBG_INIT, "QP_CTX_SIZE=%u\n", max_qp);
u32temp = nes_read_indexed(nesdev, NES_IDX_QUAD_HASH_TABLE_SIZE);
if (max_qp > ((u32)1 << (u32temp & 0x001f))) {
nes_debug(NES_DBG_INIT, "Reducing Max QPs to %u due to hash table size = 0x%08X\n",
max_qp, u32temp);
max_qp = (u32)1 << (u32temp & 0x001f);
}
hte_index_mask = ((u32)1 << ((u32temp & 0x001f)+1))-1;
nes_debug(NES_DBG_INIT, "Max QP = %u, hte_index_mask = 0x%08X.\n",
max_qp, hte_index_mask);
u32temp = nes_read_indexed(nesdev, NES_IDX_IRRQ_COUNT);
max_irrq = 1 << (u32temp & 0x001f);
if (max_qp > max_irrq) {
max_qp = max_irrq;
nes_debug(NES_DBG_INIT, "Reducing Max QPs to %u due to Available Q1s.\n",
max_qp);
}
/* there should be no reason to allocate more pds than qps */
if (num_pds > max_qp)
num_pds = max_qp;
u32temp = nes_read_indexed(nesdev, NES_IDX_MRT_SIZE);
max_mr = (u32)8192 << (u32temp & 0x7);
u32temp = nes_read_indexed(nesdev, NES_IDX_PBL_REGION_SIZE);
max_256pbl = (u32)1 << (u32temp & 0x0000001f);
max_4kpbl = (u32)1 << ((u32temp >> 16) & 0x0000001f);
max_cq = nes_read_indexed(nesdev, NES_IDX_CQ_CTX_SIZE);
u32temp = nes_read_indexed(nesdev, NES_IDX_ARP_CACHE_SIZE);
arp_table_size = 1 << u32temp;
adapter_size = (sizeof(struct nes_adapter) +
(sizeof(unsigned long)-1)) & (~(sizeof(unsigned long)-1));
adapter_size += sizeof(unsigned long) * BITS_TO_LONGS(max_qp);
adapter_size += sizeof(unsigned long) * BITS_TO_LONGS(max_mr);
adapter_size += sizeof(unsigned long) * BITS_TO_LONGS(max_cq);
adapter_size += sizeof(unsigned long) * BITS_TO_LONGS(num_pds);
adapter_size += sizeof(unsigned long) * BITS_TO_LONGS(arp_table_size);
adapter_size += sizeof(struct nes_qp **) * max_qp;
/* allocate a new adapter struct */
nesadapter = kzalloc(adapter_size, GFP_KERNEL);
if (nesadapter == NULL) {
return NULL;
}
nes_debug(NES_DBG_INIT, "Allocating new nesadapter @ %p, size = %u (actual size = %u).\n",
nesadapter, (u32)sizeof(struct nes_adapter), adapter_size);
if (nes_read_eeprom_values(nesdev, nesadapter)) {
printk(KERN_ERR PFX "Unable to read EEPROM data.\n");
kfree(nesadapter);
return NULL;
}
nesadapter->vendor_id = (((u32) nesadapter->mac_addr_high) << 8) |
(nesadapter->mac_addr_low >> 24);
pci_bus_read_config_word(nesdev->pcidev->bus, nesdev->pcidev->devfn,
PCI_DEVICE_ID, &device_id);
nesadapter->vendor_part_id = device_id;
if (nes_init_serdes(nesdev, hw_rev, port_count, nesadapter,
OneG_Mode)) {
kfree(nesadapter);
return NULL;
}
nes_init_csr_ne020(nesdev, hw_rev, port_count);
memset(nesadapter->pft_mcast_map, 255,
sizeof nesadapter->pft_mcast_map);
/* populate the new nesadapter */
nesadapter->devfn = nesdev->pcidev->devfn;
nesadapter->bus_number = nesdev->pcidev->bus->number;
nesadapter->ref_count = 1;
nesadapter->timer_int_req = 0xffff0000;
nesadapter->OneG_Mode = OneG_Mode;
nesadapter->doorbell_start = nesdev->doorbell_region;
/* nesadapter->tick_delta = clk_divisor; */
nesadapter->hw_rev = hw_rev;
nesadapter->port_count = port_count;
nesadapter->max_qp = max_qp;
nesadapter->hte_index_mask = hte_index_mask;
nesadapter->max_irrq = max_irrq;
nesadapter->max_mr = max_mr;
nesadapter->max_256pbl = max_256pbl - 1;
nesadapter->max_4kpbl = max_4kpbl - 1;
nesadapter->max_cq = max_cq;
nesadapter->free_256pbl = max_256pbl - 1;
nesadapter->free_4kpbl = max_4kpbl - 1;
nesadapter->max_pd = num_pds;
nesadapter->arp_table_size = arp_table_size;
nesadapter->et_pkt_rate_low = NES_TIMER_ENABLE_LIMIT;
if (nes_drv_opt & NES_DRV_OPT_DISABLE_INT_MOD) {
nesadapter->et_use_adaptive_rx_coalesce = 0;
nesadapter->timer_int_limit = NES_TIMER_INT_LIMIT;
nesadapter->et_rx_coalesce_usecs_irq = interrupt_mod_interval;
} else {
nesadapter->et_use_adaptive_rx_coalesce = 1;
nesadapter->timer_int_limit = NES_TIMER_INT_LIMIT_DYNAMIC;
nesadapter->et_rx_coalesce_usecs_irq = 0;
printk(PFX "%s: Using Adaptive Interrupt Moderation\n", __func__);
}
/* Setup and enable the periodic timer */
if (nesadapter->et_rx_coalesce_usecs_irq)
nes_write32(nesdev->regs+NES_PERIODIC_CONTROL, 0x80000000 |
((u32)(nesadapter->et_rx_coalesce_usecs_irq * 8)));
else
nes_write32(nesdev->regs+NES_PERIODIC_CONTROL, 0x00000000);
nesadapter->base_pd = 1;
nesadapter->device_cap_flags = IB_DEVICE_LOCAL_DMA_LKEY |
IB_DEVICE_MEM_WINDOW |
IB_DEVICE_MEM_MGT_EXTENSIONS;
nesadapter->allocated_qps = (unsigned long *)&(((unsigned char *)nesadapter)
[(sizeof(struct nes_adapter)+(sizeof(unsigned long)-1))&(~(sizeof(unsigned long)-1))]);
nesadapter->allocated_cqs = &nesadapter->allocated_qps[BITS_TO_LONGS(max_qp)];
nesadapter->allocated_mrs = &nesadapter->allocated_cqs[BITS_TO_LONGS(max_cq)];
nesadapter->allocated_pds = &nesadapter->allocated_mrs[BITS_TO_LONGS(max_mr)];
nesadapter->allocated_arps = &nesadapter->allocated_pds[BITS_TO_LONGS(num_pds)];
nesadapter->qp_table = (struct nes_qp **)(&nesadapter->allocated_arps[BITS_TO_LONGS(arp_table_size)]);
/* mark the usual suspect QPs, MR and CQs as in use */
for (u32temp = 0; u32temp < NES_FIRST_QPN; u32temp++) {
set_bit(u32temp, nesadapter->allocated_qps);
set_bit(u32temp, nesadapter->allocated_cqs);
}
set_bit(0, nesadapter->allocated_mrs);
for (u32temp = 0; u32temp < 20; u32temp++)
set_bit(u32temp, nesadapter->allocated_pds);
u32temp = nes_read_indexed(nesdev, NES_IDX_QP_MAX_CFG_SIZES);
max_rq_wrs = ((u32temp >> 8) & 3);
switch (max_rq_wrs) {
case 0:
max_rq_wrs = 4;
break;
case 1:
max_rq_wrs = 16;
break;
case 2:
max_rq_wrs = 32;
break;
case 3:
max_rq_wrs = 512;
break;
}
max_sq_wrs = (u32temp & 3);
switch (max_sq_wrs) {
case 0:
max_sq_wrs = 4;
break;
case 1:
max_sq_wrs = 16;
break;
case 2:
max_sq_wrs = 32;
break;
case 3:
max_sq_wrs = 512;
break;
}
nesadapter->max_qp_wr = min(max_rq_wrs, max_sq_wrs);
nesadapter->max_irrq_wr = (u32temp >> 16) & 3;
nesadapter->max_sge = 4;
nesadapter->max_cqe = 32766;
if (nes_read_eeprom_values(nesdev, nesadapter)) {
printk(KERN_ERR PFX "Unable to read EEPROM data.\n");
kfree(nesadapter);
return NULL;
}
u32temp = nes_read_indexed(nesdev, NES_IDX_TCP_TIMER_CONFIG);
nes_write_indexed(nesdev, NES_IDX_TCP_TIMER_CONFIG,
(u32temp & 0xff000000) | (nesadapter->tcp_timer_core_clk_divisor & 0x00ffffff));
/* setup port configuration */
if (nesadapter->port_count == 1) {
nesadapter->log_port = 0x00000000;
if (nes_drv_opt & NES_DRV_OPT_DUAL_LOGICAL_PORT)
nes_write_indexed(nesdev, NES_IDX_TX_POOL_SIZE, 0x00000002);
else
nes_write_indexed(nesdev, NES_IDX_TX_POOL_SIZE, 0x00000003);
} else {
if (nesadapter->phy_type[0] == NES_PHY_TYPE_PUMA_1G) {
nesadapter->log_port = 0x000000D8;
} else {
if (nesadapter->port_count == 2)
nesadapter->log_port = 0x00000044;
else
nesadapter->log_port = 0x000000e4;
}
nes_write_indexed(nesdev, NES_IDX_TX_POOL_SIZE, 0x00000003);
}
nes_write_indexed(nesdev, NES_IDX_NIC_LOGPORT_TO_PHYPORT,
nesadapter->log_port);
nes_debug(NES_DBG_INIT, "Probe time, LOG2PHY=%u\n",
nes_read_indexed(nesdev, NES_IDX_NIC_LOGPORT_TO_PHYPORT));
spin_lock_init(&nesadapter->resource_lock);
spin_lock_init(&nesadapter->phy_lock);
spin_lock_init(&nesadapter->pbl_lock);
spin_lock_init(&nesadapter->periodic_timer_lock);
INIT_LIST_HEAD(&nesadapter->nesvnic_list[0]);
INIT_LIST_HEAD(&nesadapter->nesvnic_list[1]);
INIT_LIST_HEAD(&nesadapter->nesvnic_list[2]);
INIT_LIST_HEAD(&nesadapter->nesvnic_list[3]);
if ((!nesadapter->OneG_Mode) && (nesadapter->port_count == 2)) {
u32 pcs_control_status0, pcs_control_status1;
u32 reset_value;
u32 i = 0;
u32 int_cnt = 0;
u32 ext_cnt = 0;
unsigned long flags;
u32 j = 0;
pcs_control_status0 = nes_read_indexed(nesdev,
NES_IDX_PHY_PCS_CONTROL_STATUS0);
pcs_control_status1 = nes_read_indexed(nesdev,
NES_IDX_PHY_PCS_CONTROL_STATUS0 + 0x200);
for (i = 0; i < NES_MAX_LINK_CHECK; i++) {
pcs_control_status0 = nes_read_indexed(nesdev,
NES_IDX_PHY_PCS_CONTROL_STATUS0);
pcs_control_status1 = nes_read_indexed(nesdev,
NES_IDX_PHY_PCS_CONTROL_STATUS0 + 0x200);
if ((0x0F000100 == (pcs_control_status0 & 0x0F000100))
|| (0x0F000100 == (pcs_control_status1 & 0x0F000100)))
int_cnt++;
msleep(1);
}
if (int_cnt > 1) {
spin_lock_irqsave(&nesadapter->phy_lock, flags);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL1, 0x0000F0C8);
mh_detected++;
reset_value = nes_read32(nesdev->regs+NES_SOFTWARE_RESET);
reset_value |= 0x0000003d;
nes_write32(nesdev->regs+NES_SOFTWARE_RESET, reset_value);
while (((nes_read32(nesdev->regs+NES_SOFTWARE_RESET)
& 0x00000040) != 0x00000040) && (j++ < 5000));
spin_unlock_irqrestore(&nesadapter->phy_lock, flags);
pcs_control_status0 = nes_read_indexed(nesdev,
NES_IDX_PHY_PCS_CONTROL_STATUS0);
pcs_control_status1 = nes_read_indexed(nesdev,
NES_IDX_PHY_PCS_CONTROL_STATUS0 + 0x200);
for (i = 0; i < NES_MAX_LINK_CHECK; i++) {
pcs_control_status0 = nes_read_indexed(nesdev,
NES_IDX_PHY_PCS_CONTROL_STATUS0);
pcs_control_status1 = nes_read_indexed(nesdev,
NES_IDX_PHY_PCS_CONTROL_STATUS0 + 0x200);
if ((0x0F000100 == (pcs_control_status0 & 0x0F000100))
|| (0x0F000100 == (pcs_control_status1 & 0x0F000100))) {
if (++ext_cnt > int_cnt) {
spin_lock_irqsave(&nesadapter->phy_lock, flags);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL1,
0x0000F088);
mh_detected++;
reset_value = nes_read32(nesdev->regs+NES_SOFTWARE_RESET);
reset_value |= 0x0000003d;
nes_write32(nesdev->regs+NES_SOFTWARE_RESET, reset_value);
while (((nes_read32(nesdev->regs+NES_SOFTWARE_RESET)
& 0x00000040) != 0x00000040) && (j++ < 5000));
spin_unlock_irqrestore(&nesadapter->phy_lock, flags);
break;
}
}
msleep(1);
}
}
}
if (nesadapter->hw_rev == NE020_REV) {
init_timer(&nesadapter->mh_timer);
nesadapter->mh_timer.function = nes_mh_fix;
nesadapter->mh_timer.expires = jiffies + (HZ/5); /* 1 second */
nesadapter->mh_timer.data = (unsigned long)nesdev;
add_timer(&nesadapter->mh_timer);
} else {
nes_write32(nesdev->regs+NES_INTF_INT_STAT, 0x0f000000);
}
init_timer(&nesadapter->lc_timer);
nesadapter->lc_timer.function = nes_clc;
nesadapter->lc_timer.expires = jiffies + 3600 * HZ; /* 1 hour */
nesadapter->lc_timer.data = (unsigned long)nesdev;
add_timer(&nesadapter->lc_timer);
list_add_tail(&nesadapter->list, &nes_adapter_list);
for (func_index = 0; func_index < 8; func_index++) {
pci_bus_read_config_word(nesdev->pcidev->bus,
PCI_DEVFN(PCI_SLOT(nesdev->pcidev->devfn),
func_index), 0, &vendor_id);
if (vendor_id == 0xffff)
break;
}
nes_debug(NES_DBG_INIT, "%s %d functions found for %s.\n", __func__,
func_index, pci_name(nesdev->pcidev));
nesadapter->adapter_fcn_count = func_index;
return nesadapter;
}
/**
* nes_reset_adapter_ne020
*/
static unsigned int nes_reset_adapter_ne020(struct nes_device *nesdev, u8 *OneG_Mode)
{
u32 port_count;
u32 u32temp;
u32 i;
u32temp = nes_read32(nesdev->regs+NES_SOFTWARE_RESET);
port_count = ((u32temp & 0x00000300) >> 8) + 1;
/* TODO: assuming that both SERDES are set the same for now */
*OneG_Mode = (u32temp & 0x00003c00) ? 0 : 1;
nes_debug(NES_DBG_INIT, "Initial Software Reset = 0x%08X, port_count=%u\n",
u32temp, port_count);
if (*OneG_Mode)
nes_debug(NES_DBG_INIT, "Running in 1G mode.\n");
u32temp &= 0xff00ffc0;
switch (port_count) {
case 1:
u32temp |= 0x00ee0000;
break;
case 2:
u32temp |= 0x00cc0000;
break;
case 4:
u32temp |= 0x00000000;
break;
default:
return 0;
break;
}
/* check and do full reset if needed */
if (nes_read_indexed(nesdev, NES_IDX_QP_CONTROL+(PCI_FUNC(nesdev->pcidev->devfn)*8))) {
nes_debug(NES_DBG_INIT, "Issuing Full Soft reset = 0x%08X\n", u32temp | 0xd);
nes_write32(nesdev->regs+NES_SOFTWARE_RESET, u32temp | 0xd);
i = 0;
while (((nes_read32(nesdev->regs+NES_SOFTWARE_RESET) & 0x00000040) == 0) && i++ < 10000)
mdelay(1);
if (i > 10000) {
nes_debug(NES_DBG_INIT, "Did not see full soft reset done.\n");
return 0;
}
i = 0;
while ((nes_read_indexed(nesdev, NES_IDX_INT_CPU_STATUS) != 0x80) && i++ < 10000)
mdelay(1);
if (i > 10000) {
printk(KERN_ERR PFX "Internal CPU not ready, status = %02X\n",
nes_read_indexed(nesdev, NES_IDX_INT_CPU_STATUS));
return 0;
}
}
/* port reset */
switch (port_count) {
case 1:
u32temp |= 0x00ee0010;
break;
case 2:
u32temp |= 0x00cc0030;
break;
case 4:
u32temp |= 0x00000030;
break;
}
nes_debug(NES_DBG_INIT, "Issuing Port Soft reset = 0x%08X\n", u32temp | 0xd);
nes_write32(nesdev->regs+NES_SOFTWARE_RESET, u32temp | 0xd);
i = 0;
while (((nes_read32(nesdev->regs+NES_SOFTWARE_RESET) & 0x00000040) == 0) && i++ < 10000)
mdelay(1);
if (i > 10000) {
nes_debug(NES_DBG_INIT, "Did not see port soft reset done.\n");
return 0;
}
/* serdes 0 */
i = 0;
while (((u32temp = (nes_read_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_STATUS0)
& 0x0000000f)) != 0x0000000f) && i++ < 5000)
mdelay(1);
if (i > 5000) {
nes_debug(NES_DBG_INIT, "Serdes 0 not ready, status=%x\n", u32temp);
return 0;
}
/* serdes 1 */
if (port_count > 1) {
i = 0;
while (((u32temp = (nes_read_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_STATUS1)
& 0x0000000f)) != 0x0000000f) && i++ < 5000)
mdelay(1);
if (i > 5000) {
nes_debug(NES_DBG_INIT, "Serdes 1 not ready, status=%x\n", u32temp);
return 0;
}
}
return port_count;
}
/**
* nes_init_serdes
*/
static int nes_init_serdes(struct nes_device *nesdev, u8 hw_rev, u8 port_count,
struct nes_adapter *nesadapter, u8 OneG_Mode)
{
int i;
u32 u32temp;
u32 sds;
if (hw_rev != NE020_REV) {
/* init serdes 0 */
switch (nesadapter->phy_type[0]) {
case NES_PHY_TYPE_CX4:
if (wide_ppm_offset)
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_CDR_CONTROL0, 0x000FFFAA);
else
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_CDR_CONTROL0, 0x000000FF);
break;
case NES_PHY_TYPE_KR:
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_CDR_CONTROL0, 0x000000FF);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_TX_EMP0, 0x00000000);
break;
case NES_PHY_TYPE_PUMA_1G:
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_CDR_CONTROL0, 0x000000FF);
sds = nes_read_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL0);
sds |= 0x00000100;
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL0, sds);
break;
default:
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_CDR_CONTROL0, 0x000000FF);
break;
}
if (!OneG_Mode)
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_TX_HIGHZ_LANE_MODE0, 0x11110000);
if (port_count < 2)
return 0;
/* init serdes 1 */
if (!(OneG_Mode && (nesadapter->phy_type[1] != NES_PHY_TYPE_PUMA_1G)))
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_CDR_CONTROL1, 0x000000FF);
switch (nesadapter->phy_type[1]) {
case NES_PHY_TYPE_ARGUS:
case NES_PHY_TYPE_SFP_D:
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_TX_EMP0, 0x00000000);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_TX_EMP1, 0x00000000);
break;
case NES_PHY_TYPE_CX4:
if (wide_ppm_offset)
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_CDR_CONTROL1, 0x000FFFAA);
break;
case NES_PHY_TYPE_KR:
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_TX_EMP1, 0x00000000);
break;
case NES_PHY_TYPE_PUMA_1G:
sds = nes_read_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL1);
sds |= 0x000000100;
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL1, sds);
}
if (!OneG_Mode) {
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_TX_HIGHZ_LANE_MODE1, 0x11110000);
sds = nes_read_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL1);
sds &= 0xFFFFFFBF;
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL1, sds);
}
} else {
/* init serdes 0 */
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL0, 0x00000008);
i = 0;
while (((u32temp = (nes_read_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_STATUS0)
& 0x0000000f)) != 0x0000000f) && i++ < 5000)
mdelay(1);
if (i > 5000) {
nes_debug(NES_DBG_PHY, "Init: serdes 0 not ready, status=%x\n", u32temp);
return 1;
}
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_TX_EMP0, 0x000bdef7);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_TX_DRIVE0, 0x9ce73000);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_RX_MODE0, 0x0ff00000);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_RX_SIGDET0, 0x00000000);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_BYPASS0, 0x00000000);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_LOOPBACK_CONTROL0, 0x00000000);
if (OneG_Mode)
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_RX_EQ_CONTROL0, 0xf0182222);
else
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_RX_EQ_CONTROL0, 0xf0042222);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_CDR_CONTROL0, 0x000000ff);
if (port_count > 1) {
/* init serdes 1 */
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL1, 0x00000048);
i = 0;
while (((u32temp = (nes_read_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_STATUS1)
& 0x0000000f)) != 0x0000000f) && (i++ < 5000))
mdelay(1);
if (i > 5000) {
printk("%s: Init: serdes 1 not ready, status=%x\n", __func__, u32temp);
/* return 1; */
}
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_TX_EMP1, 0x000bdef7);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_TX_DRIVE1, 0x9ce73000);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_RX_MODE1, 0x0ff00000);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_RX_SIGDET1, 0x00000000);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_BYPASS1, 0x00000000);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_LOOPBACK_CONTROL1, 0x00000000);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_RX_EQ_CONTROL1, 0xf0002222);
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_CDR_CONTROL1, 0x000000ff);
}
}
return 0;
}
/**
* nes_init_csr_ne020
* Initialize registers for ne020 hardware
*/
static void nes_init_csr_ne020(struct nes_device *nesdev, u8 hw_rev, u8 port_count)
{
u32 u32temp;
nes_debug(NES_DBG_INIT, "port_count=%d\n", port_count);
nes_write_indexed(nesdev, 0x000001E4, 0x00000007);
/* nes_write_indexed(nesdev, 0x000001E8, 0x000208C4); */
nes_write_indexed(nesdev, 0x000001E8, 0x00020874);
nes_write_indexed(nesdev, 0x000001D8, 0x00048002);
/* nes_write_indexed(nesdev, 0x000001D8, 0x0004B002); */
nes_write_indexed(nesdev, 0x000001FC, 0x00050005);
nes_write_indexed(nesdev, 0x00000600, 0x55555555);
nes_write_indexed(nesdev, 0x00000604, 0x55555555);
/* TODO: move these MAC register settings to NIC bringup */
nes_write_indexed(nesdev, 0x00002000, 0x00000001);
nes_write_indexed(nesdev, 0x00002004, 0x00000001);
nes_write_indexed(nesdev, 0x00002008, 0x0000FFFF);
nes_write_indexed(nesdev, 0x0000200C, 0x00000001);
nes_write_indexed(nesdev, 0x00002010, 0x000003c1);
nes_write_indexed(nesdev, 0x0000201C, 0x75345678);
if (port_count > 1) {
nes_write_indexed(nesdev, 0x00002200, 0x00000001);
nes_write_indexed(nesdev, 0x00002204, 0x00000001);
nes_write_indexed(nesdev, 0x00002208, 0x0000FFFF);
nes_write_indexed(nesdev, 0x0000220C, 0x00000001);
nes_write_indexed(nesdev, 0x00002210, 0x000003c1);
nes_write_indexed(nesdev, 0x0000221C, 0x75345678);
nes_write_indexed(nesdev, 0x00000908, 0x20000001);
}
if (port_count > 2) {
nes_write_indexed(nesdev, 0x00002400, 0x00000001);
nes_write_indexed(nesdev, 0x00002404, 0x00000001);
nes_write_indexed(nesdev, 0x00002408, 0x0000FFFF);
nes_write_indexed(nesdev, 0x0000240C, 0x00000001);
nes_write_indexed(nesdev, 0x00002410, 0x000003c1);
nes_write_indexed(nesdev, 0x0000241C, 0x75345678);
nes_write_indexed(nesdev, 0x00000910, 0x20000001);
nes_write_indexed(nesdev, 0x00002600, 0x00000001);
nes_write_indexed(nesdev, 0x00002604, 0x00000001);
nes_write_indexed(nesdev, 0x00002608, 0x0000FFFF);
nes_write_indexed(nesdev, 0x0000260C, 0x00000001);
nes_write_indexed(nesdev, 0x00002610, 0x000003c1);
nes_write_indexed(nesdev, 0x0000261C, 0x75345678);
nes_write_indexed(nesdev, 0x00000918, 0x20000001);
}
nes_write_indexed(nesdev, 0x00005000, 0x00018000);
/* nes_write_indexed(nesdev, 0x00005000, 0x00010000); */
nes_write_indexed(nesdev, NES_IDX_WQM_CONFIG1, (wqm_quanta << 1) |
0x00000001);
nes_write_indexed(nesdev, 0x00005008, 0x1F1F1F1F);
nes_write_indexed(nesdev, 0x00005010, 0x1F1F1F1F);
nes_write_indexed(nesdev, 0x00005018, 0x1F1F1F1F);
nes_write_indexed(nesdev, 0x00005020, 0x1F1F1F1F);
nes_write_indexed(nesdev, 0x00006090, 0xFFFFFFFF);
/* TODO: move this to code, get from EEPROM */
nes_write_indexed(nesdev, 0x00000900, 0x20000001);
nes_write_indexed(nesdev, 0x000060C0, 0x0000028e);
nes_write_indexed(nesdev, 0x000060C8, 0x00000020);
nes_write_indexed(nesdev, 0x000001EC, 0x7b2625a0);
/* nes_write_indexed(nesdev, 0x000001EC, 0x5f2625a0); */
if (hw_rev != NE020_REV) {
u32temp = nes_read_indexed(nesdev, 0x000008e8);
u32temp |= 0x80000000;
nes_write_indexed(nesdev, 0x000008e8, u32temp);
u32temp = nes_read_indexed(nesdev, 0x000021f8);
u32temp &= 0x7fffffff;
u32temp |= 0x7fff0010;
nes_write_indexed(nesdev, 0x000021f8, u32temp);
if (port_count > 1) {
u32temp = nes_read_indexed(nesdev, 0x000023f8);
u32temp &= 0x7fffffff;
u32temp |= 0x7fff0010;
nes_write_indexed(nesdev, 0x000023f8, u32temp);
}
}
}
/**
* nes_destroy_adapter - destroy the adapter structure
*/
void nes_destroy_adapter(struct nes_adapter *nesadapter)
{
struct nes_adapter *tmp_adapter;
list_for_each_entry(tmp_adapter, &nes_adapter_list, list) {
nes_debug(NES_DBG_SHUTDOWN, "Nes Adapter list entry = 0x%p.\n",
tmp_adapter);
}
nesadapter->ref_count--;
if (!nesadapter->ref_count) {
if (nesadapter->hw_rev == NE020_REV) {
del_timer(&nesadapter->mh_timer);
}
del_timer(&nesadapter->lc_timer);
list_del(&nesadapter->list);
kfree(nesadapter);
}
}
/**
* nes_init_cqp
*/
int nes_init_cqp(struct nes_device *nesdev)
{
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_hw_cqp_qp_context *cqp_qp_context;
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_hw_ceq *ceq;
struct nes_hw_ceq *nic_ceq;
struct nes_hw_aeq *aeq;
void *vmem;
dma_addr_t pmem;
u32 count=0;
u32 cqp_head;
u64 u64temp;
u32 u32temp;
/* allocate CQP memory */
/* Need to add max_cq to the aeq size once cq overflow checking is added back */
/* SQ is 512 byte aligned, others are 256 byte aligned */
nesdev->cqp_mem_size = 512 +
(sizeof(struct nes_hw_cqp_wqe) * NES_CQP_SQ_SIZE) +
(sizeof(struct nes_hw_cqe) * NES_CCQ_SIZE) +
max(((u32)sizeof(struct nes_hw_ceqe) * NES_CCEQ_SIZE), (u32)256) +
max(((u32)sizeof(struct nes_hw_ceqe) * NES_NIC_CEQ_SIZE), (u32)256) +
(sizeof(struct nes_hw_aeqe) * nesadapter->max_qp) +
sizeof(struct nes_hw_cqp_qp_context);
nesdev->cqp_vbase = pci_zalloc_consistent(nesdev->pcidev,
nesdev->cqp_mem_size,
&nesdev->cqp_pbase);
if (!nesdev->cqp_vbase) {
nes_debug(NES_DBG_INIT, "Unable to allocate memory for host descriptor rings\n");
return -ENOMEM;
}
/* Allocate a twice the number of CQP requests as the SQ size */
nesdev->nes_cqp_requests = kzalloc(sizeof(struct nes_cqp_request) *
2 * NES_CQP_SQ_SIZE, GFP_KERNEL);
if (nesdev->nes_cqp_requests == NULL) {
nes_debug(NES_DBG_INIT, "Unable to allocate memory CQP request entries.\n");
pci_free_consistent(nesdev->pcidev, nesdev->cqp_mem_size, nesdev->cqp.sq_vbase,
nesdev->cqp.sq_pbase);
return -ENOMEM;
}
nes_debug(NES_DBG_INIT, "Allocated CQP structures at %p (phys = %016lX), size = %u.\n",
nesdev->cqp_vbase, (unsigned long)nesdev->cqp_pbase, nesdev->cqp_mem_size);
spin_lock_init(&nesdev->cqp.lock);
init_waitqueue_head(&nesdev->cqp.waitq);
/* Setup Various Structures */
vmem = (void *)(((unsigned long)nesdev->cqp_vbase + (512 - 1)) &
~(unsigned long)(512 - 1));
pmem = (dma_addr_t)(((unsigned long long)nesdev->cqp_pbase + (512 - 1)) &
~(unsigned long long)(512 - 1));
nesdev->cqp.sq_vbase = vmem;
nesdev->cqp.sq_pbase = pmem;
nesdev->cqp.sq_size = NES_CQP_SQ_SIZE;
nesdev->cqp.sq_head = 0;
nesdev->cqp.sq_tail = 0;
nesdev->cqp.qp_id = PCI_FUNC(nesdev->pcidev->devfn);
vmem += (sizeof(struct nes_hw_cqp_wqe) * nesdev->cqp.sq_size);
pmem += (sizeof(struct nes_hw_cqp_wqe) * nesdev->cqp.sq_size);
nesdev->ccq.cq_vbase = vmem;
nesdev->ccq.cq_pbase = pmem;
nesdev->ccq.cq_size = NES_CCQ_SIZE;
nesdev->ccq.cq_head = 0;
nesdev->ccq.ce_handler = nes_cqp_ce_handler;
nesdev->ccq.cq_number = PCI_FUNC(nesdev->pcidev->devfn);
vmem += (sizeof(struct nes_hw_cqe) * nesdev->ccq.cq_size);
pmem += (sizeof(struct nes_hw_cqe) * nesdev->ccq.cq_size);
nesdev->ceq_index = PCI_FUNC(nesdev->pcidev->devfn);
ceq = &nesadapter->ceq[nesdev->ceq_index];
ceq->ceq_vbase = vmem;
ceq->ceq_pbase = pmem;
ceq->ceq_size = NES_CCEQ_SIZE;
ceq->ceq_head = 0;
vmem += max(((u32)sizeof(struct nes_hw_ceqe) * ceq->ceq_size), (u32)256);
pmem += max(((u32)sizeof(struct nes_hw_ceqe) * ceq->ceq_size), (u32)256);
nesdev->nic_ceq_index = PCI_FUNC(nesdev->pcidev->devfn) + 8;
nic_ceq = &nesadapter->ceq[nesdev->nic_ceq_index];
nic_ceq->ceq_vbase = vmem;
nic_ceq->ceq_pbase = pmem;
nic_ceq->ceq_size = NES_NIC_CEQ_SIZE;
nic_ceq->ceq_head = 0;
vmem += max(((u32)sizeof(struct nes_hw_ceqe) * nic_ceq->ceq_size), (u32)256);
pmem += max(((u32)sizeof(struct nes_hw_ceqe) * nic_ceq->ceq_size), (u32)256);
aeq = &nesadapter->aeq[PCI_FUNC(nesdev->pcidev->devfn)];
aeq->aeq_vbase = vmem;
aeq->aeq_pbase = pmem;
aeq->aeq_size = nesadapter->max_qp;
aeq->aeq_head = 0;
/* Setup QP Context */
vmem += (sizeof(struct nes_hw_aeqe) * aeq->aeq_size);
pmem += (sizeof(struct nes_hw_aeqe) * aeq->aeq_size);
cqp_qp_context = vmem;
cqp_qp_context->context_words[0] =
cpu_to_le32((PCI_FUNC(nesdev->pcidev->devfn) << 12) + (2 << 10));
cqp_qp_context->context_words[1] = 0;
cqp_qp_context->context_words[2] = cpu_to_le32((u32)nesdev->cqp.sq_pbase);
cqp_qp_context->context_words[3] = cpu_to_le32(((u64)nesdev->cqp.sq_pbase) >> 32);
/* Write the address to Create CQP */
if ((sizeof(dma_addr_t) > 4)) {
nes_write_indexed(nesdev,
NES_IDX_CREATE_CQP_HIGH + (PCI_FUNC(nesdev->pcidev->devfn) * 8),
((u64)pmem) >> 32);
} else {
nes_write_indexed(nesdev,
NES_IDX_CREATE_CQP_HIGH + (PCI_FUNC(nesdev->pcidev->devfn) * 8), 0);
}
nes_write_indexed(nesdev,
NES_IDX_CREATE_CQP_LOW + (PCI_FUNC(nesdev->pcidev->devfn) * 8),
(u32)pmem);
INIT_LIST_HEAD(&nesdev->cqp_avail_reqs);
INIT_LIST_HEAD(&nesdev->cqp_pending_reqs);
for (count = 0; count < 2*NES_CQP_SQ_SIZE; count++) {
init_waitqueue_head(&nesdev->nes_cqp_requests[count].waitq);
list_add_tail(&nesdev->nes_cqp_requests[count].list, &nesdev->cqp_avail_reqs);
}
/* Write Create CCQ WQE */
cqp_head = nesdev->cqp.sq_head++;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX,
(NES_CQP_CREATE_CQ | NES_CQP_CQ_CEQ_VALID |
NES_CQP_CQ_CHK_OVERFLOW | ((u32)nesdev->ccq.cq_size << 16)));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_ID_IDX,
(nesdev->ccq.cq_number |
((u32)nesdev->ceq_index << 16)));
u64temp = (u64)nesdev->ccq.cq_pbase;
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_CQ_WQE_PBL_LOW_IDX, u64temp);
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_CQ_CONTEXT_HIGH_IDX] = 0;
u64temp = (unsigned long)&nesdev->ccq;
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_CQ_CONTEXT_LOW_IDX] =
cpu_to_le32((u32)(u64temp >> 1));
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_CQ_CONTEXT_HIGH_IDX] =
cpu_to_le32(((u32)((u64temp) >> 33)) & 0x7FFFFFFF);
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_DOORBELL_INDEX_HIGH_IDX] = 0;
/* Write Create CEQ WQE */
cqp_head = nesdev->cqp.sq_head++;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX,
(NES_CQP_CREATE_CEQ + ((u32)nesdev->ceq_index << 8)));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_CEQ_WQE_ELEMENT_COUNT_IDX, ceq->ceq_size);
u64temp = (u64)ceq->ceq_pbase;
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_CQ_WQE_PBL_LOW_IDX, u64temp);
/* Write Create AEQ WQE */
cqp_head = nesdev->cqp.sq_head++;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX,
(NES_CQP_CREATE_AEQ + ((u32)PCI_FUNC(nesdev->pcidev->devfn) << 8)));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_AEQ_WQE_ELEMENT_COUNT_IDX, aeq->aeq_size);
u64temp = (u64)aeq->aeq_pbase;
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_CQ_WQE_PBL_LOW_IDX, u64temp);
/* Write Create NIC CEQ WQE */
cqp_head = nesdev->cqp.sq_head++;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX,
(NES_CQP_CREATE_CEQ + ((u32)nesdev->nic_ceq_index << 8)));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_CEQ_WQE_ELEMENT_COUNT_IDX, nic_ceq->ceq_size);
u64temp = (u64)nic_ceq->ceq_pbase;
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_CQ_WQE_PBL_LOW_IDX, u64temp);
/* Poll until CCQP done */
count = 0;
do {
if (count++ > 1000) {
printk(KERN_ERR PFX "Error creating CQP\n");
pci_free_consistent(nesdev->pcidev, nesdev->cqp_mem_size,
nesdev->cqp_vbase, nesdev->cqp_pbase);
return -1;
}
udelay(10);
} while (!(nes_read_indexed(nesdev,
NES_IDX_QP_CONTROL + (PCI_FUNC(nesdev->pcidev->devfn) * 8)) & (1 << 8)));
nes_debug(NES_DBG_INIT, "CQP Status = 0x%08X\n", nes_read_indexed(nesdev,
NES_IDX_QP_CONTROL+(PCI_FUNC(nesdev->pcidev->devfn)*8)));
u32temp = 0x04800000;
nes_write32(nesdev->regs+NES_WQE_ALLOC, u32temp | nesdev->cqp.qp_id);
/* wait for the CCQ, CEQ, and AEQ to get created */
count = 0;
do {
if (count++ > 1000) {
printk(KERN_ERR PFX "Error creating CCQ, CEQ, and AEQ\n");
pci_free_consistent(nesdev->pcidev, nesdev->cqp_mem_size,
nesdev->cqp_vbase, nesdev->cqp_pbase);
return -1;
}
udelay(10);
} while (((nes_read_indexed(nesdev,
NES_IDX_QP_CONTROL+(PCI_FUNC(nesdev->pcidev->devfn)*8)) & (15<<8)) != (15<<8)));
/* dump the QP status value */
nes_debug(NES_DBG_INIT, "QP Status = 0x%08X\n", nes_read_indexed(nesdev,
NES_IDX_QP_CONTROL+(PCI_FUNC(nesdev->pcidev->devfn)*8)));
nesdev->cqp.sq_tail++;
return 0;
}
/**
* nes_destroy_cqp
*/
int nes_destroy_cqp(struct nes_device *nesdev)
{
struct nes_hw_cqp_wqe *cqp_wqe;
u32 count = 0;
u32 cqp_head;
unsigned long flags;
do {
if (count++ > 1000)
break;
udelay(10);
} while (!(nesdev->cqp.sq_head == nesdev->cqp.sq_tail));
/* Reset CCQ */
nes_write32(nesdev->regs+NES_CQE_ALLOC, NES_CQE_ALLOC_RESET |
nesdev->ccq.cq_number);
/* Disable device interrupts */
nes_write32(nesdev->regs+NES_INT_MASK, 0x7fffffff);
spin_lock_irqsave(&nesdev->cqp.lock, flags);
/* Destroy the AEQ */
cqp_head = nesdev->cqp.sq_head++;
nesdev->cqp.sq_head &= nesdev->cqp.sq_size-1;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] = cpu_to_le32(NES_CQP_DESTROY_AEQ |
((u32)PCI_FUNC(nesdev->pcidev->devfn) << 8));
cqp_wqe->wqe_words[NES_CQP_WQE_COMP_CTX_HIGH_IDX] = 0;
/* Destroy the NIC CEQ */
cqp_head = nesdev->cqp.sq_head++;
nesdev->cqp.sq_head &= nesdev->cqp.sq_size-1;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] = cpu_to_le32(NES_CQP_DESTROY_CEQ |
((u32)nesdev->nic_ceq_index << 8));
/* Destroy the CEQ */
cqp_head = nesdev->cqp.sq_head++;
nesdev->cqp.sq_head &= nesdev->cqp.sq_size-1;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] = cpu_to_le32(NES_CQP_DESTROY_CEQ |
(nesdev->ceq_index << 8));
/* Destroy the CCQ */
cqp_head = nesdev->cqp.sq_head++;
nesdev->cqp.sq_head &= nesdev->cqp.sq_size-1;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] = cpu_to_le32(NES_CQP_DESTROY_CQ);
cqp_wqe->wqe_words[NES_CQP_WQE_ID_IDX] = cpu_to_le32(nesdev->ccq.cq_number |
((u32)nesdev->ceq_index << 16));
/* Destroy CQP */
cqp_head = nesdev->cqp.sq_head++;
nesdev->cqp.sq_head &= nesdev->cqp.sq_size-1;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] = cpu_to_le32(NES_CQP_DESTROY_QP |
NES_CQP_QP_TYPE_CQP);
cqp_wqe->wqe_words[NES_CQP_WQE_ID_IDX] = cpu_to_le32(nesdev->cqp.qp_id);
barrier();
/* Ring doorbell (5 WQEs) */
nes_write32(nesdev->regs+NES_WQE_ALLOC, 0x05800000 | nesdev->cqp.qp_id);
spin_unlock_irqrestore(&nesdev->cqp.lock, flags);
/* wait for the CCQ, CEQ, and AEQ to get destroyed */
count = 0;
do {
if (count++ > 1000) {
printk(KERN_ERR PFX "Function%d: Error destroying CCQ, CEQ, and AEQ\n",
PCI_FUNC(nesdev->pcidev->devfn));
break;
}
udelay(10);
} while (((nes_read_indexed(nesdev,
NES_IDX_QP_CONTROL + (PCI_FUNC(nesdev->pcidev->devfn)*8)) & (15 << 8)) != 0));
/* dump the QP status value */
nes_debug(NES_DBG_SHUTDOWN, "Function%d: QP Status = 0x%08X\n",
PCI_FUNC(nesdev->pcidev->devfn),
nes_read_indexed(nesdev,
NES_IDX_QP_CONTROL+(PCI_FUNC(nesdev->pcidev->devfn)*8)));
kfree(nesdev->nes_cqp_requests);
/* Free the control structures */
pci_free_consistent(nesdev->pcidev, nesdev->cqp_mem_size, nesdev->cqp.sq_vbase,
nesdev->cqp.sq_pbase);
return 0;
}
/**
* nes_init_1g_phy
*/
static int nes_init_1g_phy(struct nes_device *nesdev, u8 phy_type, u8 phy_index)
{
u32 counter = 0;
u16 phy_data;
int ret = 0;
nes_read_1G_phy_reg(nesdev, 1, phy_index, &phy_data);
nes_write_1G_phy_reg(nesdev, 23, phy_index, 0xb000);
/* Reset the PHY */
nes_write_1G_phy_reg(nesdev, 0, phy_index, 0x8000);
udelay(100);
counter = 0;
do {
nes_read_1G_phy_reg(nesdev, 0, phy_index, &phy_data);
if (counter++ > 100) {
ret = -1;
break;
}
} while (phy_data & 0x8000);
/* Setting no phy loopback */
phy_data &= 0xbfff;
phy_data |= 0x1140;
nes_write_1G_phy_reg(nesdev, 0, phy_index, phy_data);
nes_read_1G_phy_reg(nesdev, 0, phy_index, &phy_data);
nes_read_1G_phy_reg(nesdev, 0x17, phy_index, &phy_data);
nes_read_1G_phy_reg(nesdev, 0x1e, phy_index, &phy_data);
/* Setting the interrupt mask */
nes_read_1G_phy_reg(nesdev, 0x19, phy_index, &phy_data);
nes_write_1G_phy_reg(nesdev, 0x19, phy_index, 0xffee);
nes_read_1G_phy_reg(nesdev, 0x19, phy_index, &phy_data);
/* turning on flow control */
nes_read_1G_phy_reg(nesdev, 4, phy_index, &phy_data);
nes_write_1G_phy_reg(nesdev, 4, phy_index, (phy_data & ~(0x03E0)) | 0xc00);
nes_read_1G_phy_reg(nesdev, 4, phy_index, &phy_data);
/* Clear Half duplex */
nes_read_1G_phy_reg(nesdev, 9, phy_index, &phy_data);
nes_write_1G_phy_reg(nesdev, 9, phy_index, phy_data & ~(0x0100));
nes_read_1G_phy_reg(nesdev, 9, phy_index, &phy_data);
nes_read_1G_phy_reg(nesdev, 0, phy_index, &phy_data);
nes_write_1G_phy_reg(nesdev, 0, phy_index, phy_data | 0x0300);
return ret;
}
/**
* nes_init_2025_phy
*/
static int nes_init_2025_phy(struct nes_device *nesdev, u8 phy_type, u8 phy_index)
{
u32 temp_phy_data = 0;
u32 temp_phy_data2 = 0;
u32 counter = 0;
u32 sds;
u32 mac_index = nesdev->mac_index;
int ret = 0;
unsigned int first_attempt = 1;
/* Check firmware heartbeat */
nes_read_10G_phy_reg(nesdev, phy_index, 0x3, 0xd7ee);
temp_phy_data = (u16)nes_read_indexed(nesdev, NES_IDX_MAC_MDIO_CONTROL);
udelay(1500);
nes_read_10G_phy_reg(nesdev, phy_index, 0x3, 0xd7ee);
temp_phy_data2 = (u16)nes_read_indexed(nesdev, NES_IDX_MAC_MDIO_CONTROL);
if (temp_phy_data != temp_phy_data2) {
nes_read_10G_phy_reg(nesdev, phy_index, 0x3, 0xd7fd);
temp_phy_data = (u16)nes_read_indexed(nesdev, NES_IDX_MAC_MDIO_CONTROL);
if ((temp_phy_data & 0xff) > 0x20)
return 0;
printk(PFX "Reinitialize external PHY\n");
}
/* no heartbeat, configure the PHY */
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0x0000, 0x8000);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc300, 0x0000);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc316, 0x000A);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc318, 0x0052);
switch (phy_type) {
case NES_PHY_TYPE_ARGUS:
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc316, 0x000A);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc318, 0x0052);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc302, 0x000C);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc319, 0x0008);
nes_write_10G_phy_reg(nesdev, phy_index, 0x3, 0x0027, 0x0001);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc31a, 0x0098);
nes_write_10G_phy_reg(nesdev, phy_index, 0x3, 0x0026, 0x0E00);
/* setup LEDs */
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xd006, 0x0007);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xd007, 0x000A);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xd008, 0x0009);
break;
case NES_PHY_TYPE_SFP_D:
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc316, 0x000A);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc318, 0x0052);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc302, 0x0004);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc319, 0x0038);
nes_write_10G_phy_reg(nesdev, phy_index, 0x3, 0x0027, 0x0013);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc31a, 0x0098);
nes_write_10G_phy_reg(nesdev, phy_index, 0x3, 0x0026, 0x0E00);
/* setup LEDs */
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xd006, 0x0007);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xd007, 0x000A);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xd008, 0x0009);
break;
case NES_PHY_TYPE_KR:
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc316, 0x000A);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc318, 0x0052);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc302, 0x000C);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc319, 0x0010);
nes_write_10G_phy_reg(nesdev, phy_index, 0x3, 0x0027, 0x0013);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc31a, 0x0080);
nes_write_10G_phy_reg(nesdev, phy_index, 0x3, 0x0026, 0x0E00);
/* setup LEDs */
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xd006, 0x000B);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xd007, 0x0003);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xd008, 0x0004);
nes_write_10G_phy_reg(nesdev, phy_index, 0x3, 0x0022, 0x406D);
nes_write_10G_phy_reg(nesdev, phy_index, 0x3, 0x0023, 0x0020);
break;
}
nes_write_10G_phy_reg(nesdev, phy_index, 0x3, 0x0028, 0xA528);
/* Bring PHY out of reset */
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc300, 0x0002);
/* Check for heartbeat */
counter = 0;
mdelay(690);
nes_read_10G_phy_reg(nesdev, phy_index, 0x3, 0xd7ee);
temp_phy_data = (u16)nes_read_indexed(nesdev, NES_IDX_MAC_MDIO_CONTROL);
do {
if (counter++ > 150) {
printk(PFX "No PHY heartbeat\n");
break;
}
mdelay(1);
nes_read_10G_phy_reg(nesdev, phy_index, 0x3, 0xd7ee);
temp_phy_data2 = (u16)nes_read_indexed(nesdev, NES_IDX_MAC_MDIO_CONTROL);
} while ((temp_phy_data2 == temp_phy_data));
/* wait for tracking */
counter = 0;
do {
nes_read_10G_phy_reg(nesdev, phy_index, 0x3, 0xd7fd);
temp_phy_data = (u16)nes_read_indexed(nesdev, NES_IDX_MAC_MDIO_CONTROL);
if (counter++ > 300) {
if (((temp_phy_data & 0xff) == 0x0) && first_attempt) {
first_attempt = 0;
counter = 0;
/* reset AMCC PHY and try again */
nes_write_10G_phy_reg(nesdev, phy_index, 0x3, 0xe854, 0x00c0);
nes_write_10G_phy_reg(nesdev, phy_index, 0x3, 0xe854, 0x0040);
continue;
} else {
ret = 1;
break;
}
}
mdelay(10);
} while ((temp_phy_data & 0xff) < 0x30);
/* setup signal integrity */
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xd003, 0x0000);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xF00D, 0x00FE);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xF00E, 0x0032);
if (phy_type == NES_PHY_TYPE_KR) {
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xF00F, 0x000C);
} else {
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xF00F, 0x0002);
nes_write_10G_phy_reg(nesdev, phy_index, 0x1, 0xc314, 0x0063);
}
/* reset serdes */
sds = nes_read_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL0 + mac_index * 0x200);
sds |= 0x1;
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL0 + mac_index * 0x200, sds);
sds &= 0xfffffffe;
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL0 + mac_index * 0x200, sds);
counter = 0;
while (((nes_read32(nesdev->regs + NES_SOFTWARE_RESET) & 0x00000040) != 0x00000040)
&& (counter++ < 5000))
;
return ret;
}
/**
* nes_init_phy
*/
int nes_init_phy(struct nes_device *nesdev)
{
struct nes_adapter *nesadapter = nesdev->nesadapter;
u32 mac_index = nesdev->mac_index;
u32 tx_config = 0;
unsigned long flags;
u8 phy_type = nesadapter->phy_type[mac_index];
u8 phy_index = nesadapter->phy_index[mac_index];
int ret = 0;
tx_config = nes_read_indexed(nesdev, NES_IDX_MAC_TX_CONFIG);
if (phy_type == NES_PHY_TYPE_1G) {
/* setup 1G MDIO operation */
tx_config &= 0xFFFFFFE3;
tx_config |= 0x04;
} else {
/* setup 10G MDIO operation */
tx_config &= 0xFFFFFFE3;
tx_config |= 0x1D;
}
nes_write_indexed(nesdev, NES_IDX_MAC_TX_CONFIG, tx_config);
spin_lock_irqsave(&nesdev->nesadapter->phy_lock, flags);
switch (phy_type) {
case NES_PHY_TYPE_1G:
ret = nes_init_1g_phy(nesdev, phy_type, phy_index);
break;
case NES_PHY_TYPE_ARGUS:
case NES_PHY_TYPE_SFP_D:
case NES_PHY_TYPE_KR:
ret = nes_init_2025_phy(nesdev, phy_type, phy_index);
break;
}
spin_unlock_irqrestore(&nesdev->nesadapter->phy_lock, flags);
return ret;
}
/**
* nes_replenish_nic_rq
*/
static void nes_replenish_nic_rq(struct nes_vnic *nesvnic)
{
unsigned long flags;
dma_addr_t bus_address;
struct sk_buff *skb;
struct nes_hw_nic_rq_wqe *nic_rqe;
struct nes_hw_nic *nesnic;
struct nes_device *nesdev;
struct nes_rskb_cb *cb;
u32 rx_wqes_posted = 0;
nesnic = &nesvnic->nic;
nesdev = nesvnic->nesdev;
spin_lock_irqsave(&nesnic->rq_lock, flags);
if (nesnic->replenishing_rq !=0) {
if (((nesnic->rq_size-1) == atomic_read(&nesvnic->rx_skbs_needed)) &&
(atomic_read(&nesvnic->rx_skb_timer_running) == 0)) {
atomic_set(&nesvnic->rx_skb_timer_running, 1);
spin_unlock_irqrestore(&nesnic->rq_lock, flags);
nesvnic->rq_wqes_timer.expires = jiffies + (HZ/2); /* 1/2 second */
add_timer(&nesvnic->rq_wqes_timer);
} else
spin_unlock_irqrestore(&nesnic->rq_lock, flags);
return;
}
nesnic->replenishing_rq = 1;
spin_unlock_irqrestore(&nesnic->rq_lock, flags);
do {
skb = dev_alloc_skb(nesvnic->max_frame_size);
if (skb) {
skb->dev = nesvnic->netdev;
bus_address = pci_map_single(nesdev->pcidev,
skb->data, nesvnic->max_frame_size, PCI_DMA_FROMDEVICE);
cb = (struct nes_rskb_cb *)&skb->cb[0];
cb->busaddr = bus_address;
cb->maplen = nesvnic->max_frame_size;
nic_rqe = &nesnic->rq_vbase[nesvnic->nic.rq_head];
nic_rqe->wqe_words[NES_NIC_RQ_WQE_LENGTH_1_0_IDX] =
cpu_to_le32(nesvnic->max_frame_size);
nic_rqe->wqe_words[NES_NIC_RQ_WQE_LENGTH_3_2_IDX] = 0;
nic_rqe->wqe_words[NES_NIC_RQ_WQE_FRAG0_LOW_IDX] =
cpu_to_le32((u32)bus_address);
nic_rqe->wqe_words[NES_NIC_RQ_WQE_FRAG0_HIGH_IDX] =
cpu_to_le32((u32)((u64)bus_address >> 32));
nesnic->rx_skb[nesnic->rq_head] = skb;
nesnic->rq_head++;
nesnic->rq_head &= nesnic->rq_size - 1;
atomic_dec(&nesvnic->rx_skbs_needed);
barrier();
if (++rx_wqes_posted == 255) {
nes_write32(nesdev->regs+NES_WQE_ALLOC, (rx_wqes_posted << 24) | nesnic->qp_id);
rx_wqes_posted = 0;
}
} else {
spin_lock_irqsave(&nesnic->rq_lock, flags);
if (((nesnic->rq_size-1) == atomic_read(&nesvnic->rx_skbs_needed)) &&
(atomic_read(&nesvnic->rx_skb_timer_running) == 0)) {
atomic_set(&nesvnic->rx_skb_timer_running, 1);
spin_unlock_irqrestore(&nesnic->rq_lock, flags);
nesvnic->rq_wqes_timer.expires = jiffies + (HZ/2); /* 1/2 second */
add_timer(&nesvnic->rq_wqes_timer);
} else
spin_unlock_irqrestore(&nesnic->rq_lock, flags);
break;
}
} while (atomic_read(&nesvnic->rx_skbs_needed));
barrier();
if (rx_wqes_posted)
nes_write32(nesdev->regs+NES_WQE_ALLOC, (rx_wqes_posted << 24) | nesnic->qp_id);
nesnic->replenishing_rq = 0;
}
/**
* nes_rq_wqes_timeout
*/
static void nes_rq_wqes_timeout(unsigned long parm)
{
struct nes_vnic *nesvnic = (struct nes_vnic *)parm;
printk("%s: Timer fired.\n", __func__);
atomic_set(&nesvnic->rx_skb_timer_running, 0);
if (atomic_read(&nesvnic->rx_skbs_needed))
nes_replenish_nic_rq(nesvnic);
}
static int nes_lro_get_skb_hdr(struct sk_buff *skb, void **iphdr,
void **tcph, u64 *hdr_flags, void *priv)
{
unsigned int ip_len;
struct iphdr *iph;
skb_reset_network_header(skb);
iph = ip_hdr(skb);
if (iph->protocol != IPPROTO_TCP)
return -1;
ip_len = ip_hdrlen(skb);
skb_set_transport_header(skb, ip_len);
*tcph = tcp_hdr(skb);
*hdr_flags = LRO_IPV4 | LRO_TCP;
*iphdr = iph;
return 0;
}
/**
* nes_init_nic_qp
*/
int nes_init_nic_qp(struct nes_device *nesdev, struct net_device *netdev)
{
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_hw_nic_sq_wqe *nic_sqe;
struct nes_hw_nic_qp_context *nic_context;
struct sk_buff *skb;
struct nes_hw_nic_rq_wqe *nic_rqe;
struct nes_vnic *nesvnic = netdev_priv(netdev);
unsigned long flags;
void *vmem;
dma_addr_t pmem;
u64 u64temp;
int ret;
u32 cqp_head;
u32 counter;
u32 wqe_count;
struct nes_rskb_cb *cb;
u8 jumbomode=0;
/* Allocate fragment, SQ, RQ, and CQ; Reuse CEQ based on the PCI function */
nesvnic->nic_mem_size = 256 +
(NES_NIC_WQ_SIZE * sizeof(struct nes_first_frag)) +
(NES_NIC_WQ_SIZE * sizeof(struct nes_hw_nic_sq_wqe)) +
(NES_NIC_WQ_SIZE * sizeof(struct nes_hw_nic_rq_wqe)) +
(NES_NIC_WQ_SIZE * 2 * sizeof(struct nes_hw_nic_cqe)) +
sizeof(struct nes_hw_nic_qp_context);
nesvnic->nic_vbase = pci_zalloc_consistent(nesdev->pcidev,
nesvnic->nic_mem_size,
&nesvnic->nic_pbase);
if (!nesvnic->nic_vbase) {
nes_debug(NES_DBG_INIT, "Unable to allocate memory for NIC host descriptor rings\n");
return -ENOMEM;
}
nes_debug(NES_DBG_INIT, "Allocated NIC QP structures at %p (phys = %016lX), size = %u.\n",
nesvnic->nic_vbase, (unsigned long)nesvnic->nic_pbase, nesvnic->nic_mem_size);
vmem = (void *)(((unsigned long)nesvnic->nic_vbase + (256 - 1)) &
~(unsigned long)(256 - 1));
pmem = (dma_addr_t)(((unsigned long long)nesvnic->nic_pbase + (256 - 1)) &
~(unsigned long long)(256 - 1));
/* Setup the first Fragment buffers */
nesvnic->nic.first_frag_vbase = vmem;
for (counter = 0; counter < NES_NIC_WQ_SIZE; counter++) {
nesvnic->nic.frag_paddr[counter] = pmem;
pmem += sizeof(struct nes_first_frag);
}
/* setup the SQ */
vmem += (NES_NIC_WQ_SIZE * sizeof(struct nes_first_frag));
nesvnic->nic.sq_vbase = (void *)vmem;
nesvnic->nic.sq_pbase = pmem;
nesvnic->nic.sq_head = 0;
nesvnic->nic.sq_tail = 0;
nesvnic->nic.sq_size = NES_NIC_WQ_SIZE;
for (counter = 0; counter < NES_NIC_WQ_SIZE; counter++) {
nic_sqe = &nesvnic->nic.sq_vbase[counter];
nic_sqe->wqe_words[NES_NIC_SQ_WQE_MISC_IDX] =
cpu_to_le32(NES_NIC_SQ_WQE_DISABLE_CHKSUM |
NES_NIC_SQ_WQE_COMPLETION);
nic_sqe->wqe_words[NES_NIC_SQ_WQE_LENGTH_0_TAG_IDX] =
cpu_to_le32((u32)NES_FIRST_FRAG_SIZE << 16);
nic_sqe->wqe_words[NES_NIC_SQ_WQE_FRAG0_LOW_IDX] =
cpu_to_le32((u32)nesvnic->nic.frag_paddr[counter]);
nic_sqe->wqe_words[NES_NIC_SQ_WQE_FRAG0_HIGH_IDX] =
cpu_to_le32((u32)((u64)nesvnic->nic.frag_paddr[counter] >> 32));
}
nesvnic->get_cqp_request = nes_get_cqp_request;
nesvnic->post_cqp_request = nes_post_cqp_request;
nesvnic->mcrq_mcast_filter = NULL;
spin_lock_init(&nesvnic->nic.rq_lock);
/* setup the RQ */
vmem += (NES_NIC_WQ_SIZE * sizeof(struct nes_hw_nic_sq_wqe));
pmem += (NES_NIC_WQ_SIZE * sizeof(struct nes_hw_nic_sq_wqe));
nesvnic->nic.rq_vbase = vmem;
nesvnic->nic.rq_pbase = pmem;
nesvnic->nic.rq_head = 0;
nesvnic->nic.rq_tail = 0;
nesvnic->nic.rq_size = NES_NIC_WQ_SIZE;
/* setup the CQ */
vmem += (NES_NIC_WQ_SIZE * sizeof(struct nes_hw_nic_rq_wqe));
pmem += (NES_NIC_WQ_SIZE * sizeof(struct nes_hw_nic_rq_wqe));
if (nesdev->nesadapter->netdev_count > 2)
nesvnic->mcrq_qp_id = nesvnic->nic_index + 32;
else
nesvnic->mcrq_qp_id = nesvnic->nic.qp_id + 4;
nesvnic->nic_cq.cq_vbase = vmem;
nesvnic->nic_cq.cq_pbase = pmem;
nesvnic->nic_cq.cq_head = 0;
nesvnic->nic_cq.cq_size = NES_NIC_WQ_SIZE * 2;
nesvnic->nic_cq.ce_handler = nes_nic_napi_ce_handler;
/* Send CreateCQ request to CQP */
spin_lock_irqsave(&nesdev->cqp.lock, flags);
cqp_head = nesdev->cqp.sq_head;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] = cpu_to_le32(
NES_CQP_CREATE_CQ | NES_CQP_CQ_CEQ_VALID |
((u32)nesvnic->nic_cq.cq_size << 16));
cqp_wqe->wqe_words[NES_CQP_WQE_ID_IDX] = cpu_to_le32(
nesvnic->nic_cq.cq_number | ((u32)nesdev->nic_ceq_index << 16));
u64temp = (u64)nesvnic->nic_cq.cq_pbase;
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_CQ_WQE_PBL_LOW_IDX, u64temp);
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_CQ_CONTEXT_HIGH_IDX] = 0;
u64temp = (unsigned long)&nesvnic->nic_cq;
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_CQ_CONTEXT_LOW_IDX] = cpu_to_le32((u32)(u64temp >> 1));
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_CQ_CONTEXT_HIGH_IDX] =
cpu_to_le32(((u32)((u64temp) >> 33)) & 0x7FFFFFFF);
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_DOORBELL_INDEX_HIGH_IDX] = 0;
if (++cqp_head >= nesdev->cqp.sq_size)
cqp_head = 0;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
/* Send CreateQP request to CQP */
nic_context = (void *)(&nesvnic->nic_cq.cq_vbase[nesvnic->nic_cq.cq_size]);
nic_context->context_words[NES_NIC_CTX_MISC_IDX] =
cpu_to_le32((u32)NES_NIC_CTX_SIZE |
((u32)PCI_FUNC(nesdev->pcidev->devfn) << 12));
nes_debug(NES_DBG_INIT, "RX_WINDOW_BUFFER_PAGE_TABLE_SIZE = 0x%08X, RX_WINDOW_BUFFER_SIZE = 0x%08X\n",
nes_read_indexed(nesdev, NES_IDX_RX_WINDOW_BUFFER_PAGE_TABLE_SIZE),
nes_read_indexed(nesdev, NES_IDX_RX_WINDOW_BUFFER_SIZE));
if (nes_read_indexed(nesdev, NES_IDX_RX_WINDOW_BUFFER_SIZE) != 0) {
nic_context->context_words[NES_NIC_CTX_MISC_IDX] |= cpu_to_le32(NES_NIC_BACK_STORE);
}
u64temp = (u64)nesvnic->nic.sq_pbase;
nic_context->context_words[NES_NIC_CTX_SQ_LOW_IDX] = cpu_to_le32((u32)u64temp);
nic_context->context_words[NES_NIC_CTX_SQ_HIGH_IDX] = cpu_to_le32((u32)(u64temp >> 32));
u64temp = (u64)nesvnic->nic.rq_pbase;
nic_context->context_words[NES_NIC_CTX_RQ_LOW_IDX] = cpu_to_le32((u32)u64temp);
nic_context->context_words[NES_NIC_CTX_RQ_HIGH_IDX] = cpu_to_le32((u32)(u64temp >> 32));
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] = cpu_to_le32(NES_CQP_CREATE_QP |
NES_CQP_QP_TYPE_NIC);
cqp_wqe->wqe_words[NES_CQP_WQE_ID_IDX] = cpu_to_le32(nesvnic->nic.qp_id);
u64temp = (u64)nesvnic->nic_cq.cq_pbase +
(nesvnic->nic_cq.cq_size * sizeof(struct nes_hw_nic_cqe));
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_QP_WQE_CONTEXT_LOW_IDX, u64temp);
if (++cqp_head >= nesdev->cqp.sq_size)
cqp_head = 0;
nesdev->cqp.sq_head = cqp_head;
barrier();
/* Ring doorbell (2 WQEs) */
nes_write32(nesdev->regs+NES_WQE_ALLOC, 0x02800000 | nesdev->cqp.qp_id);
spin_unlock_irqrestore(&nesdev->cqp.lock, flags);
nes_debug(NES_DBG_INIT, "Waiting for create NIC QP%u to complete.\n",
nesvnic->nic.qp_id);
ret = wait_event_timeout(nesdev->cqp.waitq, (nesdev->cqp.sq_tail == cqp_head),
NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_INIT, "Create NIC QP%u completed, wait_event_timeout ret = %u.\n",
nesvnic->nic.qp_id, ret);
if (!ret) {
nes_debug(NES_DBG_INIT, "NIC QP%u create timeout expired\n", nesvnic->nic.qp_id);
pci_free_consistent(nesdev->pcidev, nesvnic->nic_mem_size, nesvnic->nic_vbase,
nesvnic->nic_pbase);
return -EIO;
}
/* Populate the RQ */
for (counter = 0; counter < (NES_NIC_WQ_SIZE - 1); counter++) {
skb = dev_alloc_skb(nesvnic->max_frame_size);
if (!skb) {
nes_debug(NES_DBG_INIT, "%s: out of memory for receive skb\n", netdev->name);
nes_destroy_nic_qp(nesvnic);
return -ENOMEM;
}
skb->dev = netdev;
pmem = pci_map_single(nesdev->pcidev, skb->data,
nesvnic->max_frame_size, PCI_DMA_FROMDEVICE);
cb = (struct nes_rskb_cb *)&skb->cb[0];
cb->busaddr = pmem;
cb->maplen = nesvnic->max_frame_size;
nic_rqe = &nesvnic->nic.rq_vbase[counter];
nic_rqe->wqe_words[NES_NIC_RQ_WQE_LENGTH_1_0_IDX] = cpu_to_le32(nesvnic->max_frame_size);
nic_rqe->wqe_words[NES_NIC_RQ_WQE_LENGTH_3_2_IDX] = 0;
nic_rqe->wqe_words[NES_NIC_RQ_WQE_FRAG0_LOW_IDX] = cpu_to_le32((u32)pmem);
nic_rqe->wqe_words[NES_NIC_RQ_WQE_FRAG0_HIGH_IDX] = cpu_to_le32((u32)((u64)pmem >> 32));
nesvnic->nic.rx_skb[counter] = skb;
}
wqe_count = NES_NIC_WQ_SIZE - 1;
nesvnic->nic.rq_head = wqe_count;
barrier();
do {
counter = min(wqe_count, ((u32)255));
wqe_count -= counter;
nes_write32(nesdev->regs+NES_WQE_ALLOC, (counter << 24) | nesvnic->nic.qp_id);
} while (wqe_count);
init_timer(&nesvnic->rq_wqes_timer);
nesvnic->rq_wqes_timer.function = nes_rq_wqes_timeout;
nesvnic->rq_wqes_timer.data = (unsigned long)nesvnic;
nes_debug(NES_DBG_INIT, "NAPI support Enabled\n");
if (nesdev->nesadapter->et_use_adaptive_rx_coalesce)
{
nes_nic_init_timer(nesdev);
if (netdev->mtu > 1500)
jumbomode = 1;
nes_nic_init_timer_defaults(nesdev, jumbomode);
}
if ((nesdev->nesadapter->allow_unaligned_fpdus) &&
(nes_init_mgt_qp(nesdev, netdev, nesvnic))) {
nes_debug(NES_DBG_INIT, "%s: Out of memory for pau nic\n", netdev->name);
nes_destroy_nic_qp(nesvnic);
return -ENOMEM;
}
nesvnic->lro_mgr.max_aggr = nes_lro_max_aggr;
nesvnic->lro_mgr.max_desc = NES_MAX_LRO_DESCRIPTORS;
nesvnic->lro_mgr.lro_arr = nesvnic->lro_desc;
nesvnic->lro_mgr.get_skb_header = nes_lro_get_skb_hdr;
nesvnic->lro_mgr.features = LRO_F_NAPI | LRO_F_EXTRACT_VLAN_ID;
nesvnic->lro_mgr.dev = netdev;
nesvnic->lro_mgr.ip_summed = CHECKSUM_UNNECESSARY;
nesvnic->lro_mgr.ip_summed_aggr = CHECKSUM_UNNECESSARY;
return 0;
}
/**
* nes_destroy_nic_qp
*/
void nes_destroy_nic_qp(struct nes_vnic *nesvnic)
{
u64 u64temp;
dma_addr_t bus_address;
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_hw_nic_sq_wqe *nic_sqe;
__le16 *wqe_fragment_length;
u16 wqe_fragment_index;
u32 cqp_head;
u32 wqm_cfg0;
unsigned long flags;
struct sk_buff *rx_skb;
struct nes_rskb_cb *cb;
int ret;
if (nesdev->nesadapter->allow_unaligned_fpdus)
nes_destroy_mgt(nesvnic);
/* clear wqe stall before destroying NIC QP */
wqm_cfg0 = nes_read_indexed(nesdev, NES_IDX_WQM_CONFIG0);
nes_write_indexed(nesdev, NES_IDX_WQM_CONFIG0, wqm_cfg0 & 0xFFFF7FFF);
/* Free remaining NIC receive buffers */
while (nesvnic->nic.rq_head != nesvnic->nic.rq_tail) {
rx_skb = nesvnic->nic.rx_skb[nesvnic->nic.rq_tail];
cb = (struct nes_rskb_cb *)&rx_skb->cb[0];
pci_unmap_single(nesdev->pcidev, cb->busaddr, cb->maplen,
PCI_DMA_FROMDEVICE);
dev_kfree_skb(nesvnic->nic.rx_skb[nesvnic->nic.rq_tail++]);
nesvnic->nic.rq_tail &= (nesvnic->nic.rq_size - 1);
}
/* Free remaining NIC transmit buffers */
while (nesvnic->nic.sq_head != nesvnic->nic.sq_tail) {
nic_sqe = &nesvnic->nic.sq_vbase[nesvnic->nic.sq_tail];
wqe_fragment_index = 1;
wqe_fragment_length = (__le16 *)
&nic_sqe->wqe_words[NES_NIC_SQ_WQE_LENGTH_0_TAG_IDX];
/* bump past the vlan tag */
wqe_fragment_length++;
if (le16_to_cpu(wqe_fragment_length[wqe_fragment_index]) != 0) {
u64temp = (u64)le32_to_cpu(
nic_sqe->wqe_words[NES_NIC_SQ_WQE_FRAG0_LOW_IDX+
wqe_fragment_index*2]);
u64temp += ((u64)le32_to_cpu(
nic_sqe->wqe_words[NES_NIC_SQ_WQE_FRAG0_HIGH_IDX
+ wqe_fragment_index*2]))<<32;
bus_address = (dma_addr_t)u64temp;
if (test_and_clear_bit(nesvnic->nic.sq_tail,
nesvnic->nic.first_frag_overflow)) {
pci_unmap_single(nesdev->pcidev,
bus_address,
le16_to_cpu(wqe_fragment_length[
wqe_fragment_index++]),
PCI_DMA_TODEVICE);
}
for (; wqe_fragment_index < 5; wqe_fragment_index++) {
if (wqe_fragment_length[wqe_fragment_index]) {
u64temp = le32_to_cpu(
nic_sqe->wqe_words[
NES_NIC_SQ_WQE_FRAG0_LOW_IDX+
wqe_fragment_index*2]);
u64temp += ((u64)le32_to_cpu(
nic_sqe->wqe_words[
NES_NIC_SQ_WQE_FRAG0_HIGH_IDX+
wqe_fragment_index*2]))<<32;
bus_address = (dma_addr_t)u64temp;
pci_unmap_page(nesdev->pcidev,
bus_address,
le16_to_cpu(
wqe_fragment_length[
wqe_fragment_index]),
PCI_DMA_TODEVICE);
} else
break;
}
}
if (nesvnic->nic.tx_skb[nesvnic->nic.sq_tail])
dev_kfree_skb(
nesvnic->nic.tx_skb[nesvnic->nic.sq_tail]);
nesvnic->nic.sq_tail = (nesvnic->nic.sq_tail + 1)
& (nesvnic->nic.sq_size - 1);
}
spin_lock_irqsave(&nesdev->cqp.lock, flags);
/* Destroy NIC QP */
cqp_head = nesdev->cqp.sq_head;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX,
(NES_CQP_DESTROY_QP | NES_CQP_QP_TYPE_NIC));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_ID_IDX,
nesvnic->nic.qp_id);
if (++cqp_head >= nesdev->cqp.sq_size)
cqp_head = 0;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
/* Destroy NIC CQ */
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX,
(NES_CQP_DESTROY_CQ | ((u32)nesvnic->nic_cq.cq_size << 16)));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_ID_IDX,
(nesvnic->nic_cq.cq_number | ((u32)nesdev->nic_ceq_index << 16)));
if (++cqp_head >= nesdev->cqp.sq_size)
cqp_head = 0;
nesdev->cqp.sq_head = cqp_head;
barrier();
/* Ring doorbell (2 WQEs) */
nes_write32(nesdev->regs+NES_WQE_ALLOC, 0x02800000 | nesdev->cqp.qp_id);
spin_unlock_irqrestore(&nesdev->cqp.lock, flags);
nes_debug(NES_DBG_SHUTDOWN, "Waiting for CQP, cqp_head=%u, cqp.sq_head=%u,"
" cqp.sq_tail=%u, cqp.sq_size=%u\n",
cqp_head, nesdev->cqp.sq_head,
nesdev->cqp.sq_tail, nesdev->cqp.sq_size);
ret = wait_event_timeout(nesdev->cqp.waitq, (nesdev->cqp.sq_tail == cqp_head),
NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_SHUTDOWN, "Destroy NIC QP returned, wait_event_timeout ret = %u, cqp_head=%u,"
" cqp.sq_head=%u, cqp.sq_tail=%u\n",
ret, cqp_head, nesdev->cqp.sq_head, nesdev->cqp.sq_tail);
if (!ret) {
nes_debug(NES_DBG_SHUTDOWN, "NIC QP%u destroy timeout expired\n",
nesvnic->nic.qp_id);
}
pci_free_consistent(nesdev->pcidev, nesvnic->nic_mem_size, nesvnic->nic_vbase,
nesvnic->nic_pbase);
/* restore old wqm_cfg0 value */
nes_write_indexed(nesdev, NES_IDX_WQM_CONFIG0, wqm_cfg0);
}
/**
* nes_napi_isr
*/
int nes_napi_isr(struct nes_device *nesdev)
{
struct nes_adapter *nesadapter = nesdev->nesadapter;
u32 int_stat;
if (nesdev->napi_isr_ran) {
/* interrupt status has already been read in ISR */
int_stat = nesdev->int_stat;
} else {
int_stat = nes_read32(nesdev->regs + NES_INT_STAT);
nesdev->int_stat = int_stat;
nesdev->napi_isr_ran = 1;
}
int_stat &= nesdev->int_req;
/* iff NIC, process here, else wait for DPC */
if ((int_stat) && ((int_stat & 0x0000ff00) == int_stat)) {
nesdev->napi_isr_ran = 0;
nes_write32(nesdev->regs + NES_INT_STAT,
(int_stat &
~(NES_INT_INTF | NES_INT_TIMER | NES_INT_MAC0 | NES_INT_MAC1 | NES_INT_MAC2 | NES_INT_MAC3)));
/* Process the CEQs */
nes_process_ceq(nesdev, &nesdev->nesadapter->ceq[nesdev->nic_ceq_index]);
if (unlikely((((nesadapter->et_rx_coalesce_usecs_irq) &&
(!nesadapter->et_use_adaptive_rx_coalesce)) ||
((nesadapter->et_use_adaptive_rx_coalesce) &&
(nesdev->deepcq_count > nesadapter->et_pkt_rate_low))))) {
if ((nesdev->int_req & NES_INT_TIMER) == 0) {
/* Enable Periodic timer interrupts */
nesdev->int_req |= NES_INT_TIMER;
/* ack any pending periodic timer interrupts so we don't get an immediate interrupt */
/* TODO: need to also ack other unused periodic timer values, get from nesadapter */
nes_write32(nesdev->regs+NES_TIMER_STAT,
nesdev->timer_int_req | ~(nesdev->nesadapter->timer_int_req));
nes_write32(nesdev->regs+NES_INTF_INT_MASK,
~(nesdev->intf_int_req | NES_INTF_PERIODIC_TIMER));
}
if (unlikely(nesadapter->et_use_adaptive_rx_coalesce))
{
nes_nic_init_timer(nesdev);
}
/* Enable interrupts, except CEQs */
nes_write32(nesdev->regs+NES_INT_MASK, 0x0000ffff | (~nesdev->int_req));
} else {
/* Enable interrupts, make sure timer is off */
nesdev->int_req &= ~NES_INT_TIMER;
nes_write32(nesdev->regs+NES_INTF_INT_MASK, ~(nesdev->intf_int_req));
nes_write32(nesdev->regs+NES_INT_MASK, ~nesdev->int_req);
}
nesdev->deepcq_count = 0;
return 1;
} else {
return 0;
}
}
static void process_critical_error(struct nes_device *nesdev)
{
u32 debug_error;
u32 nes_idx_debug_error_masks0 = 0;
u16 error_module = 0;
debug_error = nes_read_indexed(nesdev, NES_IDX_DEBUG_ERROR_CONTROL_STATUS);
printk(KERN_ERR PFX "Critical Error reported by device!!! 0x%02X\n",
(u16)debug_error);
nes_write_indexed(nesdev, NES_IDX_DEBUG_ERROR_CONTROL_STATUS,
0x01010000 | (debug_error & 0x0000ffff));
if (crit_err_count++ > 10)
nes_write_indexed(nesdev, NES_IDX_DEBUG_ERROR_MASKS1, 1 << 0x17);
error_module = (u16) (debug_error & 0x1F00) >> 8;
if (++nesdev->nesadapter->crit_error_count[error_module-1] >=
nes_max_critical_error_count) {
printk(KERN_ERR PFX "Masking off critical error for module "
"0x%02X\n", (u16)error_module);
nes_idx_debug_error_masks0 = nes_read_indexed(nesdev,
NES_IDX_DEBUG_ERROR_MASKS0);
nes_write_indexed(nesdev, NES_IDX_DEBUG_ERROR_MASKS0,
nes_idx_debug_error_masks0 | (1 << error_module));
}
}
/**
* nes_dpc
*/
void nes_dpc(unsigned long param)
{
struct nes_device *nesdev = (struct nes_device *)param;
struct nes_adapter *nesadapter = nesdev->nesadapter;
u32 counter;
u32 loop_counter = 0;
u32 int_status_bit;
u32 int_stat;
u32 timer_stat;
u32 temp_int_stat;
u32 intf_int_stat;
u32 processed_intf_int = 0;
u16 processed_timer_int = 0;
u16 completion_ints = 0;
u16 timer_ints = 0;
/* nes_debug(NES_DBG_ISR, "\n"); */
do {
timer_stat = 0;
if (nesdev->napi_isr_ran) {
nesdev->napi_isr_ran = 0;
int_stat = nesdev->int_stat;
} else
int_stat = nes_read32(nesdev->regs+NES_INT_STAT);
if (processed_intf_int != 0)
int_stat &= nesdev->int_req & ~NES_INT_INTF;
else
int_stat &= nesdev->int_req;
if (processed_timer_int == 0) {
processed_timer_int = 1;
if (int_stat & NES_INT_TIMER) {
timer_stat = nes_read32(nesdev->regs + NES_TIMER_STAT);
if ((timer_stat & nesdev->timer_int_req) == 0) {
int_stat &= ~NES_INT_TIMER;
}
}
} else {
int_stat &= ~NES_INT_TIMER;
}
if (int_stat) {
if (int_stat & ~(NES_INT_INTF | NES_INT_TIMER | NES_INT_MAC0|
NES_INT_MAC1|NES_INT_MAC2 | NES_INT_MAC3)) {
/* Ack the interrupts */
nes_write32(nesdev->regs+NES_INT_STAT,
(int_stat & ~(NES_INT_INTF | NES_INT_TIMER | NES_INT_MAC0|
NES_INT_MAC1 | NES_INT_MAC2 | NES_INT_MAC3)));
}
temp_int_stat = int_stat;
for (counter = 0, int_status_bit = 1; counter < 16; counter++) {
if (int_stat & int_status_bit) {
nes_process_ceq(nesdev, &nesadapter->ceq[counter]);
temp_int_stat &= ~int_status_bit;
completion_ints = 1;
}
if (!(temp_int_stat & 0x0000ffff))
break;
int_status_bit <<= 1;
}
/* Process the AEQ for this pci function */
int_status_bit = 1 << (16 + PCI_FUNC(nesdev->pcidev->devfn));
if (int_stat & int_status_bit) {
nes_process_aeq(nesdev, &nesadapter->aeq[PCI_FUNC(nesdev->pcidev->devfn)]);
}
/* Process the MAC interrupt for this pci function */
int_status_bit = 1 << (24 + nesdev->mac_index);
if (int_stat & int_status_bit) {
nes_process_mac_intr(nesdev, nesdev->mac_index);
}
if (int_stat & NES_INT_TIMER) {
if (timer_stat & nesdev->timer_int_req) {
nes_write32(nesdev->regs + NES_TIMER_STAT,
(timer_stat & nesdev->timer_int_req) |
~(nesdev->nesadapter->timer_int_req));
timer_ints = 1;
}
}
if (int_stat & NES_INT_INTF) {
processed_intf_int = 1;
intf_int_stat = nes_read32(nesdev->regs+NES_INTF_INT_STAT);
intf_int_stat &= nesdev->intf_int_req;
if (NES_INTF_INT_CRITERR & intf_int_stat) {
process_critical_error(nesdev);
}
if (NES_INTF_INT_PCIERR & intf_int_stat) {
printk(KERN_ERR PFX "PCI Error reported by device!!!\n");
BUG();
}
if (NES_INTF_INT_AEQ_OFLOW & intf_int_stat) {
printk(KERN_ERR PFX "AEQ Overflow reported by device!!!\n");
BUG();
}
nes_write32(nesdev->regs+NES_INTF_INT_STAT, intf_int_stat);
}
if (int_stat & NES_INT_TSW) {
}
}
/* Don't use the interface interrupt bit stay in loop */
int_stat &= ~NES_INT_INTF | NES_INT_TIMER | NES_INT_MAC0 |
NES_INT_MAC1 | NES_INT_MAC2 | NES_INT_MAC3;
} while ((int_stat != 0) && (loop_counter++ < MAX_DPC_ITERATIONS));
if (timer_ints == 1) {
if ((nesadapter->et_rx_coalesce_usecs_irq) || (nesadapter->et_use_adaptive_rx_coalesce)) {
if (completion_ints == 0) {
nesdev->timer_only_int_count++;
if (nesdev->timer_only_int_count>=nesadapter->timer_int_limit) {
nesdev->timer_only_int_count = 0;
nesdev->int_req &= ~NES_INT_TIMER;
nes_write32(nesdev->regs + NES_INTF_INT_MASK, ~(nesdev->intf_int_req));
nes_write32(nesdev->regs + NES_INT_MASK, ~nesdev->int_req);
} else {
nes_write32(nesdev->regs+NES_INT_MASK, 0x0000ffff | (~nesdev->int_req));
}
} else {
if (unlikely(nesadapter->et_use_adaptive_rx_coalesce))
{
nes_nic_init_timer(nesdev);
}
nesdev->timer_only_int_count = 0;
nes_write32(nesdev->regs+NES_INT_MASK, 0x0000ffff | (~nesdev->int_req));
}
} else {
nesdev->timer_only_int_count = 0;
nesdev->int_req &= ~NES_INT_TIMER;
nes_write32(nesdev->regs+NES_INTF_INT_MASK, ~(nesdev->intf_int_req));
nes_write32(nesdev->regs+NES_TIMER_STAT,
nesdev->timer_int_req | ~(nesdev->nesadapter->timer_int_req));
nes_write32(nesdev->regs+NES_INT_MASK, ~nesdev->int_req);
}
} else {
if ( (completion_ints == 1) &&
(((nesadapter->et_rx_coalesce_usecs_irq) &&
(!nesadapter->et_use_adaptive_rx_coalesce)) ||
((nesdev->deepcq_count > nesadapter->et_pkt_rate_low) &&
(nesadapter->et_use_adaptive_rx_coalesce) )) ) {
/* nes_debug(NES_DBG_ISR, "Enabling periodic timer interrupt.\n" ); */
nesdev->timer_only_int_count = 0;
nesdev->int_req |= NES_INT_TIMER;
nes_write32(nesdev->regs+NES_TIMER_STAT,
nesdev->timer_int_req | ~(nesdev->nesadapter->timer_int_req));
nes_write32(nesdev->regs+NES_INTF_INT_MASK,
~(nesdev->intf_int_req | NES_INTF_PERIODIC_TIMER));
nes_write32(nesdev->regs+NES_INT_MASK, 0x0000ffff | (~nesdev->int_req));
} else {
nes_write32(nesdev->regs+NES_INT_MASK, ~nesdev->int_req);
}
}
nesdev->deepcq_count = 0;
}
/**
* nes_process_ceq
*/
static void nes_process_ceq(struct nes_device *nesdev, struct nes_hw_ceq *ceq)
{
u64 u64temp;
struct nes_hw_cq *cq;
u32 head;
u32 ceq_size;
/* nes_debug(NES_DBG_CQ, "\n"); */
head = ceq->ceq_head;
ceq_size = ceq->ceq_size;
do {
if (le32_to_cpu(ceq->ceq_vbase[head].ceqe_words[NES_CEQE_CQ_CTX_HIGH_IDX]) &
NES_CEQE_VALID) {
u64temp = (((u64)(le32_to_cpu(ceq->ceq_vbase[head].ceqe_words[NES_CEQE_CQ_CTX_HIGH_IDX]))) << 32) |
((u64)(le32_to_cpu(ceq->ceq_vbase[head].ceqe_words[NES_CEQE_CQ_CTX_LOW_IDX])));
u64temp <<= 1;
cq = *((struct nes_hw_cq **)&u64temp);
/* nes_debug(NES_DBG_CQ, "pCQ = %p\n", cq); */
barrier();
ceq->ceq_vbase[head].ceqe_words[NES_CEQE_CQ_CTX_HIGH_IDX] = 0;
/* call the event handler */
cq->ce_handler(nesdev, cq);
if (++head >= ceq_size)
head = 0;
} else {
break;
}
} while (1);
ceq->ceq_head = head;
}
/**
* nes_process_aeq
*/
static void nes_process_aeq(struct nes_device *nesdev, struct nes_hw_aeq *aeq)
{
/* u64 u64temp; */
u32 head;
u32 aeq_size;
u32 aeqe_misc;
u32 aeqe_cq_id;
struct nes_hw_aeqe volatile *aeqe;
head = aeq->aeq_head;
aeq_size = aeq->aeq_size;
do {
aeqe = &aeq->aeq_vbase[head];
if ((le32_to_cpu(aeqe->aeqe_words[NES_AEQE_MISC_IDX]) & NES_AEQE_VALID) == 0)
break;
aeqe_misc = le32_to_cpu(aeqe->aeqe_words[NES_AEQE_MISC_IDX]);
aeqe_cq_id = le32_to_cpu(aeqe->aeqe_words[NES_AEQE_COMP_QP_CQ_ID_IDX]);
if (aeqe_misc & (NES_AEQE_QP|NES_AEQE_CQ)) {
if (aeqe_cq_id >= NES_FIRST_QPN) {
/* dealing with an accelerated QP related AE */
/*
* u64temp = (((u64)(le32_to_cpu(aeqe->aeqe_words[NES_AEQE_COMP_CTXT_HIGH_IDX]))) << 32) |
* ((u64)(le32_to_cpu(aeqe->aeqe_words[NES_AEQE_COMP_CTXT_LOW_IDX])));
*/
nes_process_iwarp_aeqe(nesdev, (struct nes_hw_aeqe *)aeqe);
} else {
/* TODO: dealing with a CQP related AE */
nes_debug(NES_DBG_AEQ, "Processing CQP related AE, misc = 0x%04X\n",
(u16)(aeqe_misc >> 16));
}
}
aeqe->aeqe_words[NES_AEQE_MISC_IDX] = 0;
if (++head >= aeq_size)
head = 0;
nes_write32(nesdev->regs + NES_AEQ_ALLOC, 1 << 16);
}
while (1);
aeq->aeq_head = head;
}
static void nes_reset_link(struct nes_device *nesdev, u32 mac_index)
{
struct nes_adapter *nesadapter = nesdev->nesadapter;
u32 reset_value;
u32 i=0;
u32 u32temp;
if (nesadapter->hw_rev == NE020_REV) {
return;
}
mh_detected++;
reset_value = nes_read32(nesdev->regs+NES_SOFTWARE_RESET);
if ((mac_index == 0) || ((mac_index == 1) && (nesadapter->OneG_Mode)))
reset_value |= 0x0000001d;
else
reset_value |= 0x0000002d;
if (4 <= (nesadapter->link_interrupt_count[mac_index] / ((u16)NES_MAX_LINK_INTERRUPTS))) {
if ((!nesadapter->OneG_Mode) && (nesadapter->port_count == 2)) {
nesadapter->link_interrupt_count[0] = 0;
nesadapter->link_interrupt_count[1] = 0;
u32temp = nes_read_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL1);
if (0x00000040 & u32temp)
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL1, 0x0000F088);
else
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL1, 0x0000F0C8);
reset_value |= 0x0000003d;
}
nesadapter->link_interrupt_count[mac_index] = 0;
}
nes_write32(nesdev->regs+NES_SOFTWARE_RESET, reset_value);
while (((nes_read32(nesdev->regs+NES_SOFTWARE_RESET)
& 0x00000040) != 0x00000040) && (i++ < 5000));
if (0x0000003d == (reset_value & 0x0000003d)) {
u32 pcs_control_status0, pcs_control_status1;
for (i = 0; i < 10; i++) {
pcs_control_status0 = nes_read_indexed(nesdev, NES_IDX_PHY_PCS_CONTROL_STATUS0);
pcs_control_status1 = nes_read_indexed(nesdev, NES_IDX_PHY_PCS_CONTROL_STATUS0 + 0x200);
if (((0x0F000000 == (pcs_control_status0 & 0x0F000000))
&& (pcs_control_status0 & 0x00100000))
|| ((0x0F000000 == (pcs_control_status1 & 0x0F000000))
&& (pcs_control_status1 & 0x00100000)))
continue;
else
break;
}
if (10 == i) {
u32temp = nes_read_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL1);
if (0x00000040 & u32temp)
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL1, 0x0000F088);
else
nes_write_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_CONTROL1, 0x0000F0C8);
nes_write32(nesdev->regs+NES_SOFTWARE_RESET, reset_value);
while (((nes_read32(nesdev->regs + NES_SOFTWARE_RESET)
& 0x00000040) != 0x00000040) && (i++ < 5000));
}
}
}
/**
* nes_process_mac_intr
*/
static void nes_process_mac_intr(struct nes_device *nesdev, u32 mac_number)
{
unsigned long flags;
u32 pcs_control_status;
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_vnic *nesvnic;
u32 mac_status;
u32 mac_index = nesdev->mac_index;
u32 u32temp;
u16 phy_data;
u16 temp_phy_data;
u32 pcs_val = 0x0f0f0000;
u32 pcs_mask = 0x0f1f0000;
u32 cdr_ctrl;
spin_lock_irqsave(&nesadapter->phy_lock, flags);
if (nesadapter->mac_sw_state[mac_number] != NES_MAC_SW_IDLE) {
spin_unlock_irqrestore(&nesadapter->phy_lock, flags);
return;
}
nesadapter->mac_sw_state[mac_number] = NES_MAC_SW_INTERRUPT;
/* ack the MAC interrupt */
mac_status = nes_read_indexed(nesdev, NES_IDX_MAC_INT_STATUS + (mac_index * 0x200));
/* Clear the interrupt */
nes_write_indexed(nesdev, NES_IDX_MAC_INT_STATUS + (mac_index * 0x200), mac_status);
nes_debug(NES_DBG_PHY, "MAC%u interrupt status = 0x%X.\n", mac_number, mac_status);
if (mac_status & (NES_MAC_INT_LINK_STAT_CHG | NES_MAC_INT_XGMII_EXT)) {
nesdev->link_status_interrupts++;
if (0 == (++nesadapter->link_interrupt_count[mac_index] % ((u16)NES_MAX_LINK_INTERRUPTS)))
nes_reset_link(nesdev, mac_index);
/* read the PHY interrupt status register */
if ((nesadapter->OneG_Mode) &&
(nesadapter->phy_type[mac_index] != NES_PHY_TYPE_PUMA_1G)) {
do {
nes_read_1G_phy_reg(nesdev, 0x1a,
nesadapter->phy_index[mac_index], &phy_data);
nes_debug(NES_DBG_PHY, "Phy%d data from register 0x1a = 0x%X.\n",
nesadapter->phy_index[mac_index], phy_data);
} while (phy_data&0x8000);
temp_phy_data = 0;
do {
nes_read_1G_phy_reg(nesdev, 0x11,
nesadapter->phy_index[mac_index], &phy_data);
nes_debug(NES_DBG_PHY, "Phy%d data from register 0x11 = 0x%X.\n",
nesadapter->phy_index[mac_index], phy_data);
if (temp_phy_data == phy_data)
break;
temp_phy_data = phy_data;
} while (1);
nes_read_1G_phy_reg(nesdev, 0x1e,
nesadapter->phy_index[mac_index], &phy_data);
nes_debug(NES_DBG_PHY, "Phy%d data from register 0x1e = 0x%X.\n",
nesadapter->phy_index[mac_index], phy_data);
nes_read_1G_phy_reg(nesdev, 1,
nesadapter->phy_index[mac_index], &phy_data);
nes_debug(NES_DBG_PHY, "1G phy%u data from register 1 = 0x%X\n",
nesadapter->phy_index[mac_index], phy_data);
if (temp_phy_data & 0x1000) {
nes_debug(NES_DBG_PHY, "The Link is up according to the PHY\n");
phy_data = 4;
} else {
nes_debug(NES_DBG_PHY, "The Link is down according to the PHY\n");
}
}
nes_debug(NES_DBG_PHY, "Eth SERDES Common Status: 0=0x%08X, 1=0x%08X\n",
nes_read_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_STATUS0),
nes_read_indexed(nesdev, NES_IDX_ETH_SERDES_COMMON_STATUS0+0x200));
if (nesadapter->phy_type[mac_index] == NES_PHY_TYPE_PUMA_1G) {
switch (mac_index) {
case 1:
case 3:
pcs_control_status = nes_read_indexed(nesdev,
NES_IDX_PHY_PCS_CONTROL_STATUS0 + 0x200);
break;
default:
pcs_control_status = nes_read_indexed(nesdev,
NES_IDX_PHY_PCS_CONTROL_STATUS0);
break;
}
} else {
pcs_control_status = nes_read_indexed(nesdev,
NES_IDX_PHY_PCS_CONTROL_STATUS0 + ((mac_index & 1) * 0x200));
pcs_control_status = nes_read_indexed(nesdev,
NES_IDX_PHY_PCS_CONTROL_STATUS0 + ((mac_index & 1) * 0x200));
}
nes_debug(NES_DBG_PHY, "PCS PHY Control/Status%u: 0x%08X\n",
mac_index, pcs_control_status);
if ((nesadapter->OneG_Mode) &&
(nesadapter->phy_type[mac_index] != NES_PHY_TYPE_PUMA_1G)) {
u32temp = 0x01010000;
if (nesadapter->port_count > 2) {
u32temp |= 0x02020000;
}
if ((pcs_control_status & u32temp)!= u32temp) {
phy_data = 0;
nes_debug(NES_DBG_PHY, "PCS says the link is down\n");
}
} else {
switch (nesadapter->phy_type[mac_index]) {
case NES_PHY_TYPE_ARGUS:
case NES_PHY_TYPE_SFP_D:
case NES_PHY_TYPE_KR:
/* clear the alarms */
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 4, 0x0008);
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 4, 0xc001);
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 4, 0xc002);
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 4, 0xc005);
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 4, 0xc006);
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 1, 0x9003);
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 1, 0x9004);
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 1, 0x9005);
/* check link status */
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 1, 0x9003);
temp_phy_data = (u16)nes_read_indexed(nesdev, NES_IDX_MAC_MDIO_CONTROL);
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 3, 0x0021);
nes_read_indexed(nesdev, NES_IDX_MAC_MDIO_CONTROL);
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 3, 0x0021);
phy_data = (u16)nes_read_indexed(nesdev, NES_IDX_MAC_MDIO_CONTROL);
phy_data = (!temp_phy_data && (phy_data == 0x8000)) ? 0x4 : 0x0;
nes_debug(NES_DBG_PHY, "%s: Phy data = 0x%04X, link was %s.\n",
__func__, phy_data, nesadapter->mac_link_down[mac_index] ? "DOWN" : "UP");
break;
case NES_PHY_TYPE_PUMA_1G:
if (mac_index < 2)
pcs_val = pcs_mask = 0x01010000;
else
pcs_val = pcs_mask = 0x02020000;
/* fall through */
default:
phy_data = (pcs_val == (pcs_control_status & pcs_mask)) ? 0x4 : 0x0;
break;
}
}
if (phy_data & 0x0004) {
if (wide_ppm_offset &&
(nesadapter->phy_type[mac_index] == NES_PHY_TYPE_CX4) &&
(nesadapter->hw_rev != NE020_REV)) {
cdr_ctrl = nes_read_indexed(nesdev,
NES_IDX_ETH_SERDES_CDR_CONTROL0 +
mac_index * 0x200);
nes_write_indexed(nesdev,
NES_IDX_ETH_SERDES_CDR_CONTROL0 +
mac_index * 0x200,
cdr_ctrl | 0x000F0000);
}
nesadapter->mac_link_down[mac_index] = 0;
list_for_each_entry(nesvnic, &nesadapter->nesvnic_list[mac_index], list) {
nes_debug(NES_DBG_PHY, "The Link is UP!!. linkup was %d\n",
nesvnic->linkup);
if (nesvnic->linkup == 0) {
printk(PFX "The Link is now up for port %s, netdev %p.\n",
nesvnic->netdev->name, nesvnic->netdev);
if (netif_queue_stopped(nesvnic->netdev))
netif_start_queue(nesvnic->netdev);
nesvnic->linkup = 1;
netif_carrier_on(nesvnic->netdev);
spin_lock(&nesvnic->port_ibevent_lock);
if (nesvnic->of_device_registered) {
if (nesdev->iw_status == 0) {
nesdev->iw_status = 1;
nes_port_ibevent(nesvnic);
}
}
spin_unlock(&nesvnic->port_ibevent_lock);
}
}
} else {
if (wide_ppm_offset &&
(nesadapter->phy_type[mac_index] == NES_PHY_TYPE_CX4) &&
(nesadapter->hw_rev != NE020_REV)) {
cdr_ctrl = nes_read_indexed(nesdev,
NES_IDX_ETH_SERDES_CDR_CONTROL0 +
mac_index * 0x200);
nes_write_indexed(nesdev,
NES_IDX_ETH_SERDES_CDR_CONTROL0 +
mac_index * 0x200,
cdr_ctrl & 0xFFF0FFFF);
}
nesadapter->mac_link_down[mac_index] = 1;
list_for_each_entry(nesvnic, &nesadapter->nesvnic_list[mac_index], list) {
nes_debug(NES_DBG_PHY, "The Link is Down!!. linkup was %d\n",
nesvnic->linkup);
if (nesvnic->linkup == 1) {
printk(PFX "The Link is now down for port %s, netdev %p.\n",
nesvnic->netdev->name, nesvnic->netdev);
if (!(netif_queue_stopped(nesvnic->netdev)))
netif_stop_queue(nesvnic->netdev);
nesvnic->linkup = 0;
netif_carrier_off(nesvnic->netdev);
spin_lock(&nesvnic->port_ibevent_lock);
if (nesvnic->of_device_registered) {
if (nesdev->iw_status == 1) {
nesdev->iw_status = 0;
nes_port_ibevent(nesvnic);
}
}
spin_unlock(&nesvnic->port_ibevent_lock);
}
}
}
if (nesadapter->phy_type[mac_index] == NES_PHY_TYPE_SFP_D) {
nesdev->link_recheck = 1;
mod_delayed_work(system_wq, &nesdev->work,
NES_LINK_RECHECK_DELAY);
}
}
spin_unlock_irqrestore(&nesadapter->phy_lock, flags);
nesadapter->mac_sw_state[mac_number] = NES_MAC_SW_IDLE;
}
void nes_recheck_link_status(struct work_struct *work)
{
unsigned long flags;
struct nes_device *nesdev = container_of(work, struct nes_device, work.work);
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_vnic *nesvnic;
u32 mac_index = nesdev->mac_index;
u16 phy_data;
u16 temp_phy_data;
spin_lock_irqsave(&nesadapter->phy_lock, flags);
/* check link status */
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 1, 0x9003);
temp_phy_data = (u16)nes_read_indexed(nesdev, NES_IDX_MAC_MDIO_CONTROL);
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 3, 0x0021);
nes_read_indexed(nesdev, NES_IDX_MAC_MDIO_CONTROL);
nes_read_10G_phy_reg(nesdev, nesadapter->phy_index[mac_index], 3, 0x0021);
phy_data = (u16)nes_read_indexed(nesdev, NES_IDX_MAC_MDIO_CONTROL);
phy_data = (!temp_phy_data && (phy_data == 0x8000)) ? 0x4 : 0x0;
nes_debug(NES_DBG_PHY, "%s: Phy data = 0x%04X, link was %s.\n",
__func__, phy_data,
nesadapter->mac_link_down[mac_index] ? "DOWN" : "UP");
if (phy_data & 0x0004) {
nesadapter->mac_link_down[mac_index] = 0;
list_for_each_entry(nesvnic, &nesadapter->nesvnic_list[mac_index], list) {
if (nesvnic->linkup == 0) {
printk(PFX "The Link is now up for port %s, netdev %p.\n",
nesvnic->netdev->name, nesvnic->netdev);
if (netif_queue_stopped(nesvnic->netdev))
netif_start_queue(nesvnic->netdev);
nesvnic->linkup = 1;
netif_carrier_on(nesvnic->netdev);
spin_lock(&nesvnic->port_ibevent_lock);
if (nesvnic->of_device_registered) {
if (nesdev->iw_status == 0) {
nesdev->iw_status = 1;
nes_port_ibevent(nesvnic);
}
}
spin_unlock(&nesvnic->port_ibevent_lock);
}
}
} else {
nesadapter->mac_link_down[mac_index] = 1;
list_for_each_entry(nesvnic, &nesadapter->nesvnic_list[mac_index], list) {
if (nesvnic->linkup == 1) {
printk(PFX "The Link is now down for port %s, netdev %p.\n",
nesvnic->netdev->name, nesvnic->netdev);
if (!(netif_queue_stopped(nesvnic->netdev)))
netif_stop_queue(nesvnic->netdev);
nesvnic->linkup = 0;
netif_carrier_off(nesvnic->netdev);
spin_lock(&nesvnic->port_ibevent_lock);
if (nesvnic->of_device_registered) {
if (nesdev->iw_status == 1) {
nesdev->iw_status = 0;
nes_port_ibevent(nesvnic);
}
}
spin_unlock(&nesvnic->port_ibevent_lock);
}
}
}
if (nesdev->link_recheck++ < NES_LINK_RECHECK_MAX)
schedule_delayed_work(&nesdev->work, NES_LINK_RECHECK_DELAY);
else
nesdev->link_recheck = 0;
spin_unlock_irqrestore(&nesadapter->phy_lock, flags);
}
static void nes_nic_napi_ce_handler(struct nes_device *nesdev, struct nes_hw_nic_cq *cq)
{
struct nes_vnic *nesvnic = container_of(cq, struct nes_vnic, nic_cq);
napi_schedule(&nesvnic->napi);
}
/* The MAX_RQES_TO_PROCESS defines how many max read requests to complete before
* getting out of nic_ce_handler
*/
#define MAX_RQES_TO_PROCESS 384
/**
* nes_nic_ce_handler
*/
void nes_nic_ce_handler(struct nes_device *nesdev, struct nes_hw_nic_cq *cq)
{
u64 u64temp;
dma_addr_t bus_address;
struct nes_hw_nic *nesnic;
struct nes_vnic *nesvnic = container_of(cq, struct nes_vnic, nic_cq);
struct nes_adapter *nesadapter = nesdev->nesadapter;
struct nes_hw_nic_rq_wqe *nic_rqe;
struct nes_hw_nic_sq_wqe *nic_sqe;
struct sk_buff *skb;
struct sk_buff *rx_skb;
struct nes_rskb_cb *cb;
__le16 *wqe_fragment_length;
u32 head;
u32 cq_size;
u32 rx_pkt_size;
u32 cqe_count=0;
u32 cqe_errv;
u32 cqe_misc;
u16 wqe_fragment_index = 1; /* first fragment (0) is used by copy buffer */
u16 vlan_tag;
u16 pkt_type;
u16 rqes_processed = 0;
u8 sq_cqes = 0;
u8 nes_use_lro = 0;
head = cq->cq_head;
cq_size = cq->cq_size;
cq->cqes_pending = 1;
if (nesvnic->netdev->features & NETIF_F_LRO)
nes_use_lro = 1;
do {
if (le32_to_cpu(cq->cq_vbase[head].cqe_words[NES_NIC_CQE_MISC_IDX]) &
NES_NIC_CQE_VALID) {
nesnic = &nesvnic->nic;
cqe_misc = le32_to_cpu(cq->cq_vbase[head].cqe_words[NES_NIC_CQE_MISC_IDX]);
if (cqe_misc & NES_NIC_CQE_SQ) {
sq_cqes++;
wqe_fragment_index = 1;
nic_sqe = &nesnic->sq_vbase[nesnic->sq_tail];
skb = nesnic->tx_skb[nesnic->sq_tail];
wqe_fragment_length = (__le16 *)&nic_sqe->wqe_words[NES_NIC_SQ_WQE_LENGTH_0_TAG_IDX];
/* bump past the vlan tag */
wqe_fragment_length++;
if (le16_to_cpu(wqe_fragment_length[wqe_fragment_index]) != 0) {
u64temp = (u64) le32_to_cpu(nic_sqe->wqe_words[NES_NIC_SQ_WQE_FRAG0_LOW_IDX +
wqe_fragment_index * 2]);
u64temp += ((u64)le32_to_cpu(nic_sqe->wqe_words[NES_NIC_SQ_WQE_FRAG0_HIGH_IDX +
wqe_fragment_index * 2])) << 32;
bus_address = (dma_addr_t)u64temp;
if (test_and_clear_bit(nesnic->sq_tail, nesnic->first_frag_overflow)) {
pci_unmap_single(nesdev->pcidev,
bus_address,
le16_to_cpu(wqe_fragment_length[wqe_fragment_index++]),
PCI_DMA_TODEVICE);
}
for (; wqe_fragment_index < 5; wqe_fragment_index++) {
if (wqe_fragment_length[wqe_fragment_index]) {
u64temp = le32_to_cpu(nic_sqe->wqe_words[NES_NIC_SQ_WQE_FRAG0_LOW_IDX +
wqe_fragment_index * 2]);
u64temp += ((u64)le32_to_cpu(nic_sqe->wqe_words[NES_NIC_SQ_WQE_FRAG0_HIGH_IDX
+ wqe_fragment_index * 2])) <<32;
bus_address = (dma_addr_t)u64temp;
pci_unmap_page(nesdev->pcidev,
bus_address,
le16_to_cpu(wqe_fragment_length[wqe_fragment_index]),
PCI_DMA_TODEVICE);
} else
break;
}
}
if (skb)
dev_kfree_skb_any(skb);
nesnic->sq_tail++;
nesnic->sq_tail &= nesnic->sq_size-1;
if (sq_cqes > 128) {
barrier();
/* restart the queue if it had been stopped */
if (netif_queue_stopped(nesvnic->netdev))
netif_wake_queue(nesvnic->netdev);
sq_cqes = 0;
}
} else {
rqes_processed ++;
cq->rx_cqes_completed++;
cq->rx_pkts_indicated++;
rx_pkt_size = cqe_misc & 0x0000ffff;
nic_rqe = &nesnic->rq_vbase[nesnic->rq_tail];
/* Get the skb */
rx_skb = nesnic->rx_skb[nesnic->rq_tail];
nic_rqe = &nesnic->rq_vbase[nesvnic->nic.rq_tail];
bus_address = (dma_addr_t)le32_to_cpu(nic_rqe->wqe_words[NES_NIC_RQ_WQE_FRAG0_LOW_IDX]);
bus_address += ((u64)le32_to_cpu(nic_rqe->wqe_words[NES_NIC_RQ_WQE_FRAG0_HIGH_IDX])) << 32;
pci_unmap_single(nesdev->pcidev, bus_address,
nesvnic->max_frame_size, PCI_DMA_FROMDEVICE);
cb = (struct nes_rskb_cb *)&rx_skb->cb[0];
cb->busaddr = 0;
/* rx_skb->tail = rx_skb->data + rx_pkt_size; */
/* rx_skb->len = rx_pkt_size; */
rx_skb->len = 0; /* TODO: see if this is necessary */
skb_put(rx_skb, rx_pkt_size);
rx_skb->protocol = eth_type_trans(rx_skb, nesvnic->netdev);
nesnic->rq_tail++;
nesnic->rq_tail &= nesnic->rq_size - 1;
atomic_inc(&nesvnic->rx_skbs_needed);
if (atomic_read(&nesvnic->rx_skbs_needed) > (nesvnic->nic.rq_size>>1)) {
nes_write32(nesdev->regs+NES_CQE_ALLOC,
cq->cq_number | (cqe_count << 16));
/* nesadapter->tune_timer.cq_count += cqe_count; */
nesdev->currcq_count += cqe_count;
cqe_count = 0;
nes_replenish_nic_rq(nesvnic);
}
pkt_type = (u16)(le32_to_cpu(cq->cq_vbase[head].cqe_words[NES_NIC_CQE_TAG_PKT_TYPE_IDX]));
cqe_errv = (cqe_misc & NES_NIC_CQE_ERRV_MASK) >> NES_NIC_CQE_ERRV_SHIFT;
rx_skb->ip_summed = CHECKSUM_NONE;
if ((NES_PKT_TYPE_TCPV4_BITS == (pkt_type & NES_PKT_TYPE_TCPV4_MASK)) ||
(NES_PKT_TYPE_UDPV4_BITS == (pkt_type & NES_PKT_TYPE_UDPV4_MASK))) {
if ((cqe_errv &
(NES_NIC_ERRV_BITS_IPV4_CSUM_ERR | NES_NIC_ERRV_BITS_TCPUDP_CSUM_ERR |
NES_NIC_ERRV_BITS_IPH_ERR | NES_NIC_ERRV_BITS_WQE_OVERRUN)) == 0) {
if (nesvnic->netdev->features & NETIF_F_RXCSUM)
rx_skb->ip_summed = CHECKSUM_UNNECESSARY;
} else
nes_debug(NES_DBG_CQ, "%s: unsuccessfully checksummed TCP or UDP packet."
" errv = 0x%X, pkt_type = 0x%X.\n",
nesvnic->netdev->name, cqe_errv, pkt_type);
} else if ((pkt_type & NES_PKT_TYPE_IPV4_MASK) == NES_PKT_TYPE_IPV4_BITS) {
if ((cqe_errv &
(NES_NIC_ERRV_BITS_IPV4_CSUM_ERR | NES_NIC_ERRV_BITS_IPH_ERR |
NES_NIC_ERRV_BITS_WQE_OVERRUN)) == 0) {
if (nesvnic->netdev->features & NETIF_F_RXCSUM) {
rx_skb->ip_summed = CHECKSUM_UNNECESSARY;
/* nes_debug(NES_DBG_CQ, "%s: Reporting successfully checksummed IPv4 packet.\n",
nesvnic->netdev->name); */
}
} else
nes_debug(NES_DBG_CQ, "%s: unsuccessfully checksummed TCP or UDP packet."
" errv = 0x%X, pkt_type = 0x%X.\n",
nesvnic->netdev->name, cqe_errv, pkt_type);
}
/* nes_debug(NES_DBG_CQ, "pkt_type=%x, APBVT_MASK=%x\n",
pkt_type, (pkt_type & NES_PKT_TYPE_APBVT_MASK)); */
if ((pkt_type & NES_PKT_TYPE_APBVT_MASK) == NES_PKT_TYPE_APBVT_BITS) {
if (nes_cm_recv(rx_skb, nesvnic->netdev))
rx_skb = NULL;
}
if (rx_skb == NULL)
goto skip_rx_indicate0;
if (cqe_misc & NES_NIC_CQE_TAG_VALID) {
vlan_tag = (u16)(le32_to_cpu(
cq->cq_vbase[head].cqe_words[NES_NIC_CQE_TAG_PKT_TYPE_IDX])
>> 16);
nes_debug(NES_DBG_CQ, "%s: Reporting stripped VLAN packet. Tag = 0x%04X\n",
nesvnic->netdev->name, vlan_tag);
__vlan_hwaccel_put_tag(rx_skb, htons(ETH_P_8021Q), vlan_tag);
}
if (nes_use_lro)
lro_receive_skb(&nesvnic->lro_mgr, rx_skb, NULL);
else
netif_receive_skb(rx_skb);
skip_rx_indicate0:
;
/* nesvnic->netstats.rx_packets++; */
/* nesvnic->netstats.rx_bytes += rx_pkt_size; */
}
cq->cq_vbase[head].cqe_words[NES_NIC_CQE_MISC_IDX] = 0;
/* Accounting... */
cqe_count++;
if (++head >= cq_size)
head = 0;
if (cqe_count == 255) {
/* Replenish Nic CQ */
nes_write32(nesdev->regs+NES_CQE_ALLOC,
cq->cq_number | (cqe_count << 16));
/* nesdev->nesadapter->tune_timer.cq_count += cqe_count; */
nesdev->currcq_count += cqe_count;
cqe_count = 0;
}
if (cq->rx_cqes_completed >= nesvnic->budget)
break;
} else {
cq->cqes_pending = 0;
break;
}
} while (1);
if (nes_use_lro)
lro_flush_all(&nesvnic->lro_mgr);
if (sq_cqes) {
barrier();
/* restart the queue if it had been stopped */
if (netif_queue_stopped(nesvnic->netdev))
netif_wake_queue(nesvnic->netdev);
}
cq->cq_head = head;
/* nes_debug(NES_DBG_CQ, "CQ%u Processed = %u cqes, new head = %u.\n",
cq->cq_number, cqe_count, cq->cq_head); */
cq->cqe_allocs_pending = cqe_count;
if (unlikely(nesadapter->et_use_adaptive_rx_coalesce))
{
/* nesdev->nesadapter->tune_timer.cq_count += cqe_count; */
nesdev->currcq_count += cqe_count;
nes_nic_tune_timer(nesdev);
}
if (atomic_read(&nesvnic->rx_skbs_needed))
nes_replenish_nic_rq(nesvnic);
}
/**
* nes_cqp_ce_handler
*/
static void nes_cqp_ce_handler(struct nes_device *nesdev, struct nes_hw_cq *cq)
{
u64 u64temp;
unsigned long flags;
struct nes_hw_cqp *cqp = NULL;
struct nes_cqp_request *cqp_request;
struct nes_hw_cqp_wqe *cqp_wqe;
u32 head;
u32 cq_size;
u32 cqe_count=0;
u32 error_code;
u32 opcode;
u32 ctx_index;
/* u32 counter; */
head = cq->cq_head;
cq_size = cq->cq_size;
do {
/* process the CQE */
/* nes_debug(NES_DBG_CQP, "head=%u cqe_words=%08X\n", head,
le32_to_cpu(cq->cq_vbase[head].cqe_words[NES_CQE_OPCODE_IDX])); */
opcode = le32_to_cpu(cq->cq_vbase[head].cqe_words[NES_CQE_OPCODE_IDX]);
if (opcode & NES_CQE_VALID) {
cqp = &nesdev->cqp;
error_code = le32_to_cpu(cq->cq_vbase[head].cqe_words[NES_CQE_ERROR_CODE_IDX]);
if (error_code) {
nes_debug(NES_DBG_CQP, "Bad Completion code for opcode 0x%02X from CQP,"
" Major/Minor codes = 0x%04X:%04X.\n",
le32_to_cpu(cq->cq_vbase[head].cqe_words[NES_CQE_OPCODE_IDX])&0x3f,
(u16)(error_code >> 16),
(u16)error_code);
}
u64temp = (((u64)(le32_to_cpu(cq->cq_vbase[head].
cqe_words[NES_CQE_COMP_COMP_CTX_HIGH_IDX]))) << 32) |
((u64)(le32_to_cpu(cq->cq_vbase[head].
cqe_words[NES_CQE_COMP_COMP_CTX_LOW_IDX])));
cqp_request = (struct nes_cqp_request *)(unsigned long)u64temp;
if (cqp_request) {
if (cqp_request->waiting) {
/* nes_debug(NES_DBG_CQP, "%s: Waking up requestor\n"); */
cqp_request->major_code = (u16)(error_code >> 16);
cqp_request->minor_code = (u16)error_code;
barrier();
cqp_request->request_done = 1;
wake_up(&cqp_request->waitq);
nes_put_cqp_request(nesdev, cqp_request);
} else {
if (cqp_request->callback)
cqp_request->cqp_callback(nesdev, cqp_request);
nes_free_cqp_request(nesdev, cqp_request);
}
} else {
wake_up(&nesdev->cqp.waitq);
}
cq->cq_vbase[head].cqe_words[NES_CQE_OPCODE_IDX] = 0;
nes_write32(nesdev->regs + NES_CQE_ALLOC, cq->cq_number | (1 << 16));
if (++cqp->sq_tail >= cqp->sq_size)
cqp->sq_tail = 0;
/* Accounting... */
cqe_count++;
if (++head >= cq_size)
head = 0;
} else {
break;
}
} while (1);
cq->cq_head = head;
spin_lock_irqsave(&nesdev->cqp.lock, flags);
while ((!list_empty(&nesdev->cqp_pending_reqs)) &&
((((nesdev->cqp.sq_tail+nesdev->cqp.sq_size)-nesdev->cqp.sq_head) &
(nesdev->cqp.sq_size - 1)) != 1)) {
cqp_request = list_entry(nesdev->cqp_pending_reqs.next,
struct nes_cqp_request, list);
list_del_init(&cqp_request->list);
head = nesdev->cqp.sq_head++;
nesdev->cqp.sq_head &= nesdev->cqp.sq_size-1;
cqp_wqe = &nesdev->cqp.sq_vbase[head];
memcpy(cqp_wqe, &cqp_request->cqp_wqe, sizeof(*cqp_wqe));
barrier();
opcode = cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX];
if ((opcode & NES_CQP_OPCODE_MASK) == NES_CQP_DOWNLOAD_SEGMENT)
ctx_index = NES_CQP_WQE_DL_COMP_CTX_LOW_IDX;
else
ctx_index = NES_CQP_WQE_COMP_CTX_LOW_IDX;
cqp_wqe->wqe_words[ctx_index] =
cpu_to_le32((u32)((unsigned long)cqp_request));
cqp_wqe->wqe_words[ctx_index + 1] =
cpu_to_le32((u32)(upper_32_bits((unsigned long)cqp_request)));
nes_debug(NES_DBG_CQP, "CQP request %p (opcode 0x%02X) put on CQPs SQ wqe%u.\n",
cqp_request, le32_to_cpu(cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX])&0x3f, head);
/* Ring doorbell (1 WQEs) */
barrier();
nes_write32(nesdev->regs+NES_WQE_ALLOC, 0x01800000 | nesdev->cqp.qp_id);
}
spin_unlock_irqrestore(&nesdev->cqp.lock, flags);
/* Arm the CCQ */
nes_write32(nesdev->regs+NES_CQE_ALLOC, NES_CQE_ALLOC_NOTIFY_NEXT |
cq->cq_number);
nes_read32(nesdev->regs+NES_CQE_ALLOC);
}
static u8 *locate_mpa(u8 *pkt, u32 aeq_info)
{
if (aeq_info & NES_AEQE_Q2_DATA_ETHERNET) {
/* skip over ethernet header */
pkt += ETH_HLEN;
/* Skip over IP and TCP headers */
pkt += 4 * (pkt[0] & 0x0f);
pkt += 4 * ((pkt[12] >> 4) & 0x0f);
}
return pkt;
}
/* Determine if incoming error pkt is rdma layer */
static u32 iwarp_opcode(struct nes_qp *nesqp, u32 aeq_info)
{
u8 *pkt;
u16 *mpa;
u32 opcode = 0xffffffff;
if (aeq_info & NES_AEQE_Q2_DATA_WRITTEN) {
pkt = nesqp->hwqp.q2_vbase + BAD_FRAME_OFFSET;
mpa = (u16 *)locate_mpa(pkt, aeq_info);
opcode = be16_to_cpu(mpa[1]) & 0xf;
}
return opcode;
}
/* Build iWARP terminate header */
static int nes_bld_terminate_hdr(struct nes_qp *nesqp, u16 async_event_id, u32 aeq_info)
{
u8 *pkt = nesqp->hwqp.q2_vbase + BAD_FRAME_OFFSET;
u16 ddp_seg_len;
int copy_len = 0;
u8 is_tagged = 0;
u8 flush_code = 0;
struct nes_terminate_hdr *termhdr;
termhdr = (struct nes_terminate_hdr *)nesqp->hwqp.q2_vbase;
memset(termhdr, 0, 64);
if (aeq_info & NES_AEQE_Q2_DATA_WRITTEN) {
/* Use data from offending packet to fill in ddp & rdma hdrs */
pkt = locate_mpa(pkt, aeq_info);
ddp_seg_len = be16_to_cpu(*(u16 *)pkt);
if (ddp_seg_len) {
copy_len = 2;
termhdr->hdrct = DDP_LEN_FLAG;
if (pkt[2] & 0x80) {
is_tagged = 1;
if (ddp_seg_len >= TERM_DDP_LEN_TAGGED) {
copy_len += TERM_DDP_LEN_TAGGED;
termhdr->hdrct |= DDP_HDR_FLAG;
}
} else {
if (ddp_seg_len >= TERM_DDP_LEN_UNTAGGED) {
copy_len += TERM_DDP_LEN_UNTAGGED;
termhdr->hdrct |= DDP_HDR_FLAG;
}
if (ddp_seg_len >= (TERM_DDP_LEN_UNTAGGED + TERM_RDMA_LEN)) {
if ((pkt[3] & RDMA_OPCODE_MASK) == RDMA_READ_REQ_OPCODE) {
copy_len += TERM_RDMA_LEN;
termhdr->hdrct |= RDMA_HDR_FLAG;
}
}
}
}
}
switch (async_event_id) {
case NES_AEQE_AEID_AMP_UNALLOCATED_STAG:
switch (iwarp_opcode(nesqp, aeq_info)) {
case IWARP_OPCODE_WRITE:
flush_code = IB_WC_LOC_PROT_ERR;
termhdr->layer_etype = (LAYER_DDP << 4) | DDP_TAGGED_BUFFER;
termhdr->error_code = DDP_TAGGED_INV_STAG;
break;
default:
flush_code = IB_WC_REM_ACCESS_ERR;
termhdr->layer_etype = (LAYER_RDMA << 4) | RDMAP_REMOTE_PROT;
termhdr->error_code = RDMAP_INV_STAG;
}
break;
case NES_AEQE_AEID_AMP_INVALID_STAG:
flush_code = IB_WC_REM_ACCESS_ERR;
termhdr->layer_etype = (LAYER_RDMA << 4) | RDMAP_REMOTE_PROT;
termhdr->error_code = RDMAP_INV_STAG;
break;
case NES_AEQE_AEID_AMP_BAD_QP:
flush_code = IB_WC_LOC_QP_OP_ERR;
termhdr->layer_etype = (LAYER_DDP << 4) | DDP_UNTAGGED_BUFFER;
termhdr->error_code = DDP_UNTAGGED_INV_QN;
break;
case NES_AEQE_AEID_AMP_BAD_STAG_KEY:
case NES_AEQE_AEID_AMP_BAD_STAG_INDEX:
switch (iwarp_opcode(nesqp, aeq_info)) {
case IWARP_OPCODE_SEND_INV:
case IWARP_OPCODE_SEND_SE_INV:
flush_code = IB_WC_REM_OP_ERR;
termhdr->layer_etype = (LAYER_RDMA << 4) | RDMAP_REMOTE_OP;
termhdr->error_code = RDMAP_CANT_INV_STAG;
break;
default:
flush_code = IB_WC_REM_ACCESS_ERR;
termhdr->layer_etype = (LAYER_RDMA << 4) | RDMAP_REMOTE_PROT;
termhdr->error_code = RDMAP_INV_STAG;
}
break;
case NES_AEQE_AEID_AMP_BOUNDS_VIOLATION:
if (aeq_info & (NES_AEQE_Q2_DATA_ETHERNET | NES_AEQE_Q2_DATA_MPA)) {
flush_code = IB_WC_LOC_PROT_ERR;
termhdr->layer_etype = (LAYER_DDP << 4) | DDP_TAGGED_BUFFER;
termhdr->error_code = DDP_TAGGED_BOUNDS;
} else {
flush_code = IB_WC_REM_ACCESS_ERR;
termhdr->layer_etype = (LAYER_RDMA << 4) | RDMAP_REMOTE_PROT;
termhdr->error_code = RDMAP_INV_BOUNDS;
}
break;
case NES_AEQE_AEID_AMP_RIGHTS_VIOLATION:
case NES_AEQE_AEID_AMP_INVALIDATE_NO_REMOTE_ACCESS_RIGHTS:
case NES_AEQE_AEID_PRIV_OPERATION_DENIED:
flush_code = IB_WC_REM_ACCESS_ERR;
termhdr->layer_etype = (LAYER_RDMA << 4) | RDMAP_REMOTE_PROT;
termhdr->error_code = RDMAP_ACCESS;
break;
case NES_AEQE_AEID_AMP_TO_WRAP:
flush_code = IB_WC_REM_ACCESS_ERR;
termhdr->layer_etype = (LAYER_RDMA << 4) | RDMAP_REMOTE_PROT;
termhdr->error_code = RDMAP_TO_WRAP;
break;
case NES_AEQE_AEID_AMP_BAD_PD:
switch (iwarp_opcode(nesqp, aeq_info)) {
case IWARP_OPCODE_WRITE:
flush_code = IB_WC_LOC_PROT_ERR;
termhdr->layer_etype = (LAYER_DDP << 4) | DDP_TAGGED_BUFFER;
termhdr->error_code = DDP_TAGGED_UNASSOC_STAG;
break;
case IWARP_OPCODE_SEND_INV:
case IWARP_OPCODE_SEND_SE_INV:
flush_code = IB_WC_REM_ACCESS_ERR;
termhdr->layer_etype = (LAYER_RDMA << 4) | RDMAP_REMOTE_PROT;
termhdr->error_code = RDMAP_CANT_INV_STAG;
break;
default:
flush_code = IB_WC_REM_ACCESS_ERR;
termhdr->layer_etype = (LAYER_RDMA << 4) | RDMAP_REMOTE_PROT;
termhdr->error_code = RDMAP_UNASSOC_STAG;
}
break;
case NES_AEQE_AEID_LLP_RECEIVED_MARKER_AND_LENGTH_FIELDS_DONT_MATCH:
flush_code = IB_WC_LOC_LEN_ERR;
termhdr->layer_etype = (LAYER_MPA << 4) | DDP_LLP;
termhdr->error_code = MPA_MARKER;
break;
case NES_AEQE_AEID_LLP_RECEIVED_MPA_CRC_ERROR:
flush_code = IB_WC_GENERAL_ERR;
termhdr->layer_etype = (LAYER_MPA << 4) | DDP_LLP;
termhdr->error_code = MPA_CRC;
break;
case NES_AEQE_AEID_LLP_SEGMENT_TOO_LARGE:
case NES_AEQE_AEID_LLP_SEGMENT_TOO_SMALL:
flush_code = IB_WC_LOC_LEN_ERR;
termhdr->layer_etype = (LAYER_DDP << 4) | DDP_CATASTROPHIC;
termhdr->error_code = DDP_CATASTROPHIC_LOCAL;
break;
case NES_AEQE_AEID_DDP_LCE_LOCAL_CATASTROPHIC:
case NES_AEQE_AEID_DDP_NO_L_BIT:
flush_code = IB_WC_FATAL_ERR;
termhdr->layer_etype = (LAYER_DDP << 4) | DDP_CATASTROPHIC;
termhdr->error_code = DDP_CATASTROPHIC_LOCAL;
break;
case NES_AEQE_AEID_DDP_INVALID_MSN_GAP_IN_MSN:
case NES_AEQE_AEID_DDP_INVALID_MSN_RANGE_IS_NOT_VALID:
flush_code = IB_WC_GENERAL_ERR;
termhdr->layer_etype = (LAYER_DDP << 4) | DDP_UNTAGGED_BUFFER;
termhdr->error_code = DDP_UNTAGGED_INV_MSN_RANGE;
break;
case NES_AEQE_AEID_DDP_UBE_DDP_MESSAGE_TOO_LONG_FOR_AVAILABLE_BUFFER:
flush_code = IB_WC_LOC_LEN_ERR;
termhdr->layer_etype = (LAYER_DDP << 4) | DDP_UNTAGGED_BUFFER;
termhdr->error_code = DDP_UNTAGGED_INV_TOO_LONG;
break;
case NES_AEQE_AEID_DDP_UBE_INVALID_DDP_VERSION:
flush_code = IB_WC_GENERAL_ERR;
if (is_tagged) {
termhdr->layer_etype = (LAYER_DDP << 4) | DDP_TAGGED_BUFFER;
termhdr->error_code = DDP_TAGGED_INV_DDP_VER;
} else {
termhdr->layer_etype = (LAYER_DDP << 4) | DDP_UNTAGGED_BUFFER;
termhdr->error_code = DDP_UNTAGGED_INV_DDP_VER;
}
break;
case NES_AEQE_AEID_DDP_UBE_INVALID_MO:
flush_code = IB_WC_GENERAL_ERR;
termhdr->layer_etype = (LAYER_DDP << 4) | DDP_UNTAGGED_BUFFER;
termhdr->error_code = DDP_UNTAGGED_INV_MO;
break;
case NES_AEQE_AEID_DDP_UBE_INVALID_MSN_NO_BUFFER_AVAILABLE:
flush_code = IB_WC_REM_OP_ERR;
termhdr->layer_etype = (LAYER_DDP << 4) | DDP_UNTAGGED_BUFFER;
termhdr->error_code = DDP_UNTAGGED_INV_MSN_NO_BUF;
break;
case NES_AEQE_AEID_DDP_UBE_INVALID_QN:
flush_code = IB_WC_GENERAL_ERR;
termhdr->layer_etype = (LAYER_DDP << 4) | DDP_UNTAGGED_BUFFER;
termhdr->error_code = DDP_UNTAGGED_INV_QN;
break;
case NES_AEQE_AEID_RDMAP_ROE_INVALID_RDMAP_VERSION:
flush_code = IB_WC_GENERAL_ERR;
termhdr->layer_etype = (LAYER_RDMA << 4) | RDMAP_REMOTE_OP;
termhdr->error_code = RDMAP_INV_RDMAP_VER;
break;
case NES_AEQE_AEID_RDMAP_ROE_UNEXPECTED_OPCODE:
flush_code = IB_WC_LOC_QP_OP_ERR;
termhdr->layer_etype = (LAYER_RDMA << 4) | RDMAP_REMOTE_OP;
termhdr->error_code = RDMAP_UNEXPECTED_OP;
break;
default:
flush_code = IB_WC_FATAL_ERR;
termhdr->layer_etype = (LAYER_RDMA << 4) | RDMAP_REMOTE_OP;
termhdr->error_code = RDMAP_UNSPECIFIED;
break;
}
if (copy_len)
memcpy(termhdr + 1, pkt, copy_len);
if ((flush_code) && ((NES_AEQE_INBOUND_RDMA & aeq_info) == 0)) {
if (aeq_info & NES_AEQE_SQ)
nesqp->term_sq_flush_code = flush_code;
else
nesqp->term_rq_flush_code = flush_code;
}
return sizeof(struct nes_terminate_hdr) + copy_len;
}
static void nes_terminate_connection(struct nes_device *nesdev, struct nes_qp *nesqp,
struct nes_hw_aeqe *aeqe, enum ib_event_type eventtype)
{
u64 context;
unsigned long flags;
u32 aeq_info;
u16 async_event_id;
u8 tcp_state;
u8 iwarp_state;
u32 termlen = 0;
u32 mod_qp_flags = NES_CQP_QP_IWARP_STATE_TERMINATE |
NES_CQP_QP_TERM_DONT_SEND_FIN;
struct nes_adapter *nesadapter = nesdev->nesadapter;
if (nesqp->term_flags & NES_TERM_SENT)
return; /* Sanity check */
aeq_info = le32_to_cpu(aeqe->aeqe_words[NES_AEQE_MISC_IDX]);
tcp_state = (aeq_info & NES_AEQE_TCP_STATE_MASK) >> NES_AEQE_TCP_STATE_SHIFT;
iwarp_state = (aeq_info & NES_AEQE_IWARP_STATE_MASK) >> NES_AEQE_IWARP_STATE_SHIFT;
async_event_id = (u16)aeq_info;
context = (unsigned long)nesadapter->qp_table[le32_to_cpu(
aeqe->aeqe_words[NES_AEQE_COMP_QP_CQ_ID_IDX]) - NES_FIRST_QPN];
if (!context) {
WARN_ON(!context);
return;
}
nesqp = (struct nes_qp *)(unsigned long)context;
spin_lock_irqsave(&nesqp->lock, flags);
nesqp->hw_iwarp_state = iwarp_state;
nesqp->hw_tcp_state = tcp_state;
nesqp->last_aeq = async_event_id;
nesqp->terminate_eventtype = eventtype;
spin_unlock_irqrestore(&nesqp->lock, flags);
if (nesadapter->send_term_ok)
termlen = nes_bld_terminate_hdr(nesqp, async_event_id, aeq_info);
else
mod_qp_flags |= NES_CQP_QP_TERM_DONT_SEND_TERM_MSG;
if (!nesdev->iw_status) {
nesqp->term_flags = NES_TERM_DONE;
nes_hw_modify_qp(nesdev, nesqp, NES_CQP_QP_IWARP_STATE_ERROR, 0, 0);
nes_cm_disconn(nesqp);
} else {
nes_terminate_start_timer(nesqp);
nesqp->term_flags |= NES_TERM_SENT;
nes_hw_modify_qp(nesdev, nesqp, mod_qp_flags, termlen, 0);
}
}
static void nes_terminate_send_fin(struct nes_device *nesdev,
struct nes_qp *nesqp, struct nes_hw_aeqe *aeqe)
{
u32 aeq_info;
u16 async_event_id;
u8 tcp_state;
u8 iwarp_state;
unsigned long flags;
aeq_info = le32_to_cpu(aeqe->aeqe_words[NES_AEQE_MISC_IDX]);
tcp_state = (aeq_info & NES_AEQE_TCP_STATE_MASK) >> NES_AEQE_TCP_STATE_SHIFT;
iwarp_state = (aeq_info & NES_AEQE_IWARP_STATE_MASK) >> NES_AEQE_IWARP_STATE_SHIFT;
async_event_id = (u16)aeq_info;
spin_lock_irqsave(&nesqp->lock, flags);
nesqp->hw_iwarp_state = iwarp_state;
nesqp->hw_tcp_state = tcp_state;
nesqp->last_aeq = async_event_id;
spin_unlock_irqrestore(&nesqp->lock, flags);
/* Send the fin only */
nes_hw_modify_qp(nesdev, nesqp, NES_CQP_QP_IWARP_STATE_TERMINATE |
NES_CQP_QP_TERM_DONT_SEND_TERM_MSG, 0, 0);
}
/* Cleanup after a terminate sent or received */
static void nes_terminate_done(struct nes_qp *nesqp, int timeout_occurred)
{
u32 next_iwarp_state = NES_CQP_QP_IWARP_STATE_ERROR;
unsigned long flags;
struct nes_vnic *nesvnic = to_nesvnic(nesqp->ibqp.device);
struct nes_device *nesdev = nesvnic->nesdev;
u8 first_time = 0;
spin_lock_irqsave(&nesqp->lock, flags);
if (nesqp->hte_added) {
nesqp->hte_added = 0;
next_iwarp_state |= NES_CQP_QP_DEL_HTE;
}
first_time = (nesqp->term_flags & NES_TERM_DONE) == 0;
nesqp->term_flags |= NES_TERM_DONE;
spin_unlock_irqrestore(&nesqp->lock, flags);
/* Make sure we go through this only once */
if (first_time) {
if (timeout_occurred == 0)
del_timer(&nesqp->terminate_timer);
else
next_iwarp_state |= NES_CQP_QP_RESET;
nes_hw_modify_qp(nesdev, nesqp, next_iwarp_state, 0, 0);
nes_cm_disconn(nesqp);
}
}
static void nes_terminate_received(struct nes_device *nesdev,
struct nes_qp *nesqp, struct nes_hw_aeqe *aeqe)
{
u32 aeq_info;
u8 *pkt;
u32 *mpa;
u8 ddp_ctl;
u8 rdma_ctl;
u16 aeq_id = 0;
aeq_info = le32_to_cpu(aeqe->aeqe_words[NES_AEQE_MISC_IDX]);
if (aeq_info & NES_AEQE_Q2_DATA_WRITTEN) {
/* Terminate is not a performance path so the silicon */
/* did not validate the frame - do it now */
pkt = nesqp->hwqp.q2_vbase + BAD_FRAME_OFFSET;
mpa = (u32 *)locate_mpa(pkt, aeq_info);
ddp_ctl = (be32_to_cpu(mpa[0]) >> 8) & 0xff;
rdma_ctl = be32_to_cpu(mpa[0]) & 0xff;
if ((ddp_ctl & 0xc0) != 0x40)
aeq_id = NES_AEQE_AEID_DDP_LCE_LOCAL_CATASTROPHIC;
else if ((ddp_ctl & 0x03) != 1)
aeq_id = NES_AEQE_AEID_DDP_UBE_INVALID_DDP_VERSION;
else if (be32_to_cpu(mpa[2]) != 2)
aeq_id = NES_AEQE_AEID_DDP_UBE_INVALID_QN;
else if (be32_to_cpu(mpa[3]) != 1)
aeq_id = NES_AEQE_AEID_DDP_INVALID_MSN_GAP_IN_MSN;
else if (be32_to_cpu(mpa[4]) != 0)
aeq_id = NES_AEQE_AEID_DDP_UBE_INVALID_MO;
else if ((rdma_ctl & 0xc0) != 0x40)
aeq_id = NES_AEQE_AEID_RDMAP_ROE_INVALID_RDMAP_VERSION;
if (aeq_id) {
/* Bad terminate recvd - send back a terminate */
aeq_info = (aeq_info & 0xffff0000) | aeq_id;
aeqe->aeqe_words[NES_AEQE_MISC_IDX] = cpu_to_le32(aeq_info);
nes_terminate_connection(nesdev, nesqp, aeqe, IB_EVENT_QP_FATAL);
return;
}
}
nesqp->term_flags |= NES_TERM_RCVD;
nesqp->terminate_eventtype = IB_EVENT_QP_FATAL;
nes_terminate_start_timer(nesqp);
nes_terminate_send_fin(nesdev, nesqp, aeqe);
}
/* Timeout routine in case terminate fails to complete */
void nes_terminate_timeout(unsigned long context)
{
struct nes_qp *nesqp = (struct nes_qp *)(unsigned long)context;
nes_terminate_done(nesqp, 1);
}
/* Set a timer in case hw cannot complete the terminate sequence */
static void nes_terminate_start_timer(struct nes_qp *nesqp)
{
mod_timer(&nesqp->terminate_timer, (jiffies + HZ));
}
/**
* nes_process_iwarp_aeqe
*/
static void nes_process_iwarp_aeqe(struct nes_device *nesdev,
struct nes_hw_aeqe *aeqe)
{
u64 context;
unsigned long flags;
struct nes_qp *nesqp;
struct nes_hw_cq *hw_cq;
struct nes_cq *nescq;
int resource_allocated;
struct nes_adapter *nesadapter = nesdev->nesadapter;
u32 aeq_info;
u32 next_iwarp_state = 0;
u32 aeqe_cq_id;
u16 async_event_id;
u8 tcp_state;
u8 iwarp_state;
struct ib_event ibevent;
nes_debug(NES_DBG_AEQ, "\n");
aeq_info = le32_to_cpu(aeqe->aeqe_words[NES_AEQE_MISC_IDX]);
if ((NES_AEQE_INBOUND_RDMA & aeq_info) || (!(NES_AEQE_QP & aeq_info))) {
context = le32_to_cpu(aeqe->aeqe_words[NES_AEQE_COMP_CTXT_LOW_IDX]);
context += ((u64)le32_to_cpu(aeqe->aeqe_words[NES_AEQE_COMP_CTXT_HIGH_IDX])) << 32;
} else {
context = (unsigned long)nesadapter->qp_table[le32_to_cpu(
aeqe->aeqe_words[NES_AEQE_COMP_QP_CQ_ID_IDX]) - NES_FIRST_QPN];
BUG_ON(!context);
}
/* context is nesqp unless async_event_id == CQ ERROR */
nesqp = (struct nes_qp *)(unsigned long)context;
async_event_id = (u16)aeq_info;
tcp_state = (aeq_info & NES_AEQE_TCP_STATE_MASK) >> NES_AEQE_TCP_STATE_SHIFT;
iwarp_state = (aeq_info & NES_AEQE_IWARP_STATE_MASK) >> NES_AEQE_IWARP_STATE_SHIFT;
nes_debug(NES_DBG_AEQ, "aeid = 0x%04X, qp-cq id = %d, aeqe = %p,"
" Tcp state = %s, iWARP state = %s\n",
async_event_id,
le32_to_cpu(aeqe->aeqe_words[NES_AEQE_COMP_QP_CQ_ID_IDX]), aeqe,
nes_tcp_state_str[tcp_state], nes_iwarp_state_str[iwarp_state]);
aeqe_cq_id = le32_to_cpu(aeqe->aeqe_words[NES_AEQE_COMP_QP_CQ_ID_IDX]);
if (aeq_info & NES_AEQE_QP) {
if (!nes_is_resource_allocated(nesadapter,
nesadapter->allocated_qps,
aeqe_cq_id))
return;
}
switch (async_event_id) {
case NES_AEQE_AEID_LLP_FIN_RECEIVED:
if (nesqp->term_flags)
return; /* Ignore it, wait for close complete */
if (atomic_inc_return(&nesqp->close_timer_started) == 1) {
if ((tcp_state == NES_AEQE_TCP_STATE_CLOSE_WAIT) &&
(nesqp->ibqp_state == IB_QPS_RTS)) {
spin_lock_irqsave(&nesqp->lock, flags);
nesqp->hw_iwarp_state = iwarp_state;
nesqp->hw_tcp_state = tcp_state;
nesqp->last_aeq = async_event_id;
next_iwarp_state = NES_CQP_QP_IWARP_STATE_CLOSING;
nesqp->hw_iwarp_state = NES_AEQE_IWARP_STATE_CLOSING;
spin_unlock_irqrestore(&nesqp->lock, flags);
nes_hw_modify_qp(nesdev, nesqp, next_iwarp_state, 0, 0);
nes_cm_disconn(nesqp);
}
nesqp->cm_id->add_ref(nesqp->cm_id);
schedule_nes_timer(nesqp->cm_node, (struct sk_buff *)nesqp,
NES_TIMER_TYPE_CLOSE, 1, 0);
nes_debug(NES_DBG_AEQ, "QP%u Not decrementing QP refcount (%d),"
" need ae to finish up, original_last_aeq = 0x%04X."
" last_aeq = 0x%04X, scheduling timer. TCP state = %d\n",
nesqp->hwqp.qp_id, atomic_read(&nesqp->refcount),
async_event_id, nesqp->last_aeq, tcp_state);
}
break;
case NES_AEQE_AEID_LLP_CLOSE_COMPLETE:
spin_lock_irqsave(&nesqp->lock, flags);
nesqp->hw_iwarp_state = iwarp_state;
nesqp->hw_tcp_state = tcp_state;
nesqp->last_aeq = async_event_id;
spin_unlock_irqrestore(&nesqp->lock, flags);
nes_cm_disconn(nesqp);
break;
case NES_AEQE_AEID_RESET_SENT:
tcp_state = NES_AEQE_TCP_STATE_CLOSED;
spin_lock_irqsave(&nesqp->lock, flags);
nesqp->hw_iwarp_state = iwarp_state;
nesqp->hw_tcp_state = tcp_state;
nesqp->last_aeq = async_event_id;
nesqp->hte_added = 0;
spin_unlock_irqrestore(&nesqp->lock, flags);
next_iwarp_state = NES_CQP_QP_IWARP_STATE_ERROR | NES_CQP_QP_DEL_HTE;
nes_hw_modify_qp(nesdev, nesqp, next_iwarp_state, 0, 0);
nes_cm_disconn(nesqp);
break;
case NES_AEQE_AEID_LLP_CONNECTION_RESET:
if (atomic_read(&nesqp->close_timer_started))
return;
spin_lock_irqsave(&nesqp->lock, flags);
nesqp->hw_iwarp_state = iwarp_state;
nesqp->hw_tcp_state = tcp_state;
nesqp->last_aeq = async_event_id;
spin_unlock_irqrestore(&nesqp->lock, flags);
nes_cm_disconn(nesqp);
break;
case NES_AEQE_AEID_TERMINATE_SENT:
nes_terminate_send_fin(nesdev, nesqp, aeqe);
break;
case NES_AEQE_AEID_LLP_TERMINATE_RECEIVED:
nes_terminate_received(nesdev, nesqp, aeqe);
break;
case NES_AEQE_AEID_AMP_BAD_STAG_KEY:
case NES_AEQE_AEID_AMP_BAD_STAG_INDEX:
case NES_AEQE_AEID_AMP_UNALLOCATED_STAG:
case NES_AEQE_AEID_AMP_INVALID_STAG:
case NES_AEQE_AEID_AMP_RIGHTS_VIOLATION:
case NES_AEQE_AEID_AMP_INVALIDATE_NO_REMOTE_ACCESS_RIGHTS:
case NES_AEQE_AEID_PRIV_OPERATION_DENIED:
case NES_AEQE_AEID_DDP_UBE_DDP_MESSAGE_TOO_LONG_FOR_AVAILABLE_BUFFER:
case NES_AEQE_AEID_AMP_BOUNDS_VIOLATION:
case NES_AEQE_AEID_AMP_TO_WRAP:
printk(KERN_ERR PFX "QP[%u] async_event_id=0x%04X IB_EVENT_QP_ACCESS_ERR\n",
nesqp->hwqp.qp_id, async_event_id);
nes_terminate_connection(nesdev, nesqp, aeqe, IB_EVENT_QP_ACCESS_ERR);
break;
case NES_AEQE_AEID_LLP_SEGMENT_TOO_LARGE:
case NES_AEQE_AEID_LLP_SEGMENT_TOO_SMALL:
case NES_AEQE_AEID_DDP_UBE_INVALID_MO:
case NES_AEQE_AEID_DDP_UBE_INVALID_QN:
if (iwarp_opcode(nesqp, aeq_info) > IWARP_OPCODE_TERM) {
aeq_info &= 0xffff0000;
aeq_info |= NES_AEQE_AEID_RDMAP_ROE_UNEXPECTED_OPCODE;
aeqe->aeqe_words[NES_AEQE_MISC_IDX] = cpu_to_le32(aeq_info);
}
case NES_AEQE_AEID_RDMAP_ROE_BAD_LLP_CLOSE:
case NES_AEQE_AEID_LLP_TOO_MANY_RETRIES:
case NES_AEQE_AEID_DDP_UBE_INVALID_MSN_NO_BUFFER_AVAILABLE:
case NES_AEQE_AEID_LLP_RECEIVED_MPA_CRC_ERROR:
case NES_AEQE_AEID_AMP_BAD_QP:
case NES_AEQE_AEID_LLP_RECEIVED_MARKER_AND_LENGTH_FIELDS_DONT_MATCH:
case NES_AEQE_AEID_DDP_LCE_LOCAL_CATASTROPHIC:
case NES_AEQE_AEID_DDP_NO_L_BIT:
case NES_AEQE_AEID_DDP_INVALID_MSN_GAP_IN_MSN:
case NES_AEQE_AEID_DDP_INVALID_MSN_RANGE_IS_NOT_VALID:
case NES_AEQE_AEID_DDP_UBE_INVALID_DDP_VERSION:
case NES_AEQE_AEID_RDMAP_ROE_INVALID_RDMAP_VERSION:
case NES_AEQE_AEID_RDMAP_ROE_UNEXPECTED_OPCODE:
case NES_AEQE_AEID_AMP_BAD_PD:
case NES_AEQE_AEID_AMP_FASTREG_SHARED:
case NES_AEQE_AEID_AMP_FASTREG_VALID_STAG:
case NES_AEQE_AEID_AMP_FASTREG_MW_STAG:
case NES_AEQE_AEID_AMP_FASTREG_INVALID_RIGHTS:
case NES_AEQE_AEID_AMP_FASTREG_PBL_TABLE_OVERFLOW:
case NES_AEQE_AEID_AMP_FASTREG_INVALID_LENGTH:
case NES_AEQE_AEID_AMP_INVALIDATE_SHARED:
case NES_AEQE_AEID_AMP_INVALIDATE_MR_WITH_BOUND_WINDOWS:
case NES_AEQE_AEID_AMP_MWBIND_VALID_STAG:
case NES_AEQE_AEID_AMP_MWBIND_OF_MR_STAG:
case NES_AEQE_AEID_AMP_MWBIND_TO_ZERO_BASED_STAG:
case NES_AEQE_AEID_AMP_MWBIND_TO_MW_STAG:
case NES_AEQE_AEID_AMP_MWBIND_INVALID_RIGHTS:
case NES_AEQE_AEID_AMP_MWBIND_INVALID_BOUNDS:
case NES_AEQE_AEID_AMP_MWBIND_TO_INVALID_PARENT:
case NES_AEQE_AEID_AMP_MWBIND_BIND_DISABLED:
case NES_AEQE_AEID_BAD_CLOSE:
case NES_AEQE_AEID_RDMA_READ_WHILE_ORD_ZERO:
case NES_AEQE_AEID_STAG_ZERO_INVALID:
case NES_AEQE_AEID_ROE_INVALID_RDMA_READ_REQUEST:
case NES_AEQE_AEID_ROE_INVALID_RDMA_WRITE_OR_READ_RESP:
printk(KERN_ERR PFX "QP[%u] async_event_id=0x%04X IB_EVENT_QP_FATAL\n",
nesqp->hwqp.qp_id, async_event_id);
print_ip(nesqp->cm_node);
if (!atomic_read(&nesqp->close_timer_started))
nes_terminate_connection(nesdev, nesqp, aeqe, IB_EVENT_QP_FATAL);
break;
case NES_AEQE_AEID_CQ_OPERATION_ERROR:
context <<= 1;
nes_debug(NES_DBG_AEQ, "Processing an NES_AEQE_AEID_CQ_OPERATION_ERROR event on CQ%u, %p\n",
le32_to_cpu(aeqe->aeqe_words[NES_AEQE_COMP_QP_CQ_ID_IDX]), (void *)(unsigned long)context);
resource_allocated = nes_is_resource_allocated(nesadapter, nesadapter->allocated_cqs,
le32_to_cpu(aeqe->aeqe_words[NES_AEQE_COMP_QP_CQ_ID_IDX]));
if (resource_allocated) {
printk(KERN_ERR PFX "%s: Processing an NES_AEQE_AEID_CQ_OPERATION_ERROR event on CQ%u\n",
__func__, le32_to_cpu(aeqe->aeqe_words[NES_AEQE_COMP_QP_CQ_ID_IDX]));
hw_cq = (struct nes_hw_cq *)(unsigned long)context;
if (hw_cq) {
nescq = container_of(hw_cq, struct nes_cq, hw_cq);
if (nescq->ibcq.event_handler) {
ibevent.device = nescq->ibcq.device;
ibevent.event = IB_EVENT_CQ_ERR;
ibevent.element.cq = &nescq->ibcq;
nescq->ibcq.event_handler(&ibevent, nescq->ibcq.cq_context);
}
}
}
break;
default:
nes_debug(NES_DBG_AEQ, "Processing an iWARP related AE for QP, misc = 0x%04X\n",
async_event_id);
break;
}
}
/**
* nes_iwarp_ce_handler
*/
void nes_iwarp_ce_handler(struct nes_device *nesdev, struct nes_hw_cq *hw_cq)
{
struct nes_cq *nescq = container_of(hw_cq, struct nes_cq, hw_cq);
/* nes_debug(NES_DBG_CQ, "Processing completion event for iWARP CQ%u.\n",
nescq->hw_cq.cq_number); */
nes_write32(nesdev->regs+NES_CQ_ACK, nescq->hw_cq.cq_number);
if (nescq->ibcq.comp_handler)
nescq->ibcq.comp_handler(&nescq->ibcq, nescq->ibcq.cq_context);
return;
}
/**
* nes_manage_apbvt()
*/
int nes_manage_apbvt(struct nes_vnic *nesvnic, u32 accel_local_port,
u32 nic_index, u32 add_port)
{
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_cqp_request *cqp_request;
int ret = 0;
u16 major_code;
/* Send manage APBVT request to CQP */
cqp_request = nes_get_cqp_request(nesdev);
if (cqp_request == NULL) {
nes_debug(NES_DBG_QP, "Failed to get a cqp_request.\n");
return -ENOMEM;
}
cqp_request->waiting = 1;
cqp_wqe = &cqp_request->cqp_wqe;
nes_debug(NES_DBG_QP, "%s APBV for local port=%u(0x%04x), nic_index=%u\n",
(add_port == NES_MANAGE_APBVT_ADD) ? "ADD" : "DEL",
accel_local_port, accel_local_port, nic_index);
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX, (NES_CQP_MANAGE_APBVT |
((add_port == NES_MANAGE_APBVT_ADD) ? NES_CQP_APBVT_ADD : 0)));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_ID_IDX,
((nic_index << NES_CQP_APBVT_NIC_SHIFT) | accel_local_port));
nes_debug(NES_DBG_QP, "Waiting for CQP completion for APBVT.\n");
atomic_set(&cqp_request->refcount, 2);
nes_post_cqp_request(nesdev, cqp_request);
if (add_port == NES_MANAGE_APBVT_ADD)
ret = wait_event_timeout(cqp_request->waitq, (cqp_request->request_done != 0),
NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_QP, "Completed, ret=%u, CQP Major:Minor codes = 0x%04X:0x%04X\n",
ret, cqp_request->major_code, cqp_request->minor_code);
major_code = cqp_request->major_code;
nes_put_cqp_request(nesdev, cqp_request);
if (!ret)
return -ETIME;
else if (major_code)
return -EIO;
else
return 0;
}
/**
* nes_manage_arp_cache
*/
void nes_manage_arp_cache(struct net_device *netdev, unsigned char *mac_addr,
u32 ip_addr, u32 action)
{
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_vnic *nesvnic = netdev_priv(netdev);
struct nes_device *nesdev;
struct nes_cqp_request *cqp_request;
int arp_index;
nesdev = nesvnic->nesdev;
arp_index = nes_arp_table(nesdev, ip_addr, mac_addr, action);
if (arp_index == -1) {
return;
}
/* update the ARP entry */
cqp_request = nes_get_cqp_request(nesdev);
if (cqp_request == NULL) {
nes_debug(NES_DBG_NETDEV, "Failed to get a cqp_request.\n");
return;
}
cqp_request->waiting = 0;
cqp_wqe = &cqp_request->cqp_wqe;
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] = cpu_to_le32(
NES_CQP_MANAGE_ARP_CACHE | NES_CQP_ARP_PERM);
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] |= cpu_to_le32(
(u32)PCI_FUNC(nesdev->pcidev->devfn) << NES_CQP_ARP_AEQ_INDEX_SHIFT);
cqp_wqe->wqe_words[NES_CQP_WQE_ID_IDX] = cpu_to_le32(arp_index);
if (action == NES_ARP_ADD) {
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] |= cpu_to_le32(NES_CQP_ARP_VALID);
cqp_wqe->wqe_words[NES_CQP_ARP_WQE_MAC_ADDR_LOW_IDX] = cpu_to_le32(
(((u32)mac_addr[2]) << 24) | (((u32)mac_addr[3]) << 16) |
(((u32)mac_addr[4]) << 8) | (u32)mac_addr[5]);
cqp_wqe->wqe_words[NES_CQP_ARP_WQE_MAC_HIGH_IDX] = cpu_to_le32(
(((u32)mac_addr[0]) << 16) | (u32)mac_addr[1]);
} else {
cqp_wqe->wqe_words[NES_CQP_ARP_WQE_MAC_ADDR_LOW_IDX] = 0;
cqp_wqe->wqe_words[NES_CQP_ARP_WQE_MAC_HIGH_IDX] = 0;
}
nes_debug(NES_DBG_NETDEV, "Not waiting for CQP, cqp.sq_head=%u, cqp.sq_tail=%u\n",
nesdev->cqp.sq_head, nesdev->cqp.sq_tail);
atomic_set(&cqp_request->refcount, 1);
nes_post_cqp_request(nesdev, cqp_request);
}
/**
* flush_wqes
*/
void flush_wqes(struct nes_device *nesdev, struct nes_qp *nesqp,
u32 which_wq, u32 wait_completion)
{
struct nes_cqp_request *cqp_request;
struct nes_hw_cqp_wqe *cqp_wqe;
u32 sq_code = (NES_IWARP_CQE_MAJOR_FLUSH << 16) | NES_IWARP_CQE_MINOR_FLUSH;
u32 rq_code = (NES_IWARP_CQE_MAJOR_FLUSH << 16) | NES_IWARP_CQE_MINOR_FLUSH;
int ret;
cqp_request = nes_get_cqp_request(nesdev);
if (cqp_request == NULL) {
nes_debug(NES_DBG_QP, "Failed to get a cqp_request.\n");
return;
}
if (wait_completion) {
cqp_request->waiting = 1;
atomic_set(&cqp_request->refcount, 2);
} else {
cqp_request->waiting = 0;
}
cqp_wqe = &cqp_request->cqp_wqe;
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
/* If wqe in error was identified, set code to be put into cqe */
if ((nesqp->term_sq_flush_code) && (which_wq & NES_CQP_FLUSH_SQ)) {
which_wq |= NES_CQP_FLUSH_MAJ_MIN;
sq_code = (CQE_MAJOR_DRV << 16) | nesqp->term_sq_flush_code;
nesqp->term_sq_flush_code = 0;
}
if ((nesqp->term_rq_flush_code) && (which_wq & NES_CQP_FLUSH_RQ)) {
which_wq |= NES_CQP_FLUSH_MAJ_MIN;
rq_code = (CQE_MAJOR_DRV << 16) | nesqp->term_rq_flush_code;
nesqp->term_rq_flush_code = 0;
}
if (which_wq & NES_CQP_FLUSH_MAJ_MIN) {
cqp_wqe->wqe_words[NES_CQP_QP_WQE_FLUSH_SQ_CODE] = cpu_to_le32(sq_code);
cqp_wqe->wqe_words[NES_CQP_QP_WQE_FLUSH_RQ_CODE] = cpu_to_le32(rq_code);
}
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] =
cpu_to_le32(NES_CQP_FLUSH_WQES | which_wq);
cqp_wqe->wqe_words[NES_CQP_WQE_ID_IDX] = cpu_to_le32(nesqp->hwqp.qp_id);
nes_post_cqp_request(nesdev, cqp_request);
if (wait_completion) {
/* Wait for CQP */
ret = wait_event_timeout(cqp_request->waitq, (cqp_request->request_done != 0),
NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_QP, "Flush SQ QP WQEs completed, ret=%u,"
" CQP Major:Minor codes = 0x%04X:0x%04X\n",
ret, cqp_request->major_code, cqp_request->minor_code);
nes_put_cqp_request(nesdev, cqp_request);
}
}
| gpl-2.0 |
AudioGod/DTS-Eagle-Integration_CAF-Android-kernel | arch/ia64/kernel/salinfo.c | 1895 | 19772 | /*
* salinfo.c
*
* Creates entries in /proc/sal for various system features.
*
* Copyright (c) 2003, 2006 Silicon Graphics, Inc. All rights reserved.
* Copyright (c) 2003 Hewlett-Packard Co
* Bjorn Helgaas <bjorn.helgaas@hp.com>
*
* 10/30/2001 jbarnes@sgi.com copied much of Stephane's palinfo
* code to create this file
* Oct 23 2003 kaos@sgi.com
* Replace IPI with set_cpus_allowed() to read a record from the required cpu.
* Redesign salinfo log processing to separate interrupt and user space
* contexts.
* Cache the record across multi-block reads from user space.
* Support > 64 cpus.
* Delete module_exit and MOD_INC/DEC_COUNT, salinfo cannot be a module.
*
* Jan 28 2004 kaos@sgi.com
* Periodically check for outstanding MCA or INIT records.
*
* Dec 5 2004 kaos@sgi.com
* Standardize which records are cleared automatically.
*
* Aug 18 2005 kaos@sgi.com
* mca.c may not pass a buffer, a NULL buffer just indicates that a new
* record is available in SAL.
* Replace some NR_CPUS by cpus_online, for hotplug cpu.
*
* Jan 5 2006 kaos@sgi.com
* Handle hotplug cpus coming online.
* Handle hotplug cpus going offline while they still have outstanding records.
* Use the cpu_* macros consistently.
* Replace the counting semaphore with a mutex and a test if the cpumask is non-empty.
* Modify the locking to make the test for "work to do" an atomic operation.
*/
#include <linux/capability.h>
#include <linux/cpu.h>
#include <linux/types.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/module.h>
#include <linux/smp.h>
#include <linux/timer.h>
#include <linux/vmalloc.h>
#include <linux/semaphore.h>
#include <asm/sal.h>
#include <asm/uaccess.h>
MODULE_AUTHOR("Jesse Barnes <jbarnes@sgi.com>");
MODULE_DESCRIPTION("/proc interface to IA-64 SAL features");
MODULE_LICENSE("GPL");
static const struct file_operations proc_salinfo_fops;
typedef struct {
const char *name; /* name of the proc entry */
unsigned long feature; /* feature bit */
struct proc_dir_entry *entry; /* registered entry (removal) */
} salinfo_entry_t;
/*
* List {name,feature} pairs for every entry in /proc/sal/<feature>
* that this module exports
*/
static const salinfo_entry_t salinfo_entries[]={
{ "bus_lock", IA64_SAL_PLATFORM_FEATURE_BUS_LOCK, },
{ "irq_redirection", IA64_SAL_PLATFORM_FEATURE_IRQ_REDIR_HINT, },
{ "ipi_redirection", IA64_SAL_PLATFORM_FEATURE_IPI_REDIR_HINT, },
{ "itc_drift", IA64_SAL_PLATFORM_FEATURE_ITC_DRIFT, },
};
#define NR_SALINFO_ENTRIES ARRAY_SIZE(salinfo_entries)
static char *salinfo_log_name[] = {
"mca",
"init",
"cmc",
"cpe",
};
static struct proc_dir_entry *salinfo_proc_entries[
ARRAY_SIZE(salinfo_entries) + /* /proc/sal/bus_lock */
ARRAY_SIZE(salinfo_log_name) + /* /proc/sal/{mca,...} */
(2 * ARRAY_SIZE(salinfo_log_name)) + /* /proc/sal/mca/{event,data} */
1]; /* /proc/sal */
/* Some records we get ourselves, some are accessed as saved data in buffers
* that are owned by mca.c.
*/
struct salinfo_data_saved {
u8* buffer;
u64 size;
u64 id;
int cpu;
};
/* State transitions. Actions are :-
* Write "read <cpunum>" to the data file.
* Write "clear <cpunum>" to the data file.
* Write "oemdata <cpunum> <offset> to the data file.
* Read from the data file.
* Close the data file.
*
* Start state is NO_DATA.
*
* NO_DATA
* write "read <cpunum>" -> NO_DATA or LOG_RECORD.
* write "clear <cpunum>" -> NO_DATA or LOG_RECORD.
* write "oemdata <cpunum> <offset> -> return -EINVAL.
* read data -> return EOF.
* close -> unchanged. Free record areas.
*
* LOG_RECORD
* write "read <cpunum>" -> NO_DATA or LOG_RECORD.
* write "clear <cpunum>" -> NO_DATA or LOG_RECORD.
* write "oemdata <cpunum> <offset> -> format the oem data, goto OEMDATA.
* read data -> return the INIT/MCA/CMC/CPE record.
* close -> unchanged. Keep record areas.
*
* OEMDATA
* write "read <cpunum>" -> NO_DATA or LOG_RECORD.
* write "clear <cpunum>" -> NO_DATA or LOG_RECORD.
* write "oemdata <cpunum> <offset> -> format the oem data, goto OEMDATA.
* read data -> return the formatted oemdata.
* close -> unchanged. Keep record areas.
*
* Closing the data file does not change the state. This allows shell scripts
* to manipulate salinfo data, each shell redirection opens the file, does one
* action then closes it again. The record areas are only freed at close when
* the state is NO_DATA.
*/
enum salinfo_state {
STATE_NO_DATA,
STATE_LOG_RECORD,
STATE_OEMDATA,
};
struct salinfo_data {
cpumask_t cpu_event; /* which cpus have outstanding events */
struct semaphore mutex;
u8 *log_buffer;
u64 log_size;
u8 *oemdata; /* decoded oem data */
u64 oemdata_size;
int open; /* single-open to prevent races */
u8 type;
u8 saved_num; /* using a saved record? */
enum salinfo_state state :8; /* processing state */
u8 padding;
int cpu_check; /* next CPU to check */
struct salinfo_data_saved data_saved[5];/* save last 5 records from mca.c, must be < 255 */
};
static struct salinfo_data salinfo_data[ARRAY_SIZE(salinfo_log_name)];
static DEFINE_SPINLOCK(data_lock);
static DEFINE_SPINLOCK(data_saved_lock);
/** salinfo_platform_oemdata - optional callback to decode oemdata from an error
* record.
* @sect_header: pointer to the start of the section to decode.
* @oemdata: returns vmalloc area containing the decoded output.
* @oemdata_size: returns length of decoded output (strlen).
*
* Description: If user space asks for oem data to be decoded by the kernel
* and/or prom and the platform has set salinfo_platform_oemdata to the address
* of a platform specific routine then call that routine. salinfo_platform_oemdata
* vmalloc's and formats its output area, returning the address of the text
* and its strlen. Returns 0 for success, -ve for error. The callback is
* invoked on the cpu that generated the error record.
*/
int (*salinfo_platform_oemdata)(const u8 *sect_header, u8 **oemdata, u64 *oemdata_size);
struct salinfo_platform_oemdata_parms {
const u8 *efi_guid;
u8 **oemdata;
u64 *oemdata_size;
int ret;
};
/* Kick the mutex that tells user space that there is work to do. Instead of
* trying to track the state of the mutex across multiple cpus, in user
* context, interrupt context, non-maskable interrupt context and hotplug cpu,
* it is far easier just to grab the mutex if it is free then release it.
*
* This routine must be called with data_saved_lock held, to make the down/up
* operation atomic.
*/
static void
salinfo_work_to_do(struct salinfo_data *data)
{
(void)(down_trylock(&data->mutex) ?: 0);
up(&data->mutex);
}
static void
salinfo_platform_oemdata_cpu(void *context)
{
struct salinfo_platform_oemdata_parms *parms = context;
parms->ret = salinfo_platform_oemdata(parms->efi_guid, parms->oemdata, parms->oemdata_size);
}
static void
shift1_data_saved (struct salinfo_data *data, int shift)
{
memcpy(data->data_saved+shift, data->data_saved+shift+1,
(ARRAY_SIZE(data->data_saved) - (shift+1)) * sizeof(data->data_saved[0]));
memset(data->data_saved + ARRAY_SIZE(data->data_saved) - 1, 0,
sizeof(data->data_saved[0]));
}
/* This routine is invoked in interrupt context. Note: mca.c enables
* interrupts before calling this code for CMC/CPE. MCA and INIT events are
* not irq safe, do not call any routines that use spinlocks, they may deadlock.
* MCA and INIT records are recorded, a timer event will look for any
* outstanding events and wake up the user space code.
*
* The buffer passed from mca.c points to the output from ia64_log_get. This is
* a persistent buffer but its contents can change between the interrupt and
* when user space processes the record. Save the record id to identify
* changes. If the buffer is NULL then just update the bitmap.
*/
void
salinfo_log_wakeup(int type, u8 *buffer, u64 size, int irqsafe)
{
struct salinfo_data *data = salinfo_data + type;
struct salinfo_data_saved *data_saved;
unsigned long flags = 0;
int i;
int saved_size = ARRAY_SIZE(data->data_saved);
BUG_ON(type >= ARRAY_SIZE(salinfo_log_name));
if (irqsafe)
spin_lock_irqsave(&data_saved_lock, flags);
if (buffer) {
for (i = 0, data_saved = data->data_saved; i < saved_size; ++i, ++data_saved) {
if (!data_saved->buffer)
break;
}
if (i == saved_size) {
if (!data->saved_num) {
shift1_data_saved(data, 0);
data_saved = data->data_saved + saved_size - 1;
} else
data_saved = NULL;
}
if (data_saved) {
data_saved->cpu = smp_processor_id();
data_saved->id = ((sal_log_record_header_t *)buffer)->id;
data_saved->size = size;
data_saved->buffer = buffer;
}
}
cpu_set(smp_processor_id(), data->cpu_event);
if (irqsafe) {
salinfo_work_to_do(data);
spin_unlock_irqrestore(&data_saved_lock, flags);
}
}
/* Check for outstanding MCA/INIT records every minute (arbitrary) */
#define SALINFO_TIMER_DELAY (60*HZ)
static struct timer_list salinfo_timer;
extern void ia64_mlogbuf_dump(void);
static void
salinfo_timeout_check(struct salinfo_data *data)
{
unsigned long flags;
if (!data->open)
return;
if (!cpus_empty(data->cpu_event)) {
spin_lock_irqsave(&data_saved_lock, flags);
salinfo_work_to_do(data);
spin_unlock_irqrestore(&data_saved_lock, flags);
}
}
static void
salinfo_timeout (unsigned long arg)
{
ia64_mlogbuf_dump();
salinfo_timeout_check(salinfo_data + SAL_INFO_TYPE_MCA);
salinfo_timeout_check(salinfo_data + SAL_INFO_TYPE_INIT);
salinfo_timer.expires = jiffies + SALINFO_TIMER_DELAY;
add_timer(&salinfo_timer);
}
static int
salinfo_event_open(struct inode *inode, struct file *file)
{
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
return 0;
}
static ssize_t
salinfo_event_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
{
struct salinfo_data *data = PDE_DATA(file_inode(file));
char cmd[32];
size_t size;
int i, n, cpu = -1;
retry:
if (cpus_empty(data->cpu_event) && down_trylock(&data->mutex)) {
if (file->f_flags & O_NONBLOCK)
return -EAGAIN;
if (down_interruptible(&data->mutex))
return -EINTR;
}
n = data->cpu_check;
for (i = 0; i < nr_cpu_ids; i++) {
if (cpu_isset(n, data->cpu_event)) {
if (!cpu_online(n)) {
cpu_clear(n, data->cpu_event);
continue;
}
cpu = n;
break;
}
if (++n == nr_cpu_ids)
n = 0;
}
if (cpu == -1)
goto retry;
ia64_mlogbuf_dump();
/* for next read, start checking at next CPU */
data->cpu_check = cpu;
if (++data->cpu_check == nr_cpu_ids)
data->cpu_check = 0;
snprintf(cmd, sizeof(cmd), "read %d\n", cpu);
size = strlen(cmd);
if (size > count)
size = count;
if (copy_to_user(buffer, cmd, size))
return -EFAULT;
return size;
}
static const struct file_operations salinfo_event_fops = {
.open = salinfo_event_open,
.read = salinfo_event_read,
.llseek = noop_llseek,
};
static int
salinfo_log_open(struct inode *inode, struct file *file)
{
struct salinfo_data *data = PDE_DATA(inode);
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
spin_lock(&data_lock);
if (data->open) {
spin_unlock(&data_lock);
return -EBUSY;
}
data->open = 1;
spin_unlock(&data_lock);
if (data->state == STATE_NO_DATA &&
!(data->log_buffer = vmalloc(ia64_sal_get_state_info_size(data->type)))) {
data->open = 0;
return -ENOMEM;
}
return 0;
}
static int
salinfo_log_release(struct inode *inode, struct file *file)
{
struct salinfo_data *data = PDE_DATA(inode);
if (data->state == STATE_NO_DATA) {
vfree(data->log_buffer);
vfree(data->oemdata);
data->log_buffer = NULL;
data->oemdata = NULL;
}
spin_lock(&data_lock);
data->open = 0;
spin_unlock(&data_lock);
return 0;
}
static void
call_on_cpu(int cpu, void (*fn)(void *), void *arg)
{
cpumask_t save_cpus_allowed = current->cpus_allowed;
set_cpus_allowed_ptr(current, cpumask_of(cpu));
(*fn)(arg);
set_cpus_allowed_ptr(current, &save_cpus_allowed);
}
static void
salinfo_log_read_cpu(void *context)
{
struct salinfo_data *data = context;
sal_log_record_header_t *rh;
data->log_size = ia64_sal_get_state_info(data->type, (u64 *) data->log_buffer);
rh = (sal_log_record_header_t *)(data->log_buffer);
/* Clear corrected errors as they are read from SAL */
if (rh->severity == sal_log_severity_corrected)
ia64_sal_clear_state_info(data->type);
}
static void
salinfo_log_new_read(int cpu, struct salinfo_data *data)
{
struct salinfo_data_saved *data_saved;
unsigned long flags;
int i;
int saved_size = ARRAY_SIZE(data->data_saved);
data->saved_num = 0;
spin_lock_irqsave(&data_saved_lock, flags);
retry:
for (i = 0, data_saved = data->data_saved; i < saved_size; ++i, ++data_saved) {
if (data_saved->buffer && data_saved->cpu == cpu) {
sal_log_record_header_t *rh = (sal_log_record_header_t *)(data_saved->buffer);
data->log_size = data_saved->size;
memcpy(data->log_buffer, rh, data->log_size);
barrier(); /* id check must not be moved */
if (rh->id == data_saved->id) {
data->saved_num = i+1;
break;
}
/* saved record changed by mca.c since interrupt, discard it */
shift1_data_saved(data, i);
goto retry;
}
}
spin_unlock_irqrestore(&data_saved_lock, flags);
if (!data->saved_num)
call_on_cpu(cpu, salinfo_log_read_cpu, data);
if (!data->log_size) {
data->state = STATE_NO_DATA;
cpu_clear(cpu, data->cpu_event);
} else {
data->state = STATE_LOG_RECORD;
}
}
static ssize_t
salinfo_log_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
{
struct salinfo_data *data = PDE_DATA(file_inode(file));
u8 *buf;
u64 bufsize;
if (data->state == STATE_LOG_RECORD) {
buf = data->log_buffer;
bufsize = data->log_size;
} else if (data->state == STATE_OEMDATA) {
buf = data->oemdata;
bufsize = data->oemdata_size;
} else {
buf = NULL;
bufsize = 0;
}
return simple_read_from_buffer(buffer, count, ppos, buf, bufsize);
}
static void
salinfo_log_clear_cpu(void *context)
{
struct salinfo_data *data = context;
ia64_sal_clear_state_info(data->type);
}
static int
salinfo_log_clear(struct salinfo_data *data, int cpu)
{
sal_log_record_header_t *rh;
unsigned long flags;
spin_lock_irqsave(&data_saved_lock, flags);
data->state = STATE_NO_DATA;
if (!cpu_isset(cpu, data->cpu_event)) {
spin_unlock_irqrestore(&data_saved_lock, flags);
return 0;
}
cpu_clear(cpu, data->cpu_event);
if (data->saved_num) {
shift1_data_saved(data, data->saved_num - 1);
data->saved_num = 0;
}
spin_unlock_irqrestore(&data_saved_lock, flags);
rh = (sal_log_record_header_t *)(data->log_buffer);
/* Corrected errors have already been cleared from SAL */
if (rh->severity != sal_log_severity_corrected)
call_on_cpu(cpu, salinfo_log_clear_cpu, data);
/* clearing a record may make a new record visible */
salinfo_log_new_read(cpu, data);
if (data->state == STATE_LOG_RECORD) {
spin_lock_irqsave(&data_saved_lock, flags);
cpu_set(cpu, data->cpu_event);
salinfo_work_to_do(data);
spin_unlock_irqrestore(&data_saved_lock, flags);
}
return 0;
}
static ssize_t
salinfo_log_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
{
struct salinfo_data *data = PDE_DATA(file_inode(file));
char cmd[32];
size_t size;
u32 offset;
int cpu;
size = sizeof(cmd);
if (count < size)
size = count;
if (copy_from_user(cmd, buffer, size))
return -EFAULT;
if (sscanf(cmd, "read %d", &cpu) == 1) {
salinfo_log_new_read(cpu, data);
} else if (sscanf(cmd, "clear %d", &cpu) == 1) {
int ret;
if ((ret = salinfo_log_clear(data, cpu)))
count = ret;
} else if (sscanf(cmd, "oemdata %d %d", &cpu, &offset) == 2) {
if (data->state != STATE_LOG_RECORD && data->state != STATE_OEMDATA)
return -EINVAL;
if (offset > data->log_size - sizeof(efi_guid_t))
return -EINVAL;
data->state = STATE_OEMDATA;
if (salinfo_platform_oemdata) {
struct salinfo_platform_oemdata_parms parms = {
.efi_guid = data->log_buffer + offset,
.oemdata = &data->oemdata,
.oemdata_size = &data->oemdata_size
};
call_on_cpu(cpu, salinfo_platform_oemdata_cpu, &parms);
if (parms.ret)
count = parms.ret;
} else
data->oemdata_size = 0;
} else
return -EINVAL;
return count;
}
static const struct file_operations salinfo_data_fops = {
.open = salinfo_log_open,
.release = salinfo_log_release,
.read = salinfo_log_read,
.write = salinfo_log_write,
.llseek = default_llseek,
};
static int __cpuinit
salinfo_cpu_callback(struct notifier_block *nb, unsigned long action, void *hcpu)
{
unsigned int i, cpu = (unsigned long)hcpu;
unsigned long flags;
struct salinfo_data *data;
switch (action) {
case CPU_ONLINE:
case CPU_ONLINE_FROZEN:
spin_lock_irqsave(&data_saved_lock, flags);
for (i = 0, data = salinfo_data;
i < ARRAY_SIZE(salinfo_data);
++i, ++data) {
cpu_set(cpu, data->cpu_event);
salinfo_work_to_do(data);
}
spin_unlock_irqrestore(&data_saved_lock, flags);
break;
case CPU_DEAD:
case CPU_DEAD_FROZEN:
spin_lock_irqsave(&data_saved_lock, flags);
for (i = 0, data = salinfo_data;
i < ARRAY_SIZE(salinfo_data);
++i, ++data) {
struct salinfo_data_saved *data_saved;
int j;
for (j = ARRAY_SIZE(data->data_saved) - 1, data_saved = data->data_saved + j;
j >= 0;
--j, --data_saved) {
if (data_saved->buffer && data_saved->cpu == cpu) {
shift1_data_saved(data, j);
}
}
cpu_clear(cpu, data->cpu_event);
}
spin_unlock_irqrestore(&data_saved_lock, flags);
break;
}
return NOTIFY_OK;
}
static struct notifier_block salinfo_cpu_notifier __cpuinitdata =
{
.notifier_call = salinfo_cpu_callback,
.priority = 0,
};
static int __init
salinfo_init(void)
{
struct proc_dir_entry *salinfo_dir; /* /proc/sal dir entry */
struct proc_dir_entry **sdir = salinfo_proc_entries; /* keeps track of every entry */
struct proc_dir_entry *dir, *entry;
struct salinfo_data *data;
int i, j;
salinfo_dir = proc_mkdir("sal", NULL);
if (!salinfo_dir)
return 0;
for (i=0; i < NR_SALINFO_ENTRIES; i++) {
/* pass the feature bit in question as misc data */
*sdir++ = proc_create_data(salinfo_entries[i].name, 0, salinfo_dir,
&proc_salinfo_fops,
(void *)salinfo_entries[i].feature);
}
for (i = 0; i < ARRAY_SIZE(salinfo_log_name); i++) {
data = salinfo_data + i;
data->type = i;
sema_init(&data->mutex, 1);
dir = proc_mkdir(salinfo_log_name[i], salinfo_dir);
if (!dir)
continue;
entry = proc_create_data("event", S_IRUSR, dir,
&salinfo_event_fops, data);
if (!entry)
continue;
*sdir++ = entry;
entry = proc_create_data("data", S_IRUSR | S_IWUSR, dir,
&salinfo_data_fops, data);
if (!entry)
continue;
*sdir++ = entry;
/* we missed any events before now */
for_each_online_cpu(j)
cpu_set(j, data->cpu_event);
*sdir++ = dir;
}
*sdir++ = salinfo_dir;
init_timer(&salinfo_timer);
salinfo_timer.expires = jiffies + SALINFO_TIMER_DELAY;
salinfo_timer.function = &salinfo_timeout;
add_timer(&salinfo_timer);
register_hotcpu_notifier(&salinfo_cpu_notifier);
return 0;
}
/*
* 'data' contains an integer that corresponds to the feature we're
* testing
*/
static int proc_salinfo_show(struct seq_file *m, void *v)
{
unsigned long data = (unsigned long)v;
seq_puts(m, (sal_platform_features & data) ? "1\n" : "0\n");
return 0;
}
static int proc_salinfo_open(struct inode *inode, struct file *file)
{
return single_open(file, proc_salinfo_show, PDE_DATA(inode));
}
static const struct file_operations proc_salinfo_fops = {
.open = proc_salinfo_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
module_init(salinfo_init);
| gpl-2.0 |
ariafan/S5501-3.10 | drivers/net/wireless/ti/wl18xx/cmd.c | 2663 | 2153 | /*
* This file is part of wl18xx
*
* Copyright (C) 2011 Texas Instruments Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "../wlcore/cmd.h"
#include "../wlcore/debug.h"
#include "../wlcore/hw_ops.h"
#include "cmd.h"
int wl18xx_cmd_channel_switch(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
struct ieee80211_channel_switch *ch_switch)
{
struct wl18xx_cmd_channel_switch *cmd;
u32 supported_rates;
int ret;
wl1271_debug(DEBUG_ACX, "cmd channel switch");
cmd = kzalloc(sizeof(*cmd), GFP_KERNEL);
if (!cmd) {
ret = -ENOMEM;
goto out;
}
cmd->role_id = wlvif->role_id;
cmd->channel = ch_switch->chandef.chan->hw_value;
cmd->switch_time = ch_switch->count;
cmd->stop_tx = ch_switch->block_tx;
switch (ch_switch->chandef.chan->band) {
case IEEE80211_BAND_2GHZ:
cmd->band = WLCORE_BAND_2_4GHZ;
break;
case IEEE80211_BAND_5GHZ:
cmd->band = WLCORE_BAND_5GHZ;
break;
default:
wl1271_error("invalid channel switch band: %d",
ch_switch->chandef.chan->band);
ret = -EINVAL;
goto out_free;
}
supported_rates = CONF_TX_ENABLED_RATES | CONF_TX_MCS_RATES |
wlcore_hw_sta_get_ap_rate_mask(wl, wlvif);
if (wlvif->p2p)
supported_rates &= ~CONF_TX_CCK_RATES;
cmd->local_supported_rates = cpu_to_le32(supported_rates);
cmd->channel_type = wlvif->channel_type;
ret = wl1271_cmd_send(wl, CMD_CHANNEL_SWITCH, cmd, sizeof(*cmd), 0);
if (ret < 0) {
wl1271_error("failed to send channel switch command");
goto out_free;
}
out_free:
kfree(cmd);
out:
return ret;
}
| gpl-2.0 |
tbalden/One_X-2.6.39.4 | drivers/usb/gadget/multi.c | 2663 | 8199 | /*
* multi.c -- Multifunction Composite driver
*
* Copyright (C) 2008 David Brownell
* Copyright (C) 2008 Nokia Corporation
* Copyright (C) 2009 Samsung Electronics
* Author: Michal Nazarewicz (m.nazarewicz@samsung.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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/utsname.h>
#include <linux/module.h>
#if defined USB_ETH_RNDIS
# undef USB_ETH_RNDIS
#endif
#ifdef CONFIG_USB_G_MULTI_RNDIS
# define USB_ETH_RNDIS y
#endif
#define DRIVER_DESC "Multifunction Composite Gadget"
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_AUTHOR("Michal Nazarewicz");
MODULE_LICENSE("GPL");
/***************************** All the files... *****************************/
/*
* kbuild is not very cooperative with respect to linking separately
* compiled library objects into one module. So for now we won't use
* separate compilation ... ensuring init/exit sections work to shrink
* the runtime footprint, and giving us at least some parts of what
* a "gcc --combine ... part1.c part2.c part3.c ... " build would.
*/
#include "composite.c"
#include "usbstring.c"
#include "config.c"
#include "epautoconf.c"
#include "f_mass_storage.c"
#include "u_serial.c"
#include "f_acm.c"
#include "f_ecm.c"
#include "f_subset.c"
#ifdef USB_ETH_RNDIS
# include "f_rndis.c"
# include "rndis.c"
#endif
#include "u_ether.c"
/***************************** Device Descriptor ****************************/
#define MULTI_VENDOR_NUM 0x1d6b /* Linux Foundation */
#define MULTI_PRODUCT_NUM 0x0104 /* Multifunction Composite Gadget */
enum {
__MULTI_NO_CONFIG,
#ifdef CONFIG_USB_G_MULTI_RNDIS
MULTI_RNDIS_CONFIG_NUM,
#endif
#ifdef CONFIG_USB_G_MULTI_CDC
MULTI_CDC_CONFIG_NUM,
#endif
};
static struct usb_device_descriptor device_desc = {
.bLength = sizeof device_desc,
.bDescriptorType = USB_DT_DEVICE,
.bcdUSB = cpu_to_le16(0x0200),
.bDeviceClass = USB_CLASS_MISC /* 0xEF */,
.bDeviceSubClass = 2,
.bDeviceProtocol = 1,
/* Vendor and product id can be overridden by module parameters. */
.idVendor = cpu_to_le16(MULTI_VENDOR_NUM),
.idProduct = cpu_to_le16(MULTI_PRODUCT_NUM),
};
static const struct usb_descriptor_header *otg_desc[] = {
(struct usb_descriptor_header *) &(struct usb_otg_descriptor){
.bLength = sizeof(struct usb_otg_descriptor),
.bDescriptorType = USB_DT_OTG,
/*
* REVISIT SRP-only hardware is possible, although
* it would not be called "OTG" ...
*/
.bmAttributes = USB_OTG_SRP | USB_OTG_HNP,
},
NULL,
};
enum {
#ifdef CONFIG_USB_G_MULTI_RNDIS
MULTI_STRING_RNDIS_CONFIG_IDX,
#endif
#ifdef CONFIG_USB_G_MULTI_CDC
MULTI_STRING_CDC_CONFIG_IDX,
#endif
};
static struct usb_string strings_dev[] = {
#ifdef CONFIG_USB_G_MULTI_RNDIS
[MULTI_STRING_RNDIS_CONFIG_IDX].s = "Multifunction with RNDIS",
#endif
#ifdef CONFIG_USB_G_MULTI_CDC
[MULTI_STRING_CDC_CONFIG_IDX].s = "Multifunction with CDC ECM",
#endif
{ } /* end of list */
};
static struct usb_gadget_strings *dev_strings[] = {
&(struct usb_gadget_strings){
.language = 0x0409, /* en-us */
.strings = strings_dev,
},
NULL,
};
/****************************** Configurations ******************************/
static struct fsg_module_parameters fsg_mod_data = { .stall = 1 };
FSG_MODULE_PARAMETERS(/* no prefix */, fsg_mod_data);
static struct fsg_common fsg_common;
static u8 hostaddr[ETH_ALEN];
/********** RNDIS **********/
#ifdef USB_ETH_RNDIS
static __init int rndis_do_config(struct usb_configuration *c)
{
int ret;
if (gadget_is_otg(c->cdev->gadget)) {
c->descriptors = otg_desc;
c->bmAttributes |= USB_CONFIG_ATT_WAKEUP;
}
ret = rndis_bind_config(c, hostaddr);
if (ret < 0)
return ret;
ret = acm_bind_config(c, 0);
if (ret < 0)
return ret;
ret = fsg_bind_config(c->cdev, c, &fsg_common);
if (ret < 0)
return ret;
return 0;
}
static int rndis_config_register(struct usb_composite_dev *cdev)
{
static struct usb_configuration config = {
.bConfigurationValue = MULTI_RNDIS_CONFIG_NUM,
.bmAttributes = USB_CONFIG_ATT_SELFPOWER,
};
config.label = strings_dev[MULTI_STRING_RNDIS_CONFIG_IDX].s;
config.iConfiguration = strings_dev[MULTI_STRING_RNDIS_CONFIG_IDX].id;
return usb_add_config(cdev, &config, rndis_do_config);
}
#else
static int rndis_config_register(struct usb_composite_dev *cdev)
{
return 0;
}
#endif
/********** CDC ECM **********/
#ifdef CONFIG_USB_G_MULTI_CDC
static __init int cdc_do_config(struct usb_configuration *c)
{
int ret;
if (gadget_is_otg(c->cdev->gadget)) {
c->descriptors = otg_desc;
c->bmAttributes |= USB_CONFIG_ATT_WAKEUP;
}
ret = ecm_bind_config(c, hostaddr);
if (ret < 0)
return ret;
ret = acm_bind_config(c, 0);
if (ret < 0)
return ret;
ret = fsg_bind_config(c->cdev, c, &fsg_common);
if (ret < 0)
return ret;
return 0;
}
static int cdc_config_register(struct usb_composite_dev *cdev)
{
static struct usb_configuration config = {
.bConfigurationValue = MULTI_CDC_CONFIG_NUM,
.bmAttributes = USB_CONFIG_ATT_SELFPOWER,
};
config.label = strings_dev[MULTI_STRING_CDC_CONFIG_IDX].s;
config.iConfiguration = strings_dev[MULTI_STRING_CDC_CONFIG_IDX].id;
return usb_add_config(cdev, &config, cdc_do_config);
}
#else
static int cdc_config_register(struct usb_composite_dev *cdev)
{
return 0;
}
#endif
/****************************** Gadget Bind ******************************/
static int __ref multi_bind(struct usb_composite_dev *cdev)
{
struct usb_gadget *gadget = cdev->gadget;
int status, gcnum;
if (!can_support_ecm(cdev->gadget)) {
dev_err(&gadget->dev, "controller '%s' not usable\n",
gadget->name);
return -EINVAL;
}
/* set up network link layer */
status = gether_setup(cdev->gadget, hostaddr);
if (status < 0)
return status;
/* set up serial link layer */
status = gserial_setup(cdev->gadget, 1);
if (status < 0)
goto fail0;
/* set up mass storage function */
{
void *retp;
retp = fsg_common_from_params(&fsg_common, cdev, &fsg_mod_data);
if (IS_ERR(retp)) {
status = PTR_ERR(retp);
goto fail1;
}
}
/* set bcdDevice */
gcnum = usb_gadget_controller_number(gadget);
if (gcnum >= 0) {
device_desc.bcdDevice = cpu_to_le16(0x0300 | gcnum);
} else {
WARNING(cdev, "controller '%s' not recognized\n", gadget->name);
device_desc.bcdDevice = cpu_to_le16(0x0300 | 0x0099);
}
/* allocate string IDs */
status = usb_string_ids_tab(cdev, strings_dev);
if (unlikely(status < 0))
goto fail2;
/* register configurations */
status = rndis_config_register(cdev);
if (unlikely(status < 0))
goto fail2;
status = cdc_config_register(cdev);
if (unlikely(status < 0))
goto fail2;
/* we're done */
dev_info(&gadget->dev, DRIVER_DESC "\n");
fsg_common_put(&fsg_common);
return 0;
/* error recovery */
fail2:
fsg_common_put(&fsg_common);
fail1:
gserial_cleanup();
fail0:
gether_cleanup();
return status;
}
static int __exit multi_unbind(struct usb_composite_dev *cdev)
{
gserial_cleanup();
gether_cleanup();
return 0;
}
/****************************** Some noise ******************************/
static struct usb_composite_driver multi_driver = {
.name = "g_multi",
.dev = &device_desc,
.strings = dev_strings,
.unbind = __exit_p(multi_unbind),
.iProduct = DRIVER_DESC,
.needs_serial = 1,
};
static int __init multi_init(void)
{
return usb_composite_probe(&multi_driver, multi_bind);
}
module_init(multi_init);
static void __exit multi_exit(void)
{
usb_composite_unregister(&multi_driver);
}
module_exit(multi_exit);
| gpl-2.0 |
kakazhang/kernel | drivers/video/aty/radeon_base.c | 2919 | 76856 | /*
* drivers/video/aty/radeon_base.c
*
* framebuffer driver for ATI Radeon chipset video boards
*
* Copyright 2003 Ben. Herrenschmidt <benh@kernel.crashing.org>
* Copyright 2000 Ani Joshi <ajoshi@kernel.crashing.org>
*
* i2c bits from Luca Tettamanti <kronos@kronoz.cjb.net>
*
* Special thanks to ATI DevRel team for their hardware donations.
*
* ...Insert GPL boilerplate here...
*
* Significant portions of this driver apdated from XFree86 Radeon
* driver which has the following copyright notice:
*
* Copyright 2000 ATI Technologies Inc., Markham, Ontario, and
* VA Linux Systems Inc., Fremont, California.
*
* 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 on the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON-INFRINGEMENT. IN NO EVENT SHALL ATI, VA LINUX SYSTEMS AND/OR
* THEIR 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.
*
* XFree86 driver authors:
*
* Kevin E. Martin <martin@xfree86.org>
* Rickard E. Faith <faith@valinux.com>
* Alan Hourihane <alanh@fairlite.demon.co.uk>
*
*/
#define RADEON_VERSION "0.2.0"
#include "radeonfb.h"
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/time.h>
#include <linux/fb.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include <linux/device.h>
#include <asm/io.h>
#include <linux/uaccess.h>
#ifdef CONFIG_PPC_OF
#include <asm/pci-bridge.h>
#include "../macmodes.h"
#ifdef CONFIG_BOOTX_TEXT
#include <asm/btext.h>
#endif
#endif /* CONFIG_PPC_OF */
#ifdef CONFIG_MTRR
#include <asm/mtrr.h>
#endif
#include <video/radeon.h>
#include <linux/radeonfb.h>
#include "../edid.h" // MOVE THAT TO include/video
#include "ati_ids.h"
#define MAX_MAPPED_VRAM (2048*2048*4)
#define MIN_MAPPED_VRAM (1024*768*1)
#define CHIP_DEF(id, family, flags) \
{ PCI_VENDOR_ID_ATI, id, PCI_ANY_ID, PCI_ANY_ID, 0, 0, (flags) | (CHIP_FAMILY_##family) }
static struct pci_device_id radeonfb_pci_table[] = {
/* Radeon Xpress 200m */
CHIP_DEF(PCI_CHIP_RS480_5955, RS480, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RS482_5975, RS480, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* Mobility M6 */
CHIP_DEF(PCI_CHIP_RADEON_LY, RV100, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RADEON_LZ, RV100, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* Radeon VE/7000 */
CHIP_DEF(PCI_CHIP_RV100_QY, RV100, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV100_QZ, RV100, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RN50, RV100, CHIP_HAS_CRTC2),
/* Radeon IGP320M (U1) */
CHIP_DEF(PCI_CHIP_RS100_4336, RS100, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* Radeon IGP320 (A3) */
CHIP_DEF(PCI_CHIP_RS100_4136, RS100, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
/* IGP330M/340M/350M (U2) */
CHIP_DEF(PCI_CHIP_RS200_4337, RS200, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* IGP330/340/350 (A4) */
CHIP_DEF(PCI_CHIP_RS200_4137, RS200, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
/* Mobility 7000 IGP */
CHIP_DEF(PCI_CHIP_RS250_4437, RS200, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* 7000 IGP (A4+) */
CHIP_DEF(PCI_CHIP_RS250_4237, RS200, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
/* 8500 AIW */
CHIP_DEF(PCI_CHIP_R200_BB, R200, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R200_BC, R200, CHIP_HAS_CRTC2),
/* 8700/8800 */
CHIP_DEF(PCI_CHIP_R200_QH, R200, CHIP_HAS_CRTC2),
/* 8500 */
CHIP_DEF(PCI_CHIP_R200_QL, R200, CHIP_HAS_CRTC2),
/* 9100 */
CHIP_DEF(PCI_CHIP_R200_QM, R200, CHIP_HAS_CRTC2),
/* Mobility M7 */
CHIP_DEF(PCI_CHIP_RADEON_LW, RV200, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RADEON_LX, RV200, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* 7500 */
CHIP_DEF(PCI_CHIP_RV200_QW, RV200, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV200_QX, RV200, CHIP_HAS_CRTC2),
/* Mobility M9 */
CHIP_DEF(PCI_CHIP_RV250_Ld, RV250, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV250_Le, RV250, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV250_Lf, RV250, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV250_Lg, RV250, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* 9000/Pro */
CHIP_DEF(PCI_CHIP_RV250_If, RV250, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV250_Ig, RV250, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RC410_5A62, RC410, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* Mobility 9100 IGP (U3) */
CHIP_DEF(PCI_CHIP_RS300_5835, RS300, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RS350_7835, RS300, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* 9100 IGP (A5) */
CHIP_DEF(PCI_CHIP_RS300_5834, RS300, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
CHIP_DEF(PCI_CHIP_RS350_7834, RS300, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
/* Mobility 9200 (M9+) */
CHIP_DEF(PCI_CHIP_RV280_5C61, RV280, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV280_5C63, RV280, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* 9200 */
CHIP_DEF(PCI_CHIP_RV280_5960, RV280, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV280_5961, RV280, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV280_5962, RV280, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV280_5964, RV280, CHIP_HAS_CRTC2),
/* 9500 */
CHIP_DEF(PCI_CHIP_R300_AD, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_AE, R300, CHIP_HAS_CRTC2),
/* 9600TX / FireGL Z1 */
CHIP_DEF(PCI_CHIP_R300_AF, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_AG, R300, CHIP_HAS_CRTC2),
/* 9700/9500/Pro/FireGL X1 */
CHIP_DEF(PCI_CHIP_R300_ND, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_NE, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_NF, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_NG, R300, CHIP_HAS_CRTC2),
/* Mobility M10/M11 */
CHIP_DEF(PCI_CHIP_RV350_NP, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NQ, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NR, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NS, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NT, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NV, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* 9600/FireGL T2 */
CHIP_DEF(PCI_CHIP_RV350_AP, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV350_AQ, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV360_AR, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV350_AS, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV350_AT, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV350_AV, RV350, CHIP_HAS_CRTC2),
/* 9800/Pro/FileGL X2 */
CHIP_DEF(PCI_CHIP_R350_AH, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_AI, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_AJ, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_AK, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_NH, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_NI, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R360_NJ, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_NK, R350, CHIP_HAS_CRTC2),
/* Newer stuff */
CHIP_DEF(PCI_CHIP_RV380_3E50, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV380_3E54, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV380_3150, RV380, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV380_3154, RV380, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV370_5B60, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5B62, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5B63, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5B64, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5B65, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5460, RV380, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV370_5464, RV380, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_R420_JH, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JI, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JJ, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JK, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JL, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JM, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JN, R420, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_R420_JP, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UH, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UI, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UJ, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UK, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UQ, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UR, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UT, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_5D57, R420, CHIP_HAS_CRTC2),
/* Original Radeon/7200 */
CHIP_DEF(PCI_CHIP_RADEON_QD, RADEON, 0),
CHIP_DEF(PCI_CHIP_RADEON_QE, RADEON, 0),
CHIP_DEF(PCI_CHIP_RADEON_QF, RADEON, 0),
CHIP_DEF(PCI_CHIP_RADEON_QG, RADEON, 0),
{ 0, }
};
MODULE_DEVICE_TABLE(pci, radeonfb_pci_table);
typedef struct {
u16 reg;
u32 val;
} reg_val;
/* these common regs are cleared before mode setting so they do not
* interfere with anything
*/
static reg_val common_regs[] = {
{ OVR_CLR, 0 },
{ OVR_WID_LEFT_RIGHT, 0 },
{ OVR_WID_TOP_BOTTOM, 0 },
{ OV0_SCALE_CNTL, 0 },
{ SUBPIC_CNTL, 0 },
{ VIPH_CONTROL, 0 },
{ I2C_CNTL_1, 0 },
{ GEN_INT_CNTL, 0 },
{ CAP0_TRIG_CNTL, 0 },
{ CAP1_TRIG_CNTL, 0 },
};
/*
* globals
*/
static char *mode_option;
static char *monitor_layout;
static int noaccel = 0;
static int default_dynclk = -2;
static int nomodeset = 0;
static int ignore_edid = 0;
static int mirror = 0;
static int panel_yres = 0;
static int force_dfp = 0;
static int force_measure_pll = 0;
#ifdef CONFIG_MTRR
static int nomtrr = 0;
#endif
static int force_sleep;
static int ignore_devlist;
#ifdef CONFIG_PMAC_BACKLIGHT
static int backlight = 1;
#else
static int backlight = 0;
#endif
/*
* prototypes
*/
static void radeon_unmap_ROM(struct radeonfb_info *rinfo, struct pci_dev *dev)
{
if (!rinfo->bios_seg)
return;
pci_unmap_rom(dev, rinfo->bios_seg);
}
static int __devinit radeon_map_ROM(struct radeonfb_info *rinfo, struct pci_dev *dev)
{
void __iomem *rom;
u16 dptr;
u8 rom_type;
size_t rom_size;
/* If this is a primary card, there is a shadow copy of the
* ROM somewhere in the first meg. We will just ignore the copy
* and use the ROM directly.
*/
/* Fix from ATI for problem with Radeon hardware not leaving ROM enabled */
unsigned int temp;
temp = INREG(MPP_TB_CONFIG);
temp &= 0x00ffffffu;
temp |= 0x04 << 24;
OUTREG(MPP_TB_CONFIG, temp);
temp = INREG(MPP_TB_CONFIG);
rom = pci_map_rom(dev, &rom_size);
if (!rom) {
printk(KERN_ERR "radeonfb (%s): ROM failed to map\n",
pci_name(rinfo->pdev));
return -ENOMEM;
}
rinfo->bios_seg = rom;
/* Very simple test to make sure it appeared */
if (BIOS_IN16(0) != 0xaa55) {
printk(KERN_DEBUG "radeonfb (%s): Invalid ROM signature %x "
"should be 0xaa55\n",
pci_name(rinfo->pdev), BIOS_IN16(0));
goto failed;
}
/* Look for the PCI data to check the ROM type */
dptr = BIOS_IN16(0x18);
/* Check the PCI data signature. If it's wrong, we still assume a normal x86 ROM
* for now, until I've verified this works everywhere. The goal here is more
* to phase out Open Firmware images.
*
* Currently, we only look at the first PCI data, we could iteratre and deal with
* them all, and we should use fb_bios_start relative to start of image and not
* relative start of ROM, but so far, I never found a dual-image ATI card
*
* typedef struct {
* u32 signature; + 0x00
* u16 vendor; + 0x04
* u16 device; + 0x06
* u16 reserved_1; + 0x08
* u16 dlen; + 0x0a
* u8 drevision; + 0x0c
* u8 class_hi; + 0x0d
* u16 class_lo; + 0x0e
* u16 ilen; + 0x10
* u16 irevision; + 0x12
* u8 type; + 0x14
* u8 indicator; + 0x15
* u16 reserved_2; + 0x16
* } pci_data_t;
*/
if (BIOS_IN32(dptr) != (('R' << 24) | ('I' << 16) | ('C' << 8) | 'P')) {
printk(KERN_WARNING "radeonfb (%s): PCI DATA signature in ROM"
"incorrect: %08x\n", pci_name(rinfo->pdev), BIOS_IN32(dptr));
goto anyway;
}
rom_type = BIOS_IN8(dptr + 0x14);
switch(rom_type) {
case 0:
printk(KERN_INFO "radeonfb: Found Intel x86 BIOS ROM Image\n");
break;
case 1:
printk(KERN_INFO "radeonfb: Found Open Firmware ROM Image\n");
goto failed;
case 2:
printk(KERN_INFO "radeonfb: Found HP PA-RISC ROM Image\n");
goto failed;
default:
printk(KERN_INFO "radeonfb: Found unknown type %d ROM Image\n", rom_type);
goto failed;
}
anyway:
/* Locate the flat panel infos, do some sanity checking !!! */
rinfo->fp_bios_start = BIOS_IN16(0x48);
return 0;
failed:
rinfo->bios_seg = NULL;
radeon_unmap_ROM(rinfo, dev);
return -ENXIO;
}
#ifdef CONFIG_X86
static int __devinit radeon_find_mem_vbios(struct radeonfb_info *rinfo)
{
/* I simplified this code as we used to miss the signatures in
* a lot of case. It's now closer to XFree, we just don't check
* for signatures at all... Something better will have to be done
* if we end up having conflicts
*/
u32 segstart;
void __iomem *rom_base = NULL;
for(segstart=0x000c0000; segstart<0x000f0000; segstart+=0x00001000) {
rom_base = ioremap(segstart, 0x10000);
if (rom_base == NULL)
return -ENOMEM;
if (readb(rom_base) == 0x55 && readb(rom_base + 1) == 0xaa)
break;
iounmap(rom_base);
rom_base = NULL;
}
if (rom_base == NULL)
return -ENXIO;
/* Locate the flat panel infos, do some sanity checking !!! */
rinfo->bios_seg = rom_base;
rinfo->fp_bios_start = BIOS_IN16(0x48);
return 0;
}
#endif
#if defined(CONFIG_PPC_OF) || defined(CONFIG_SPARC)
/*
* Read XTAL (ref clock), SCLK and MCLK from Open Firmware device
* tree. Hopefully, ATI OF driver is kind enough to fill these
*/
static int __devinit radeon_read_xtal_OF (struct radeonfb_info *rinfo)
{
struct device_node *dp = rinfo->of_node;
const u32 *val;
if (dp == NULL)
return -ENODEV;
val = of_get_property(dp, "ATY,RefCLK", NULL);
if (!val || !*val) {
printk(KERN_WARNING "radeonfb: No ATY,RefCLK property !\n");
return -EINVAL;
}
rinfo->pll.ref_clk = (*val) / 10;
val = of_get_property(dp, "ATY,SCLK", NULL);
if (val && *val)
rinfo->pll.sclk = (*val) / 10;
val = of_get_property(dp, "ATY,MCLK", NULL);
if (val && *val)
rinfo->pll.mclk = (*val) / 10;
return 0;
}
#endif /* CONFIG_PPC_OF || CONFIG_SPARC */
/*
* Read PLL infos from chip registers
*/
static int __devinit radeon_probe_pll_params(struct radeonfb_info *rinfo)
{
unsigned char ppll_div_sel;
unsigned Ns, Nm, M;
unsigned sclk, mclk, tmp, ref_div;
int hTotal, vTotal, num, denom, m, n;
unsigned long long hz, vclk;
long xtal;
struct timeval start_tv, stop_tv;
long total_secs, total_usecs;
int i;
/* Ugh, we cut interrupts, bad bad bad, but we want some precision
* here, so... --BenH
*/
/* Flush PCI buffers ? */
tmp = INREG16(DEVICE_ID);
local_irq_disable();
for(i=0; i<1000000; i++)
if (((INREG(CRTC_VLINE_CRNT_VLINE) >> 16) & 0x3ff) == 0)
break;
do_gettimeofday(&start_tv);
for(i=0; i<1000000; i++)
if (((INREG(CRTC_VLINE_CRNT_VLINE) >> 16) & 0x3ff) != 0)
break;
for(i=0; i<1000000; i++)
if (((INREG(CRTC_VLINE_CRNT_VLINE) >> 16) & 0x3ff) == 0)
break;
do_gettimeofday(&stop_tv);
local_irq_enable();
total_secs = stop_tv.tv_sec - start_tv.tv_sec;
if (total_secs > 10)
return -1;
total_usecs = stop_tv.tv_usec - start_tv.tv_usec;
total_usecs += total_secs * 1000000;
if (total_usecs < 0)
total_usecs = -total_usecs;
hz = 1000000/total_usecs;
hTotal = ((INREG(CRTC_H_TOTAL_DISP) & 0x1ff) + 1) * 8;
vTotal = ((INREG(CRTC_V_TOTAL_DISP) & 0x3ff) + 1);
vclk = (long long)hTotal * (long long)vTotal * hz;
switch((INPLL(PPLL_REF_DIV) & 0x30000) >> 16) {
case 0:
default:
num = 1;
denom = 1;
break;
case 1:
n = ((INPLL(M_SPLL_REF_FB_DIV) >> 16) & 0xff);
m = (INPLL(M_SPLL_REF_FB_DIV) & 0xff);
num = 2*n;
denom = 2*m;
break;
case 2:
n = ((INPLL(M_SPLL_REF_FB_DIV) >> 8) & 0xff);
m = (INPLL(M_SPLL_REF_FB_DIV) & 0xff);
num = 2*n;
denom = 2*m;
break;
}
ppll_div_sel = INREG8(CLOCK_CNTL_INDEX + 1) & 0x3;
radeon_pll_errata_after_index(rinfo);
n = (INPLL(PPLL_DIV_0 + ppll_div_sel) & 0x7ff);
m = (INPLL(PPLL_REF_DIV) & 0x3ff);
num *= n;
denom *= m;
switch ((INPLL(PPLL_DIV_0 + ppll_div_sel) >> 16) & 0x7) {
case 1:
denom *= 2;
break;
case 2:
denom *= 4;
break;
case 3:
denom *= 8;
break;
case 4:
denom *= 3;
break;
case 6:
denom *= 6;
break;
case 7:
denom *= 12;
break;
}
vclk *= denom;
do_div(vclk, 1000 * num);
xtal = vclk;
if ((xtal > 26900) && (xtal < 27100))
xtal = 2700;
else if ((xtal > 14200) && (xtal < 14400))
xtal = 1432;
else if ((xtal > 29400) && (xtal < 29600))
xtal = 2950;
else {
printk(KERN_WARNING "xtal calculation failed: %ld\n", xtal);
return -1;
}
tmp = INPLL(M_SPLL_REF_FB_DIV);
ref_div = INPLL(PPLL_REF_DIV) & 0x3ff;
Ns = (tmp & 0xff0000) >> 16;
Nm = (tmp & 0xff00) >> 8;
M = (tmp & 0xff);
sclk = round_div((2 * Ns * xtal), (2 * M));
mclk = round_div((2 * Nm * xtal), (2 * M));
/* we're done, hopefully these are sane values */
rinfo->pll.ref_clk = xtal;
rinfo->pll.ref_div = ref_div;
rinfo->pll.sclk = sclk;
rinfo->pll.mclk = mclk;
return 0;
}
/*
* Retrieve PLL infos by different means (BIOS, Open Firmware, register probing...)
*/
static void __devinit radeon_get_pllinfo(struct radeonfb_info *rinfo)
{
/*
* In the case nothing works, these are defaults; they are mostly
* incomplete, however. It does provide ppll_max and _min values
* even for most other methods, however.
*/
switch (rinfo->chipset) {
case PCI_DEVICE_ID_ATI_RADEON_QW:
case PCI_DEVICE_ID_ATI_RADEON_QX:
rinfo->pll.ppll_max = 35000;
rinfo->pll.ppll_min = 12000;
rinfo->pll.mclk = 23000;
rinfo->pll.sclk = 23000;
rinfo->pll.ref_clk = 2700;
break;
case PCI_DEVICE_ID_ATI_RADEON_QL:
case PCI_DEVICE_ID_ATI_RADEON_QN:
case PCI_DEVICE_ID_ATI_RADEON_QO:
case PCI_DEVICE_ID_ATI_RADEON_Ql:
case PCI_DEVICE_ID_ATI_RADEON_BB:
rinfo->pll.ppll_max = 35000;
rinfo->pll.ppll_min = 12000;
rinfo->pll.mclk = 27500;
rinfo->pll.sclk = 27500;
rinfo->pll.ref_clk = 2700;
break;
case PCI_DEVICE_ID_ATI_RADEON_Id:
case PCI_DEVICE_ID_ATI_RADEON_Ie:
case PCI_DEVICE_ID_ATI_RADEON_If:
case PCI_DEVICE_ID_ATI_RADEON_Ig:
rinfo->pll.ppll_max = 35000;
rinfo->pll.ppll_min = 12000;
rinfo->pll.mclk = 25000;
rinfo->pll.sclk = 25000;
rinfo->pll.ref_clk = 2700;
break;
case PCI_DEVICE_ID_ATI_RADEON_ND:
case PCI_DEVICE_ID_ATI_RADEON_NE:
case PCI_DEVICE_ID_ATI_RADEON_NF:
case PCI_DEVICE_ID_ATI_RADEON_NG:
rinfo->pll.ppll_max = 40000;
rinfo->pll.ppll_min = 20000;
rinfo->pll.mclk = 27000;
rinfo->pll.sclk = 27000;
rinfo->pll.ref_clk = 2700;
break;
case PCI_DEVICE_ID_ATI_RADEON_QD:
case PCI_DEVICE_ID_ATI_RADEON_QE:
case PCI_DEVICE_ID_ATI_RADEON_QF:
case PCI_DEVICE_ID_ATI_RADEON_QG:
default:
rinfo->pll.ppll_max = 35000;
rinfo->pll.ppll_min = 12000;
rinfo->pll.mclk = 16600;
rinfo->pll.sclk = 16600;
rinfo->pll.ref_clk = 2700;
break;
}
rinfo->pll.ref_div = INPLL(PPLL_REF_DIV) & PPLL_REF_DIV_MASK;
#if defined(CONFIG_PPC_OF) || defined(CONFIG_SPARC)
/*
* Retrieve PLL infos from Open Firmware first
*/
if (!force_measure_pll && radeon_read_xtal_OF(rinfo) == 0) {
printk(KERN_INFO "radeonfb: Retrieved PLL infos from Open Firmware\n");
goto found;
}
#endif /* CONFIG_PPC_OF || CONFIG_SPARC */
/*
* Check out if we have an X86 which gave us some PLL informations
* and if yes, retrieve them
*/
if (!force_measure_pll && rinfo->bios_seg) {
u16 pll_info_block = BIOS_IN16(rinfo->fp_bios_start + 0x30);
rinfo->pll.sclk = BIOS_IN16(pll_info_block + 0x08);
rinfo->pll.mclk = BIOS_IN16(pll_info_block + 0x0a);
rinfo->pll.ref_clk = BIOS_IN16(pll_info_block + 0x0e);
rinfo->pll.ref_div = BIOS_IN16(pll_info_block + 0x10);
rinfo->pll.ppll_min = BIOS_IN32(pll_info_block + 0x12);
rinfo->pll.ppll_max = BIOS_IN32(pll_info_block + 0x16);
printk(KERN_INFO "radeonfb: Retrieved PLL infos from BIOS\n");
goto found;
}
/*
* We didn't get PLL parameters from either OF or BIOS, we try to
* probe them
*/
if (radeon_probe_pll_params(rinfo) == 0) {
printk(KERN_INFO "radeonfb: Retrieved PLL infos from registers\n");
goto found;
}
/*
* Fall back to already-set defaults...
*/
printk(KERN_INFO "radeonfb: Used default PLL infos\n");
found:
/*
* Some methods fail to retrieve SCLK and MCLK values, we apply default
* settings in this case (200Mhz). If that really happens often, we
* could fetch from registers instead...
*/
if (rinfo->pll.mclk == 0)
rinfo->pll.mclk = 20000;
if (rinfo->pll.sclk == 0)
rinfo->pll.sclk = 20000;
printk("radeonfb: Reference=%d.%02d MHz (RefDiv=%d) Memory=%d.%02d Mhz, System=%d.%02d MHz\n",
rinfo->pll.ref_clk / 100, rinfo->pll.ref_clk % 100,
rinfo->pll.ref_div,
rinfo->pll.mclk / 100, rinfo->pll.mclk % 100,
rinfo->pll.sclk / 100, rinfo->pll.sclk % 100);
printk("radeonfb: PLL min %d max %d\n", rinfo->pll.ppll_min, rinfo->pll.ppll_max);
}
static int radeonfb_check_var (struct fb_var_screeninfo *var, struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
struct fb_var_screeninfo v;
int nom, den;
unsigned int pitch;
if (radeon_match_mode(rinfo, &v, var))
return -EINVAL;
switch (v.bits_per_pixel) {
case 0 ... 8:
v.bits_per_pixel = 8;
break;
case 9 ... 16:
v.bits_per_pixel = 16;
break;
case 17 ... 24:
#if 0 /* Doesn't seem to work */
v.bits_per_pixel = 24;
break;
#endif
return -EINVAL;
case 25 ... 32:
v.bits_per_pixel = 32;
break;
default:
return -EINVAL;
}
switch (var_to_depth(&v)) {
case 8:
nom = den = 1;
v.red.offset = v.green.offset = v.blue.offset = 0;
v.red.length = v.green.length = v.blue.length = 8;
v.transp.offset = v.transp.length = 0;
break;
case 15:
nom = 2;
den = 1;
v.red.offset = 10;
v.green.offset = 5;
v.blue.offset = 0;
v.red.length = v.green.length = v.blue.length = 5;
v.transp.offset = v.transp.length = 0;
break;
case 16:
nom = 2;
den = 1;
v.red.offset = 11;
v.green.offset = 5;
v.blue.offset = 0;
v.red.length = 5;
v.green.length = 6;
v.blue.length = 5;
v.transp.offset = v.transp.length = 0;
break;
case 24:
nom = 4;
den = 1;
v.red.offset = 16;
v.green.offset = 8;
v.blue.offset = 0;
v.red.length = v.blue.length = v.green.length = 8;
v.transp.offset = v.transp.length = 0;
break;
case 32:
nom = 4;
den = 1;
v.red.offset = 16;
v.green.offset = 8;
v.blue.offset = 0;
v.red.length = v.blue.length = v.green.length = 8;
v.transp.offset = 24;
v.transp.length = 8;
break;
default:
printk ("radeonfb: mode %dx%dx%d rejected, color depth invalid\n",
var->xres, var->yres, var->bits_per_pixel);
return -EINVAL;
}
if (v.yres_virtual < v.yres)
v.yres_virtual = v.yres;
if (v.xres_virtual < v.xres)
v.xres_virtual = v.xres;
/* XXX I'm adjusting xres_virtual to the pitch, that may help XFree
* with some panels, though I don't quite like this solution
*/
if (rinfo->info->flags & FBINFO_HWACCEL_DISABLED) {
v.xres_virtual = v.xres_virtual & ~7ul;
} else {
pitch = ((v.xres_virtual * ((v.bits_per_pixel + 1) / 8) + 0x3f)
& ~(0x3f)) >> 6;
v.xres_virtual = (pitch << 6) / ((v.bits_per_pixel + 1) / 8);
}
if (((v.xres_virtual * v.yres_virtual * nom) / den) > rinfo->mapped_vram)
return -EINVAL;
if (v.xres_virtual < v.xres)
v.xres = v.xres_virtual;
if (v.xoffset < 0)
v.xoffset = 0;
if (v.yoffset < 0)
v.yoffset = 0;
if (v.xoffset > v.xres_virtual - v.xres)
v.xoffset = v.xres_virtual - v.xres - 1;
if (v.yoffset > v.yres_virtual - v.yres)
v.yoffset = v.yres_virtual - v.yres - 1;
v.red.msb_right = v.green.msb_right = v.blue.msb_right =
v.transp.offset = v.transp.length =
v.transp.msb_right = 0;
memcpy(var, &v, sizeof(v));
return 0;
}
static int radeonfb_pan_display (struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
if ((var->xoffset + var->xres > var->xres_virtual)
|| (var->yoffset + var->yres > var->yres_virtual))
return -EINVAL;
if (rinfo->asleep)
return 0;
radeon_fifo_wait(2);
OUTREG(CRTC_OFFSET, ((var->yoffset * var->xres_virtual + var->xoffset)
* var->bits_per_pixel / 8) & ~7);
return 0;
}
static int radeonfb_ioctl (struct fb_info *info, unsigned int cmd,
unsigned long arg)
{
struct radeonfb_info *rinfo = info->par;
unsigned int tmp;
u32 value = 0;
int rc;
switch (cmd) {
/*
* TODO: set mirror accordingly for non-Mobility chipsets with 2 CRTC's
* and do something better using 2nd CRTC instead of just hackish
* routing to second output
*/
case FBIO_RADEON_SET_MIRROR:
if (!rinfo->is_mobility)
return -EINVAL;
rc = get_user(value, (__u32 __user *)arg);
if (rc)
return rc;
radeon_fifo_wait(2);
if (value & 0x01) {
tmp = INREG(LVDS_GEN_CNTL);
tmp |= (LVDS_ON | LVDS_BLON);
} else {
tmp = INREG(LVDS_GEN_CNTL);
tmp &= ~(LVDS_ON | LVDS_BLON);
}
OUTREG(LVDS_GEN_CNTL, tmp);
if (value & 0x02) {
tmp = INREG(CRTC_EXT_CNTL);
tmp |= CRTC_CRT_ON;
mirror = 1;
} else {
tmp = INREG(CRTC_EXT_CNTL);
tmp &= ~CRTC_CRT_ON;
mirror = 0;
}
OUTREG(CRTC_EXT_CNTL, tmp);
return 0;
case FBIO_RADEON_GET_MIRROR:
if (!rinfo->is_mobility)
return -EINVAL;
tmp = INREG(LVDS_GEN_CNTL);
if ((LVDS_ON | LVDS_BLON) & tmp)
value |= 0x01;
tmp = INREG(CRTC_EXT_CNTL);
if (CRTC_CRT_ON & tmp)
value |= 0x02;
return put_user(value, (__u32 __user *)arg);
default:
return -EINVAL;
}
return -EINVAL;
}
int radeon_screen_blank(struct radeonfb_info *rinfo, int blank, int mode_switch)
{
u32 val;
u32 tmp_pix_clks;
int unblank = 0;
if (rinfo->lock_blank)
return 0;
radeon_engine_idle();
val = INREG(CRTC_EXT_CNTL);
val &= ~(CRTC_DISPLAY_DIS | CRTC_HSYNC_DIS |
CRTC_VSYNC_DIS);
switch (blank) {
case FB_BLANK_VSYNC_SUSPEND:
val |= (CRTC_DISPLAY_DIS | CRTC_VSYNC_DIS);
break;
case FB_BLANK_HSYNC_SUSPEND:
val |= (CRTC_DISPLAY_DIS | CRTC_HSYNC_DIS);
break;
case FB_BLANK_POWERDOWN:
val |= (CRTC_DISPLAY_DIS | CRTC_VSYNC_DIS |
CRTC_HSYNC_DIS);
break;
case FB_BLANK_NORMAL:
val |= CRTC_DISPLAY_DIS;
break;
case FB_BLANK_UNBLANK:
default:
unblank = 1;
}
OUTREG(CRTC_EXT_CNTL, val);
switch (rinfo->mon1_type) {
case MT_DFP:
if (unblank)
OUTREGP(FP_GEN_CNTL, (FP_FPON | FP_TMDS_EN),
~(FP_FPON | FP_TMDS_EN));
else {
if (mode_switch || blank == FB_BLANK_NORMAL)
break;
OUTREGP(FP_GEN_CNTL, 0, ~(FP_FPON | FP_TMDS_EN));
}
break;
case MT_LCD:
del_timer_sync(&rinfo->lvds_timer);
val = INREG(LVDS_GEN_CNTL);
if (unblank) {
u32 target_val = (val & ~LVDS_DISPLAY_DIS) | LVDS_BLON | LVDS_ON
| LVDS_EN | (rinfo->init_state.lvds_gen_cntl
& (LVDS_DIGON | LVDS_BL_MOD_EN));
if ((val ^ target_val) == LVDS_DISPLAY_DIS)
OUTREG(LVDS_GEN_CNTL, target_val);
else if ((val ^ target_val) != 0) {
OUTREG(LVDS_GEN_CNTL, target_val
& ~(LVDS_ON | LVDS_BL_MOD_EN));
rinfo->init_state.lvds_gen_cntl &= ~LVDS_STATE_MASK;
rinfo->init_state.lvds_gen_cntl |=
target_val & LVDS_STATE_MASK;
if (mode_switch) {
radeon_msleep(rinfo->panel_info.pwr_delay);
OUTREG(LVDS_GEN_CNTL, target_val);
}
else {
rinfo->pending_lvds_gen_cntl = target_val;
mod_timer(&rinfo->lvds_timer,
jiffies +
msecs_to_jiffies(rinfo->panel_info.pwr_delay));
}
}
} else {
val |= LVDS_DISPLAY_DIS;
OUTREG(LVDS_GEN_CNTL, val);
/* We don't do a full switch-off on a simple mode switch */
if (mode_switch || blank == FB_BLANK_NORMAL)
break;
/* Asic bug, when turning off LVDS_ON, we have to make sure
* RADEON_PIXCLK_LVDS_ALWAYS_ON bit is off
*/
tmp_pix_clks = INPLL(PIXCLKS_CNTL);
if (rinfo->is_mobility || rinfo->is_IGP)
OUTPLLP(PIXCLKS_CNTL, 0, ~PIXCLK_LVDS_ALWAYS_ONb);
val &= ~(LVDS_BL_MOD_EN);
OUTREG(LVDS_GEN_CNTL, val);
udelay(100);
val &= ~(LVDS_ON | LVDS_EN);
OUTREG(LVDS_GEN_CNTL, val);
val &= ~LVDS_DIGON;
rinfo->pending_lvds_gen_cntl = val;
mod_timer(&rinfo->lvds_timer,
jiffies +
msecs_to_jiffies(rinfo->panel_info.pwr_delay));
rinfo->init_state.lvds_gen_cntl &= ~LVDS_STATE_MASK;
rinfo->init_state.lvds_gen_cntl |= val & LVDS_STATE_MASK;
if (rinfo->is_mobility || rinfo->is_IGP)
OUTPLL(PIXCLKS_CNTL, tmp_pix_clks);
}
break;
case MT_CRT:
// todo: powerdown DAC
default:
break;
}
return 0;
}
static int radeonfb_blank (int blank, struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
if (rinfo->asleep)
return 0;
return radeon_screen_blank(rinfo, blank, 0);
}
static int radeon_setcolreg (unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct radeonfb_info *rinfo)
{
u32 pindex;
unsigned int i;
if (regno > 255)
return -EINVAL;
red >>= 8;
green >>= 8;
blue >>= 8;
rinfo->palette[regno].red = red;
rinfo->palette[regno].green = green;
rinfo->palette[regno].blue = blue;
/* default */
pindex = regno;
if (!rinfo->asleep) {
radeon_fifo_wait(9);
if (rinfo->bpp == 16) {
pindex = regno * 8;
if (rinfo->depth == 16 && regno > 63)
return -EINVAL;
if (rinfo->depth == 15 && regno > 31)
return -EINVAL;
/* For 565, the green component is mixed one order
* below
*/
if (rinfo->depth == 16) {
OUTREG(PALETTE_INDEX, pindex>>1);
OUTREG(PALETTE_DATA,
(rinfo->palette[regno>>1].red << 16) |
(green << 8) |
(rinfo->palette[regno>>1].blue));
green = rinfo->palette[regno<<1].green;
}
}
if (rinfo->depth != 16 || regno < 32) {
OUTREG(PALETTE_INDEX, pindex);
OUTREG(PALETTE_DATA, (red << 16) |
(green << 8) | blue);
}
}
if (regno < 16) {
u32 *pal = rinfo->info->pseudo_palette;
switch (rinfo->depth) {
case 15:
pal[regno] = (regno << 10) | (regno << 5) | regno;
break;
case 16:
pal[regno] = (regno << 11) | (regno << 5) | regno;
break;
case 24:
pal[regno] = (regno << 16) | (regno << 8) | regno;
break;
case 32:
i = (regno << 8) | regno;
pal[regno] = (i << 16) | i;
break;
}
}
return 0;
}
static int radeonfb_setcolreg (unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
u32 dac_cntl2, vclk_cntl = 0;
int rc;
if (!rinfo->asleep) {
if (rinfo->is_mobility) {
vclk_cntl = INPLL(VCLK_ECP_CNTL);
OUTPLL(VCLK_ECP_CNTL,
vclk_cntl & ~PIXCLK_DAC_ALWAYS_ONb);
}
/* Make sure we are on first palette */
if (rinfo->has_CRTC2) {
dac_cntl2 = INREG(DAC_CNTL2);
dac_cntl2 &= ~DAC2_PALETTE_ACCESS_CNTL;
OUTREG(DAC_CNTL2, dac_cntl2);
}
}
rc = radeon_setcolreg (regno, red, green, blue, transp, rinfo);
if (!rinfo->asleep && rinfo->is_mobility)
OUTPLL(VCLK_ECP_CNTL, vclk_cntl);
return rc;
}
static int radeonfb_setcmap(struct fb_cmap *cmap, struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
u16 *red, *green, *blue, *transp;
u32 dac_cntl2, vclk_cntl = 0;
int i, start, rc = 0;
if (!rinfo->asleep) {
if (rinfo->is_mobility) {
vclk_cntl = INPLL(VCLK_ECP_CNTL);
OUTPLL(VCLK_ECP_CNTL,
vclk_cntl & ~PIXCLK_DAC_ALWAYS_ONb);
}
/* Make sure we are on first palette */
if (rinfo->has_CRTC2) {
dac_cntl2 = INREG(DAC_CNTL2);
dac_cntl2 &= ~DAC2_PALETTE_ACCESS_CNTL;
OUTREG(DAC_CNTL2, dac_cntl2);
}
}
red = cmap->red;
green = cmap->green;
blue = cmap->blue;
transp = cmap->transp;
start = cmap->start;
for (i = 0; i < cmap->len; i++) {
u_int hred, hgreen, hblue, htransp = 0xffff;
hred = *red++;
hgreen = *green++;
hblue = *blue++;
if (transp)
htransp = *transp++;
rc = radeon_setcolreg (start++, hred, hgreen, hblue, htransp,
rinfo);
if (rc)
break;
}
if (!rinfo->asleep && rinfo->is_mobility)
OUTPLL(VCLK_ECP_CNTL, vclk_cntl);
return rc;
}
static void radeon_save_state (struct radeonfb_info *rinfo,
struct radeon_regs *save)
{
/* CRTC regs */
save->crtc_gen_cntl = INREG(CRTC_GEN_CNTL);
save->crtc_ext_cntl = INREG(CRTC_EXT_CNTL);
save->crtc_more_cntl = INREG(CRTC_MORE_CNTL);
save->dac_cntl = INREG(DAC_CNTL);
save->crtc_h_total_disp = INREG(CRTC_H_TOTAL_DISP);
save->crtc_h_sync_strt_wid = INREG(CRTC_H_SYNC_STRT_WID);
save->crtc_v_total_disp = INREG(CRTC_V_TOTAL_DISP);
save->crtc_v_sync_strt_wid = INREG(CRTC_V_SYNC_STRT_WID);
save->crtc_pitch = INREG(CRTC_PITCH);
save->surface_cntl = INREG(SURFACE_CNTL);
/* FP regs */
save->fp_crtc_h_total_disp = INREG(FP_CRTC_H_TOTAL_DISP);
save->fp_crtc_v_total_disp = INREG(FP_CRTC_V_TOTAL_DISP);
save->fp_gen_cntl = INREG(FP_GEN_CNTL);
save->fp_h_sync_strt_wid = INREG(FP_H_SYNC_STRT_WID);
save->fp_horz_stretch = INREG(FP_HORZ_STRETCH);
save->fp_v_sync_strt_wid = INREG(FP_V_SYNC_STRT_WID);
save->fp_vert_stretch = INREG(FP_VERT_STRETCH);
save->lvds_gen_cntl = INREG(LVDS_GEN_CNTL);
save->lvds_pll_cntl = INREG(LVDS_PLL_CNTL);
save->tmds_crc = INREG(TMDS_CRC);
save->tmds_transmitter_cntl = INREG(TMDS_TRANSMITTER_CNTL);
save->vclk_ecp_cntl = INPLL(VCLK_ECP_CNTL);
/* PLL regs */
save->clk_cntl_index = INREG(CLOCK_CNTL_INDEX) & ~0x3f;
radeon_pll_errata_after_index(rinfo);
save->ppll_div_3 = INPLL(PPLL_DIV_3);
save->ppll_ref_div = INPLL(PPLL_REF_DIV);
}
static void radeon_write_pll_regs(struct radeonfb_info *rinfo, struct radeon_regs *mode)
{
int i;
radeon_fifo_wait(20);
/* Workaround from XFree */
if (rinfo->is_mobility) {
/* A temporal workaround for the occasional blanking on certain laptop
* panels. This appears to related to the PLL divider registers
* (fail to lock?). It occurs even when all dividers are the same
* with their old settings. In this case we really don't need to
* fiddle with PLL registers. By doing this we can avoid the blanking
* problem with some panels.
*/
if ((mode->ppll_ref_div == (INPLL(PPLL_REF_DIV) & PPLL_REF_DIV_MASK)) &&
(mode->ppll_div_3 == (INPLL(PPLL_DIV_3) &
(PPLL_POST3_DIV_MASK | PPLL_FB3_DIV_MASK)))) {
/* We still have to force a switch to selected PPLL div thanks to
* an XFree86 driver bug which will switch it away in some cases
* even when using UseFDev */
OUTREGP(CLOCK_CNTL_INDEX,
mode->clk_cntl_index & PPLL_DIV_SEL_MASK,
~PPLL_DIV_SEL_MASK);
radeon_pll_errata_after_index(rinfo);
radeon_pll_errata_after_data(rinfo);
return;
}
}
/* Swich VCKL clock input to CPUCLK so it stays fed while PPLL updates*/
OUTPLLP(VCLK_ECP_CNTL, VCLK_SRC_SEL_CPUCLK, ~VCLK_SRC_SEL_MASK);
/* Reset PPLL & enable atomic update */
OUTPLLP(PPLL_CNTL,
PPLL_RESET | PPLL_ATOMIC_UPDATE_EN | PPLL_VGA_ATOMIC_UPDATE_EN,
~(PPLL_RESET | PPLL_ATOMIC_UPDATE_EN | PPLL_VGA_ATOMIC_UPDATE_EN));
/* Switch to selected PPLL divider */
OUTREGP(CLOCK_CNTL_INDEX,
mode->clk_cntl_index & PPLL_DIV_SEL_MASK,
~PPLL_DIV_SEL_MASK);
radeon_pll_errata_after_index(rinfo);
radeon_pll_errata_after_data(rinfo);
/* Set PPLL ref. div */
if (IS_R300_VARIANT(rinfo) ||
rinfo->family == CHIP_FAMILY_RS300 ||
rinfo->family == CHIP_FAMILY_RS400 ||
rinfo->family == CHIP_FAMILY_RS480) {
if (mode->ppll_ref_div & R300_PPLL_REF_DIV_ACC_MASK) {
/* When restoring console mode, use saved PPLL_REF_DIV
* setting.
*/
OUTPLLP(PPLL_REF_DIV, mode->ppll_ref_div, 0);
} else {
/* R300 uses ref_div_acc field as real ref divider */
OUTPLLP(PPLL_REF_DIV,
(mode->ppll_ref_div << R300_PPLL_REF_DIV_ACC_SHIFT),
~R300_PPLL_REF_DIV_ACC_MASK);
}
} else
OUTPLLP(PPLL_REF_DIV, mode->ppll_ref_div, ~PPLL_REF_DIV_MASK);
/* Set PPLL divider 3 & post divider*/
OUTPLLP(PPLL_DIV_3, mode->ppll_div_3, ~PPLL_FB3_DIV_MASK);
OUTPLLP(PPLL_DIV_3, mode->ppll_div_3, ~PPLL_POST3_DIV_MASK);
/* Write update */
while (INPLL(PPLL_REF_DIV) & PPLL_ATOMIC_UPDATE_R)
;
OUTPLLP(PPLL_REF_DIV, PPLL_ATOMIC_UPDATE_W, ~PPLL_ATOMIC_UPDATE_W);
/* Wait read update complete */
/* FIXME: Certain revisions of R300 can't recover here. Not sure of
the cause yet, but this workaround will mask the problem for now.
Other chips usually will pass at the very first test, so the
workaround shouldn't have any effect on them. */
for (i = 0; (i < 10000 && INPLL(PPLL_REF_DIV) & PPLL_ATOMIC_UPDATE_R); i++)
;
OUTPLL(HTOTAL_CNTL, 0);
/* Clear reset & atomic update */
OUTPLLP(PPLL_CNTL, 0,
~(PPLL_RESET | PPLL_SLEEP | PPLL_ATOMIC_UPDATE_EN | PPLL_VGA_ATOMIC_UPDATE_EN));
/* We may want some locking ... oh well */
radeon_msleep(5);
/* Switch back VCLK source to PPLL */
OUTPLLP(VCLK_ECP_CNTL, VCLK_SRC_SEL_PPLLCLK, ~VCLK_SRC_SEL_MASK);
}
/*
* Timer function for delayed LVDS panel power up/down
*/
static void radeon_lvds_timer_func(unsigned long data)
{
struct radeonfb_info *rinfo = (struct radeonfb_info *)data;
radeon_engine_idle();
OUTREG(LVDS_GEN_CNTL, rinfo->pending_lvds_gen_cntl);
}
/*
* Apply a video mode. This will apply the whole register set, including
* the PLL registers, to the card
*/
void radeon_write_mode (struct radeonfb_info *rinfo, struct radeon_regs *mode,
int regs_only)
{
int i;
int primary_mon = PRIMARY_MONITOR(rinfo);
if (nomodeset)
return;
if (!regs_only)
radeon_screen_blank(rinfo, FB_BLANK_NORMAL, 0);
radeon_fifo_wait(31);
for (i=0; i<10; i++)
OUTREG(common_regs[i].reg, common_regs[i].val);
/* Apply surface registers */
for (i=0; i<8; i++) {
OUTREG(SURFACE0_LOWER_BOUND + 0x10*i, mode->surf_lower_bound[i]);
OUTREG(SURFACE0_UPPER_BOUND + 0x10*i, mode->surf_upper_bound[i]);
OUTREG(SURFACE0_INFO + 0x10*i, mode->surf_info[i]);
}
OUTREG(CRTC_GEN_CNTL, mode->crtc_gen_cntl);
OUTREGP(CRTC_EXT_CNTL, mode->crtc_ext_cntl,
~(CRTC_HSYNC_DIS | CRTC_VSYNC_DIS | CRTC_DISPLAY_DIS));
OUTREG(CRTC_MORE_CNTL, mode->crtc_more_cntl);
OUTREGP(DAC_CNTL, mode->dac_cntl, DAC_RANGE_CNTL | DAC_BLANKING);
OUTREG(CRTC_H_TOTAL_DISP, mode->crtc_h_total_disp);
OUTREG(CRTC_H_SYNC_STRT_WID, mode->crtc_h_sync_strt_wid);
OUTREG(CRTC_V_TOTAL_DISP, mode->crtc_v_total_disp);
OUTREG(CRTC_V_SYNC_STRT_WID, mode->crtc_v_sync_strt_wid);
OUTREG(CRTC_OFFSET, 0);
OUTREG(CRTC_OFFSET_CNTL, 0);
OUTREG(CRTC_PITCH, mode->crtc_pitch);
OUTREG(SURFACE_CNTL, mode->surface_cntl);
radeon_write_pll_regs(rinfo, mode);
if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) {
radeon_fifo_wait(10);
OUTREG(FP_CRTC_H_TOTAL_DISP, mode->fp_crtc_h_total_disp);
OUTREG(FP_CRTC_V_TOTAL_DISP, mode->fp_crtc_v_total_disp);
OUTREG(FP_H_SYNC_STRT_WID, mode->fp_h_sync_strt_wid);
OUTREG(FP_V_SYNC_STRT_WID, mode->fp_v_sync_strt_wid);
OUTREG(FP_HORZ_STRETCH, mode->fp_horz_stretch);
OUTREG(FP_VERT_STRETCH, mode->fp_vert_stretch);
OUTREG(FP_GEN_CNTL, mode->fp_gen_cntl);
OUTREG(TMDS_CRC, mode->tmds_crc);
OUTREG(TMDS_TRANSMITTER_CNTL, mode->tmds_transmitter_cntl);
}
if (!regs_only)
radeon_screen_blank(rinfo, FB_BLANK_UNBLANK, 0);
radeon_fifo_wait(2);
OUTPLL(VCLK_ECP_CNTL, mode->vclk_ecp_cntl);
return;
}
/*
* Calculate the PLL values for a given mode
*/
static void radeon_calc_pll_regs(struct radeonfb_info *rinfo, struct radeon_regs *regs,
unsigned long freq)
{
const struct {
int divider;
int bitvalue;
} *post_div,
post_divs[] = {
{ 1, 0 },
{ 2, 1 },
{ 4, 2 },
{ 8, 3 },
{ 3, 4 },
{ 16, 5 },
{ 6, 6 },
{ 12, 7 },
{ 0, 0 },
};
int fb_div, pll_output_freq = 0;
int uses_dvo = 0;
/* Check if the DVO port is enabled and sourced from the primary CRTC. I'm
* not sure which model starts having FP2_GEN_CNTL, I assume anything more
* recent than an r(v)100...
*/
#if 1
/* XXX I had reports of flicker happening with the cinema display
* on TMDS1 that seem to be fixed if I also forbit odd dividers in
* this case. This could just be a bandwidth calculation issue, I
* haven't implemented the bandwidth code yet, but in the meantime,
* forcing uses_dvo to 1 fixes it and shouln't have bad side effects,
* I haven't seen a case were were absolutely needed an odd PLL
* divider. I'll find a better fix once I have more infos on the
* real cause of the problem.
*/
while (rinfo->has_CRTC2) {
u32 fp2_gen_cntl = INREG(FP2_GEN_CNTL);
u32 disp_output_cntl;
int source;
/* FP2 path not enabled */
if ((fp2_gen_cntl & FP2_ON) == 0)
break;
/* Not all chip revs have the same format for this register,
* extract the source selection
*/
if (rinfo->family == CHIP_FAMILY_R200 || IS_R300_VARIANT(rinfo)) {
source = (fp2_gen_cntl >> 10) & 0x3;
/* sourced from transform unit, check for transform unit
* own source
*/
if (source == 3) {
disp_output_cntl = INREG(DISP_OUTPUT_CNTL);
source = (disp_output_cntl >> 12) & 0x3;
}
} else
source = (fp2_gen_cntl >> 13) & 0x1;
/* sourced from CRTC2 -> exit */
if (source == 1)
break;
/* so we end up on CRTC1, let's set uses_dvo to 1 now */
uses_dvo = 1;
break;
}
#else
uses_dvo = 1;
#endif
if (freq > rinfo->pll.ppll_max)
freq = rinfo->pll.ppll_max;
if (freq*12 < rinfo->pll.ppll_min)
freq = rinfo->pll.ppll_min / 12;
pr_debug("freq = %lu, PLL min = %u, PLL max = %u\n",
freq, rinfo->pll.ppll_min, rinfo->pll.ppll_max);
for (post_div = &post_divs[0]; post_div->divider; ++post_div) {
pll_output_freq = post_div->divider * freq;
/* If we output to the DVO port (external TMDS), we don't allow an
* odd PLL divider as those aren't supported on this path
*/
if (uses_dvo && (post_div->divider & 1))
continue;
if (pll_output_freq >= rinfo->pll.ppll_min &&
pll_output_freq <= rinfo->pll.ppll_max)
break;
}
/* If we fall through the bottom, try the "default value"
given by the terminal post_div->bitvalue */
if ( !post_div->divider ) {
post_div = &post_divs[post_div->bitvalue];
pll_output_freq = post_div->divider * freq;
}
pr_debug("ref_div = %d, ref_clk = %d, output_freq = %d\n",
rinfo->pll.ref_div, rinfo->pll.ref_clk,
pll_output_freq);
/* If we fall through the bottom, try the "default value"
given by the terminal post_div->bitvalue */
if ( !post_div->divider ) {
post_div = &post_divs[post_div->bitvalue];
pll_output_freq = post_div->divider * freq;
}
pr_debug("ref_div = %d, ref_clk = %d, output_freq = %d\n",
rinfo->pll.ref_div, rinfo->pll.ref_clk,
pll_output_freq);
fb_div = round_div(rinfo->pll.ref_div*pll_output_freq,
rinfo->pll.ref_clk);
regs->ppll_ref_div = rinfo->pll.ref_div;
regs->ppll_div_3 = fb_div | (post_div->bitvalue << 16);
pr_debug("post div = 0x%x\n", post_div->bitvalue);
pr_debug("fb_div = 0x%x\n", fb_div);
pr_debug("ppll_div_3 = 0x%x\n", regs->ppll_div_3);
}
static int radeonfb_set_par(struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
struct fb_var_screeninfo *mode = &info->var;
struct radeon_regs *newmode;
int hTotal, vTotal, hSyncStart, hSyncEnd,
hSyncPol, vSyncStart, vSyncEnd, vSyncPol, cSync;
u8 hsync_adj_tab[] = {0, 0x12, 9, 9, 6, 5};
u8 hsync_fudge_fp[] = {2, 2, 0, 0, 5, 5};
u32 sync, h_sync_pol, v_sync_pol, dotClock, pixClock;
int i, freq;
int format = 0;
int nopllcalc = 0;
int hsync_start, hsync_fudge, bytpp, hsync_wid, vsync_wid;
int primary_mon = PRIMARY_MONITOR(rinfo);
int depth = var_to_depth(mode);
int use_rmx = 0;
newmode = kmalloc(sizeof(struct radeon_regs), GFP_KERNEL);
if (!newmode)
return -ENOMEM;
/* We always want engine to be idle on a mode switch, even
* if we won't actually change the mode
*/
radeon_engine_idle();
hSyncStart = mode->xres + mode->right_margin;
hSyncEnd = hSyncStart + mode->hsync_len;
hTotal = hSyncEnd + mode->left_margin;
vSyncStart = mode->yres + mode->lower_margin;
vSyncEnd = vSyncStart + mode->vsync_len;
vTotal = vSyncEnd + mode->upper_margin;
pixClock = mode->pixclock;
sync = mode->sync;
h_sync_pol = sync & FB_SYNC_HOR_HIGH_ACT ? 0 : 1;
v_sync_pol = sync & FB_SYNC_VERT_HIGH_ACT ? 0 : 1;
if (primary_mon == MT_DFP || primary_mon == MT_LCD) {
if (rinfo->panel_info.xres < mode->xres)
mode->xres = rinfo->panel_info.xres;
if (rinfo->panel_info.yres < mode->yres)
mode->yres = rinfo->panel_info.yres;
hTotal = mode->xres + rinfo->panel_info.hblank;
hSyncStart = mode->xres + rinfo->panel_info.hOver_plus;
hSyncEnd = hSyncStart + rinfo->panel_info.hSync_width;
vTotal = mode->yres + rinfo->panel_info.vblank;
vSyncStart = mode->yres + rinfo->panel_info.vOver_plus;
vSyncEnd = vSyncStart + rinfo->panel_info.vSync_width;
h_sync_pol = !rinfo->panel_info.hAct_high;
v_sync_pol = !rinfo->panel_info.vAct_high;
pixClock = 100000000 / rinfo->panel_info.clock;
if (rinfo->panel_info.use_bios_dividers) {
nopllcalc = 1;
newmode->ppll_div_3 = rinfo->panel_info.fbk_divider |
(rinfo->panel_info.post_divider << 16);
newmode->ppll_ref_div = rinfo->panel_info.ref_divider;
}
}
dotClock = 1000000000 / pixClock;
freq = dotClock / 10; /* x100 */
pr_debug("hStart = %d, hEnd = %d, hTotal = %d\n",
hSyncStart, hSyncEnd, hTotal);
pr_debug("vStart = %d, vEnd = %d, vTotal = %d\n",
vSyncStart, vSyncEnd, vTotal);
hsync_wid = (hSyncEnd - hSyncStart) / 8;
vsync_wid = vSyncEnd - vSyncStart;
if (hsync_wid == 0)
hsync_wid = 1;
else if (hsync_wid > 0x3f) /* max */
hsync_wid = 0x3f;
if (vsync_wid == 0)
vsync_wid = 1;
else if (vsync_wid > 0x1f) /* max */
vsync_wid = 0x1f;
hSyncPol = mode->sync & FB_SYNC_HOR_HIGH_ACT ? 0 : 1;
vSyncPol = mode->sync & FB_SYNC_VERT_HIGH_ACT ? 0 : 1;
cSync = mode->sync & FB_SYNC_COMP_HIGH_ACT ? (1 << 4) : 0;
format = radeon_get_dstbpp(depth);
bytpp = mode->bits_per_pixel >> 3;
if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD))
hsync_fudge = hsync_fudge_fp[format-1];
else
hsync_fudge = hsync_adj_tab[format-1];
hsync_start = hSyncStart - 8 + hsync_fudge;
newmode->crtc_gen_cntl = CRTC_EXT_DISP_EN | CRTC_EN |
(format << 8);
/* Clear auto-center etc... */
newmode->crtc_more_cntl = rinfo->init_state.crtc_more_cntl;
newmode->crtc_more_cntl &= 0xfffffff0;
if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) {
newmode->crtc_ext_cntl = VGA_ATI_LINEAR | XCRT_CNT_EN;
if (mirror)
newmode->crtc_ext_cntl |= CRTC_CRT_ON;
newmode->crtc_gen_cntl &= ~(CRTC_DBL_SCAN_EN |
CRTC_INTERLACE_EN);
} else {
newmode->crtc_ext_cntl = VGA_ATI_LINEAR | XCRT_CNT_EN |
CRTC_CRT_ON;
}
newmode->dac_cntl = /* INREG(DAC_CNTL) | */ DAC_MASK_ALL | DAC_VGA_ADR_EN |
DAC_8BIT_EN;
newmode->crtc_h_total_disp = ((((hTotal / 8) - 1) & 0x3ff) |
(((mode->xres / 8) - 1) << 16));
newmode->crtc_h_sync_strt_wid = ((hsync_start & 0x1fff) |
(hsync_wid << 16) | (h_sync_pol << 23));
newmode->crtc_v_total_disp = ((vTotal - 1) & 0xffff) |
((mode->yres - 1) << 16);
newmode->crtc_v_sync_strt_wid = (((vSyncStart - 1) & 0xfff) |
(vsync_wid << 16) | (v_sync_pol << 23));
if (!(info->flags & FBINFO_HWACCEL_DISABLED)) {
/* We first calculate the engine pitch */
rinfo->pitch = ((mode->xres_virtual * ((mode->bits_per_pixel + 1) / 8) + 0x3f)
& ~(0x3f)) >> 6;
/* Then, re-multiply it to get the CRTC pitch */
newmode->crtc_pitch = (rinfo->pitch << 3) / ((mode->bits_per_pixel + 1) / 8);
} else
newmode->crtc_pitch = (mode->xres_virtual >> 3);
newmode->crtc_pitch |= (newmode->crtc_pitch << 16);
/*
* It looks like recent chips have a problem with SURFACE_CNTL,
* setting SURF_TRANSLATION_DIS completely disables the
* swapper as well, so we leave it unset now.
*/
newmode->surface_cntl = 0;
#if defined(__BIG_ENDIAN)
/* Setup swapping on both apertures, though we currently
* only use aperture 0, enabling swapper on aperture 1
* won't harm
*/
switch (mode->bits_per_pixel) {
case 16:
newmode->surface_cntl |= NONSURF_AP0_SWP_16BPP;
newmode->surface_cntl |= NONSURF_AP1_SWP_16BPP;
break;
case 24:
case 32:
newmode->surface_cntl |= NONSURF_AP0_SWP_32BPP;
newmode->surface_cntl |= NONSURF_AP1_SWP_32BPP;
break;
}
#endif
/* Clear surface registers */
for (i=0; i<8; i++) {
newmode->surf_lower_bound[i] = 0;
newmode->surf_upper_bound[i] = 0x1f;
newmode->surf_info[i] = 0;
}
pr_debug("h_total_disp = 0x%x\t hsync_strt_wid = 0x%x\n",
newmode->crtc_h_total_disp, newmode->crtc_h_sync_strt_wid);
pr_debug("v_total_disp = 0x%x\t vsync_strt_wid = 0x%x\n",
newmode->crtc_v_total_disp, newmode->crtc_v_sync_strt_wid);
rinfo->bpp = mode->bits_per_pixel;
rinfo->depth = depth;
pr_debug("pixclock = %lu\n", (unsigned long)pixClock);
pr_debug("freq = %lu\n", (unsigned long)freq);
/* We use PPLL_DIV_3 */
newmode->clk_cntl_index = 0x300;
/* Calculate PPLL value if necessary */
if (!nopllcalc)
radeon_calc_pll_regs(rinfo, newmode, freq);
newmode->vclk_ecp_cntl = rinfo->init_state.vclk_ecp_cntl;
if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) {
unsigned int hRatio, vRatio;
if (mode->xres > rinfo->panel_info.xres)
mode->xres = rinfo->panel_info.xres;
if (mode->yres > rinfo->panel_info.yres)
mode->yres = rinfo->panel_info.yres;
newmode->fp_horz_stretch = (((rinfo->panel_info.xres / 8) - 1)
<< HORZ_PANEL_SHIFT);
newmode->fp_vert_stretch = ((rinfo->panel_info.yres - 1)
<< VERT_PANEL_SHIFT);
if (mode->xres != rinfo->panel_info.xres) {
hRatio = round_div(mode->xres * HORZ_STRETCH_RATIO_MAX,
rinfo->panel_info.xres);
newmode->fp_horz_stretch = (((((unsigned long)hRatio) & HORZ_STRETCH_RATIO_MASK)) |
(newmode->fp_horz_stretch &
(HORZ_PANEL_SIZE | HORZ_FP_LOOP_STRETCH |
HORZ_AUTO_RATIO_INC)));
newmode->fp_horz_stretch |= (HORZ_STRETCH_BLEND |
HORZ_STRETCH_ENABLE);
use_rmx = 1;
}
newmode->fp_horz_stretch &= ~HORZ_AUTO_RATIO;
if (mode->yres != rinfo->panel_info.yres) {
vRatio = round_div(mode->yres * VERT_STRETCH_RATIO_MAX,
rinfo->panel_info.yres);
newmode->fp_vert_stretch = (((((unsigned long)vRatio) & VERT_STRETCH_RATIO_MASK)) |
(newmode->fp_vert_stretch &
(VERT_PANEL_SIZE | VERT_STRETCH_RESERVED)));
newmode->fp_vert_stretch |= (VERT_STRETCH_BLEND |
VERT_STRETCH_ENABLE);
use_rmx = 1;
}
newmode->fp_vert_stretch &= ~VERT_AUTO_RATIO_EN;
newmode->fp_gen_cntl = (rinfo->init_state.fp_gen_cntl & (u32)
~(FP_SEL_CRTC2 |
FP_RMX_HVSYNC_CONTROL_EN |
FP_DFP_SYNC_SEL |
FP_CRT_SYNC_SEL |
FP_CRTC_LOCK_8DOT |
FP_USE_SHADOW_EN |
FP_CRTC_USE_SHADOW_VEND |
FP_CRT_SYNC_ALT));
newmode->fp_gen_cntl |= (FP_CRTC_DONT_SHADOW_VPAR |
FP_CRTC_DONT_SHADOW_HEND |
FP_PANEL_FORMAT);
if (IS_R300_VARIANT(rinfo) ||
(rinfo->family == CHIP_FAMILY_R200)) {
newmode->fp_gen_cntl &= ~R200_FP_SOURCE_SEL_MASK;
if (use_rmx)
newmode->fp_gen_cntl |= R200_FP_SOURCE_SEL_RMX;
else
newmode->fp_gen_cntl |= R200_FP_SOURCE_SEL_CRTC1;
} else
newmode->fp_gen_cntl |= FP_SEL_CRTC1;
newmode->lvds_gen_cntl = rinfo->init_state.lvds_gen_cntl;
newmode->lvds_pll_cntl = rinfo->init_state.lvds_pll_cntl;
newmode->tmds_crc = rinfo->init_state.tmds_crc;
newmode->tmds_transmitter_cntl = rinfo->init_state.tmds_transmitter_cntl;
if (primary_mon == MT_LCD) {
newmode->lvds_gen_cntl |= (LVDS_ON | LVDS_BLON);
newmode->fp_gen_cntl &= ~(FP_FPON | FP_TMDS_EN);
} else {
/* DFP */
newmode->fp_gen_cntl |= (FP_FPON | FP_TMDS_EN);
newmode->tmds_transmitter_cntl &= ~(TMDS_PLLRST);
/* TMDS_PLL_EN bit is reversed on RV (and mobility) chips */
if (IS_R300_VARIANT(rinfo) ||
(rinfo->family == CHIP_FAMILY_R200) || !rinfo->has_CRTC2)
newmode->tmds_transmitter_cntl &= ~TMDS_PLL_EN;
else
newmode->tmds_transmitter_cntl |= TMDS_PLL_EN;
newmode->crtc_ext_cntl &= ~CRTC_CRT_ON;
}
newmode->fp_crtc_h_total_disp = (((rinfo->panel_info.hblank / 8) & 0x3ff) |
(((mode->xres / 8) - 1) << 16));
newmode->fp_crtc_v_total_disp = (rinfo->panel_info.vblank & 0xffff) |
((mode->yres - 1) << 16);
newmode->fp_h_sync_strt_wid = ((rinfo->panel_info.hOver_plus & 0x1fff) |
(hsync_wid << 16) | (h_sync_pol << 23));
newmode->fp_v_sync_strt_wid = ((rinfo->panel_info.vOver_plus & 0xfff) |
(vsync_wid << 16) | (v_sync_pol << 23));
}
/* do it! */
if (!rinfo->asleep) {
memcpy(&rinfo->state, newmode, sizeof(*newmode));
radeon_write_mode (rinfo, newmode, 0);
/* (re)initialize the engine */
if (!(info->flags & FBINFO_HWACCEL_DISABLED))
radeonfb_engine_init (rinfo);
}
/* Update fix */
if (!(info->flags & FBINFO_HWACCEL_DISABLED))
info->fix.line_length = rinfo->pitch*64;
else
info->fix.line_length = mode->xres_virtual
* ((mode->bits_per_pixel + 1) / 8);
info->fix.visual = rinfo->depth == 8 ? FB_VISUAL_PSEUDOCOLOR
: FB_VISUAL_DIRECTCOLOR;
#ifdef CONFIG_BOOTX_TEXT
/* Update debug text engine */
btext_update_display(rinfo->fb_base_phys, mode->xres, mode->yres,
rinfo->depth, info->fix.line_length);
#endif
kfree(newmode);
return 0;
}
static struct fb_ops radeonfb_ops = {
.owner = THIS_MODULE,
.fb_check_var = radeonfb_check_var,
.fb_set_par = radeonfb_set_par,
.fb_setcolreg = radeonfb_setcolreg,
.fb_setcmap = radeonfb_setcmap,
.fb_pan_display = radeonfb_pan_display,
.fb_blank = radeonfb_blank,
.fb_ioctl = radeonfb_ioctl,
.fb_sync = radeonfb_sync,
.fb_fillrect = radeonfb_fillrect,
.fb_copyarea = radeonfb_copyarea,
.fb_imageblit = radeonfb_imageblit,
};
static int __devinit radeon_set_fbinfo (struct radeonfb_info *rinfo)
{
struct fb_info *info = rinfo->info;
info->par = rinfo;
info->pseudo_palette = rinfo->pseudo_palette;
info->flags = FBINFO_DEFAULT
| FBINFO_HWACCEL_COPYAREA
| FBINFO_HWACCEL_FILLRECT
| FBINFO_HWACCEL_XPAN
| FBINFO_HWACCEL_YPAN;
info->fbops = &radeonfb_ops;
info->screen_base = rinfo->fb_base;
info->screen_size = rinfo->mapped_vram;
/* Fill fix common fields */
strlcpy(info->fix.id, rinfo->name, sizeof(info->fix.id));
info->fix.smem_start = rinfo->fb_base_phys;
info->fix.smem_len = rinfo->video_ram;
info->fix.type = FB_TYPE_PACKED_PIXELS;
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
info->fix.xpanstep = 8;
info->fix.ypanstep = 1;
info->fix.ywrapstep = 0;
info->fix.type_aux = 0;
info->fix.mmio_start = rinfo->mmio_base_phys;
info->fix.mmio_len = RADEON_REGSIZE;
info->fix.accel = FB_ACCEL_ATI_RADEON;
fb_alloc_cmap(&info->cmap, 256, 0);
if (noaccel)
info->flags |= FBINFO_HWACCEL_DISABLED;
return 0;
}
/*
* This reconfigure the card's internal memory map. In theory, we'd like
* to setup the card's memory at the same address as it's PCI bus address,
* and the AGP aperture right after that so that system RAM on 32 bits
* machines at least, is directly accessible. However, doing so would
* conflict with the current XFree drivers...
* Ultimately, I hope XFree, GATOS and ATI binary drivers will all agree
* on the proper way to set this up and duplicate this here. In the meantime,
* I put the card's memory at 0 in card space and AGP at some random high
* local (0xe0000000 for now) that will be changed by XFree/DRI anyway
*/
#ifdef CONFIG_PPC_OF
#undef SET_MC_FB_FROM_APERTURE
static void fixup_memory_mappings(struct radeonfb_info *rinfo)
{
u32 save_crtc_gen_cntl, save_crtc2_gen_cntl = 0;
u32 save_crtc_ext_cntl;
u32 aper_base, aper_size;
u32 agp_base;
/* First, we disable display to avoid interfering */
if (rinfo->has_CRTC2) {
save_crtc2_gen_cntl = INREG(CRTC2_GEN_CNTL);
OUTREG(CRTC2_GEN_CNTL, save_crtc2_gen_cntl | CRTC2_DISP_REQ_EN_B);
}
save_crtc_gen_cntl = INREG(CRTC_GEN_CNTL);
save_crtc_ext_cntl = INREG(CRTC_EXT_CNTL);
OUTREG(CRTC_EXT_CNTL, save_crtc_ext_cntl | CRTC_DISPLAY_DIS);
OUTREG(CRTC_GEN_CNTL, save_crtc_gen_cntl | CRTC_DISP_REQ_EN_B);
mdelay(100);
aper_base = INREG(CNFG_APER_0_BASE);
aper_size = INREG(CNFG_APER_SIZE);
#ifdef SET_MC_FB_FROM_APERTURE
/* Set framebuffer to be at the same address as set in PCI BAR */
OUTREG(MC_FB_LOCATION,
((aper_base + aper_size - 1) & 0xffff0000) | (aper_base >> 16));
rinfo->fb_local_base = aper_base;
#else
OUTREG(MC_FB_LOCATION, 0x7fff0000);
rinfo->fb_local_base = 0;
#endif
agp_base = aper_base + aper_size;
if (agp_base & 0xf0000000)
agp_base = (aper_base | 0x0fffffff) + 1;
/* Set AGP to be just after the framebuffer on a 256Mb boundary. This
* assumes the FB isn't mapped to 0xf0000000 or above, but this is
* always the case on PPCs afaik.
*/
#ifdef SET_MC_FB_FROM_APERTURE
OUTREG(MC_AGP_LOCATION, 0xffff0000 | (agp_base >> 16));
#else
OUTREG(MC_AGP_LOCATION, 0xffffe000);
#endif
/* Fixup the display base addresses & engine offsets while we
* are at it as well
*/
#ifdef SET_MC_FB_FROM_APERTURE
OUTREG(DISPLAY_BASE_ADDR, aper_base);
if (rinfo->has_CRTC2)
OUTREG(CRTC2_DISPLAY_BASE_ADDR, aper_base);
OUTREG(OV0_BASE_ADDR, aper_base);
#else
OUTREG(DISPLAY_BASE_ADDR, 0);
if (rinfo->has_CRTC2)
OUTREG(CRTC2_DISPLAY_BASE_ADDR, 0);
OUTREG(OV0_BASE_ADDR, 0);
#endif
mdelay(100);
/* Restore display settings */
OUTREG(CRTC_GEN_CNTL, save_crtc_gen_cntl);
OUTREG(CRTC_EXT_CNTL, save_crtc_ext_cntl);
if (rinfo->has_CRTC2)
OUTREG(CRTC2_GEN_CNTL, save_crtc2_gen_cntl);
pr_debug("aper_base: %08x MC_FB_LOC to: %08x, MC_AGP_LOC to: %08x\n",
aper_base,
((aper_base + aper_size - 1) & 0xffff0000) | (aper_base >> 16),
0xffff0000 | (agp_base >> 16));
}
#endif /* CONFIG_PPC_OF */
static void radeon_identify_vram(struct radeonfb_info *rinfo)
{
u32 tmp;
/* framebuffer size */
if ((rinfo->family == CHIP_FAMILY_RS100) ||
(rinfo->family == CHIP_FAMILY_RS200) ||
(rinfo->family == CHIP_FAMILY_RS300) ||
(rinfo->family == CHIP_FAMILY_RC410) ||
(rinfo->family == CHIP_FAMILY_RS400) ||
(rinfo->family == CHIP_FAMILY_RS480) ) {
u32 tom = INREG(NB_TOM);
tmp = ((((tom >> 16) - (tom & 0xffff) + 1) << 6) * 1024);
radeon_fifo_wait(6);
OUTREG(MC_FB_LOCATION, tom);
OUTREG(DISPLAY_BASE_ADDR, (tom & 0xffff) << 16);
OUTREG(CRTC2_DISPLAY_BASE_ADDR, (tom & 0xffff) << 16);
OUTREG(OV0_BASE_ADDR, (tom & 0xffff) << 16);
/* This is supposed to fix the crtc2 noise problem. */
OUTREG(GRPH2_BUFFER_CNTL, INREG(GRPH2_BUFFER_CNTL) & ~0x7f0000);
if ((rinfo->family == CHIP_FAMILY_RS100) ||
(rinfo->family == CHIP_FAMILY_RS200)) {
/* This is to workaround the asic bug for RMX, some versions
of BIOS dosen't have this register initialized correctly.
*/
OUTREGP(CRTC_MORE_CNTL, CRTC_H_CUTOFF_ACTIVE_EN,
~CRTC_H_CUTOFF_ACTIVE_EN);
}
} else {
tmp = INREG(CNFG_MEMSIZE);
}
/* mem size is bits [28:0], mask off the rest */
rinfo->video_ram = tmp & CNFG_MEMSIZE_MASK;
/*
* Hack to get around some busted production M6's
* reporting no ram
*/
if (rinfo->video_ram == 0) {
switch (rinfo->pdev->device) {
case PCI_CHIP_RADEON_LY:
case PCI_CHIP_RADEON_LZ:
rinfo->video_ram = 8192 * 1024;
break;
default:
break;
}
}
/*
* Now try to identify VRAM type
*/
if (rinfo->is_IGP || (rinfo->family >= CHIP_FAMILY_R300) ||
(INREG(MEM_SDRAM_MODE_REG) & (1<<30)))
rinfo->vram_ddr = 1;
else
rinfo->vram_ddr = 0;
tmp = INREG(MEM_CNTL);
if (IS_R300_VARIANT(rinfo)) {
tmp &= R300_MEM_NUM_CHANNELS_MASK;
switch (tmp) {
case 0: rinfo->vram_width = 64; break;
case 1: rinfo->vram_width = 128; break;
case 2: rinfo->vram_width = 256; break;
default: rinfo->vram_width = 128; break;
}
} else if ((rinfo->family == CHIP_FAMILY_RV100) ||
(rinfo->family == CHIP_FAMILY_RS100) ||
(rinfo->family == CHIP_FAMILY_RS200)){
if (tmp & RV100_MEM_HALF_MODE)
rinfo->vram_width = 32;
else
rinfo->vram_width = 64;
} else {
if (tmp & MEM_NUM_CHANNELS_MASK)
rinfo->vram_width = 128;
else
rinfo->vram_width = 64;
}
/* This may not be correct, as some cards can have half of channel disabled
* ToDo: identify these cases
*/
pr_debug("radeonfb (%s): Found %ldk of %s %d bits wide videoram\n",
pci_name(rinfo->pdev),
rinfo->video_ram / 1024,
rinfo->vram_ddr ? "DDR" : "SDRAM",
rinfo->vram_width);
}
/*
* Sysfs
*/
static ssize_t radeon_show_one_edid(char *buf, loff_t off, size_t count, const u8 *edid)
{
return memory_read_from_buffer(buf, count, &off, edid, EDID_LENGTH);
}
static ssize_t radeon_show_edid1(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct pci_dev *pdev = to_pci_dev(dev);
struct fb_info *info = pci_get_drvdata(pdev);
struct radeonfb_info *rinfo = info->par;
return radeon_show_one_edid(buf, off, count, rinfo->mon1_EDID);
}
static ssize_t radeon_show_edid2(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct pci_dev *pdev = to_pci_dev(dev);
struct fb_info *info = pci_get_drvdata(pdev);
struct radeonfb_info *rinfo = info->par;
return radeon_show_one_edid(buf, off, count, rinfo->mon2_EDID);
}
static struct bin_attribute edid1_attr = {
.attr = {
.name = "edid1",
.mode = 0444,
},
.size = EDID_LENGTH,
.read = radeon_show_edid1,
};
static struct bin_attribute edid2_attr = {
.attr = {
.name = "edid2",
.mode = 0444,
},
.size = EDID_LENGTH,
.read = radeon_show_edid2,
};
static int __devinit radeonfb_pci_register (struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct fb_info *info;
struct radeonfb_info *rinfo;
int ret;
unsigned char c1, c2;
int err = 0;
pr_debug("radeonfb_pci_register BEGIN\n");
/* Enable device in PCI config */
ret = pci_enable_device(pdev);
if (ret < 0) {
printk(KERN_ERR "radeonfb (%s): Cannot enable PCI device\n",
pci_name(pdev));
goto err_out;
}
info = framebuffer_alloc(sizeof(struct radeonfb_info), &pdev->dev);
if (!info) {
printk (KERN_ERR "radeonfb (%s): could not allocate memory\n",
pci_name(pdev));
ret = -ENOMEM;
goto err_disable;
}
rinfo = info->par;
rinfo->info = info;
rinfo->pdev = pdev;
spin_lock_init(&rinfo->reg_lock);
init_timer(&rinfo->lvds_timer);
rinfo->lvds_timer.function = radeon_lvds_timer_func;
rinfo->lvds_timer.data = (unsigned long)rinfo;
c1 = ent->device >> 8;
c2 = ent->device & 0xff;
if (isprint(c1) && isprint(c2))
snprintf(rinfo->name, sizeof(rinfo->name),
"ATI Radeon %x \"%c%c\"", ent->device & 0xffff, c1, c2);
else
snprintf(rinfo->name, sizeof(rinfo->name),
"ATI Radeon %x", ent->device & 0xffff);
rinfo->family = ent->driver_data & CHIP_FAMILY_MASK;
rinfo->chipset = pdev->device;
rinfo->has_CRTC2 = (ent->driver_data & CHIP_HAS_CRTC2) != 0;
rinfo->is_mobility = (ent->driver_data & CHIP_IS_MOBILITY) != 0;
rinfo->is_IGP = (ent->driver_data & CHIP_IS_IGP) != 0;
/* Set base addrs */
rinfo->fb_base_phys = pci_resource_start (pdev, 0);
rinfo->mmio_base_phys = pci_resource_start (pdev, 2);
/* request the mem regions */
ret = pci_request_region(pdev, 0, "radeonfb framebuffer");
if (ret < 0) {
printk( KERN_ERR "radeonfb (%s): cannot request region 0.\n",
pci_name(rinfo->pdev));
goto err_release_fb;
}
ret = pci_request_region(pdev, 2, "radeonfb mmio");
if (ret < 0) {
printk( KERN_ERR "radeonfb (%s): cannot request region 2.\n",
pci_name(rinfo->pdev));
goto err_release_pci0;
}
/* map the regions */
rinfo->mmio_base = ioremap(rinfo->mmio_base_phys, RADEON_REGSIZE);
if (!rinfo->mmio_base) {
printk(KERN_ERR "radeonfb (%s): cannot map MMIO\n",
pci_name(rinfo->pdev));
ret = -EIO;
goto err_release_pci2;
}
rinfo->fb_local_base = INREG(MC_FB_LOCATION) << 16;
/*
* Check for errata
*/
rinfo->errata = 0;
if (rinfo->family == CHIP_FAMILY_R300 &&
(INREG(CNFG_CNTL) & CFG_ATI_REV_ID_MASK)
== CFG_ATI_REV_A11)
rinfo->errata |= CHIP_ERRATA_R300_CG;
if (rinfo->family == CHIP_FAMILY_RV200 ||
rinfo->family == CHIP_FAMILY_RS200)
rinfo->errata |= CHIP_ERRATA_PLL_DUMMYREADS;
if (rinfo->family == CHIP_FAMILY_RV100 ||
rinfo->family == CHIP_FAMILY_RS100 ||
rinfo->family == CHIP_FAMILY_RS200)
rinfo->errata |= CHIP_ERRATA_PLL_DELAY;
#if defined(CONFIG_PPC_OF) || defined(CONFIG_SPARC)
/* On PPC, we obtain the OF device-node pointer to the firmware
* data for this chip
*/
rinfo->of_node = pci_device_to_OF_node(pdev);
if (rinfo->of_node == NULL)
printk(KERN_WARNING "radeonfb (%s): Cannot match card to OF node !\n",
pci_name(rinfo->pdev));
#endif /* CONFIG_PPC_OF || CONFIG_SPARC */
#ifdef CONFIG_PPC_OF
/* On PPC, the firmware sets up a memory mapping that tends
* to cause lockups when enabling the engine. We reconfigure
* the card internal memory mappings properly
*/
fixup_memory_mappings(rinfo);
#endif /* CONFIG_PPC_OF */
/* Get VRAM size and type */
radeon_identify_vram(rinfo);
rinfo->mapped_vram = min_t(unsigned long, MAX_MAPPED_VRAM, rinfo->video_ram);
do {
rinfo->fb_base = ioremap (rinfo->fb_base_phys,
rinfo->mapped_vram);
} while (rinfo->fb_base == NULL &&
((rinfo->mapped_vram /= 2) >= MIN_MAPPED_VRAM));
if (rinfo->fb_base == NULL) {
printk (KERN_ERR "radeonfb (%s): cannot map FB\n",
pci_name(rinfo->pdev));
ret = -EIO;
goto err_unmap_rom;
}
pr_debug("radeonfb (%s): mapped %ldk videoram\n", pci_name(rinfo->pdev),
rinfo->mapped_vram/1024);
/*
* Map the BIOS ROM if any and retrieve PLL parameters from
* the BIOS. We skip that on mobility chips as the real panel
* values we need aren't in the ROM but in the BIOS image in
* memory. This is definitely not the best meacnism though,
* we really need the arch code to tell us which is the "primary"
* video adapter to use the memory image (or better, the arch
* should provide us a copy of the BIOS image to shield us from
* archs who would store that elsewhere and/or could initialize
* more than one adapter during boot).
*/
if (!rinfo->is_mobility)
radeon_map_ROM(rinfo, pdev);
/*
* On x86, the primary display on laptop may have it's BIOS
* ROM elsewhere, try to locate it at the legacy memory hole.
* We probably need to make sure this is the primary display,
* but that is difficult without some arch support.
*/
#ifdef CONFIG_X86
if (rinfo->bios_seg == NULL)
radeon_find_mem_vbios(rinfo);
#endif
/* If both above failed, try the BIOS ROM again for mobility
* chips
*/
if (rinfo->bios_seg == NULL && rinfo->is_mobility)
radeon_map_ROM(rinfo, pdev);
/* Get informations about the board's PLL */
radeon_get_pllinfo(rinfo);
#ifdef CONFIG_FB_RADEON_I2C
/* Register I2C bus */
radeon_create_i2c_busses(rinfo);
#endif
/* set all the vital stuff */
radeon_set_fbinfo (rinfo);
/* Probe screen types */
radeon_probe_screens(rinfo, monitor_layout, ignore_edid);
/* Build mode list, check out panel native model */
radeon_check_modes(rinfo, mode_option);
/* Register some sysfs stuff (should be done better) */
if (rinfo->mon1_EDID)
err |= sysfs_create_bin_file(&rinfo->pdev->dev.kobj,
&edid1_attr);
if (rinfo->mon2_EDID)
err |= sysfs_create_bin_file(&rinfo->pdev->dev.kobj,
&edid2_attr);
if (err)
pr_warning("%s() Creating sysfs files failed, continuing\n",
__func__);
/* save current mode regs before we switch into the new one
* so we can restore this upon __exit
*/
radeon_save_state (rinfo, &rinfo->init_state);
memcpy(&rinfo->state, &rinfo->init_state, sizeof(struct radeon_regs));
/* Setup Power Management capabilities */
if (default_dynclk < -1) {
/* -2 is special: means ON on mobility chips and do not
* change on others
*/
radeonfb_pm_init(rinfo, rinfo->is_mobility ? 1 : -1, ignore_devlist, force_sleep);
} else
radeonfb_pm_init(rinfo, default_dynclk, ignore_devlist, force_sleep);
pci_set_drvdata(pdev, info);
/* Register with fbdev layer */
ret = register_framebuffer(info);
if (ret < 0) {
printk (KERN_ERR "radeonfb (%s): could not register framebuffer\n",
pci_name(rinfo->pdev));
goto err_unmap_fb;
}
#ifdef CONFIG_MTRR
rinfo->mtrr_hdl = nomtrr ? -1 : mtrr_add(rinfo->fb_base_phys,
rinfo->video_ram,
MTRR_TYPE_WRCOMB, 1);
#endif
if (backlight)
radeonfb_bl_init(rinfo);
printk ("radeonfb (%s): %s\n", pci_name(rinfo->pdev), rinfo->name);
if (rinfo->bios_seg)
radeon_unmap_ROM(rinfo, pdev);
pr_debug("radeonfb_pci_register END\n");
return 0;
err_unmap_fb:
iounmap(rinfo->fb_base);
err_unmap_rom:
kfree(rinfo->mon1_EDID);
kfree(rinfo->mon2_EDID);
if (rinfo->mon1_modedb)
fb_destroy_modedb(rinfo->mon1_modedb);
fb_dealloc_cmap(&info->cmap);
#ifdef CONFIG_FB_RADEON_I2C
radeon_delete_i2c_busses(rinfo);
#endif
if (rinfo->bios_seg)
radeon_unmap_ROM(rinfo, pdev);
iounmap(rinfo->mmio_base);
err_release_pci2:
pci_release_region(pdev, 2);
err_release_pci0:
pci_release_region(pdev, 0);
err_release_fb:
framebuffer_release(info);
err_disable:
err_out:
return ret;
}
static void __devexit radeonfb_pci_unregister (struct pci_dev *pdev)
{
struct fb_info *info = pci_get_drvdata(pdev);
struct radeonfb_info *rinfo = info->par;
if (!rinfo)
return;
radeonfb_pm_exit(rinfo);
if (rinfo->mon1_EDID)
sysfs_remove_bin_file(&rinfo->pdev->dev.kobj, &edid1_attr);
if (rinfo->mon2_EDID)
sysfs_remove_bin_file(&rinfo->pdev->dev.kobj, &edid2_attr);
#if 0
/* restore original state
*
* Doesn't quite work yet, I suspect if we come from a legacy
* VGA mode (or worse, text mode), we need to do some VGA black
* magic here that I know nothing about. --BenH
*/
radeon_write_mode (rinfo, &rinfo->init_state, 1);
#endif
del_timer_sync(&rinfo->lvds_timer);
#ifdef CONFIG_MTRR
if (rinfo->mtrr_hdl >= 0)
mtrr_del(rinfo->mtrr_hdl, 0, 0);
#endif
unregister_framebuffer(info);
radeonfb_bl_exit(rinfo);
iounmap(rinfo->mmio_base);
iounmap(rinfo->fb_base);
pci_release_region(pdev, 2);
pci_release_region(pdev, 0);
kfree(rinfo->mon1_EDID);
kfree(rinfo->mon2_EDID);
if (rinfo->mon1_modedb)
fb_destroy_modedb(rinfo->mon1_modedb);
#ifdef CONFIG_FB_RADEON_I2C
radeon_delete_i2c_busses(rinfo);
#endif
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
}
static struct pci_driver radeonfb_driver = {
.name = "radeonfb",
.id_table = radeonfb_pci_table,
.probe = radeonfb_pci_register,
.remove = __devexit_p(radeonfb_pci_unregister),
#ifdef CONFIG_PM
.suspend = radeonfb_pci_suspend,
.resume = radeonfb_pci_resume,
#endif /* CONFIG_PM */
};
#ifndef MODULE
static int __init radeonfb_setup (char *options)
{
char *this_opt;
if (!options || !*options)
return 0;
while ((this_opt = strsep (&options, ",")) != NULL) {
if (!*this_opt)
continue;
if (!strncmp(this_opt, "noaccel", 7)) {
noaccel = 1;
} else if (!strncmp(this_opt, "mirror", 6)) {
mirror = 1;
} else if (!strncmp(this_opt, "force_dfp", 9)) {
force_dfp = 1;
} else if (!strncmp(this_opt, "panel_yres:", 11)) {
panel_yres = simple_strtoul((this_opt+11), NULL, 0);
} else if (!strncmp(this_opt, "backlight:", 10)) {
backlight = simple_strtoul(this_opt+10, NULL, 0);
#ifdef CONFIG_MTRR
} else if (!strncmp(this_opt, "nomtrr", 6)) {
nomtrr = 1;
#endif
} else if (!strncmp(this_opt, "nomodeset", 9)) {
nomodeset = 1;
} else if (!strncmp(this_opt, "force_measure_pll", 17)) {
force_measure_pll = 1;
} else if (!strncmp(this_opt, "ignore_edid", 11)) {
ignore_edid = 1;
#if defined(CONFIG_PM) && defined(CONFIG_X86)
} else if (!strncmp(this_opt, "force_sleep", 11)) {
force_sleep = 1;
} else if (!strncmp(this_opt, "ignore_devlist", 14)) {
ignore_devlist = 1;
#endif
} else
mode_option = this_opt;
}
return 0;
}
#endif /* MODULE */
static int __init radeonfb_init (void)
{
#ifndef MODULE
char *option = NULL;
if (fb_get_options("radeonfb", &option))
return -ENODEV;
radeonfb_setup(option);
#endif
return pci_register_driver (&radeonfb_driver);
}
static void __exit radeonfb_exit (void)
{
pci_unregister_driver (&radeonfb_driver);
}
module_init(radeonfb_init);
module_exit(radeonfb_exit);
MODULE_AUTHOR("Ani Joshi");
MODULE_DESCRIPTION("framebuffer driver for ATI Radeon chipset");
MODULE_LICENSE("GPL");
module_param(noaccel, bool, 0);
module_param(default_dynclk, int, 0);
MODULE_PARM_DESC(default_dynclk, "int: -2=enable on mobility only,-1=do not change,0=off,1=on");
MODULE_PARM_DESC(noaccel, "bool: disable acceleration");
module_param(nomodeset, bool, 0);
MODULE_PARM_DESC(nomodeset, "bool: disable actual setting of video mode");
module_param(mirror, bool, 0);
MODULE_PARM_DESC(mirror, "bool: mirror the display to both monitors");
module_param(force_dfp, bool, 0);
MODULE_PARM_DESC(force_dfp, "bool: force display to dfp");
module_param(ignore_edid, bool, 0);
MODULE_PARM_DESC(ignore_edid, "bool: Ignore EDID data when doing DDC probe");
module_param(monitor_layout, charp, 0);
MODULE_PARM_DESC(monitor_layout, "Specify monitor mapping (like XFree86)");
module_param(force_measure_pll, bool, 0);
MODULE_PARM_DESC(force_measure_pll, "Force measurement of PLL (debug)");
#ifdef CONFIG_MTRR
module_param(nomtrr, bool, 0);
MODULE_PARM_DESC(nomtrr, "bool: disable use of MTRR registers");
#endif
module_param(panel_yres, int, 0);
MODULE_PARM_DESC(panel_yres, "int: set panel yres");
module_param(mode_option, charp, 0);
MODULE_PARM_DESC(mode_option, "Specify resolution as \"<xres>x<yres>[-<bpp>][@<refresh>]\" ");
#if defined(CONFIG_PM) && defined(CONFIG_X86)
module_param(force_sleep, bool, 0);
MODULE_PARM_DESC(force_sleep, "bool: force D2 sleep mode on all hardware");
module_param(ignore_devlist, bool, 0);
MODULE_PARM_DESC(ignore_devlist, "bool: ignore workarounds for bugs in specific laptops");
#endif
| gpl-2.0 |
jaronow/LGE970_ICS_kernel | drivers/staging/cx25821/cx25821-alsa.c | 2919 | 19866 | /*
* Driver for the Conexant CX25821 PCIe bridge
*
* Copyright (C) 2009 Conexant Systems Inc.
* Authors <shu.lin@conexant.com>, <hiep.huynh@conexant.com>
* Based on SAA713x ALSA driver and CX88 driver
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/vmalloc.h>
#include <linux/dma-mapping.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/control.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#include "cx25821.h"
#include "cx25821-reg.h"
#define AUDIO_SRAM_CHANNEL SRAM_CH08
#define dprintk(level, fmt, arg...) \
do { \
if (debug >= level) \
pr_info("%s/1: " fmt, chip->dev->name, ##arg); \
} while (0)
#define dprintk_core(level, fmt, arg...) \
do { \
if (debug >= level) \
printk(KERN_DEBUG "%s/1: " fmt, chip->dev->name, ##arg); \
} while (0)
/****************************************************************************
Data type declarations - Can be moded to a header file later
****************************************************************************/
static struct snd_card *snd_cx25821_cards[SNDRV_CARDS];
static int devno;
struct cx25821_audio_buffer {
unsigned int bpl;
struct btcx_riscmem risc;
struct videobuf_dmabuf dma;
};
struct cx25821_audio_dev {
struct cx25821_dev *dev;
struct cx25821_dmaqueue q;
/* pci i/o */
struct pci_dev *pci;
/* audio controls */
int irq;
struct snd_card *card;
unsigned long iobase;
spinlock_t reg_lock;
atomic_t count;
unsigned int dma_size;
unsigned int period_size;
unsigned int num_periods;
struct videobuf_dmabuf *dma_risc;
struct cx25821_audio_buffer *buf;
struct snd_pcm_substream *substream;
};
/****************************************************************************
Module global static vars
****************************************************************************/
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static int enable[SNDRV_CARDS] = { 1, [1 ... (SNDRV_CARDS - 1)] = 1 };
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable cx25821 soundcard. default enabled.");
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for cx25821 capture interface(s).");
/****************************************************************************
Module macros
****************************************************************************/
MODULE_DESCRIPTION("ALSA driver module for cx25821 based capture cards");
MODULE_AUTHOR("Hiep Huynh");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Conexant,25821}"); /* "{{Conexant,23881}," */
static unsigned int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "enable debug messages");
/****************************************************************************
Module specific funtions
****************************************************************************/
/* Constants taken from cx88-reg.h */
#define AUD_INT_DN_RISCI1 (1 << 0)
#define AUD_INT_UP_RISCI1 (1 << 1)
#define AUD_INT_RDS_DN_RISCI1 (1 << 2)
#define AUD_INT_DN_RISCI2 (1 << 4) /* yes, 3 is skipped */
#define AUD_INT_UP_RISCI2 (1 << 5)
#define AUD_INT_RDS_DN_RISCI2 (1 << 6)
#define AUD_INT_DN_SYNC (1 << 12)
#define AUD_INT_UP_SYNC (1 << 13)
#define AUD_INT_RDS_DN_SYNC (1 << 14)
#define AUD_INT_OPC_ERR (1 << 16)
#define AUD_INT_BER_IRQ (1 << 20)
#define AUD_INT_MCHG_IRQ (1 << 21)
#define GP_COUNT_CONTROL_RESET 0x3
#define PCI_MSK_AUD_EXT (1 << 4)
#define PCI_MSK_AUD_INT (1 << 3)
/*
* BOARD Specific: Sets audio DMA
*/
static int _cx25821_start_audio_dma(struct cx25821_audio_dev *chip)
{
struct cx25821_audio_buffer *buf = chip->buf;
struct cx25821_dev *dev = chip->dev;
struct sram_channel *audio_ch =
&cx25821_sram_channels[AUDIO_SRAM_CHANNEL];
u32 tmp = 0;
/* enable output on the GPIO 0 for the MCLK ADC (Audio) */
cx25821_set_gpiopin_direction(chip->dev, 0, 0);
/* Make sure RISC/FIFO are off before changing FIFO/RISC settings */
cx_clear(AUD_INT_DMA_CTL,
FLD_AUD_DST_A_RISC_EN | FLD_AUD_DST_A_FIFO_EN);
/* setup fifo + format - out channel */
cx25821_sram_channel_setup_audio(chip->dev, audio_ch, buf->bpl,
buf->risc.dma);
/* sets bpl size */
cx_write(AUD_A_LNGTH, buf->bpl);
/* reset counter */
/* GP_COUNT_CONTROL_RESET = 0x3 */
cx_write(AUD_A_GPCNT_CTL, GP_COUNT_CONTROL_RESET);
atomic_set(&chip->count, 0);
/* Set the input mode to 16-bit */
tmp = cx_read(AUD_A_CFG);
cx_write(AUD_A_CFG,
tmp | FLD_AUD_DST_PK_MODE | FLD_AUD_DST_ENABLE |
FLD_AUD_CLK_ENABLE);
/*
pr_info("DEBUG: Start audio DMA, %d B/line, cmds_start(0x%x)= %d lines/FIFO, %d periods, %d byte buffer\n",
buf->bpl, audio_ch->cmds_start,
cx_read(audio_ch->cmds_start + 12)>>1,
chip->num_periods, buf->bpl * chip->num_periods);
*/
/* Enables corresponding bits at AUD_INT_STAT */
cx_write(AUD_A_INT_MSK,
FLD_AUD_DST_RISCI1 | FLD_AUD_DST_OF | FLD_AUD_DST_SYNC |
FLD_AUD_DST_OPC_ERR);
/* Clean any pending interrupt bits already set */
cx_write(AUD_A_INT_STAT, ~0);
/* enable audio irqs */
cx_set(PCI_INT_MSK, chip->dev->pci_irqmask | PCI_MSK_AUD_INT);
/* Turn on audio downstream fifo and risc enable 0x101 */
tmp = cx_read(AUD_INT_DMA_CTL);
cx_set(AUD_INT_DMA_CTL,
tmp | (FLD_AUD_DST_A_RISC_EN | FLD_AUD_DST_A_FIFO_EN));
mdelay(100);
return 0;
}
/*
* BOARD Specific: Resets audio DMA
*/
static int _cx25821_stop_audio_dma(struct cx25821_audio_dev *chip)
{
struct cx25821_dev *dev = chip->dev;
/* stop dma */
cx_clear(AUD_INT_DMA_CTL,
FLD_AUD_DST_A_RISC_EN | FLD_AUD_DST_A_FIFO_EN);
/* disable irqs */
cx_clear(PCI_INT_MSK, PCI_MSK_AUD_INT);
cx_clear(AUD_A_INT_MSK,
AUD_INT_OPC_ERR | AUD_INT_DN_SYNC | AUD_INT_DN_RISCI2 |
AUD_INT_DN_RISCI1);
return 0;
}
#define MAX_IRQ_LOOP 50
/*
* BOARD Specific: IRQ dma bits
*/
static char *cx25821_aud_irqs[32] = {
"dn_risci1", "up_risci1", "rds_dn_risc1", /* 0-2 */
NULL, /* reserved */
"dn_risci2", "up_risci2", "rds_dn_risc2", /* 4-6 */
NULL, /* reserved */
"dnf_of", "upf_uf", "rds_dnf_uf", /* 8-10 */
NULL, /* reserved */
"dn_sync", "up_sync", "rds_dn_sync", /* 12-14 */
NULL, /* reserved */
"opc_err", "par_err", "rip_err", /* 16-18 */
"pci_abort", "ber_irq", "mchg_irq" /* 19-21 */
};
/*
* BOARD Specific: Threats IRQ audio specific calls
*/
static void cx25821_aud_irq(struct cx25821_audio_dev *chip, u32 status,
u32 mask)
{
struct cx25821_dev *dev = chip->dev;
if (0 == (status & mask))
return;
cx_write(AUD_A_INT_STAT, status);
if (debug > 1 || (status & mask & ~0xff))
cx25821_print_irqbits(dev->name, "irq aud",
cx25821_aud_irqs,
ARRAY_SIZE(cx25821_aud_irqs), status,
mask);
/* risc op code error */
if (status & AUD_INT_OPC_ERR) {
pr_warn("WARNING %s/1: Audio risc op code error\n", dev->name);
cx_clear(AUD_INT_DMA_CTL,
FLD_AUD_DST_A_RISC_EN | FLD_AUD_DST_A_FIFO_EN);
cx25821_sram_channel_dump_audio(dev,
&cx25821_sram_channels
[AUDIO_SRAM_CHANNEL]);
}
if (status & AUD_INT_DN_SYNC) {
pr_warn("WARNING %s: Downstream sync error!\n", dev->name);
cx_write(AUD_A_GPCNT_CTL, GP_COUNT_CONTROL_RESET);
return;
}
/* risc1 downstream */
if (status & AUD_INT_DN_RISCI1) {
atomic_set(&chip->count, cx_read(AUD_A_GPCNT));
snd_pcm_period_elapsed(chip->substream);
}
}
/*
* BOARD Specific: Handles IRQ calls
*/
static irqreturn_t cx25821_irq(int irq, void *dev_id)
{
struct cx25821_audio_dev *chip = dev_id;
struct cx25821_dev *dev = chip->dev;
u32 status, pci_status;
u32 audint_status, audint_mask;
int loop, handled = 0;
int audint_count = 0;
audint_status = cx_read(AUD_A_INT_STAT);
audint_mask = cx_read(AUD_A_INT_MSK);
audint_count = cx_read(AUD_A_GPCNT);
status = cx_read(PCI_INT_STAT);
for (loop = 0; loop < 1; loop++) {
status = cx_read(PCI_INT_STAT);
if (0 == status) {
status = cx_read(PCI_INT_STAT);
audint_status = cx_read(AUD_A_INT_STAT);
audint_mask = cx_read(AUD_A_INT_MSK);
if (status) {
handled = 1;
cx_write(PCI_INT_STAT, status);
cx25821_aud_irq(chip, audint_status,
audint_mask);
break;
} else
goto out;
}
handled = 1;
cx_write(PCI_INT_STAT, status);
cx25821_aud_irq(chip, audint_status, audint_mask);
}
pci_status = cx_read(PCI_INT_STAT);
if (handled)
cx_write(PCI_INT_STAT, pci_status);
out:
return IRQ_RETVAL(handled);
}
static int dsp_buffer_free(struct cx25821_audio_dev *chip)
{
BUG_ON(!chip->dma_size);
dprintk(2, "Freeing buffer\n");
videobuf_dma_unmap(&chip->pci->dev, chip->dma_risc);
videobuf_dma_free(chip->dma_risc);
btcx_riscmem_free(chip->pci, &chip->buf->risc);
kfree(chip->buf);
chip->dma_risc = NULL;
chip->dma_size = 0;
return 0;
}
/****************************************************************************
ALSA PCM Interface
****************************************************************************/
/*
* Digital hardware definition
*/
#define DEFAULT_FIFO_SIZE 384
static struct snd_pcm_hardware snd_cx25821_digital_hw = {
.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_MMAP_VALID,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_48000,
.rate_min = 48000,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
/* Analog audio output will be full of clicks and pops if there
are not exactly four lines in the SRAM FIFO buffer. */
.period_bytes_min = DEFAULT_FIFO_SIZE / 3,
.period_bytes_max = DEFAULT_FIFO_SIZE / 3,
.periods_min = 1,
.periods_max = AUDIO_LINE_SIZE,
/* 128 * 128 = 16384 = 1024 * 16 */
.buffer_bytes_max = (AUDIO_LINE_SIZE * AUDIO_LINE_SIZE),
};
/*
* audio pcm capture open callback
*/
static int snd_cx25821_pcm_open(struct snd_pcm_substream *substream)
{
struct cx25821_audio_dev *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
unsigned int bpl = 0;
if (!chip) {
pr_err("DEBUG: cx25821 can't find device struct. Can't proceed with open\n");
return -ENODEV;
}
err =
snd_pcm_hw_constraint_pow2(runtime, 0, SNDRV_PCM_HW_PARAM_PERIODS);
if (err < 0)
goto _error;
chip->substream = substream;
runtime->hw = snd_cx25821_digital_hw;
if (cx25821_sram_channels[AUDIO_SRAM_CHANNEL].fifo_size !=
DEFAULT_FIFO_SIZE) {
/* since there are 3 audio Clusters */
bpl = cx25821_sram_channels[AUDIO_SRAM_CHANNEL].fifo_size / 3;
bpl &= ~7; /* must be multiple of 8 */
if (bpl > AUDIO_LINE_SIZE)
bpl = AUDIO_LINE_SIZE;
runtime->hw.period_bytes_min = bpl;
runtime->hw.period_bytes_max = bpl;
}
return 0;
_error:
dprintk(1, "Error opening PCM!\n");
return err;
}
/*
* audio close callback
*/
static int snd_cx25821_close(struct snd_pcm_substream *substream)
{
return 0;
}
/*
* hw_params callback
*/
static int snd_cx25821_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct cx25821_audio_dev *chip = snd_pcm_substream_chip(substream);
struct videobuf_dmabuf *dma;
struct cx25821_audio_buffer *buf;
int ret;
if (substream->runtime->dma_area) {
dsp_buffer_free(chip);
substream->runtime->dma_area = NULL;
}
chip->period_size = params_period_bytes(hw_params);
chip->num_periods = params_periods(hw_params);
chip->dma_size = chip->period_size * params_periods(hw_params);
BUG_ON(!chip->dma_size);
BUG_ON(chip->num_periods & (chip->num_periods - 1));
buf = kzalloc(sizeof(*buf), GFP_KERNEL);
if (NULL == buf)
return -ENOMEM;
if (chip->period_size > AUDIO_LINE_SIZE)
chip->period_size = AUDIO_LINE_SIZE;
buf->bpl = chip->period_size;
dma = &buf->dma;
videobuf_dma_init(dma);
ret = videobuf_dma_init_kernel(dma, PCI_DMA_FROMDEVICE,
(PAGE_ALIGN(chip->dma_size) >>
PAGE_SHIFT));
if (ret < 0)
goto error;
ret = videobuf_dma_map(&chip->pci->dev, dma);
if (ret < 0)
goto error;
ret =
cx25821_risc_databuffer_audio(chip->pci, &buf->risc, dma->sglist,
chip->period_size, chip->num_periods,
1);
if (ret < 0) {
pr_info("DEBUG: ERROR after cx25821_risc_databuffer_audio()\n");
goto error;
}
/* Loop back to start of program */
buf->risc.jmp[0] = cpu_to_le32(RISC_JUMP | RISC_IRQ1 | RISC_CNT_INC);
buf->risc.jmp[1] = cpu_to_le32(buf->risc.dma);
buf->risc.jmp[2] = cpu_to_le32(0); /* bits 63-32 */
chip->buf = buf;
chip->dma_risc = dma;
substream->runtime->dma_area = chip->dma_risc->vaddr;
substream->runtime->dma_bytes = chip->dma_size;
substream->runtime->dma_addr = 0;
return 0;
error:
kfree(buf);
return ret;
}
/*
* hw free callback
*/
static int snd_cx25821_hw_free(struct snd_pcm_substream *substream)
{
struct cx25821_audio_dev *chip = snd_pcm_substream_chip(substream);
if (substream->runtime->dma_area) {
dsp_buffer_free(chip);
substream->runtime->dma_area = NULL;
}
return 0;
}
/*
* prepare callback
*/
static int snd_cx25821_prepare(struct snd_pcm_substream *substream)
{
return 0;
}
/*
* trigger callback
*/
static int snd_cx25821_card_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct cx25821_audio_dev *chip = snd_pcm_substream_chip(substream);
int err = 0;
/* Local interrupts are already disabled by ALSA */
spin_lock(&chip->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
err = _cx25821_start_audio_dma(chip);
break;
case SNDRV_PCM_TRIGGER_STOP:
err = _cx25821_stop_audio_dma(chip);
break;
default:
err = -EINVAL;
break;
}
spin_unlock(&chip->reg_lock);
return err;
}
/*
* pointer callback
*/
static snd_pcm_uframes_t snd_cx25821_pointer(struct snd_pcm_substream
*substream)
{
struct cx25821_audio_dev *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
u16 count;
count = atomic_read(&chip->count);
return runtime->period_size * (count & (runtime->periods - 1));
}
/*
* page callback (needed for mmap)
*/
static struct page *snd_cx25821_page(struct snd_pcm_substream *substream,
unsigned long offset)
{
void *pageptr = substream->runtime->dma_area + offset;
return vmalloc_to_page(pageptr);
}
/*
* operators
*/
static struct snd_pcm_ops snd_cx25821_pcm_ops = {
.open = snd_cx25821_pcm_open,
.close = snd_cx25821_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cx25821_hw_params,
.hw_free = snd_cx25821_hw_free,
.prepare = snd_cx25821_prepare,
.trigger = snd_cx25821_card_trigger,
.pointer = snd_cx25821_pointer,
.page = snd_cx25821_page,
};
/*
* ALSA create a PCM device: Called when initializing the board.
* Sets up the name and hooks up the callbacks
*/
static int snd_cx25821_pcm(struct cx25821_audio_dev *chip, int device,
char *name)
{
struct snd_pcm *pcm;
int err;
err = snd_pcm_new(chip->card, name, device, 0, 1, &pcm);
if (err < 0) {
pr_info("ERROR: FAILED snd_pcm_new() in %s\n", __func__);
return err;
}
pcm->private_data = chip;
pcm->info_flags = 0;
strcpy(pcm->name, name);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_cx25821_pcm_ops);
return 0;
}
/****************************************************************************
Basic Flow for Sound Devices
****************************************************************************/
/*
* PCI ID Table - 14f1:8801 and 14f1:8811 means function 1: Audio
* Only boards with eeprom and byte 1 at eeprom=1 have it
*/
static DEFINE_PCI_DEVICE_TABLE(cx25821_audio_pci_tbl) = {
{0x14f1, 0x0920, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{0,}
};
MODULE_DEVICE_TABLE(pci, cx25821_audio_pci_tbl);
/*
* Not used in the function snd_cx25821_dev_free so removing
* from the file.
*/
/*
static int snd_cx25821_free(struct cx25821_audio_dev *chip)
{
if (chip->irq >= 0)
free_irq(chip->irq, chip);
cx25821_dev_unregister(chip->dev);
pci_disable_device(chip->pci);
return 0;
}
*/
/*
* Component Destructor
*/
static void snd_cx25821_dev_free(struct snd_card *card)
{
struct cx25821_audio_dev *chip = card->private_data;
/* snd_cx25821_free(chip); */
snd_card_free(chip->card);
}
/*
* Alsa Constructor - Component probe
*/
static int cx25821_audio_initdev(struct cx25821_dev *dev)
{
struct snd_card *card;
struct cx25821_audio_dev *chip;
int err;
if (devno >= SNDRV_CARDS) {
pr_info("DEBUG ERROR: devno >= SNDRV_CARDS %s\n", __func__);
return -ENODEV;
}
if (!enable[devno]) {
++devno;
pr_info("DEBUG ERROR: !enable[devno] %s\n", __func__);
return -ENOENT;
}
err = snd_card_create(index[devno], id[devno], THIS_MODULE,
sizeof(struct cx25821_audio_dev), &card);
if (err < 0) {
pr_info("DEBUG ERROR: cannot create snd_card_new in %s\n",
__func__);
return err;
}
strcpy(card->driver, "cx25821");
/* Card "creation" */
card->private_free = snd_cx25821_dev_free;
chip = card->private_data;
spin_lock_init(&chip->reg_lock);
chip->dev = dev;
chip->card = card;
chip->pci = dev->pci;
chip->iobase = pci_resource_start(dev->pci, 0);
chip->irq = dev->pci->irq;
err = request_irq(dev->pci->irq, cx25821_irq,
IRQF_SHARED | IRQF_DISABLED, chip->dev->name, chip);
if (err < 0) {
pr_err("ERROR %s: can't get IRQ %d for ALSA\n",
chip->dev->name, dev->pci->irq);
goto error;
}
err = snd_cx25821_pcm(chip, 0, "cx25821 Digital");
if (err < 0) {
pr_info("DEBUG ERROR: cannot create snd_cx25821_pcm %s\n",
__func__);
goto error;
}
snd_card_set_dev(card, &chip->pci->dev);
strcpy(card->shortname, "cx25821");
sprintf(card->longname, "%s at 0x%lx irq %d", chip->dev->name,
chip->iobase, chip->irq);
strcpy(card->mixername, "CX25821");
pr_info("%s/%i: ALSA support for cx25821 boards\n",
card->driver, devno);
err = snd_card_register(card);
if (err < 0) {
pr_info("DEBUG ERROR: cannot register sound card %s\n",
__func__);
goto error;
}
snd_cx25821_cards[devno] = card;
devno++;
return 0;
error:
snd_card_free(card);
return err;
}
/****************************************************************************
LINUX MODULE INIT
****************************************************************************/
static void cx25821_audio_fini(void)
{
snd_card_free(snd_cx25821_cards[0]);
}
/*
* Module initializer
*
* Loops through present saa7134 cards, and assigns an ALSA device
* to each one
*
*/
static int cx25821_alsa_init(void)
{
struct cx25821_dev *dev = NULL;
struct list_head *list;
mutex_lock(&cx25821_devlist_mutex);
list_for_each(list, &cx25821_devlist) {
dev = list_entry(list, struct cx25821_dev, devlist);
cx25821_audio_initdev(dev);
}
mutex_unlock(&cx25821_devlist_mutex);
if (dev == NULL)
pr_info("ERROR ALSA: no cx25821 cards found\n");
return 0;
}
late_initcall(cx25821_alsa_init);
module_exit(cx25821_audio_fini);
/* ----------------------------------------------------------- */
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
Snuzzo/vigor_mofokernel | drivers/staging/rtl8192u/ieee80211/scatterwalk.c | 3175 | 3163 | /*
* Cryptographic API.
*
* Cipher operations.
*
* Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
* 2002 Adam J. Richter <adam@yggdrasil.com>
* 2004 Jean-Luc Cooke <jlcooke@certainkey.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 "kmap_types.h"
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/highmem.h>
#include <asm/scatterlist.h>
#include "internal.h"
#include "scatterwalk.h"
enum km_type crypto_km_types[] = {
KM_USER0,
KM_USER1,
KM_SOFTIRQ0,
KM_SOFTIRQ1,
};
void *scatterwalk_whichbuf(struct scatter_walk *walk, unsigned int nbytes, void *scratch)
{
if (nbytes <= walk->len_this_page &&
(((unsigned long)walk->data) & (PAGE_CACHE_SIZE - 1)) + nbytes <=
PAGE_CACHE_SIZE)
return walk->data;
else
return scratch;
}
static void memcpy_dir(void *buf, void *sgdata, size_t nbytes, int out)
{
if (out)
memcpy(sgdata, buf, nbytes);
else
memcpy(buf, sgdata, nbytes);
}
void scatterwalk_start(struct scatter_walk *walk, struct scatterlist *sg)
{
unsigned int rest_of_page;
walk->sg = sg;
walk->page = sg->page;
walk->len_this_segment = sg->length;
rest_of_page = PAGE_CACHE_SIZE - (sg->offset & (PAGE_CACHE_SIZE - 1));
walk->len_this_page = min(sg->length, rest_of_page);
walk->offset = sg->offset;
}
void scatterwalk_map(struct scatter_walk *walk, int out)
{
walk->data = crypto_kmap(walk->page, out) + walk->offset;
}
static void scatterwalk_pagedone(struct scatter_walk *walk, int out,
unsigned int more)
{
/* walk->data may be pointing the first byte of the next page;
however, we know we transferred at least one byte. So,
walk->data - 1 will be a virtual address in the mapped page. */
if (out)
flush_dcache_page(walk->page);
if (more) {
walk->len_this_segment -= walk->len_this_page;
if (walk->len_this_segment) {
walk->page++;
walk->len_this_page = min(walk->len_this_segment,
(unsigned)PAGE_CACHE_SIZE);
walk->offset = 0;
}
else
scatterwalk_start(walk, sg_next(walk->sg));
}
}
void scatterwalk_done(struct scatter_walk *walk, int out, int more)
{
crypto_kunmap(walk->data, out);
if (walk->len_this_page == 0 || !more)
scatterwalk_pagedone(walk, out, more);
}
/*
* Do not call this unless the total length of all of the fragments
* has been verified as multiple of the block size.
*/
int scatterwalk_copychunks(void *buf, struct scatter_walk *walk,
size_t nbytes, int out)
{
if (buf != walk->data) {
while (nbytes > walk->len_this_page) {
memcpy_dir(buf, walk->data, walk->len_this_page, out);
buf += walk->len_this_page;
nbytes -= walk->len_this_page;
crypto_kunmap(walk->data, out);
scatterwalk_pagedone(walk, out, 1);
scatterwalk_map(walk, out);
}
memcpy_dir(buf, walk->data, nbytes, out);
}
walk->offset += nbytes;
walk->len_this_page -= nbytes;
walk->len_this_segment -= nbytes;
return 0;
}
| gpl-2.0 |
Stane1983/buildroot-linux-kernel-m6 | drivers/isdn/hisax/hfc_sx.c | 3175 | 44866 | /* $Id: hfc_sx.c,v 1.12.2.5 2004/02/11 13:21:33 keil Exp $
*
* level driver for Cologne Chip Designs hfc-s+/sp based cards
*
* Author Werner Cornelius
* based on existing driver for CCD HFC PCI cards
* Copyright by Werner Cornelius <werner@isdn4linux.de>
*
* 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 "hfc_sx.h"
#include "isdnl1.h"
#include <linux/interrupt.h>
#include <linux/isapnp.h>
#include <linux/slab.h>
static const char *hfcsx_revision = "$Revision: 1.12.2.5 $";
/***************************************/
/* IRQ-table for CCDs demo board */
/* IRQs 6,5,10,11,12,15 are supported */
/***************************************/
/* Teles 16.3c Vendor Id TAG2620, Version 1.0, Vendor version 2.1
*
* Thanks to Uwe Wisniewski
*
* ISA-SLOT Signal PIN
* B25 IRQ3 92 IRQ_G
* B23 IRQ5 94 IRQ_A
* B4 IRQ2/9 95 IRQ_B
* D3 IRQ10 96 IRQ_C
* D4 IRQ11 97 IRQ_D
* D5 IRQ12 98 IRQ_E
* D6 IRQ15 99 IRQ_F
*/
#undef CCD_DEMO_BOARD
#ifdef CCD_DEMO_BOARD
static u_char ccd_sp_irqtab[16] = {
0,0,0,0,0,2,1,0,0,0,3,4,5,0,0,6
};
#else /* Teles 16.3c */
static u_char ccd_sp_irqtab[16] = {
0,0,0,7,0,1,0,0,0,2,3,4,5,0,0,6
};
#endif
#define NT_T1_COUNT 20 /* number of 3.125ms interrupts for G2 timeout */
#define byteout(addr,val) outb(val,addr)
#define bytein(addr) inb(addr)
/******************************/
/* In/Out access to registers */
/******************************/
static inline void
Write_hfc(struct IsdnCardState *cs, u_char regnum, u_char val)
{
byteout(cs->hw.hfcsx.base+1, regnum);
byteout(cs->hw.hfcsx.base, val);
}
static inline u_char
Read_hfc(struct IsdnCardState *cs, u_char regnum)
{
u_char ret;
byteout(cs->hw.hfcsx.base+1, regnum);
ret = bytein(cs->hw.hfcsx.base);
return(ret);
}
/**************************************************/
/* select a fifo and remember which one for reuse */
/**************************************************/
static void
fifo_select(struct IsdnCardState *cs, u_char fifo)
{
if (fifo == cs->hw.hfcsx.last_fifo)
return; /* still valid */
byteout(cs->hw.hfcsx.base+1, HFCSX_FIF_SEL);
byteout(cs->hw.hfcsx.base, fifo);
while (bytein(cs->hw.hfcsx.base+1) & 1); /* wait for busy */
udelay(4);
byteout(cs->hw.hfcsx.base, fifo);
while (bytein(cs->hw.hfcsx.base+1) & 1); /* wait for busy */
}
/******************************************/
/* reset the specified fifo to defaults. */
/* If its a send fifo init needed markers */
/******************************************/
static void
reset_fifo(struct IsdnCardState *cs, u_char fifo)
{
fifo_select(cs, fifo); /* first select the fifo */
byteout(cs->hw.hfcsx.base+1, HFCSX_CIRM);
byteout(cs->hw.hfcsx.base, cs->hw.hfcsx.cirm | 0x80); /* reset cmd */
udelay(1);
while (bytein(cs->hw.hfcsx.base+1) & 1); /* wait for busy */
}
/*************************************************************/
/* write_fifo writes the skb contents to the desired fifo */
/* if no space is available or an error occurs 0 is returned */
/* the skb is not released in any way. */
/*************************************************************/
static int
write_fifo(struct IsdnCardState *cs, struct sk_buff *skb, u_char fifo, int trans_max)
{
unsigned short *msp;
int fifo_size, count, z1, z2;
u_char f_msk, f1, f2, *src;
if (skb->len <= 0) return(0);
if (fifo & 1) return(0); /* no write fifo */
fifo_select(cs, fifo);
if (fifo & 4) {
fifo_size = D_FIFO_SIZE; /* D-channel */
f_msk = MAX_D_FRAMES;
if (trans_max) return(0); /* only HDLC */
}
else {
fifo_size = cs->hw.hfcsx.b_fifo_size; /* B-channel */
f_msk = MAX_B_FRAMES;
}
z1 = Read_hfc(cs, HFCSX_FIF_Z1H);
z1 = ((z1 << 8) | Read_hfc(cs, HFCSX_FIF_Z1L));
/* Check for transparent mode */
if (trans_max) {
z2 = Read_hfc(cs, HFCSX_FIF_Z2H);
z2 = ((z2 << 8) | Read_hfc(cs, HFCSX_FIF_Z2L));
count = z2 - z1;
if (count <= 0)
count += fifo_size; /* free bytes */
if (count < skb->len+1) return(0); /* no room */
count = fifo_size - count; /* bytes still not send */
if (count > 2 * trans_max) return(0); /* delay to long */
count = skb->len;
src = skb->data;
while (count--)
Write_hfc(cs, HFCSX_FIF_DWR, *src++);
return(1); /* success */
}
msp = ((struct hfcsx_extra *)(cs->hw.hfcsx.extra))->marker;
msp += (((fifo >> 1) & 3) * (MAX_B_FRAMES+1));
f1 = Read_hfc(cs, HFCSX_FIF_F1) & f_msk;
f2 = Read_hfc(cs, HFCSX_FIF_F2) & f_msk;
count = f1 - f2; /* frame count actually buffered */
if (count < 0)
count += (f_msk + 1); /* if wrap around */
if (count > f_msk-1) {
if (cs->debug & L1_DEB_ISAC_FIFO)
debugl1(cs, "hfcsx_write_fifo %d more as %d frames",fifo,f_msk-1);
return(0);
}
*(msp + f1) = z1; /* remember marker */
if (cs->debug & L1_DEB_ISAC_FIFO)
debugl1(cs, "hfcsx_write_fifo %d f1(%x) f2(%x) z1(f1)(%x)",
fifo, f1, f2, z1);
/* now determine free bytes in FIFO buffer */
count = *(msp + f2) - z1;
if (count <= 0)
count += fifo_size; /* count now contains available bytes */
if (cs->debug & L1_DEB_ISAC_FIFO)
debugl1(cs, "hfcsx_write_fifo %d count(%u/%d)",
fifo, skb->len, count);
if (count < skb->len) {
if (cs->debug & L1_DEB_ISAC_FIFO)
debugl1(cs, "hfcsx_write_fifo %d no fifo mem", fifo);
return(0);
}
count = skb->len; /* get frame len */
src = skb->data; /* source pointer */
while (count--)
Write_hfc(cs, HFCSX_FIF_DWR, *src++);
Read_hfc(cs, HFCSX_FIF_INCF1); /* increment F1 */
udelay(1);
while (bytein(cs->hw.hfcsx.base+1) & 1); /* wait for busy */
return(1);
}
/***************************************************************/
/* read_fifo reads data to an skb from the desired fifo */
/* if no data is available or an error occurs NULL is returned */
/* the skb is not released in any way. */
/***************************************************************/
static struct sk_buff *
read_fifo(struct IsdnCardState *cs, u_char fifo, int trans_max)
{ int fifo_size, count, z1, z2;
u_char f_msk, f1, f2, *dst;
struct sk_buff *skb;
if (!(fifo & 1)) return(NULL); /* no read fifo */
fifo_select(cs, fifo);
if (fifo & 4) {
fifo_size = D_FIFO_SIZE; /* D-channel */
f_msk = MAX_D_FRAMES;
if (trans_max) return(NULL); /* only hdlc */
}
else {
fifo_size = cs->hw.hfcsx.b_fifo_size; /* B-channel */
f_msk = MAX_B_FRAMES;
}
/* transparent mode */
if (trans_max) {
z1 = Read_hfc(cs, HFCSX_FIF_Z1H);
z1 = ((z1 << 8) | Read_hfc(cs, HFCSX_FIF_Z1L));
z2 = Read_hfc(cs, HFCSX_FIF_Z2H);
z2 = ((z2 << 8) | Read_hfc(cs, HFCSX_FIF_Z2L));
/* now determine bytes in actual FIFO buffer */
count = z1 - z2;
if (count <= 0)
count += fifo_size; /* count now contains buffered bytes */
count++;
if (count > trans_max)
count = trans_max; /* limit length */
skb = dev_alloc_skb(count);
if (skb) {
dst = skb_put(skb, count);
while (count--)
*dst++ = Read_hfc(cs, HFCSX_FIF_DRD);
return skb;
} else
return NULL; /* no memory */
}
do {
f1 = Read_hfc(cs, HFCSX_FIF_F1) & f_msk;
f2 = Read_hfc(cs, HFCSX_FIF_F2) & f_msk;
if (f1 == f2) return(NULL); /* no frame available */
z1 = Read_hfc(cs, HFCSX_FIF_Z1H);
z1 = ((z1 << 8) | Read_hfc(cs, HFCSX_FIF_Z1L));
z2 = Read_hfc(cs, HFCSX_FIF_Z2H);
z2 = ((z2 << 8) | Read_hfc(cs, HFCSX_FIF_Z2L));
if (cs->debug & L1_DEB_ISAC_FIFO)
debugl1(cs, "hfcsx_read_fifo %d f1(%x) f2(%x) z1(f2)(%x) z2(f2)(%x)",
fifo, f1, f2, z1, z2);
/* now determine bytes in actual FIFO buffer */
count = z1 - z2;
if (count <= 0)
count += fifo_size; /* count now contains buffered bytes */
count++;
if (cs->debug & L1_DEB_ISAC_FIFO)
debugl1(cs, "hfcsx_read_fifo %d count %u)",
fifo, count);
if ((count > fifo_size) || (count < 4)) {
if (cs->debug & L1_DEB_WARN)
debugl1(cs, "hfcsx_read_fifo %d paket inv. len %d ", fifo , count);
while (count) {
count--; /* empty fifo */
Read_hfc(cs, HFCSX_FIF_DRD);
}
skb = NULL;
} else
if ((skb = dev_alloc_skb(count - 3))) {
count -= 3;
dst = skb_put(skb, count);
while (count--)
*dst++ = Read_hfc(cs, HFCSX_FIF_DRD);
Read_hfc(cs, HFCSX_FIF_DRD); /* CRC 1 */
Read_hfc(cs, HFCSX_FIF_DRD); /* CRC 2 */
if (Read_hfc(cs, HFCSX_FIF_DRD)) {
dev_kfree_skb_irq(skb);
if (cs->debug & L1_DEB_ISAC_FIFO)
debugl1(cs, "hfcsx_read_fifo %d crc error", fifo);
skb = NULL;
}
} else {
printk(KERN_WARNING "HFC-SX: receive out of memory\n");
return(NULL);
}
Read_hfc(cs, HFCSX_FIF_INCF2); /* increment F2 */
udelay(1);
while (bytein(cs->hw.hfcsx.base+1) & 1); /* wait for busy */
udelay(1);
} while (!skb); /* retry in case of crc error */
return(skb);
}
/******************************************/
/* free hardware resources used by driver */
/******************************************/
static void
release_io_hfcsx(struct IsdnCardState *cs)
{
cs->hw.hfcsx.int_m2 = 0; /* interrupt output off ! */
Write_hfc(cs, HFCSX_INT_M2, cs->hw.hfcsx.int_m2);
Write_hfc(cs, HFCSX_CIRM, HFCSX_RESET); /* Reset On */
msleep(30); /* Timeout 30ms */
Write_hfc(cs, HFCSX_CIRM, 0); /* Reset Off */
del_timer(&cs->hw.hfcsx.timer);
release_region(cs->hw.hfcsx.base, 2); /* release IO-Block */
kfree(cs->hw.hfcsx.extra);
cs->hw.hfcsx.extra = NULL;
}
/**********************************************************/
/* set_fifo_size determines the size of the RAM and FIFOs */
/* returning 0 -> need to reset the chip again. */
/**********************************************************/
static int set_fifo_size(struct IsdnCardState *cs)
{
if (cs->hw.hfcsx.b_fifo_size) return(1); /* already determined */
if ((cs->hw.hfcsx.chip >> 4) == 9) {
cs->hw.hfcsx.b_fifo_size = B_FIFO_SIZE_32K;
return(1);
}
cs->hw.hfcsx.b_fifo_size = B_FIFO_SIZE_8K;
cs->hw.hfcsx.cirm |= 0x10; /* only 8K of ram */
return(0);
}
/********************************************************************************/
/* function called to reset the HFC SX chip. A complete software reset of chip */
/* and fifos is done. */
/********************************************************************************/
static void
reset_hfcsx(struct IsdnCardState *cs)
{
cs->hw.hfcsx.int_m2 = 0; /* interrupt output off ! */
Write_hfc(cs, HFCSX_INT_M2, cs->hw.hfcsx.int_m2);
printk(KERN_INFO "HFC_SX: resetting card\n");
while (1) {
Write_hfc(cs, HFCSX_CIRM, HFCSX_RESET | cs->hw.hfcsx.cirm ); /* Reset */
mdelay(30);
Write_hfc(cs, HFCSX_CIRM, cs->hw.hfcsx.cirm); /* Reset Off */
mdelay(20);
if (Read_hfc(cs, HFCSX_STATUS) & 2)
printk(KERN_WARNING "HFC-SX init bit busy\n");
cs->hw.hfcsx.last_fifo = 0xff; /* invalidate */
if (!set_fifo_size(cs)) continue;
break;
}
cs->hw.hfcsx.trm = 0 + HFCSX_BTRANS_THRESMASK; /* no echo connect , threshold */
Write_hfc(cs, HFCSX_TRM, cs->hw.hfcsx.trm);
Write_hfc(cs, HFCSX_CLKDEL, 0x0e); /* ST-Bit delay for TE-Mode */
cs->hw.hfcsx.sctrl_e = HFCSX_AUTO_AWAKE;
Write_hfc(cs, HFCSX_SCTRL_E, cs->hw.hfcsx.sctrl_e); /* S/T Auto awake */
cs->hw.hfcsx.bswapped = 0; /* no exchange */
cs->hw.hfcsx.nt_mode = 0; /* we are in TE mode */
cs->hw.hfcsx.ctmt = HFCSX_TIM3_125 | HFCSX_AUTO_TIMER;
Write_hfc(cs, HFCSX_CTMT, cs->hw.hfcsx.ctmt);
cs->hw.hfcsx.int_m1 = HFCSX_INTS_DTRANS | HFCSX_INTS_DREC |
HFCSX_INTS_L1STATE | HFCSX_INTS_TIMER;
Write_hfc(cs, HFCSX_INT_M1, cs->hw.hfcsx.int_m1);
/* Clear already pending ints */
if (Read_hfc(cs, HFCSX_INT_S1));
Write_hfc(cs, HFCSX_STATES, HFCSX_LOAD_STATE | 2); /* HFC ST 2 */
udelay(10);
Write_hfc(cs, HFCSX_STATES, 2); /* HFC ST 2 */
cs->hw.hfcsx.mst_m = HFCSX_MASTER; /* HFC Master Mode */
Write_hfc(cs, HFCSX_MST_MODE, cs->hw.hfcsx.mst_m);
cs->hw.hfcsx.sctrl = 0x40; /* set tx_lo mode, error in datasheet ! */
Write_hfc(cs, HFCSX_SCTRL, cs->hw.hfcsx.sctrl);
cs->hw.hfcsx.sctrl_r = 0;
Write_hfc(cs, HFCSX_SCTRL_R, cs->hw.hfcsx.sctrl_r);
/* Init GCI/IOM2 in master mode */
/* Slots 0 and 1 are set for B-chan 1 and 2 */
/* D- and monitor/CI channel are not enabled */
/* STIO1 is used as output for data, B1+B2 from ST->IOM+HFC */
/* STIO2 is used as data input, B1+B2 from IOM->ST */
/* ST B-channel send disabled -> continuous 1s */
/* The IOM slots are always enabled */
cs->hw.hfcsx.conn = 0x36; /* set data flow directions */
Write_hfc(cs, HFCSX_CONNECT, cs->hw.hfcsx.conn);
Write_hfc(cs, HFCSX_B1_SSL, 0x80); /* B1-Slot 0 STIO1 out enabled */
Write_hfc(cs, HFCSX_B2_SSL, 0x81); /* B2-Slot 1 STIO1 out enabled */
Write_hfc(cs, HFCSX_B1_RSL, 0x80); /* B1-Slot 0 STIO2 in enabled */
Write_hfc(cs, HFCSX_B2_RSL, 0x81); /* B2-Slot 1 STIO2 in enabled */
/* Finally enable IRQ output */
cs->hw.hfcsx.int_m2 = HFCSX_IRQ_ENABLE;
Write_hfc(cs, HFCSX_INT_M2, cs->hw.hfcsx.int_m2);
if (Read_hfc(cs, HFCSX_INT_S2));
}
/***************************************************/
/* Timer function called when kernel timer expires */
/***************************************************/
static void
hfcsx_Timer(struct IsdnCardState *cs)
{
cs->hw.hfcsx.timer.expires = jiffies + 75;
/* WD RESET */
/* WriteReg(cs, HFCD_DATA, HFCD_CTMT, cs->hw.hfcsx.ctmt | 0x80);
add_timer(&cs->hw.hfcsx.timer);
*/
}
/************************************************/
/* select a b-channel entry matching and active */
/************************************************/
static
struct BCState *
Sel_BCS(struct IsdnCardState *cs, int channel)
{
if (cs->bcs[0].mode && (cs->bcs[0].channel == channel))
return (&cs->bcs[0]);
else if (cs->bcs[1].mode && (cs->bcs[1].channel == channel))
return (&cs->bcs[1]);
else
return (NULL);
}
/*******************************/
/* D-channel receive procedure */
/*******************************/
static
int
receive_dmsg(struct IsdnCardState *cs)
{
struct sk_buff *skb;
int count = 5;
if (test_and_set_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
debugl1(cs, "rec_dmsg blocked");
return (1);
}
do {
skb = read_fifo(cs, HFCSX_SEL_D_RX, 0);
if (skb) {
skb_queue_tail(&cs->rq, skb);
schedule_event(cs, D_RCVBUFREADY);
}
} while (--count && skb);
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
return (1);
}
/**********************************/
/* B-channel main receive routine */
/**********************************/
static void
main_rec_hfcsx(struct BCState *bcs)
{
struct IsdnCardState *cs = bcs->cs;
int count = 5;
struct sk_buff *skb;
Begin:
count--;
if (test_and_set_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
debugl1(cs, "rec_data %d blocked", bcs->channel);
return;
}
skb = read_fifo(cs, ((bcs->channel) && (!cs->hw.hfcsx.bswapped)) ?
HFCSX_SEL_B2_RX : HFCSX_SEL_B1_RX,
(bcs->mode == L1_MODE_TRANS) ?
HFCSX_BTRANS_THRESHOLD : 0);
if (skb) {
skb_queue_tail(&bcs->rqueue, skb);
schedule_event(bcs, B_RCVBUFREADY);
}
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
if (count && skb)
goto Begin;
return;
}
/**************************/
/* D-channel send routine */
/**************************/
static void
hfcsx_fill_dfifo(struct IsdnCardState *cs)
{
if (!cs->tx_skb)
return;
if (cs->tx_skb->len <= 0)
return;
if (write_fifo(cs, cs->tx_skb, HFCSX_SEL_D_TX, 0)) {
dev_kfree_skb_any(cs->tx_skb);
cs->tx_skb = NULL;
}
return;
}
/**************************/
/* B-channel send routine */
/**************************/
static void
hfcsx_fill_fifo(struct BCState *bcs)
{
struct IsdnCardState *cs = bcs->cs;
if (!bcs->tx_skb)
return;
if (bcs->tx_skb->len <= 0)
return;
if (write_fifo(cs, bcs->tx_skb,
((bcs->channel) && (!cs->hw.hfcsx.bswapped)) ?
HFCSX_SEL_B2_TX : HFCSX_SEL_B1_TX,
(bcs->mode == L1_MODE_TRANS) ?
HFCSX_BTRANS_THRESHOLD : 0)) {
bcs->tx_cnt -= bcs->tx_skb->len;
if (test_bit(FLG_LLI_L1WAKEUP,&bcs->st->lli.flag) &&
(PACKET_NOACK != bcs->tx_skb->pkt_type)) {
u_long flags;
spin_lock_irqsave(&bcs->aclock, flags);
bcs->ackcnt += bcs->tx_skb->len;
spin_unlock_irqrestore(&bcs->aclock, flags);
schedule_event(bcs, B_ACKPENDING);
}
dev_kfree_skb_any(bcs->tx_skb);
bcs->tx_skb = NULL;
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
}
}
/**********************************************/
/* D-channel l1 state call for leased NT-mode */
/**********************************************/
static void
dch_nt_l2l1(struct PStack *st, int pr, void *arg)
{
struct IsdnCardState *cs = (struct IsdnCardState *) st->l1.hardware;
switch (pr) {
case (PH_DATA | REQUEST):
case (PH_PULL | REQUEST):
case (PH_PULL | INDICATION):
st->l1.l1hw(st, pr, arg);
break;
case (PH_ACTIVATE | REQUEST):
st->l1.l1l2(st, PH_ACTIVATE | CONFIRM, NULL);
break;
case (PH_TESTLOOP | REQUEST):
if (1 & (long) arg)
debugl1(cs, "PH_TEST_LOOP B1");
if (2 & (long) arg)
debugl1(cs, "PH_TEST_LOOP B2");
if (!(3 & (long) arg))
debugl1(cs, "PH_TEST_LOOP DISABLED");
st->l1.l1hw(st, HW_TESTLOOP | REQUEST, arg);
break;
default:
if (cs->debug)
debugl1(cs, "dch_nt_l2l1 msg %04X unhandled", pr);
break;
}
}
/***********************/
/* set/reset echo mode */
/***********************/
static int
hfcsx_auxcmd(struct IsdnCardState *cs, isdn_ctrl * ic)
{
unsigned long flags;
int i = *(unsigned int *) ic->parm.num;
if ((ic->arg == 98) &&
(!(cs->hw.hfcsx.int_m1 & (HFCSX_INTS_B2TRANS + HFCSX_INTS_B2REC + HFCSX_INTS_B1TRANS + HFCSX_INTS_B1REC)))) {
spin_lock_irqsave(&cs->lock, flags);
Write_hfc(cs, HFCSX_STATES, HFCSX_LOAD_STATE | 0); /* HFC ST G0 */
udelay(10);
cs->hw.hfcsx.sctrl |= SCTRL_MODE_NT;
Write_hfc(cs, HFCSX_SCTRL, cs->hw.hfcsx.sctrl); /* set NT-mode */
udelay(10);
Write_hfc(cs, HFCSX_STATES, HFCSX_LOAD_STATE | 1); /* HFC ST G1 */
udelay(10);
Write_hfc(cs, HFCSX_STATES, 1 | HFCSX_ACTIVATE | HFCSX_DO_ACTION);
cs->dc.hfcsx.ph_state = 1;
cs->hw.hfcsx.nt_mode = 1;
cs->hw.hfcsx.nt_timer = 0;
spin_unlock_irqrestore(&cs->lock, flags);
cs->stlist->l2.l2l1 = dch_nt_l2l1;
debugl1(cs, "NT mode activated");
return (0);
}
if ((cs->chanlimit > 1) || (cs->hw.hfcsx.bswapped) ||
(cs->hw.hfcsx.nt_mode) || (ic->arg != 12))
return (-EINVAL);
if (i) {
cs->logecho = 1;
cs->hw.hfcsx.trm |= 0x20; /* enable echo chan */
cs->hw.hfcsx.int_m1 |= HFCSX_INTS_B2REC;
/* reset Channel !!!!! */
} else {
cs->logecho = 0;
cs->hw.hfcsx.trm &= ~0x20; /* disable echo chan */
cs->hw.hfcsx.int_m1 &= ~HFCSX_INTS_B2REC;
}
cs->hw.hfcsx.sctrl_r &= ~SCTRL_B2_ENA;
cs->hw.hfcsx.sctrl &= ~SCTRL_B2_ENA;
cs->hw.hfcsx.conn |= 0x10; /* B2-IOM -> B2-ST */
cs->hw.hfcsx.ctmt &= ~2;
spin_lock_irqsave(&cs->lock, flags);
Write_hfc(cs, HFCSX_CTMT, cs->hw.hfcsx.ctmt);
Write_hfc(cs, HFCSX_SCTRL_R, cs->hw.hfcsx.sctrl_r);
Write_hfc(cs, HFCSX_SCTRL, cs->hw.hfcsx.sctrl);
Write_hfc(cs, HFCSX_CONNECT, cs->hw.hfcsx.conn);
Write_hfc(cs, HFCSX_TRM, cs->hw.hfcsx.trm);
Write_hfc(cs, HFCSX_INT_M1, cs->hw.hfcsx.int_m1);
spin_unlock_irqrestore(&cs->lock, flags);
return (0);
} /* hfcsx_auxcmd */
/*****************************/
/* E-channel receive routine */
/*****************************/
static void
receive_emsg(struct IsdnCardState *cs)
{
int count = 5;
u_char *ptr;
struct sk_buff *skb;
if (test_and_set_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
debugl1(cs, "echo_rec_data blocked");
return;
}
do {
skb = read_fifo(cs, HFCSX_SEL_B2_RX, 0);
if (skb) {
if (cs->debug & DEB_DLOG_HEX) {
ptr = cs->dlog;
if ((skb->len) < MAX_DLOG_SPACE / 3 - 10) {
*ptr++ = 'E';
*ptr++ = 'C';
*ptr++ = 'H';
*ptr++ = 'O';
*ptr++ = ':';
ptr += QuickHex(ptr, skb->data, skb->len);
ptr--;
*ptr++ = '\n';
*ptr = 0;
HiSax_putstatus(cs, NULL, cs->dlog);
} else
HiSax_putstatus(cs, "LogEcho: ", "warning Frame too big (%d)", skb->len);
}
dev_kfree_skb_any(skb);
}
} while (--count && skb);
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
return;
} /* receive_emsg */
/*********************/
/* Interrupt handler */
/*********************/
static irqreturn_t
hfcsx_interrupt(int intno, void *dev_id)
{
struct IsdnCardState *cs = dev_id;
u_char exval;
struct BCState *bcs;
int count = 15;
u_long flags;
u_char val, stat;
if (!(cs->hw.hfcsx.int_m2 & 0x08))
return IRQ_NONE; /* not initialised */
spin_lock_irqsave(&cs->lock, flags);
if (HFCSX_ANYINT & (stat = Read_hfc(cs, HFCSX_STATUS))) {
val = Read_hfc(cs, HFCSX_INT_S1);
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "HFC-SX: stat(%02x) s1(%02x)", stat, val);
} else {
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_NONE;
}
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "HFC-SX irq %x %s", val,
test_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags) ?
"locked" : "unlocked");
val &= cs->hw.hfcsx.int_m1;
if (val & 0x40) { /* state machine irq */
exval = Read_hfc(cs, HFCSX_STATES) & 0xf;
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "ph_state chg %d->%d", cs->dc.hfcsx.ph_state,
exval);
cs->dc.hfcsx.ph_state = exval;
schedule_event(cs, D_L1STATECHANGE);
val &= ~0x40;
}
if (val & 0x80) { /* timer irq */
if (cs->hw.hfcsx.nt_mode) {
if ((--cs->hw.hfcsx.nt_timer) < 0)
schedule_event(cs, D_L1STATECHANGE);
}
val &= ~0x80;
Write_hfc(cs, HFCSX_CTMT, cs->hw.hfcsx.ctmt | HFCSX_CLTIMER);
}
while (val) {
if (test_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
cs->hw.hfcsx.int_s1 |= val;
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
if (cs->hw.hfcsx.int_s1 & 0x18) {
exval = val;
val = cs->hw.hfcsx.int_s1;
cs->hw.hfcsx.int_s1 = exval;
}
if (val & 0x08) {
if (!(bcs = Sel_BCS(cs, cs->hw.hfcsx.bswapped ? 1 : 0))) {
if (cs->debug)
debugl1(cs, "hfcsx spurious 0x08 IRQ");
} else
main_rec_hfcsx(bcs);
}
if (val & 0x10) {
if (cs->logecho)
receive_emsg(cs);
else if (!(bcs = Sel_BCS(cs, 1))) {
if (cs->debug)
debugl1(cs, "hfcsx spurious 0x10 IRQ");
} else
main_rec_hfcsx(bcs);
}
if (val & 0x01) {
if (!(bcs = Sel_BCS(cs, cs->hw.hfcsx.bswapped ? 1 : 0))) {
if (cs->debug)
debugl1(cs, "hfcsx spurious 0x01 IRQ");
} else {
if (bcs->tx_skb) {
if (!test_and_set_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
hfcsx_fill_fifo(bcs);
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
} else
debugl1(cs, "fill_data %d blocked", bcs->channel);
} else {
if ((bcs->tx_skb = skb_dequeue(&bcs->squeue))) {
if (!test_and_set_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
hfcsx_fill_fifo(bcs);
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
} else
debugl1(cs, "fill_data %d blocked", bcs->channel);
} else {
schedule_event(bcs, B_XMTBUFREADY);
}
}
}
}
if (val & 0x02) {
if (!(bcs = Sel_BCS(cs, 1))) {
if (cs->debug)
debugl1(cs, "hfcsx spurious 0x02 IRQ");
} else {
if (bcs->tx_skb) {
if (!test_and_set_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
hfcsx_fill_fifo(bcs);
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
} else
debugl1(cs, "fill_data %d blocked", bcs->channel);
} else {
if ((bcs->tx_skb = skb_dequeue(&bcs->squeue))) {
if (!test_and_set_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
hfcsx_fill_fifo(bcs);
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
} else
debugl1(cs, "fill_data %d blocked", bcs->channel);
} else {
schedule_event(bcs, B_XMTBUFREADY);
}
}
}
}
if (val & 0x20) { /* receive dframe */
receive_dmsg(cs);
}
if (val & 0x04) { /* dframe transmitted */
if (test_and_clear_bit(FLG_DBUSY_TIMER, &cs->HW_Flags))
del_timer(&cs->dbusytimer);
if (test_and_clear_bit(FLG_L1_DBUSY, &cs->HW_Flags))
schedule_event(cs, D_CLEARBUSY);
if (cs->tx_skb) {
if (cs->tx_skb->len) {
if (!test_and_set_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
hfcsx_fill_dfifo(cs);
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
} else {
debugl1(cs, "hfcsx_fill_dfifo irq blocked");
}
goto afterXPR;
} else {
dev_kfree_skb_irq(cs->tx_skb);
cs->tx_cnt = 0;
cs->tx_skb = NULL;
}
}
if ((cs->tx_skb = skb_dequeue(&cs->sq))) {
cs->tx_cnt = 0;
if (!test_and_set_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
hfcsx_fill_dfifo(cs);
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
} else {
debugl1(cs, "hfcsx_fill_dfifo irq blocked");
}
} else
schedule_event(cs, D_XMTBUFREADY);
}
afterXPR:
if (cs->hw.hfcsx.int_s1 && count--) {
val = cs->hw.hfcsx.int_s1;
cs->hw.hfcsx.int_s1 = 0;
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "HFC-SX irq %x loop %d", val, 15 - count);
} else
val = 0;
}
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
/********************************************************************/
/* timer callback for D-chan busy resolution. Currently no function */
/********************************************************************/
static void
hfcsx_dbusy_timer(struct IsdnCardState *cs)
{
}
/*************************************/
/* Layer 1 D-channel hardware access */
/*************************************/
static void
HFCSX_l1hw(struct PStack *st, int pr, void *arg)
{
struct IsdnCardState *cs = (struct IsdnCardState *) st->l1.hardware;
struct sk_buff *skb = arg;
u_long flags;
switch (pr) {
case (PH_DATA | REQUEST):
if (cs->debug & DEB_DLOG_HEX)
LogFrame(cs, skb->data, skb->len);
if (cs->debug & DEB_DLOG_VERBOSE)
dlogframe(cs, skb, 0);
spin_lock_irqsave(&cs->lock, flags);
if (cs->tx_skb) {
skb_queue_tail(&cs->sq, skb);
#ifdef L2FRAME_DEBUG /* psa */
if (cs->debug & L1_DEB_LAPD)
Logl2Frame(cs, skb, "PH_DATA Queued", 0);
#endif
} else {
cs->tx_skb = skb;
cs->tx_cnt = 0;
#ifdef L2FRAME_DEBUG /* psa */
if (cs->debug & L1_DEB_LAPD)
Logl2Frame(cs, skb, "PH_DATA", 0);
#endif
if (!test_and_set_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
hfcsx_fill_dfifo(cs);
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
} else
debugl1(cs, "hfcsx_fill_dfifo blocked");
}
spin_unlock_irqrestore(&cs->lock, flags);
break;
case (PH_PULL | INDICATION):
spin_lock_irqsave(&cs->lock, flags);
if (cs->tx_skb) {
if (cs->debug & L1_DEB_WARN)
debugl1(cs, " l2l1 tx_skb exist this shouldn't happen");
skb_queue_tail(&cs->sq, skb);
spin_unlock_irqrestore(&cs->lock, flags);
break;
}
if (cs->debug & DEB_DLOG_HEX)
LogFrame(cs, skb->data, skb->len);
if (cs->debug & DEB_DLOG_VERBOSE)
dlogframe(cs, skb, 0);
cs->tx_skb = skb;
cs->tx_cnt = 0;
#ifdef L2FRAME_DEBUG /* psa */
if (cs->debug & L1_DEB_LAPD)
Logl2Frame(cs, skb, "PH_DATA_PULLED", 0);
#endif
if (!test_and_set_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
hfcsx_fill_dfifo(cs);
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
} else
debugl1(cs, "hfcsx_fill_dfifo blocked");
spin_unlock_irqrestore(&cs->lock, flags);
break;
case (PH_PULL | REQUEST):
#ifdef L2FRAME_DEBUG /* psa */
if (cs->debug & L1_DEB_LAPD)
debugl1(cs, "-> PH_REQUEST_PULL");
#endif
if (!cs->tx_skb) {
test_and_clear_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
st->l1.l1l2(st, PH_PULL | CONFIRM, NULL);
} else
test_and_set_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
break;
case (HW_RESET | REQUEST):
spin_lock_irqsave(&cs->lock, flags);
Write_hfc(cs, HFCSX_STATES, HFCSX_LOAD_STATE | 3); /* HFC ST 3 */
udelay(6);
Write_hfc(cs, HFCSX_STATES, 3); /* HFC ST 2 */
cs->hw.hfcsx.mst_m |= HFCSX_MASTER;
Write_hfc(cs, HFCSX_MST_MODE, cs->hw.hfcsx.mst_m);
Write_hfc(cs, HFCSX_STATES, HFCSX_ACTIVATE | HFCSX_DO_ACTION);
spin_unlock_irqrestore(&cs->lock, flags);
l1_msg(cs, HW_POWERUP | CONFIRM, NULL);
break;
case (HW_ENABLE | REQUEST):
spin_lock_irqsave(&cs->lock, flags);
Write_hfc(cs, HFCSX_STATES, HFCSX_ACTIVATE | HFCSX_DO_ACTION);
spin_unlock_irqrestore(&cs->lock, flags);
break;
case (HW_DEACTIVATE | REQUEST):
spin_lock_irqsave(&cs->lock, flags);
cs->hw.hfcsx.mst_m &= ~HFCSX_MASTER;
Write_hfc(cs, HFCSX_MST_MODE, cs->hw.hfcsx.mst_m);
spin_unlock_irqrestore(&cs->lock, flags);
break;
case (HW_INFO3 | REQUEST):
spin_lock_irqsave(&cs->lock, flags);
cs->hw.hfcsx.mst_m |= HFCSX_MASTER;
Write_hfc(cs, HFCSX_MST_MODE, cs->hw.hfcsx.mst_m);
spin_unlock_irqrestore(&cs->lock, flags);
break;
case (HW_TESTLOOP | REQUEST):
spin_lock_irqsave(&cs->lock, flags);
switch ((long) arg) {
case (1):
Write_hfc(cs, HFCSX_B1_SSL, 0x80); /* tx slot */
Write_hfc(cs, HFCSX_B1_RSL, 0x80); /* rx slot */
cs->hw.hfcsx.conn = (cs->hw.hfcsx.conn & ~7) | 1;
Write_hfc(cs, HFCSX_CONNECT, cs->hw.hfcsx.conn);
break;
case (2):
Write_hfc(cs, HFCSX_B2_SSL, 0x81); /* tx slot */
Write_hfc(cs, HFCSX_B2_RSL, 0x81); /* rx slot */
cs->hw.hfcsx.conn = (cs->hw.hfcsx.conn & ~0x38) | 0x08;
Write_hfc(cs, HFCSX_CONNECT, cs->hw.hfcsx.conn);
break;
default:
spin_unlock_irqrestore(&cs->lock, flags);
if (cs->debug & L1_DEB_WARN)
debugl1(cs, "hfcsx_l1hw loop invalid %4lx", (unsigned long)arg);
return;
}
cs->hw.hfcsx.trm |= 0x80; /* enable IOM-loop */
Write_hfc(cs, HFCSX_TRM, cs->hw.hfcsx.trm);
spin_unlock_irqrestore(&cs->lock, flags);
break;
default:
if (cs->debug & L1_DEB_WARN)
debugl1(cs, "hfcsx_l1hw unknown pr %4x", pr);
break;
}
}
/***********************************************/
/* called during init setting l1 stack pointer */
/***********************************************/
static void
setstack_hfcsx(struct PStack *st, struct IsdnCardState *cs)
{
st->l1.l1hw = HFCSX_l1hw;
}
/**************************************/
/* send B-channel data if not blocked */
/**************************************/
static void
hfcsx_send_data(struct BCState *bcs)
{
struct IsdnCardState *cs = bcs->cs;
if (!test_and_set_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
hfcsx_fill_fifo(bcs);
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
} else
debugl1(cs, "send_data %d blocked", bcs->channel);
}
/***************************************************************/
/* activate/deactivate hardware for selected channels and mode */
/***************************************************************/
static void
mode_hfcsx(struct BCState *bcs, int mode, int bc)
{
struct IsdnCardState *cs = bcs->cs;
int fifo2;
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "HFCSX bchannel mode %d bchan %d/%d",
mode, bc, bcs->channel);
bcs->mode = mode;
bcs->channel = bc;
fifo2 = bc;
if (cs->chanlimit > 1) {
cs->hw.hfcsx.bswapped = 0; /* B1 and B2 normal mode */
cs->hw.hfcsx.sctrl_e &= ~0x80;
} else {
if (bc) {
if (mode != L1_MODE_NULL) {
cs->hw.hfcsx.bswapped = 1; /* B1 and B2 exchanged */
cs->hw.hfcsx.sctrl_e |= 0x80;
} else {
cs->hw.hfcsx.bswapped = 0; /* B1 and B2 normal mode */
cs->hw.hfcsx.sctrl_e &= ~0x80;
}
fifo2 = 0;
} else {
cs->hw.hfcsx.bswapped = 0; /* B1 and B2 normal mode */
cs->hw.hfcsx.sctrl_e &= ~0x80;
}
}
switch (mode) {
case (L1_MODE_NULL):
if (bc) {
cs->hw.hfcsx.sctrl &= ~SCTRL_B2_ENA;
cs->hw.hfcsx.sctrl_r &= ~SCTRL_B2_ENA;
} else {
cs->hw.hfcsx.sctrl &= ~SCTRL_B1_ENA;
cs->hw.hfcsx.sctrl_r &= ~SCTRL_B1_ENA;
}
if (fifo2) {
cs->hw.hfcsx.int_m1 &= ~(HFCSX_INTS_B2TRANS + HFCSX_INTS_B2REC);
} else {
cs->hw.hfcsx.int_m1 &= ~(HFCSX_INTS_B1TRANS + HFCSX_INTS_B1REC);
}
break;
case (L1_MODE_TRANS):
if (bc) {
cs->hw.hfcsx.sctrl |= SCTRL_B2_ENA;
cs->hw.hfcsx.sctrl_r |= SCTRL_B2_ENA;
} else {
cs->hw.hfcsx.sctrl |= SCTRL_B1_ENA;
cs->hw.hfcsx.sctrl_r |= SCTRL_B1_ENA;
}
if (fifo2) {
cs->hw.hfcsx.int_m1 |= (HFCSX_INTS_B2TRANS + HFCSX_INTS_B2REC);
cs->hw.hfcsx.ctmt |= 2;
cs->hw.hfcsx.conn &= ~0x18;
} else {
cs->hw.hfcsx.int_m1 |= (HFCSX_INTS_B1TRANS + HFCSX_INTS_B1REC);
cs->hw.hfcsx.ctmt |= 1;
cs->hw.hfcsx.conn &= ~0x03;
}
break;
case (L1_MODE_HDLC):
if (bc) {
cs->hw.hfcsx.sctrl |= SCTRL_B2_ENA;
cs->hw.hfcsx.sctrl_r |= SCTRL_B2_ENA;
} else {
cs->hw.hfcsx.sctrl |= SCTRL_B1_ENA;
cs->hw.hfcsx.sctrl_r |= SCTRL_B1_ENA;
}
if (fifo2) {
cs->hw.hfcsx.int_m1 |= (HFCSX_INTS_B2TRANS + HFCSX_INTS_B2REC);
cs->hw.hfcsx.ctmt &= ~2;
cs->hw.hfcsx.conn &= ~0x18;
} else {
cs->hw.hfcsx.int_m1 |= (HFCSX_INTS_B1TRANS + HFCSX_INTS_B1REC);
cs->hw.hfcsx.ctmt &= ~1;
cs->hw.hfcsx.conn &= ~0x03;
}
break;
case (L1_MODE_EXTRN):
if (bc) {
cs->hw.hfcsx.conn |= 0x10;
cs->hw.hfcsx.sctrl |= SCTRL_B2_ENA;
cs->hw.hfcsx.sctrl_r |= SCTRL_B2_ENA;
cs->hw.hfcsx.int_m1 &= ~(HFCSX_INTS_B2TRANS + HFCSX_INTS_B2REC);
} else {
cs->hw.hfcsx.conn |= 0x02;
cs->hw.hfcsx.sctrl |= SCTRL_B1_ENA;
cs->hw.hfcsx.sctrl_r |= SCTRL_B1_ENA;
cs->hw.hfcsx.int_m1 &= ~(HFCSX_INTS_B1TRANS + HFCSX_INTS_B1REC);
}
break;
}
Write_hfc(cs, HFCSX_SCTRL_E, cs->hw.hfcsx.sctrl_e);
Write_hfc(cs, HFCSX_INT_M1, cs->hw.hfcsx.int_m1);
Write_hfc(cs, HFCSX_SCTRL, cs->hw.hfcsx.sctrl);
Write_hfc(cs, HFCSX_SCTRL_R, cs->hw.hfcsx.sctrl_r);
Write_hfc(cs, HFCSX_CTMT, cs->hw.hfcsx.ctmt);
Write_hfc(cs, HFCSX_CONNECT, cs->hw.hfcsx.conn);
if (mode != L1_MODE_EXTRN) {
reset_fifo(cs, fifo2 ? HFCSX_SEL_B2_RX : HFCSX_SEL_B1_RX);
reset_fifo(cs, fifo2 ? HFCSX_SEL_B2_TX : HFCSX_SEL_B1_TX);
}
}
/******************************/
/* Layer2 -> Layer 1 Transfer */
/******************************/
static void
hfcsx_l2l1(struct PStack *st, int pr, void *arg)
{
struct BCState *bcs = st->l1.bcs;
struct sk_buff *skb = arg;
u_long flags;
switch (pr) {
case (PH_DATA | REQUEST):
spin_lock_irqsave(&bcs->cs->lock, flags);
if (bcs->tx_skb) {
skb_queue_tail(&bcs->squeue, skb);
} else {
bcs->tx_skb = skb;
// test_and_set_bit(BC_FLG_BUSY, &bcs->Flag);
bcs->cs->BC_Send_Data(bcs);
}
spin_unlock_irqrestore(&bcs->cs->lock, flags);
break;
case (PH_PULL | INDICATION):
spin_lock_irqsave(&bcs->cs->lock, flags);
if (bcs->tx_skb) {
printk(KERN_WARNING "hfc_l2l1: this shouldn't happen\n");
} else {
// test_and_set_bit(BC_FLG_BUSY, &bcs->Flag);
bcs->tx_skb = skb;
bcs->cs->BC_Send_Data(bcs);
}
spin_unlock_irqrestore(&bcs->cs->lock, flags);
break;
case (PH_PULL | REQUEST):
if (!bcs->tx_skb) {
test_and_clear_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
st->l1.l1l2(st, PH_PULL | CONFIRM, NULL);
} else
test_and_set_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
break;
case (PH_ACTIVATE | REQUEST):
spin_lock_irqsave(&bcs->cs->lock, flags);
test_and_set_bit(BC_FLG_ACTIV, &bcs->Flag);
mode_hfcsx(bcs, st->l1.mode, st->l1.bc);
spin_unlock_irqrestore(&bcs->cs->lock, flags);
l1_msg_b(st, pr, arg);
break;
case (PH_DEACTIVATE | REQUEST):
l1_msg_b(st, pr, arg);
break;
case (PH_DEACTIVATE | CONFIRM):
spin_lock_irqsave(&bcs->cs->lock, flags);
test_and_clear_bit(BC_FLG_ACTIV, &bcs->Flag);
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
mode_hfcsx(bcs, 0, st->l1.bc);
spin_unlock_irqrestore(&bcs->cs->lock, flags);
st->l1.l1l2(st, PH_DEACTIVATE | CONFIRM, NULL);
break;
}
}
/******************************************/
/* deactivate B-channel access and queues */
/******************************************/
static void
close_hfcsx(struct BCState *bcs)
{
mode_hfcsx(bcs, 0, bcs->channel);
if (test_and_clear_bit(BC_FLG_INIT, &bcs->Flag)) {
skb_queue_purge(&bcs->rqueue);
skb_queue_purge(&bcs->squeue);
if (bcs->tx_skb) {
dev_kfree_skb_any(bcs->tx_skb);
bcs->tx_skb = NULL;
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
}
}
}
/*************************************/
/* init B-channel queues and control */
/*************************************/
static int
open_hfcsxstate(struct IsdnCardState *cs, struct BCState *bcs)
{
if (!test_and_set_bit(BC_FLG_INIT, &bcs->Flag)) {
skb_queue_head_init(&bcs->rqueue);
skb_queue_head_init(&bcs->squeue);
}
bcs->tx_skb = NULL;
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
bcs->event = 0;
bcs->tx_cnt = 0;
return (0);
}
/*********************************/
/* inits the stack for B-channel */
/*********************************/
static int
setstack_2b(struct PStack *st, struct BCState *bcs)
{
bcs->channel = st->l1.bc;
if (open_hfcsxstate(st->l1.hardware, bcs))
return (-1);
st->l1.bcs = bcs;
st->l2.l2l1 = hfcsx_l2l1;
setstack_manager(st);
bcs->st = st;
setstack_l1_B(st);
return (0);
}
/***************************/
/* handle L1 state changes */
/***************************/
static void
hfcsx_bh(struct work_struct *work)
{
struct IsdnCardState *cs =
container_of(work, struct IsdnCardState, tqueue);
u_long flags;
if (test_and_clear_bit(D_L1STATECHANGE, &cs->event)) {
if (!cs->hw.hfcsx.nt_mode)
switch (cs->dc.hfcsx.ph_state) {
case (0):
l1_msg(cs, HW_RESET | INDICATION, NULL);
break;
case (3):
l1_msg(cs, HW_DEACTIVATE | INDICATION, NULL);
break;
case (8):
l1_msg(cs, HW_RSYNC | INDICATION, NULL);
break;
case (6):
l1_msg(cs, HW_INFO2 | INDICATION, NULL);
break;
case (7):
l1_msg(cs, HW_INFO4_P8 | INDICATION, NULL);
break;
default:
break;
} else {
switch (cs->dc.hfcsx.ph_state) {
case (2):
spin_lock_irqsave(&cs->lock, flags);
if (cs->hw.hfcsx.nt_timer < 0) {
cs->hw.hfcsx.nt_timer = 0;
cs->hw.hfcsx.int_m1 &= ~HFCSX_INTS_TIMER;
Write_hfc(cs, HFCSX_INT_M1, cs->hw.hfcsx.int_m1);
/* Clear already pending ints */
if (Read_hfc(cs, HFCSX_INT_S1));
Write_hfc(cs, HFCSX_STATES, 4 | HFCSX_LOAD_STATE);
udelay(10);
Write_hfc(cs, HFCSX_STATES, 4);
cs->dc.hfcsx.ph_state = 4;
} else {
cs->hw.hfcsx.int_m1 |= HFCSX_INTS_TIMER;
Write_hfc(cs, HFCSX_INT_M1, cs->hw.hfcsx.int_m1);
cs->hw.hfcsx.ctmt &= ~HFCSX_AUTO_TIMER;
cs->hw.hfcsx.ctmt |= HFCSX_TIM3_125;
Write_hfc(cs, HFCSX_CTMT, cs->hw.hfcsx.ctmt | HFCSX_CLTIMER);
Write_hfc(cs, HFCSX_CTMT, cs->hw.hfcsx.ctmt | HFCSX_CLTIMER);
cs->hw.hfcsx.nt_timer = NT_T1_COUNT;
Write_hfc(cs, HFCSX_STATES, 2 | HFCSX_NT_G2_G3); /* allow G2 -> G3 transition */
}
spin_unlock_irqrestore(&cs->lock, flags);
break;
case (1):
case (3):
case (4):
spin_lock_irqsave(&cs->lock, flags);
cs->hw.hfcsx.nt_timer = 0;
cs->hw.hfcsx.int_m1 &= ~HFCSX_INTS_TIMER;
Write_hfc(cs, HFCSX_INT_M1, cs->hw.hfcsx.int_m1);
spin_unlock_irqrestore(&cs->lock, flags);
break;
default:
break;
}
}
}
if (test_and_clear_bit(D_RCVBUFREADY, &cs->event))
DChannel_proc_rcv(cs);
if (test_and_clear_bit(D_XMTBUFREADY, &cs->event))
DChannel_proc_xmt(cs);
}
/********************************/
/* called for card init message */
/********************************/
static void inithfcsx(struct IsdnCardState *cs)
{
cs->setstack_d = setstack_hfcsx;
cs->BC_Send_Data = &hfcsx_send_data;
cs->bcs[0].BC_SetStack = setstack_2b;
cs->bcs[1].BC_SetStack = setstack_2b;
cs->bcs[0].BC_Close = close_hfcsx;
cs->bcs[1].BC_Close = close_hfcsx;
mode_hfcsx(cs->bcs, 0, 0);
mode_hfcsx(cs->bcs + 1, 0, 1);
}
/*******************************************/
/* handle card messages from control layer */
/*******************************************/
static int
hfcsx_card_msg(struct IsdnCardState *cs, int mt, void *arg)
{
u_long flags;
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "HFCSX: card_msg %x", mt);
switch (mt) {
case CARD_RESET:
spin_lock_irqsave(&cs->lock, flags);
reset_hfcsx(cs);
spin_unlock_irqrestore(&cs->lock, flags);
return (0);
case CARD_RELEASE:
release_io_hfcsx(cs);
return (0);
case CARD_INIT:
spin_lock_irqsave(&cs->lock, flags);
inithfcsx(cs);
spin_unlock_irqrestore(&cs->lock, flags);
msleep(80); /* Timeout 80ms */
/* now switch timer interrupt off */
spin_lock_irqsave(&cs->lock, flags);
cs->hw.hfcsx.int_m1 &= ~HFCSX_INTS_TIMER;
Write_hfc(cs, HFCSX_INT_M1, cs->hw.hfcsx.int_m1);
/* reinit mode reg */
Write_hfc(cs, HFCSX_MST_MODE, cs->hw.hfcsx.mst_m);
spin_unlock_irqrestore(&cs->lock, flags);
return (0);
case CARD_TEST:
return (0);
}
return (0);
}
#ifdef __ISAPNP__
static struct isapnp_device_id hfc_ids[] __devinitdata = {
{ ISAPNP_VENDOR('T', 'A', 'G'), ISAPNP_FUNCTION(0x2620),
ISAPNP_VENDOR('T', 'A', 'G'), ISAPNP_FUNCTION(0x2620),
(unsigned long) "Teles 16.3c2" },
{ 0, }
};
static struct isapnp_device_id *ipid __devinitdata = &hfc_ids[0];
static struct pnp_card *pnp_c __devinitdata = NULL;
#endif
int __devinit
setup_hfcsx(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
char tmp[64];
strcpy(tmp, hfcsx_revision);
printk(KERN_INFO "HiSax: HFC-SX driver Rev. %s\n", HiSax_getrev(tmp));
#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[1] = pnp_port_start(pnp_d, 0);
card->para[0] = pnp_irq(pnp_d, 0);
if (!card->para[0] || !card->para[1]) {
printk(KERN_ERR "HFC PnP:some resources are missing %ld/%lx\n",
card->para[0], card->para[1]);
pnp_disable_dev(pnp_d);
return(0);
}
break;
} else {
printk(KERN_ERR "HFC PnP: PnP error card found, no device\n");
}
}
ipid++;
pnp_c = NULL;
}
if (!ipid->card_vendor) {
printk(KERN_INFO "HFC PnP: no ISAPnP card found\n");
return(0);
}
}
#endif
cs->hw.hfcsx.base = card->para[1] & 0xfffe;
cs->irq = card->para[0];
cs->hw.hfcsx.int_s1 = 0;
cs->dc.hfcsx.ph_state = 0;
cs->hw.hfcsx.fifo = 255;
if ((cs->typ == ISDN_CTYPE_HFC_SX) ||
(cs->typ == ISDN_CTYPE_HFC_SP_PCMCIA)) {
if ((!cs->hw.hfcsx.base) || !request_region(cs->hw.hfcsx.base, 2, "HFCSX isdn")) {
printk(KERN_WARNING
"HiSax: HFC-SX io-base %#lx already in use\n",
cs->hw.hfcsx.base);
return(0);
}
byteout(cs->hw.hfcsx.base, cs->hw.hfcsx.base & 0xFF);
byteout(cs->hw.hfcsx.base + 1,
((cs->hw.hfcsx.base >> 8) & 3) | 0x54);
udelay(10);
cs->hw.hfcsx.chip = Read_hfc(cs,HFCSX_CHIP_ID);
switch (cs->hw.hfcsx.chip >> 4) {
case 1:
tmp[0] ='+';
break;
case 9:
tmp[0] ='P';
break;
default:
printk(KERN_WARNING
"HFC-SX: invalid chip id 0x%x\n",
cs->hw.hfcsx.chip >> 4);
release_region(cs->hw.hfcsx.base, 2);
return(0);
}
if (!ccd_sp_irqtab[cs->irq & 0xF]) {
printk(KERN_WARNING
"HFC_SX: invalid irq %d specified\n",cs->irq & 0xF);
release_region(cs->hw.hfcsx.base, 2);
return(0);
}
if (!(cs->hw.hfcsx.extra = (void *)
kmalloc(sizeof(struct hfcsx_extra), GFP_ATOMIC))) {
release_region(cs->hw.hfcsx.base, 2);
printk(KERN_WARNING "HFC-SX: unable to allocate memory\n");
return(0);
}
printk(KERN_INFO "HFC-S%c chip detected at base 0x%x IRQ %d HZ %d\n",
tmp[0], (u_int) cs->hw.hfcsx.base, cs->irq, HZ);
cs->hw.hfcsx.int_m2 = 0; /* disable alle interrupts */
cs->hw.hfcsx.int_m1 = 0;
Write_hfc(cs, HFCSX_INT_M1, cs->hw.hfcsx.int_m1);
Write_hfc(cs, HFCSX_INT_M2, cs->hw.hfcsx.int_m2);
} else
return (0); /* no valid card type */
cs->dbusytimer.function = (void *) hfcsx_dbusy_timer;
cs->dbusytimer.data = (long) cs;
init_timer(&cs->dbusytimer);
INIT_WORK(&cs->tqueue, hfcsx_bh);
cs->readisac = NULL;
cs->writeisac = NULL;
cs->readisacfifo = NULL;
cs->writeisacfifo = NULL;
cs->BC_Read_Reg = NULL;
cs->BC_Write_Reg = NULL;
cs->irq_func = &hfcsx_interrupt;
cs->hw.hfcsx.timer.function = (void *) hfcsx_Timer;
cs->hw.hfcsx.timer.data = (long) cs;
cs->hw.hfcsx.b_fifo_size = 0; /* fifo size still unknown */
cs->hw.hfcsx.cirm = ccd_sp_irqtab[cs->irq & 0xF]; /* RAM not evaluated */
init_timer(&cs->hw.hfcsx.timer);
reset_hfcsx(cs);
cs->cardmsg = &hfcsx_card_msg;
cs->auxcmd = &hfcsx_auxcmd;
return (1);
}
| gpl-2.0 |
MinimalOS-AOSP/kernel_moto_shamu | arch/mips/netlogic/xlr/platform-flash.c | 3431 | 5630 | /*
* Copyright 2011, Netlogic Microsystems.
* Copyright 2004, Matt Porter <mporter@kernel.crashing.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/device.h>
#include <linux/platform_device.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/resource.h>
#include <linux/spi/flash.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/physmap.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <asm/netlogic/haldefs.h>
#include <asm/netlogic/xlr/iomap.h>
#include <asm/netlogic/xlr/flash.h>
#include <asm/netlogic/xlr/bridge.h>
#include <asm/netlogic/xlr/gpio.h>
#include <asm/netlogic/xlr/xlr.h>
/*
* Default NOR partition layout
*/
static struct mtd_partition xlr_nor_parts[] = {
{
.name = "User FS",
.offset = 0x800000,
.size = MTDPART_SIZ_FULL,
}
};
/*
* Default NAND partition layout
*/
static struct mtd_partition xlr_nand_parts[] = {
{
.name = "Root Filesystem",
.offset = 64 * 64 * 2048,
.size = 432 * 64 * 2048,
},
{
.name = "Home Filesystem",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
},
};
/* Use PHYSMAP flash for NOR */
struct physmap_flash_data xlr_nor_data = {
.width = 2,
.parts = xlr_nor_parts,
.nr_parts = ARRAY_SIZE(xlr_nor_parts),
};
static struct resource xlr_nor_res[] = {
{
.flags = IORESOURCE_MEM,
},
};
static struct platform_device xlr_nor_dev = {
.name = "physmap-flash",
.dev = {
.platform_data = &xlr_nor_data,
},
.num_resources = ARRAY_SIZE(xlr_nor_res),
.resource = xlr_nor_res,
};
const char *xlr_part_probes[] = { "cmdlinepart", NULL };
/*
* Use "gen_nand" driver for NAND flash
*
* There seems to be no way to store a private pointer containing
* platform specific info in gen_nand drivier. We will use a global
* struct for now, since we currently have only one NAND chip per board.
*/
struct xlr_nand_flash_priv {
int cs;
uint64_t flash_mmio;
};
static struct xlr_nand_flash_priv nand_priv;
static void xlr_nand_ctrl(struct mtd_info *mtd, int cmd,
unsigned int ctrl)
{
if (ctrl & NAND_CLE)
nlm_write_reg(nand_priv.flash_mmio,
FLASH_NAND_CLE(nand_priv.cs), cmd);
else if (ctrl & NAND_ALE)
nlm_write_reg(nand_priv.flash_mmio,
FLASH_NAND_ALE(nand_priv.cs), cmd);
}
struct platform_nand_data xlr_nand_data = {
.chip = {
.nr_chips = 1,
.nr_partitions = ARRAY_SIZE(xlr_nand_parts),
.chip_delay = 50,
.partitions = xlr_nand_parts,
.part_probe_types = xlr_part_probes,
},
.ctrl = {
.cmd_ctrl = xlr_nand_ctrl,
},
};
static struct resource xlr_nand_res[] = {
{
.flags = IORESOURCE_MEM,
},
};
static struct platform_device xlr_nand_dev = {
.name = "gen_nand",
.id = -1,
.num_resources = ARRAY_SIZE(xlr_nand_res),
.resource = xlr_nand_res,
.dev = {
.platform_data = &xlr_nand_data,
}
};
/*
* XLR/XLS supports upto 8 devices on its FLASH interface. The value in
* FLASH_BAR (on the MEM/IO bridge) gives the base for mapping all the
* flash devices.
* Under this, each flash device has an offset and size given by the
* CSBASE_ADDR and CSBASE_MASK registers for the device.
*
* The CSBASE_ registers are expected to be setup by the bootloader.
*/
static void setup_flash_resource(uint64_t flash_mmio,
uint64_t flash_map_base, int cs, struct resource *res)
{
u32 base, mask;
base = nlm_read_reg(flash_mmio, FLASH_CSBASE_ADDR(cs));
mask = nlm_read_reg(flash_mmio, FLASH_CSADDR_MASK(cs));
res->start = flash_map_base + ((unsigned long)base << 16);
res->end = res->start + (mask + 1) * 64 * 1024;
}
static int __init xlr_flash_init(void)
{
uint64_t gpio_mmio, flash_mmio, flash_map_base;
u32 gpio_resetcfg, flash_bar;
int cs, boot_nand, boot_nor;
/* Flash address bits 39:24 is in bridge flash BAR */
flash_bar = nlm_read_reg(nlm_io_base, BRIDGE_FLASH_BAR);
flash_map_base = (flash_bar & 0xffff0000) << 8;
gpio_mmio = nlm_mmio_base(NETLOGIC_IO_GPIO_OFFSET);
flash_mmio = nlm_mmio_base(NETLOGIC_IO_FLASH_OFFSET);
/* Get the chip reset config */
gpio_resetcfg = nlm_read_reg(gpio_mmio, GPIO_PWRON_RESET_CFG_REG);
/* Check for boot flash type */
boot_nor = boot_nand = 0;
if (nlm_chip_is_xls()) {
/* On XLS, check boot from NAND bit (GPIO reset reg bit 16) */
if (gpio_resetcfg & (1 << 16))
boot_nand = 1;
/* check boot from PCMCIA, (GPIO reset reg bit 15 */
if ((gpio_resetcfg & (1 << 15)) == 0)
boot_nor = 1; /* not set, booted from NOR */
} else { /* XLR */
/* check boot from PCMCIA (bit 16 in GPIO reset on XLR) */
if ((gpio_resetcfg & (1 << 16)) == 0)
boot_nor = 1; /* not set, booted from NOR */
}
/* boot flash at chip select 0 */
cs = 0;
if (boot_nand) {
nand_priv.cs = cs;
nand_priv.flash_mmio = flash_mmio;
setup_flash_resource(flash_mmio, flash_map_base, cs,
xlr_nand_res);
/* Initialize NAND flash at CS 0 */
nlm_write_reg(flash_mmio, FLASH_CSDEV_PARM(cs),
FLASH_NAND_CSDEV_PARAM);
nlm_write_reg(flash_mmio, FLASH_CSTIME_PARMA(cs),
FLASH_NAND_CSTIME_PARAMA);
nlm_write_reg(flash_mmio, FLASH_CSTIME_PARMB(cs),
FLASH_NAND_CSTIME_PARAMB);
pr_info("ChipSelect %d: NAND Flash %pR\n", cs, xlr_nand_res);
return platform_device_register(&xlr_nand_dev);
}
if (boot_nor) {
setup_flash_resource(flash_mmio, flash_map_base, cs,
xlr_nor_res);
pr_info("ChipSelect %d: NOR Flash %pR\n", cs, xlr_nor_res);
return platform_device_register(&xlr_nor_dev);
}
return 0;
}
arch_initcall(xlr_flash_init);
| gpl-2.0 |
nmenon/linux-omap-ti-pm | drivers/isdn/pcbit/drv.c | 3431 | 22459 | /*
* PCBIT-D interface with isdn4linux
*
* Copyright (C) 1996 Universidade de Lisboa
*
* Written by Pedro Roque Marques (roque@di.fc.ul.pt)
*
* This software may be used and distributed according to the terms of
* the GNU General Public License, incorporated herein by reference.
*/
/*
* Fixes:
*
* Nuno Grilo <l38486@alfa.ist.utl.pt>
* fixed msn_list NULL pointer dereference.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/string.h>
#include <linux/skbuff.h>
#include <linux/isdnif.h>
#include <asm/string.h>
#include <asm/io.h>
#include <linux/ioport.h>
#include "pcbit.h"
#include "edss1.h"
#include "layer2.h"
#include "capi.h"
extern ushort last_ref_num;
static int pcbit_ioctl(isdn_ctrl* ctl);
static char* pcbit_devname[MAX_PCBIT_CARDS] = {
"pcbit0",
"pcbit1",
"pcbit2",
"pcbit3"
};
/*
* prototypes
*/
static int pcbit_command(isdn_ctrl* ctl);
static int pcbit_stat(u_char __user * buf, int len, int, int);
static int pcbit_xmit(int driver, int chan, int ack, struct sk_buff *skb);
static int pcbit_writecmd(const u_char __user *, int, int, int);
static int set_protocol_running(struct pcbit_dev * dev);
static void pcbit_clear_msn(struct pcbit_dev *dev);
static void pcbit_set_msn(struct pcbit_dev *dev, char *list);
static int pcbit_check_msn(struct pcbit_dev *dev, char *msn);
int pcbit_init_dev(int board, int mem_base, int irq)
{
struct pcbit_dev *dev;
isdn_if *dev_if;
if ((dev=kzalloc(sizeof(struct pcbit_dev), GFP_KERNEL)) == NULL)
{
printk("pcbit_init: couldn't malloc pcbit_dev struct\n");
return -ENOMEM;
}
dev_pcbit[board] = dev;
init_waitqueue_head(&dev->set_running_wq);
spin_lock_init(&dev->lock);
if (mem_base >= 0xA0000 && mem_base <= 0xFFFFF ) {
dev->ph_mem = mem_base;
if (!request_mem_region(dev->ph_mem, 4096, "PCBIT mem")) {
printk(KERN_WARNING
"PCBIT: memory region %lx-%lx already in use\n",
dev->ph_mem, dev->ph_mem + 4096);
kfree(dev);
dev_pcbit[board] = NULL;
return -EACCES;
}
dev->sh_mem = ioremap(dev->ph_mem, 4096);
}
else
{
printk("memory address invalid");
kfree(dev);
dev_pcbit[board] = NULL;
return -EACCES;
}
dev->b1 = kzalloc(sizeof(struct pcbit_chan), GFP_KERNEL);
if (!dev->b1) {
printk("pcbit_init: couldn't malloc pcbit_chan struct\n");
iounmap(dev->sh_mem);
release_mem_region(dev->ph_mem, 4096);
kfree(dev);
return -ENOMEM;
}
dev->b2 = kzalloc(sizeof(struct pcbit_chan), GFP_KERNEL);
if (!dev->b2) {
printk("pcbit_init: couldn't malloc pcbit_chan struct\n");
kfree(dev->b1);
iounmap(dev->sh_mem);
release_mem_region(dev->ph_mem, 4096);
kfree(dev);
return -ENOMEM;
}
dev->b2->id = 1;
INIT_WORK(&dev->qdelivery, pcbit_deliver);
/*
* interrupts
*/
if (request_irq(irq, &pcbit_irq_handler, 0, pcbit_devname[board], dev) != 0)
{
kfree(dev->b1);
kfree(dev->b2);
iounmap(dev->sh_mem);
release_mem_region(dev->ph_mem, 4096);
kfree(dev);
dev_pcbit[board] = NULL;
return -EIO;
}
dev->irq = irq;
/* next frame to be received */
dev->rcv_seq = 0;
dev->send_seq = 0;
dev->unack_seq = 0;
dev->hl_hdrlen = 16;
dev_if = kmalloc(sizeof(isdn_if), GFP_KERNEL);
if (!dev_if) {
free_irq(irq, dev);
kfree(dev->b1);
kfree(dev->b2);
iounmap(dev->sh_mem);
release_mem_region(dev->ph_mem, 4096);
kfree(dev);
dev_pcbit[board] = NULL;
return -EIO;
}
dev->dev_if = dev_if;
dev_if->owner = THIS_MODULE;
dev_if->channels = 2;
dev_if->features = (ISDN_FEATURE_P_EURO | ISDN_FEATURE_L3_TRANS |
ISDN_FEATURE_L2_HDLC | ISDN_FEATURE_L2_TRANS );
dev_if->writebuf_skb = pcbit_xmit;
dev_if->hl_hdrlen = 16;
dev_if->maxbufsize = MAXBUFSIZE;
dev_if->command = pcbit_command;
dev_if->writecmd = pcbit_writecmd;
dev_if->readstat = pcbit_stat;
strcpy(dev_if->id, pcbit_devname[board]);
if (!register_isdn(dev_if)) {
free_irq(irq, dev);
kfree(dev->b1);
kfree(dev->b2);
iounmap(dev->sh_mem);
release_mem_region(dev->ph_mem, 4096);
kfree(dev);
dev_pcbit[board] = NULL;
return -EIO;
}
dev->id = dev_if->channels;
dev->l2_state = L2_DOWN;
dev->free = 511;
/*
* set_protocol_running(dev);
*/
return 0;
}
#ifdef MODULE
void pcbit_terminate(int board)
{
struct pcbit_dev * dev;
dev = dev_pcbit[board];
if (dev) {
/* unregister_isdn(dev->dev_if); */
free_irq(dev->irq, dev);
pcbit_clear_msn(dev);
kfree(dev->dev_if);
if (dev->b1->fsm_timer.function)
del_timer(&dev->b1->fsm_timer);
if (dev->b2->fsm_timer.function)
del_timer(&dev->b2->fsm_timer);
kfree(dev->b1);
kfree(dev->b2);
iounmap(dev->sh_mem);
release_mem_region(dev->ph_mem, 4096);
kfree(dev);
}
}
#endif
static int pcbit_command(isdn_ctrl* ctl)
{
struct pcbit_dev *dev;
struct pcbit_chan *chan;
struct callb_data info;
dev = finddev(ctl->driver);
if (!dev)
{
printk("pcbit_command: unknown device\n");
return -1;
}
chan = (ctl->arg & 0x0F) ? dev->b2 : dev->b1;
switch(ctl->command) {
case ISDN_CMD_IOCTL:
return pcbit_ioctl(ctl);
break;
case ISDN_CMD_DIAL:
info.type = EV_USR_SETUP_REQ;
info.data.setup.CalledPN = (char *) &ctl->parm.setup.phone;
pcbit_fsm_event(dev, chan, EV_USR_SETUP_REQ, &info);
break;
case ISDN_CMD_ACCEPTD:
pcbit_fsm_event(dev, chan, EV_USR_SETUP_RESP, NULL);
break;
case ISDN_CMD_ACCEPTB:
printk("ISDN_CMD_ACCEPTB - not really needed\n");
break;
case ISDN_CMD_HANGUP:
pcbit_fsm_event(dev, chan, EV_USR_RELEASE_REQ, NULL);
break;
case ISDN_CMD_SETL2:
chan->proto = (ctl->arg >> 8);
break;
case ISDN_CMD_CLREAZ:
pcbit_clear_msn(dev);
break;
case ISDN_CMD_SETEAZ:
pcbit_set_msn(dev, ctl->parm.num);
break;
case ISDN_CMD_SETL3:
if ((ctl->arg >> 8) != ISDN_PROTO_L3_TRANS)
printk(KERN_DEBUG "L3 protocol unknown\n");
break;
default:
printk(KERN_DEBUG "pcbit_command: unknown command\n");
break;
};
return 0;
}
/*
* Another Hack :-(
* on some conditions the board stops sending TDATA_CONFs
* let's see if we can turn around the problem
*/
#ifdef BLOCK_TIMER
static void pcbit_block_timer(unsigned long data)
{
struct pcbit_chan *chan;
struct pcbit_dev * dev;
isdn_ctrl ictl;
chan = (struct pcbit_chan *) data;
dev = chan2dev(chan);
if (dev == NULL) {
printk(KERN_DEBUG "pcbit: chan2dev failed\n");
return;
}
del_timer(&chan->block_timer);
chan->block_timer.function = NULL;
#ifdef DEBUG
printk(KERN_DEBUG "pcbit_block_timer\n");
#endif
chan->queued = 0;
ictl.driver = dev->id;
ictl.command = ISDN_STAT_BSENT;
ictl.arg = chan->id;
dev->dev_if->statcallb(&ictl);
}
#endif
static int pcbit_xmit(int driver, int chnum, int ack, struct sk_buff *skb)
{
ushort hdrlen;
int refnum, len;
struct pcbit_chan * chan;
struct pcbit_dev *dev;
dev = finddev(driver);
if (dev == NULL)
{
printk("finddev returned NULL");
return -1;
}
chan = chnum ? dev->b2 : dev->b1;
if (chan->fsm_state != ST_ACTIVE)
return -1;
if (chan->queued >= MAX_QUEUED )
{
#ifdef DEBUG_QUEUE
printk(KERN_DEBUG
"pcbit: %d packets already in queue - write fails\n",
chan->queued);
#endif
/*
* packet stays on the head of the device queue
* since dev_start_xmit will fail
* see net/core/dev.c
*/
#ifdef BLOCK_TIMER
if (chan->block_timer.function == NULL) {
init_timer(&chan->block_timer);
chan->block_timer.function = &pcbit_block_timer;
chan->block_timer.data = (long) chan;
chan->block_timer.expires = jiffies + 1 * HZ;
add_timer(&chan->block_timer);
}
#endif
return 0;
}
chan->queued++;
len = skb->len;
hdrlen = capi_tdata_req(chan, skb);
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_TDATA_REQ, refnum, skb, hdrlen);
return len;
}
static int pcbit_writecmd(const u_char __user *buf, int len, int driver, int channel)
{
struct pcbit_dev * dev;
int i, j;
const u_char * loadbuf;
u_char * ptr = NULL;
u_char *cbuf;
int errstat;
dev = finddev(driver);
if (!dev)
{
printk("pcbit_writecmd: couldn't find device");
return -ENODEV;
}
switch(dev->l2_state) {
case L2_LWMODE:
/* check (size <= rdp_size); write buf into board */
if (len < 0 || len > BANK4 + 1 || len > 1024)
{
printk("pcbit_writecmd: invalid length %d\n", len);
return -EINVAL;
}
cbuf = memdup_user(buf, len);
if (IS_ERR(cbuf))
return PTR_ERR(cbuf);
memcpy_toio(dev->sh_mem, cbuf, len);
kfree(cbuf);
return len;
case L2_FWMODE:
/* this is the hard part */
/* dumb board */
/* get it into kernel space */
if ((ptr = kmalloc(len, GFP_KERNEL))==NULL)
return -ENOMEM;
if (copy_from_user(ptr, buf, len)) {
kfree(ptr);
return -EFAULT;
}
loadbuf = ptr;
errstat = 0;
for (i=0; i < len; i++)
{
for(j=0; j < LOAD_RETRY; j++)
if (!(readb(dev->sh_mem + dev->loadptr)))
break;
if (j == LOAD_RETRY)
{
errstat = -ETIME;
printk("TIMEOUT i=%d\n", i);
break;
}
writeb(loadbuf[i], dev->sh_mem + dev->loadptr + 1);
writeb(0x01, dev->sh_mem + dev->loadptr);
dev->loadptr += 2;
if (dev->loadptr > LOAD_ZONE_END)
dev->loadptr = LOAD_ZONE_START;
}
kfree(ptr);
return errstat ? errstat : len;
default:
return -EBUSY;
}
}
/*
* demultiplexing of messages
*
*/
void pcbit_l3_receive(struct pcbit_dev * dev, ulong msg,
struct sk_buff * skb,
ushort hdr_len, ushort refnum)
{
struct pcbit_chan *chan;
struct sk_buff *skb2;
unsigned short len;
struct callb_data cbdata;
int complete, err;
isdn_ctrl ictl;
switch(msg) {
case MSG_TDATA_IND:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
chan->r_refnum = skb->data[7];
skb_pull(skb, 8);
dev->dev_if->rcvcallb_skb(dev->id, chan->id, skb);
if (capi_tdata_resp(chan, &skb2) > 0)
pcbit_l2_write(dev, MSG_TDATA_RESP, refnum,
skb2, skb2->len);
return;
break;
case MSG_TDATA_CONF:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
#ifdef DEBUG
if ( (*((ushort *) (skb->data + 2) )) != 0) {
printk(KERN_DEBUG "TDATA_CONF error\n");
}
#endif
#ifdef BLOCK_TIMER
if (chan->queued == MAX_QUEUED) {
del_timer(&chan->block_timer);
chan->block_timer.function = NULL;
}
#endif
chan->queued--;
ictl.driver = dev->id;
ictl.command = ISDN_STAT_BSENT;
ictl.arg = chan->id;
dev->dev_if->statcallb(&ictl);
break;
case MSG_CONN_IND:
/*
* channel: 1st not used will do
* if both are used we're in trouble
*/
if (!dev->b1->fsm_state)
chan = dev->b1;
else if (!dev->b2->fsm_state)
chan = dev->b2;
else {
printk(KERN_INFO
"Incoming connection: no channels available");
if ((len = capi_disc_req(*(ushort*)(skb->data), &skb2, CAUSE_NOCHAN)) > 0)
pcbit_l2_write(dev, MSG_DISC_REQ, refnum, skb2, len);
break;
}
cbdata.data.setup.CalledPN = NULL;
cbdata.data.setup.CallingPN = NULL;
capi_decode_conn_ind(chan, skb, &cbdata);
cbdata.type = EV_NET_SETUP;
pcbit_fsm_event(dev, chan, EV_NET_SETUP, NULL);
if (pcbit_check_msn(dev, cbdata.data.setup.CallingPN))
pcbit_fsm_event(dev, chan, EV_USR_PROCED_REQ, &cbdata);
else
pcbit_fsm_event(dev, chan, EV_USR_RELEASE_REQ, NULL);
kfree(cbdata.data.setup.CalledPN);
kfree(cbdata.data.setup.CallingPN);
break;
case MSG_CONN_CONF:
/*
* We should be able to find the channel by the message
* reference number. The current version of the firmware
* doesn't sent the ref number correctly.
*/
#ifdef DEBUG
printk(KERN_DEBUG "refnum=%04x b1=%04x b2=%04x\n", refnum,
dev->b1->s_refnum,
dev->b2->s_refnum);
#endif
/* We just try to find a channel in the right state */
if (dev->b1->fsm_state == ST_CALL_INIT)
chan = dev->b1;
else {
if (dev->b2->s_refnum == ST_CALL_INIT)
chan = dev->b2;
else {
chan = NULL;
printk(KERN_WARNING "Connection Confirm - no channel in Call Init state\n");
break;
}
}
if (capi_decode_conn_conf(chan, skb, &complete)) {
printk(KERN_DEBUG "conn_conf indicates error\n");
pcbit_fsm_event(dev, chan, EV_ERROR, NULL);
}
else
if (complete)
pcbit_fsm_event(dev, chan, EV_NET_CALL_PROC, NULL);
else
pcbit_fsm_event(dev, chan, EV_NET_SETUP_ACK, NULL);
break;
case MSG_CONN_ACTV_IND:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
if (capi_decode_conn_actv_ind(chan, skb)) {
printk("error in capi_decode_conn_actv_ind\n");
/* pcbit_fsm_event(dev, chan, EV_ERROR, NULL); */
break;
}
chan->r_refnum = refnum;
pcbit_fsm_event(dev, chan, EV_NET_CONN, NULL);
break;
case MSG_CONN_ACTV_CONF:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
if (capi_decode_conn_actv_conf(chan, skb) == 0)
pcbit_fsm_event(dev, chan, EV_NET_CONN_ACK, NULL);
else
printk(KERN_DEBUG "decode_conn_actv_conf failed\n");
break;
case MSG_SELP_CONF:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
if (!(err = capi_decode_sel_proto_conf(chan, skb)))
pcbit_fsm_event(dev, chan, EV_NET_SELP_RESP, NULL);
else {
/* Error */
printk("error %d - capi_decode_sel_proto_conf\n", err);
}
break;
case MSG_ACT_TRANSP_CONF:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
if (!capi_decode_actv_trans_conf(chan, skb))
pcbit_fsm_event(dev, chan, EV_NET_ACTV_RESP, NULL);
break;
case MSG_DISC_IND:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
if (!capi_decode_disc_ind(chan, skb))
pcbit_fsm_event(dev, chan, EV_NET_DISC, NULL);
else
printk(KERN_WARNING "capi_decode_disc_ind - error\n");
break;
case MSG_DISC_CONF:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
if (!capi_decode_disc_ind(chan, skb))
pcbit_fsm_event(dev, chan, EV_NET_RELEASE, NULL);
else
printk(KERN_WARNING "capi_decode_disc_conf - error\n");
break;
case MSG_INFO_IND:
#ifdef DEBUG
printk(KERN_DEBUG "received Info Indication - discarded\n");
#endif
break;
#ifdef DEBUG
case MSG_DEBUG_188:
capi_decode_debug_188(skb->data, skb->len);
break;
default:
printk(KERN_DEBUG "pcbit_l3_receive: unknown message %08lx\n",
msg);
break;
#endif
}
kfree_skb(skb);
}
/*
* Single statbuf
* should be a statbuf per device
*/
static char statbuf[STATBUF_LEN];
static int stat_st = 0;
static int stat_end = 0;
static int pcbit_stat(u_char __user *buf, int len, int driver, int channel)
{
int stat_count;
stat_count = stat_end - stat_st;
if (stat_count < 0)
stat_count = STATBUF_LEN - stat_st + stat_end;
/* FIXME: should we sleep and wait for more cookies ? */
if (len > stat_count)
len = stat_count;
if (stat_st < stat_end)
{
if (copy_to_user(buf, statbuf + stat_st, len))
return -EFAULT;
stat_st += len;
}
else
{
if (len > STATBUF_LEN - stat_st)
{
if (copy_to_user(buf, statbuf + stat_st,
STATBUF_LEN - stat_st))
return -EFAULT;
if (copy_to_user(buf, statbuf,
len - (STATBUF_LEN - stat_st)))
return -EFAULT;
stat_st = len - (STATBUF_LEN - stat_st);
}
else
{
if (copy_to_user(buf, statbuf + stat_st, len))
return -EFAULT;
stat_st += len;
if (stat_st == STATBUF_LEN)
stat_st = 0;
}
}
if (stat_st == stat_end)
stat_st = stat_end = 0;
return len;
}
static void pcbit_logstat(struct pcbit_dev *dev, char *str)
{
int i;
isdn_ctrl ictl;
for (i=stat_end; i<strlen(str); i++)
{
statbuf[i]=str[i];
stat_end = (stat_end + 1) % STATBUF_LEN;
if (stat_end == stat_st)
stat_st = (stat_st + 1) % STATBUF_LEN;
}
ictl.command=ISDN_STAT_STAVAIL;
ictl.driver=dev->id;
ictl.arg=strlen(str);
dev->dev_if->statcallb(&ictl);
}
void pcbit_state_change(struct pcbit_dev * dev, struct pcbit_chan * chan,
unsigned short i, unsigned short ev, unsigned short f)
{
char buf[256];
sprintf(buf, "change on device: %d channel:%d\n%s -> %s -> %s\n",
dev->id, chan->id,
isdn_state_table[i], strisdnevent(ev), isdn_state_table[f]
);
#ifdef DEBUG
printk("%s", buf);
#endif
pcbit_logstat(dev, buf);
}
static void set_running_timeout(unsigned long ptr)
{
struct pcbit_dev * dev;
#ifdef DEBUG
printk(KERN_DEBUG "set_running_timeout\n");
#endif
dev = (struct pcbit_dev *) ptr;
wake_up_interruptible(&dev->set_running_wq);
}
static int set_protocol_running(struct pcbit_dev * dev)
{
isdn_ctrl ctl;
init_timer(&dev->set_running_timer);
dev->set_running_timer.function = &set_running_timeout;
dev->set_running_timer.data = (ulong) dev;
dev->set_running_timer.expires = jiffies + SET_RUN_TIMEOUT;
/* kick it */
dev->l2_state = L2_STARTING;
writeb((0x80U | ((dev->rcv_seq & 0x07) << 3) | (dev->send_seq & 0x07)),
dev->sh_mem + BANK4);
add_timer(&dev->set_running_timer);
interruptible_sleep_on(&dev->set_running_wq);
del_timer(&dev->set_running_timer);
if (dev->l2_state == L2_RUNNING)
{
printk(KERN_DEBUG "pcbit: running\n");
dev->unack_seq = dev->send_seq;
dev->writeptr = dev->sh_mem;
dev->readptr = dev->sh_mem + BANK2;
/* tell the good news to the upper layer */
ctl.driver = dev->id;
ctl.command = ISDN_STAT_RUN;
dev->dev_if->statcallb(&ctl);
}
else
{
printk(KERN_DEBUG "pcbit: initialization failed\n");
printk(KERN_DEBUG "pcbit: firmware not loaded\n");
dev->l2_state = L2_DOWN;
#ifdef DEBUG
printk(KERN_DEBUG "Bank3 = %02x\n",
readb(dev->sh_mem + BANK3));
#endif
writeb(0x40, dev->sh_mem + BANK4);
/* warn the upper layer */
ctl.driver = dev->id;
ctl.command = ISDN_STAT_STOP;
dev->dev_if->statcallb(&ctl);
return -EL2HLT; /* Level 2 halted */
}
return 0;
}
static int pcbit_ioctl(isdn_ctrl* ctl)
{
struct pcbit_dev * dev;
struct pcbit_ioctl *cmd;
dev = finddev(ctl->driver);
if (!dev)
{
printk(KERN_DEBUG "pcbit_ioctl: unknown device\n");
return -ENODEV;
}
cmd = (struct pcbit_ioctl *) ctl->parm.num;
switch(ctl->arg) {
case PCBIT_IOCTL_GETSTAT:
cmd->info.l2_status = dev->l2_state;
break;
case PCBIT_IOCTL_STRLOAD:
if (dev->l2_state == L2_RUNNING)
return -EBUSY;
dev->unack_seq = dev->send_seq = dev->rcv_seq = 0;
dev->writeptr = dev->sh_mem;
dev->readptr = dev->sh_mem + BANK2;
dev->l2_state = L2_LOADING;
break;
case PCBIT_IOCTL_LWMODE:
if (dev->l2_state != L2_LOADING)
return -EINVAL;
dev->l2_state = L2_LWMODE;
break;
case PCBIT_IOCTL_FWMODE:
if (dev->l2_state == L2_RUNNING)
return -EBUSY;
dev->loadptr = LOAD_ZONE_START;
dev->l2_state = L2_FWMODE;
break;
case PCBIT_IOCTL_ENDLOAD:
if (dev->l2_state == L2_RUNNING)
return -EBUSY;
dev->l2_state = L2_DOWN;
break;
case PCBIT_IOCTL_SETBYTE:
if (dev->l2_state == L2_RUNNING)
return -EBUSY;
/* check addr */
if (cmd->info.rdp_byte.addr > BANK4)
return -EFAULT;
writeb(cmd->info.rdp_byte.value, dev->sh_mem + cmd->info.rdp_byte.addr);
break;
case PCBIT_IOCTL_GETBYTE:
if (dev->l2_state == L2_RUNNING)
return -EBUSY;
/* check addr */
if (cmd->info.rdp_byte.addr > BANK4)
{
printk("getbyte: invalid addr %04x\n", cmd->info.rdp_byte.addr);
return -EFAULT;
}
cmd->info.rdp_byte.value = readb(dev->sh_mem + cmd->info.rdp_byte.addr);
break;
case PCBIT_IOCTL_RUNNING:
if (dev->l2_state == L2_RUNNING)
return -EBUSY;
return set_protocol_running(dev);
break;
case PCBIT_IOCTL_WATCH188:
if (dev->l2_state != L2_LOADING)
return -EINVAL;
pcbit_l2_write(dev, MSG_WATCH188, 0x0001, NULL, 0);
break;
case PCBIT_IOCTL_PING188:
if (dev->l2_state != L2_LOADING)
return -EINVAL;
pcbit_l2_write(dev, MSG_PING188_REQ, 0x0001, NULL, 0);
break;
case PCBIT_IOCTL_APION:
if (dev->l2_state != L2_LOADING)
return -EINVAL;
pcbit_l2_write(dev, MSG_API_ON, 0x0001, NULL, 0);
break;
case PCBIT_IOCTL_STOP:
dev->l2_state = L2_DOWN;
writeb(0x40, dev->sh_mem + BANK4);
dev->rcv_seq = 0;
dev->send_seq = 0;
dev->unack_seq = 0;
break;
default:
printk("error: unknown ioctl\n");
break;
};
return 0;
}
/*
* MSN list handling
*
* if null reject all calls
* if first entry has null MSN accept all calls
*/
static void pcbit_clear_msn(struct pcbit_dev *dev)
{
struct msn_entry *ptr, *back;
for (ptr=dev->msn_list; ptr; )
{
back = ptr->next;
kfree(ptr);
ptr = back;
}
dev->msn_list = NULL;
}
static void pcbit_set_msn(struct pcbit_dev *dev, char *list)
{
struct msn_entry *ptr;
struct msn_entry *back = NULL;
char *cp, *sp;
int len;
if (strlen(list) == 0) {
ptr = kmalloc(sizeof(struct msn_entry), GFP_ATOMIC);
if (!ptr) {
printk(KERN_WARNING "kmalloc failed\n");
return;
}
ptr->msn = NULL;
ptr->next = dev->msn_list;
dev->msn_list = ptr;
return;
}
if (dev->msn_list)
for (back=dev->msn_list; back->next; back=back->next);
sp = list;
do {
cp=strchr(sp, ',');
if (cp)
len = cp - sp;
else
len = strlen(sp);
ptr = kmalloc(sizeof(struct msn_entry), GFP_ATOMIC);
if (!ptr) {
printk(KERN_WARNING "kmalloc failed\n");
return;
}
ptr->next = NULL;
ptr->msn = kmalloc(len, GFP_ATOMIC);
if (!ptr->msn) {
printk(KERN_WARNING "kmalloc failed\n");
kfree(ptr);
return;
}
memcpy(ptr->msn, sp, len - 1);
ptr->msn[len] = 0;
#ifdef DEBUG
printk(KERN_DEBUG "msn: %s\n", ptr->msn);
#endif
if (dev->msn_list == NULL)
dev->msn_list = ptr;
else
back->next = ptr;
back = ptr;
sp += len;
} while(cp);
}
/*
* check if we do signal or reject an incoming call
*/
static int pcbit_check_msn(struct pcbit_dev *dev, char *msn)
{
struct msn_entry *ptr;
for (ptr=dev->msn_list; ptr; ptr=ptr->next) {
if (ptr->msn == NULL)
return 1;
if (strcmp(ptr->msn, msn) == 0)
return 1;
}
return 0;
}
| gpl-2.0 |
hiikezoe/android_kernel_kyocera_dm015k | net/netfilter/nf_conntrack_ecache.c | 4455 | 6726 | /* Event cache for netfilter. */
/* (C) 1999-2001 Paul `Rusty' Russell
* (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
* (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/types.h>
#include <linux/netfilter.h>
#include <linux/skbuff.h>
#include <linux/vmalloc.h>
#include <linux/stddef.h>
#include <linux/err.h>
#include <linux/percpu.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_core.h>
#include <net/netfilter/nf_conntrack_extend.h>
static DEFINE_MUTEX(nf_ct_ecache_mutex);
/* deliver cached events and clear cache entry - must be called with locally
* disabled softirqs */
void nf_ct_deliver_cached_events(struct nf_conn *ct)
{
struct net *net = nf_ct_net(ct);
unsigned long events, missed;
struct nf_ct_event_notifier *notify;
struct nf_conntrack_ecache *e;
struct nf_ct_event item;
int ret;
rcu_read_lock();
notify = rcu_dereference(net->ct.nf_conntrack_event_cb);
if (notify == NULL)
goto out_unlock;
e = nf_ct_ecache_find(ct);
if (e == NULL)
goto out_unlock;
events = xchg(&e->cache, 0);
if (!nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct) || !events)
goto out_unlock;
/* We make a copy of the missed event cache without taking
* the lock, thus we may send missed events twice. However,
* this does not harm and it happens very rarely. */
missed = e->missed;
if (!((events | missed) & e->ctmask))
goto out_unlock;
item.ct = ct;
item.pid = 0;
item.report = 0;
ret = notify->fcn(events | missed, &item);
if (likely(ret >= 0 && !missed))
goto out_unlock;
spin_lock_bh(&ct->lock);
if (ret < 0)
e->missed |= events;
else
e->missed &= ~missed;
spin_unlock_bh(&ct->lock);
out_unlock:
rcu_read_unlock();
}
EXPORT_SYMBOL_GPL(nf_ct_deliver_cached_events);
int nf_conntrack_register_notifier(struct net *net,
struct nf_ct_event_notifier *new)
{
int ret = 0;
struct nf_ct_event_notifier *notify;
mutex_lock(&nf_ct_ecache_mutex);
notify = rcu_dereference_protected(net->ct.nf_conntrack_event_cb,
lockdep_is_held(&nf_ct_ecache_mutex));
if (notify != NULL) {
ret = -EBUSY;
goto out_unlock;
}
rcu_assign_pointer(net->ct.nf_conntrack_event_cb, new);
mutex_unlock(&nf_ct_ecache_mutex);
return ret;
out_unlock:
mutex_unlock(&nf_ct_ecache_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(nf_conntrack_register_notifier);
void nf_conntrack_unregister_notifier(struct net *net,
struct nf_ct_event_notifier *new)
{
struct nf_ct_event_notifier *notify;
mutex_lock(&nf_ct_ecache_mutex);
notify = rcu_dereference_protected(net->ct.nf_conntrack_event_cb,
lockdep_is_held(&nf_ct_ecache_mutex));
BUG_ON(notify != new);
RCU_INIT_POINTER(net->ct.nf_conntrack_event_cb, NULL);
mutex_unlock(&nf_ct_ecache_mutex);
}
EXPORT_SYMBOL_GPL(nf_conntrack_unregister_notifier);
int nf_ct_expect_register_notifier(struct net *net,
struct nf_exp_event_notifier *new)
{
int ret = 0;
struct nf_exp_event_notifier *notify;
mutex_lock(&nf_ct_ecache_mutex);
notify = rcu_dereference_protected(net->ct.nf_expect_event_cb,
lockdep_is_held(&nf_ct_ecache_mutex));
if (notify != NULL) {
ret = -EBUSY;
goto out_unlock;
}
rcu_assign_pointer(net->ct.nf_expect_event_cb, new);
mutex_unlock(&nf_ct_ecache_mutex);
return ret;
out_unlock:
mutex_unlock(&nf_ct_ecache_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(nf_ct_expect_register_notifier);
void nf_ct_expect_unregister_notifier(struct net *net,
struct nf_exp_event_notifier *new)
{
struct nf_exp_event_notifier *notify;
mutex_lock(&nf_ct_ecache_mutex);
notify = rcu_dereference_protected(net->ct.nf_expect_event_cb,
lockdep_is_held(&nf_ct_ecache_mutex));
BUG_ON(notify != new);
RCU_INIT_POINTER(net->ct.nf_expect_event_cb, NULL);
mutex_unlock(&nf_ct_ecache_mutex);
}
EXPORT_SYMBOL_GPL(nf_ct_expect_unregister_notifier);
#define NF_CT_EVENTS_DEFAULT 1
static int nf_ct_events __read_mostly = NF_CT_EVENTS_DEFAULT;
static int nf_ct_events_retry_timeout __read_mostly = 15*HZ;
#ifdef CONFIG_SYSCTL
static struct ctl_table event_sysctl_table[] = {
{
.procname = "nf_conntrack_events",
.data = &init_net.ct.sysctl_events,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "nf_conntrack_events_retry_timeout",
.data = &init_net.ct.sysctl_events_retry_timeout,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{}
};
#endif /* CONFIG_SYSCTL */
static struct nf_ct_ext_type event_extend __read_mostly = {
.len = sizeof(struct nf_conntrack_ecache),
.align = __alignof__(struct nf_conntrack_ecache),
.id = NF_CT_EXT_ECACHE,
};
#ifdef CONFIG_SYSCTL
static int nf_conntrack_event_init_sysctl(struct net *net)
{
struct ctl_table *table;
table = kmemdup(event_sysctl_table, sizeof(event_sysctl_table),
GFP_KERNEL);
if (!table)
goto out;
table[0].data = &net->ct.sysctl_events;
table[1].data = &net->ct.sysctl_events_retry_timeout;
net->ct.event_sysctl_header =
register_net_sysctl_table(net,
nf_net_netfilter_sysctl_path, table);
if (!net->ct.event_sysctl_header) {
printk(KERN_ERR "nf_ct_event: can't register to sysctl.\n");
goto out_register;
}
return 0;
out_register:
kfree(table);
out:
return -ENOMEM;
}
static void nf_conntrack_event_fini_sysctl(struct net *net)
{
struct ctl_table *table;
table = net->ct.event_sysctl_header->ctl_table_arg;
unregister_net_sysctl_table(net->ct.event_sysctl_header);
kfree(table);
}
#else
static int nf_conntrack_event_init_sysctl(struct net *net)
{
return 0;
}
static void nf_conntrack_event_fini_sysctl(struct net *net)
{
}
#endif /* CONFIG_SYSCTL */
int nf_conntrack_ecache_init(struct net *net)
{
int ret;
net->ct.sysctl_events = nf_ct_events;
net->ct.sysctl_events_retry_timeout = nf_ct_events_retry_timeout;
if (net_eq(net, &init_net)) {
ret = nf_ct_extend_register(&event_extend);
if (ret < 0) {
printk(KERN_ERR "nf_ct_event: Unable to register "
"event extension.\n");
goto out_extend_register;
}
}
ret = nf_conntrack_event_init_sysctl(net);
if (ret < 0)
goto out_sysctl;
return 0;
out_sysctl:
if (net_eq(net, &init_net))
nf_ct_extend_unregister(&event_extend);
out_extend_register:
return ret;
}
void nf_conntrack_ecache_fini(struct net *net)
{
nf_conntrack_event_fini_sysctl(net);
if (net_eq(net, &init_net))
nf_ct_extend_unregister(&event_extend);
}
| gpl-2.0 |
CrawX/linux-fslc | drivers/isdn/divert/divert_init.c | 4711 | 2299 | /* $Id divert_init.c,v 1.5.6.2 2001/01/24 22:18:17 kai Exp $
*
* Module init for DSS1 diversion services for i4l.
*
* Copyright 1999 by Werner Cornelius (werner@isdn4linux.de)
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include "isdn_divert.h"
MODULE_DESCRIPTION("ISDN4Linux: Call diversion support");
MODULE_AUTHOR("Werner Cornelius");
MODULE_LICENSE("GPL");
/****************************************/
/* structure containing interface to hl */
/****************************************/
isdn_divert_if divert_if = {
DIVERT_IF_MAGIC, /* magic value */
DIVERT_CMD_REG, /* register cmd */
ll_callback, /* callback routine from ll */
NULL, /* command still not specified */
NULL, /* drv_to_name */
NULL, /* name_to_drv */
};
/*************************/
/* Module interface code */
/* no cmd line parms */
/*************************/
static int __init divert_init(void)
{
int i;
if (divert_dev_init()) {
printk(KERN_WARNING "dss1_divert: cannot install device, not loaded\n");
return (-EIO);
}
if ((i = DIVERT_REG_NAME(&divert_if)) != DIVERT_NO_ERR) {
divert_dev_deinit();
printk(KERN_WARNING "dss1_divert: error %d registering module, not loaded\n", i);
return (-EIO);
}
printk(KERN_INFO "dss1_divert module successfully installed\n");
return (0);
}
/**********************/
/* Module deinit code */
/**********************/
static void __exit divert_exit(void)
{
unsigned long flags;
int i;
spin_lock_irqsave(&divert_lock, flags);
divert_if.cmd = DIVERT_CMD_REL; /* release */
if ((i = DIVERT_REG_NAME(&divert_if)) != DIVERT_NO_ERR) {
printk(KERN_WARNING "dss1_divert: error %d releasing module\n", i);
spin_unlock_irqrestore(&divert_lock, flags);
return;
}
if (divert_dev_deinit()) {
printk(KERN_WARNING "dss1_divert: device busy, remove cancelled\n");
spin_unlock_irqrestore(&divert_lock, flags);
return;
}
spin_unlock_irqrestore(&divert_lock, flags);
deleterule(-1); /* delete all rules and free mem */
deleteprocs();
printk(KERN_INFO "dss1_divert module successfully removed \n");
}
module_init(divert_init);
module_exit(divert_exit);
| gpl-2.0 |
Albinoman887/android_kernel_htc_msm8660 | drivers/scsi/aacraid/dpcsup.c | 8039 | 11592 | /*
* Adaptec AAC series RAID controller driver
* (c) Copyright 2001 Red Hat Inc.
*
* based on the old aacraid driver that is..
* Adaptec aacraid device driver for Linux.
*
* Copyright (c) 2000-2010 Adaptec, Inc.
* 2010 PMC-Sierra, Inc. (aacraid@pmc-sierra.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Module Name:
* dpcsup.c
*
* Abstract: All DPC processing routines for the cyclone board occur here.
*
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/completion.h>
#include <linux/blkdev.h>
#include <linux/semaphore.h>
#include "aacraid.h"
/**
* aac_response_normal - Handle command replies
* @q: Queue to read from
*
* This DPC routine will be run when the adapter interrupts us to let us
* know there is a response on our normal priority queue. We will pull off
* all QE there are and wake up all the waiters before exiting. We will
* take a spinlock out on the queue before operating on it.
*/
unsigned int aac_response_normal(struct aac_queue * q)
{
struct aac_dev * dev = q->dev;
struct aac_entry *entry;
struct hw_fib * hwfib;
struct fib * fib;
int consumed = 0;
unsigned long flags, mflags;
spin_lock_irqsave(q->lock, flags);
/*
* Keep pulling response QEs off the response queue and waking
* up the waiters until there are no more QEs. We then return
* back to the system. If no response was requesed we just
* deallocate the Fib here and continue.
*/
while(aac_consumer_get(dev, q, &entry))
{
int fast;
u32 index = le32_to_cpu(entry->addr);
fast = index & 0x01;
fib = &dev->fibs[index >> 2];
hwfib = fib->hw_fib_va;
aac_consumer_free(dev, q, HostNormRespQueue);
/*
* Remove this fib from the Outstanding I/O queue.
* But only if it has not already been timed out.
*
* If the fib has been timed out already, then just
* continue. The caller has already been notified that
* the fib timed out.
*/
dev->queues->queue[AdapNormCmdQueue].numpending--;
if (unlikely(fib->flags & FIB_CONTEXT_FLAG_TIMED_OUT)) {
spin_unlock_irqrestore(q->lock, flags);
aac_fib_complete(fib);
aac_fib_free(fib);
spin_lock_irqsave(q->lock, flags);
continue;
}
spin_unlock_irqrestore(q->lock, flags);
if (fast) {
/*
* Doctor the fib
*/
*(__le32 *)hwfib->data = cpu_to_le32(ST_OK);
hwfib->header.XferState |= cpu_to_le32(AdapterProcessed);
}
FIB_COUNTER_INCREMENT(aac_config.FibRecved);
if (hwfib->header.Command == cpu_to_le16(NuFileSystem))
{
__le32 *pstatus = (__le32 *)hwfib->data;
if (*pstatus & cpu_to_le32(0xffff0000))
*pstatus = cpu_to_le32(ST_OK);
}
if (hwfib->header.XferState & cpu_to_le32(NoResponseExpected | Async))
{
if (hwfib->header.XferState & cpu_to_le32(NoResponseExpected))
FIB_COUNTER_INCREMENT(aac_config.NoResponseRecved);
else
FIB_COUNTER_INCREMENT(aac_config.AsyncRecved);
/*
* NOTE: we cannot touch the fib after this
* call, because it may have been deallocated.
*/
fib->flags = 0;
fib->callback(fib->callback_data, fib);
} else {
unsigned long flagv;
spin_lock_irqsave(&fib->event_lock, flagv);
if (!fib->done) {
fib->done = 1;
up(&fib->event_wait);
}
spin_unlock_irqrestore(&fib->event_lock, flagv);
spin_lock_irqsave(&dev->manage_lock, mflags);
dev->management_fib_count--;
spin_unlock_irqrestore(&dev->manage_lock, mflags);
FIB_COUNTER_INCREMENT(aac_config.NormalRecved);
if (fib->done == 2) {
spin_lock_irqsave(&fib->event_lock, flagv);
fib->done = 0;
spin_unlock_irqrestore(&fib->event_lock, flagv);
aac_fib_complete(fib);
aac_fib_free(fib);
}
}
consumed++;
spin_lock_irqsave(q->lock, flags);
}
if (consumed > aac_config.peak_fibs)
aac_config.peak_fibs = consumed;
if (consumed == 0)
aac_config.zero_fibs++;
spin_unlock_irqrestore(q->lock, flags);
return 0;
}
/**
* aac_command_normal - handle commands
* @q: queue to process
*
* This DPC routine will be queued when the adapter interrupts us to
* let us know there is a command on our normal priority queue. We will
* pull off all QE there are and wake up all the waiters before exiting.
* We will take a spinlock out on the queue before operating on it.
*/
unsigned int aac_command_normal(struct aac_queue *q)
{
struct aac_dev * dev = q->dev;
struct aac_entry *entry;
unsigned long flags;
spin_lock_irqsave(q->lock, flags);
/*
* Keep pulling response QEs off the response queue and waking
* up the waiters until there are no more QEs. We then return
* back to the system.
*/
while(aac_consumer_get(dev, q, &entry))
{
struct fib fibctx;
struct hw_fib * hw_fib;
u32 index;
struct fib *fib = &fibctx;
index = le32_to_cpu(entry->addr) / sizeof(struct hw_fib);
hw_fib = &dev->aif_base_va[index];
/*
* Allocate a FIB at all costs. For non queued stuff
* we can just use the stack so we are happy. We need
* a fib object in order to manage the linked lists
*/
if (dev->aif_thread)
if((fib = kmalloc(sizeof(struct fib), GFP_ATOMIC)) == NULL)
fib = &fibctx;
memset(fib, 0, sizeof(struct fib));
INIT_LIST_HEAD(&fib->fiblink);
fib->type = FSAFS_NTC_FIB_CONTEXT;
fib->size = sizeof(struct fib);
fib->hw_fib_va = hw_fib;
fib->data = hw_fib->data;
fib->dev = dev;
if (dev->aif_thread && fib != &fibctx) {
list_add_tail(&fib->fiblink, &q->cmdq);
aac_consumer_free(dev, q, HostNormCmdQueue);
wake_up_interruptible(&q->cmdready);
} else {
aac_consumer_free(dev, q, HostNormCmdQueue);
spin_unlock_irqrestore(q->lock, flags);
/*
* Set the status of this FIB
*/
*(__le32 *)hw_fib->data = cpu_to_le32(ST_OK);
aac_fib_adapter_complete(fib, sizeof(u32));
spin_lock_irqsave(q->lock, flags);
}
}
spin_unlock_irqrestore(q->lock, flags);
return 0;
}
/*
*
* aac_aif_callback
* @context: the context set in the fib - here it is scsi cmd
* @fibptr: pointer to the fib
*
* Handles the AIFs - new method (SRC)
*
*/
static void aac_aif_callback(void *context, struct fib * fibptr)
{
struct fib *fibctx;
struct aac_dev *dev;
struct aac_aifcmd *cmd;
int status;
fibctx = (struct fib *)context;
BUG_ON(fibptr == NULL);
dev = fibptr->dev;
if (fibptr->hw_fib_va->header.XferState &
cpu_to_le32(NoMoreAifDataAvailable)) {
aac_fib_complete(fibptr);
aac_fib_free(fibptr);
return;
}
aac_intr_normal(dev, 0, 1, 0, fibptr->hw_fib_va);
aac_fib_init(fibctx);
cmd = (struct aac_aifcmd *) fib_data(fibctx);
cmd->command = cpu_to_le32(AifReqEvent);
status = aac_fib_send(AifRequest,
fibctx,
sizeof(struct hw_fib)-sizeof(struct aac_fibhdr),
FsaNormal,
0, 1,
(fib_callback)aac_aif_callback, fibctx);
}
/**
* aac_intr_normal - Handle command replies
* @dev: Device
* @index: completion reference
*
* This DPC routine will be run when the adapter interrupts us to let us
* know there is a response on our normal priority queue. We will pull off
* all QE there are and wake up all the waiters before exiting.
*/
unsigned int aac_intr_normal(struct aac_dev *dev, u32 index,
int isAif, int isFastResponse, struct hw_fib *aif_fib)
{
unsigned long mflags;
dprintk((KERN_INFO "aac_intr_normal(%p,%x)\n", dev, index));
if (isAif == 1) { /* AIF - common */
struct hw_fib * hw_fib;
struct fib * fib;
struct aac_queue *q = &dev->queues->queue[HostNormCmdQueue];
unsigned long flags;
/*
* Allocate a FIB. For non queued stuff we can just use
* the stack so we are happy. We need a fib object in order to
* manage the linked lists.
*/
if ((!dev->aif_thread)
|| (!(fib = kzalloc(sizeof(struct fib),GFP_ATOMIC))))
return 1;
if (!(hw_fib = kzalloc(sizeof(struct hw_fib),GFP_ATOMIC))) {
kfree (fib);
return 1;
}
if (aif_fib != NULL) {
memcpy(hw_fib, aif_fib, sizeof(struct hw_fib));
} else {
memcpy(hw_fib,
(struct hw_fib *)(((uintptr_t)(dev->regs.sa)) +
index), sizeof(struct hw_fib));
}
INIT_LIST_HEAD(&fib->fiblink);
fib->type = FSAFS_NTC_FIB_CONTEXT;
fib->size = sizeof(struct fib);
fib->hw_fib_va = hw_fib;
fib->data = hw_fib->data;
fib->dev = dev;
spin_lock_irqsave(q->lock, flags);
list_add_tail(&fib->fiblink, &q->cmdq);
wake_up_interruptible(&q->cmdready);
spin_unlock_irqrestore(q->lock, flags);
return 1;
} else if (isAif == 2) { /* AIF - new (SRC) */
struct fib *fibctx;
struct aac_aifcmd *cmd;
fibctx = aac_fib_alloc(dev);
if (!fibctx)
return 1;
aac_fib_init(fibctx);
cmd = (struct aac_aifcmd *) fib_data(fibctx);
cmd->command = cpu_to_le32(AifReqEvent);
return aac_fib_send(AifRequest,
fibctx,
sizeof(struct hw_fib)-sizeof(struct aac_fibhdr),
FsaNormal,
0, 1,
(fib_callback)aac_aif_callback, fibctx);
} else {
struct fib *fib = &dev->fibs[index];
struct hw_fib * hwfib = fib->hw_fib_va;
/*
* Remove this fib from the Outstanding I/O queue.
* But only if it has not already been timed out.
*
* If the fib has been timed out already, then just
* continue. The caller has already been notified that
* the fib timed out.
*/
dev->queues->queue[AdapNormCmdQueue].numpending--;
if (unlikely(fib->flags & FIB_CONTEXT_FLAG_TIMED_OUT)) {
aac_fib_complete(fib);
aac_fib_free(fib);
return 0;
}
if (isFastResponse) {
/*
* Doctor the fib
*/
*(__le32 *)hwfib->data = cpu_to_le32(ST_OK);
hwfib->header.XferState |= cpu_to_le32(AdapterProcessed);
}
FIB_COUNTER_INCREMENT(aac_config.FibRecved);
if (hwfib->header.Command == cpu_to_le16(NuFileSystem))
{
__le32 *pstatus = (__le32 *)hwfib->data;
if (*pstatus & cpu_to_le32(0xffff0000))
*pstatus = cpu_to_le32(ST_OK);
}
if (hwfib->header.XferState & cpu_to_le32(NoResponseExpected | Async))
{
if (hwfib->header.XferState & cpu_to_le32(NoResponseExpected))
FIB_COUNTER_INCREMENT(aac_config.NoResponseRecved);
else
FIB_COUNTER_INCREMENT(aac_config.AsyncRecved);
/*
* NOTE: we cannot touch the fib after this
* call, because it may have been deallocated.
*/
fib->flags = 0;
fib->callback(fib->callback_data, fib);
} else {
unsigned long flagv;
dprintk((KERN_INFO "event_wait up\n"));
spin_lock_irqsave(&fib->event_lock, flagv);
if (!fib->done) {
fib->done = 1;
up(&fib->event_wait);
}
spin_unlock_irqrestore(&fib->event_lock, flagv);
spin_lock_irqsave(&dev->manage_lock, mflags);
dev->management_fib_count--;
spin_unlock_irqrestore(&dev->manage_lock, mflags);
FIB_COUNTER_INCREMENT(aac_config.NormalRecved);
if (fib->done == 2) {
spin_lock_irqsave(&fib->event_lock, flagv);
fib->done = 0;
spin_unlock_irqrestore(&fib->event_lock, flagv);
aac_fib_complete(fib);
aac_fib_free(fib);
}
}
return 0;
}
}
| gpl-2.0 |
mostafa-z/Gabriel_LG_LP_Kernel | arch/powerpc/mm/gup.c | 8039 | 4676 | /*
* Lockless get_user_pages_fast for powerpc
*
* Copyright (C) 2008 Nick Piggin
* Copyright (C) 2008 Novell Inc.
*/
#undef DEBUG
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/hugetlb.h>
#include <linux/vmstat.h>
#include <linux/pagemap.h>
#include <linux/rwsem.h>
#include <asm/pgtable.h>
#ifdef __HAVE_ARCH_PTE_SPECIAL
/*
* The performance critical leaf functions are made noinline otherwise gcc
* inlines everything into a single function which results in too much
* register pressure.
*/
static noinline int gup_pte_range(pmd_t pmd, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
unsigned long mask, result;
pte_t *ptep;
result = _PAGE_PRESENT|_PAGE_USER;
if (write)
result |= _PAGE_RW;
mask = result | _PAGE_SPECIAL;
ptep = pte_offset_kernel(&pmd, addr);
do {
pte_t pte = *ptep;
struct page *page;
if ((pte_val(pte) & mask) != result)
return 0;
VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
page = pte_page(pte);
if (!page_cache_get_speculative(page))
return 0;
if (unlikely(pte_val(pte) != pte_val(*ptep))) {
put_page(page);
return 0;
}
pages[*nr] = page;
(*nr)++;
} while (ptep++, addr += PAGE_SIZE, addr != end);
return 1;
}
static int gup_pmd_range(pud_t pud, unsigned long addr, unsigned long end,
int write, struct page **pages, int *nr)
{
unsigned long next;
pmd_t *pmdp;
pmdp = pmd_offset(&pud, addr);
do {
pmd_t pmd = *pmdp;
next = pmd_addr_end(addr, end);
if (pmd_none(pmd))
return 0;
if (is_hugepd(pmdp)) {
if (!gup_hugepd((hugepd_t *)pmdp, PMD_SHIFT,
addr, next, write, pages, nr))
return 0;
} else if (!gup_pte_range(pmd, addr, next, write, pages, nr))
return 0;
} while (pmdp++, addr = next, addr != end);
return 1;
}
static int gup_pud_range(pgd_t pgd, unsigned long addr, unsigned long end,
int write, struct page **pages, int *nr)
{
unsigned long next;
pud_t *pudp;
pudp = pud_offset(&pgd, addr);
do {
pud_t pud = *pudp;
next = pud_addr_end(addr, end);
if (pud_none(pud))
return 0;
if (is_hugepd(pudp)) {
if (!gup_hugepd((hugepd_t *)pudp, PUD_SHIFT,
addr, next, write, pages, nr))
return 0;
} else if (!gup_pmd_range(pud, addr, next, write, pages, nr))
return 0;
} while (pudp++, addr = next, addr != end);
return 1;
}
int get_user_pages_fast(unsigned long start, int nr_pages, int write,
struct page **pages)
{
struct mm_struct *mm = current->mm;
unsigned long addr, len, end;
unsigned long next;
pgd_t *pgdp;
int nr = 0;
pr_devel("%s(%lx,%x,%s)\n", __func__, start, nr_pages, write ? "write" : "read");
start &= PAGE_MASK;
addr = start;
len = (unsigned long) nr_pages << PAGE_SHIFT;
end = start + len;
if (unlikely(!access_ok(write ? VERIFY_WRITE : VERIFY_READ,
start, len)))
goto slow_irqon;
pr_devel(" aligned: %lx .. %lx\n", start, end);
/*
* XXX: batch / limit 'nr', to avoid large irq off latency
* needs some instrumenting to determine the common sizes used by
* important workloads (eg. DB2), and whether limiting the batch size
* will decrease performance.
*
* It seems like we're in the clear for the moment. Direct-IO is
* the main guy that batches up lots of get_user_pages, and even
* they are limited to 64-at-a-time which is not so many.
*/
/*
* This doesn't prevent pagetable teardown, but does prevent
* the pagetables from being freed on powerpc.
*
* So long as we atomically load page table pointers versus teardown,
* we can follow the address down to the the page and take a ref on it.
*/
local_irq_disable();
pgdp = pgd_offset(mm, addr);
do {
pgd_t pgd = *pgdp;
pr_devel(" %016lx: normal pgd %p\n", addr,
(void *)pgd_val(pgd));
next = pgd_addr_end(addr, end);
if (pgd_none(pgd))
goto slow;
if (is_hugepd(pgdp)) {
if (!gup_hugepd((hugepd_t *)pgdp, PGDIR_SHIFT,
addr, next, write, pages, &nr))
goto slow;
} else if (!gup_pud_range(pgd, addr, next, write, pages, &nr))
goto slow;
} while (pgdp++, addr = next, addr != end);
local_irq_enable();
VM_BUG_ON(nr != (end - start) >> PAGE_SHIFT);
return nr;
{
int ret;
slow:
local_irq_enable();
slow_irqon:
pr_devel(" slow path ! nr = %d\n", nr);
/* Try to get the remaining pages with get_user_pages */
start += nr << PAGE_SHIFT;
pages += nr;
down_read(&mm->mmap_sem);
ret = get_user_pages(current, mm, start,
(end - start) >> PAGE_SHIFT, write, 0, pages, NULL);
up_read(&mm->mmap_sem);
/* Have to be a bit careful with return values */
if (nr > 0) {
if (ret < 0)
ret = nr;
else
ret += nr;
}
return ret;
}
}
#endif /* __HAVE_ARCH_PTE_SPECIAL */
| gpl-2.0 |
freexperia/android_kernel_semc_msm7x30 | drivers/oprofile/buffer_sync.c | 8039 | 13822 | /**
* @file buffer_sync.c
*
* @remark Copyright 2002-2009 OProfile authors
* @remark Read the file COPYING
*
* @author John Levon <levon@movementarian.org>
* @author Barry Kasindorf
* @author Robert Richter <robert.richter@amd.com>
*
* This is the core of the buffer management. Each
* CPU buffer is processed and entered into the
* global event buffer. Such processing is necessary
* in several circumstances, mentioned below.
*
* The processing does the job of converting the
* transitory EIP value into a persistent dentry/offset
* value that the profiler can record at its leisure.
*
* See fs/dcookies.c for a description of the dentry/offset
* objects.
*/
#include <linux/mm.h>
#include <linux/workqueue.h>
#include <linux/notifier.h>
#include <linux/dcookies.h>
#include <linux/profile.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/oprofile.h>
#include <linux/sched.h>
#include <linux/gfp.h>
#include "oprofile_stats.h"
#include "event_buffer.h"
#include "cpu_buffer.h"
#include "buffer_sync.h"
static LIST_HEAD(dying_tasks);
static LIST_HEAD(dead_tasks);
static cpumask_var_t marked_cpus;
static DEFINE_SPINLOCK(task_mortuary);
static void process_task_mortuary(void);
/* Take ownership of the task struct and place it on the
* list for processing. Only after two full buffer syncs
* does the task eventually get freed, because by then
* we are sure we will not reference it again.
* Can be invoked from softirq via RCU callback due to
* call_rcu() of the task struct, hence the _irqsave.
*/
static int
task_free_notify(struct notifier_block *self, unsigned long val, void *data)
{
unsigned long flags;
struct task_struct *task = data;
spin_lock_irqsave(&task_mortuary, flags);
list_add(&task->tasks, &dying_tasks);
spin_unlock_irqrestore(&task_mortuary, flags);
return NOTIFY_OK;
}
/* The task is on its way out. A sync of the buffer means we can catch
* any remaining samples for this task.
*/
static int
task_exit_notify(struct notifier_block *self, unsigned long val, void *data)
{
/* To avoid latency problems, we only process the current CPU,
* hoping that most samples for the task are on this CPU
*/
sync_buffer(raw_smp_processor_id());
return 0;
}
/* The task is about to try a do_munmap(). We peek at what it's going to
* do, and if it's an executable region, process the samples first, so
* we don't lose any. This does not have to be exact, it's a QoI issue
* only.
*/
static int
munmap_notify(struct notifier_block *self, unsigned long val, void *data)
{
unsigned long addr = (unsigned long)data;
struct mm_struct *mm = current->mm;
struct vm_area_struct *mpnt;
down_read(&mm->mmap_sem);
mpnt = find_vma(mm, addr);
if (mpnt && mpnt->vm_file && (mpnt->vm_flags & VM_EXEC)) {
up_read(&mm->mmap_sem);
/* To avoid latency problems, we only process the current CPU,
* hoping that most samples for the task are on this CPU
*/
sync_buffer(raw_smp_processor_id());
return 0;
}
up_read(&mm->mmap_sem);
return 0;
}
/* We need to be told about new modules so we don't attribute to a previously
* loaded module, or drop the samples on the floor.
*/
static int
module_load_notify(struct notifier_block *self, unsigned long val, void *data)
{
#ifdef CONFIG_MODULES
if (val != MODULE_STATE_COMING)
return 0;
/* FIXME: should we process all CPU buffers ? */
mutex_lock(&buffer_mutex);
add_event_entry(ESCAPE_CODE);
add_event_entry(MODULE_LOADED_CODE);
mutex_unlock(&buffer_mutex);
#endif
return 0;
}
static struct notifier_block task_free_nb = {
.notifier_call = task_free_notify,
};
static struct notifier_block task_exit_nb = {
.notifier_call = task_exit_notify,
};
static struct notifier_block munmap_nb = {
.notifier_call = munmap_notify,
};
static struct notifier_block module_load_nb = {
.notifier_call = module_load_notify,
};
static void free_all_tasks(void)
{
/* make sure we don't leak task structs */
process_task_mortuary();
process_task_mortuary();
}
int sync_start(void)
{
int err;
if (!zalloc_cpumask_var(&marked_cpus, GFP_KERNEL))
return -ENOMEM;
err = task_handoff_register(&task_free_nb);
if (err)
goto out1;
err = profile_event_register(PROFILE_TASK_EXIT, &task_exit_nb);
if (err)
goto out2;
err = profile_event_register(PROFILE_MUNMAP, &munmap_nb);
if (err)
goto out3;
err = register_module_notifier(&module_load_nb);
if (err)
goto out4;
start_cpu_work();
out:
return err;
out4:
profile_event_unregister(PROFILE_MUNMAP, &munmap_nb);
out3:
profile_event_unregister(PROFILE_TASK_EXIT, &task_exit_nb);
out2:
task_handoff_unregister(&task_free_nb);
free_all_tasks();
out1:
free_cpumask_var(marked_cpus);
goto out;
}
void sync_stop(void)
{
end_cpu_work();
unregister_module_notifier(&module_load_nb);
profile_event_unregister(PROFILE_MUNMAP, &munmap_nb);
profile_event_unregister(PROFILE_TASK_EXIT, &task_exit_nb);
task_handoff_unregister(&task_free_nb);
barrier(); /* do all of the above first */
flush_cpu_work();
free_all_tasks();
free_cpumask_var(marked_cpus);
}
/* Optimisation. We can manage without taking the dcookie sem
* because we cannot reach this code without at least one
* dcookie user still being registered (namely, the reader
* of the event buffer). */
static inline unsigned long fast_get_dcookie(struct path *path)
{
unsigned long cookie;
if (path->dentry->d_flags & DCACHE_COOKIE)
return (unsigned long)path->dentry;
get_dcookie(path, &cookie);
return cookie;
}
/* Look up the dcookie for the task's first VM_EXECUTABLE mapping,
* which corresponds loosely to "application name". This is
* not strictly necessary but allows oprofile to associate
* shared-library samples with particular applications
*/
static unsigned long get_exec_dcookie(struct mm_struct *mm)
{
unsigned long cookie = NO_COOKIE;
struct vm_area_struct *vma;
if (!mm)
goto out;
for (vma = mm->mmap; vma; vma = vma->vm_next) {
if (!vma->vm_file)
continue;
if (!(vma->vm_flags & VM_EXECUTABLE))
continue;
cookie = fast_get_dcookie(&vma->vm_file->f_path);
break;
}
out:
return cookie;
}
/* Convert the EIP value of a sample into a persistent dentry/offset
* pair that can then be added to the global event buffer. We make
* sure to do this lookup before a mm->mmap modification happens so
* we don't lose track.
*/
static unsigned long
lookup_dcookie(struct mm_struct *mm, unsigned long addr, off_t *offset)
{
unsigned long cookie = NO_COOKIE;
struct vm_area_struct *vma;
for (vma = find_vma(mm, addr); vma; vma = vma->vm_next) {
if (addr < vma->vm_start || addr >= vma->vm_end)
continue;
if (vma->vm_file) {
cookie = fast_get_dcookie(&vma->vm_file->f_path);
*offset = (vma->vm_pgoff << PAGE_SHIFT) + addr -
vma->vm_start;
} else {
/* must be an anonymous map */
*offset = addr;
}
break;
}
if (!vma)
cookie = INVALID_COOKIE;
return cookie;
}
static unsigned long last_cookie = INVALID_COOKIE;
static void add_cpu_switch(int i)
{
add_event_entry(ESCAPE_CODE);
add_event_entry(CPU_SWITCH_CODE);
add_event_entry(i);
last_cookie = INVALID_COOKIE;
}
static void add_kernel_ctx_switch(unsigned int in_kernel)
{
add_event_entry(ESCAPE_CODE);
if (in_kernel)
add_event_entry(KERNEL_ENTER_SWITCH_CODE);
else
add_event_entry(KERNEL_EXIT_SWITCH_CODE);
}
static void
add_user_ctx_switch(struct task_struct const *task, unsigned long cookie)
{
add_event_entry(ESCAPE_CODE);
add_event_entry(CTX_SWITCH_CODE);
add_event_entry(task->pid);
add_event_entry(cookie);
/* Another code for daemon back-compat */
add_event_entry(ESCAPE_CODE);
add_event_entry(CTX_TGID_CODE);
add_event_entry(task->tgid);
}
static void add_cookie_switch(unsigned long cookie)
{
add_event_entry(ESCAPE_CODE);
add_event_entry(COOKIE_SWITCH_CODE);
add_event_entry(cookie);
}
static void add_trace_begin(void)
{
add_event_entry(ESCAPE_CODE);
add_event_entry(TRACE_BEGIN_CODE);
}
static void add_data(struct op_entry *entry, struct mm_struct *mm)
{
unsigned long code, pc, val;
unsigned long cookie;
off_t offset;
if (!op_cpu_buffer_get_data(entry, &code))
return;
if (!op_cpu_buffer_get_data(entry, &pc))
return;
if (!op_cpu_buffer_get_size(entry))
return;
if (mm) {
cookie = lookup_dcookie(mm, pc, &offset);
if (cookie == NO_COOKIE)
offset = pc;
if (cookie == INVALID_COOKIE) {
atomic_inc(&oprofile_stats.sample_lost_no_mapping);
offset = pc;
}
if (cookie != last_cookie) {
add_cookie_switch(cookie);
last_cookie = cookie;
}
} else
offset = pc;
add_event_entry(ESCAPE_CODE);
add_event_entry(code);
add_event_entry(offset); /* Offset from Dcookie */
while (op_cpu_buffer_get_data(entry, &val))
add_event_entry(val);
}
static inline void add_sample_entry(unsigned long offset, unsigned long event)
{
add_event_entry(offset);
add_event_entry(event);
}
/*
* Add a sample to the global event buffer. If possible the
* sample is converted into a persistent dentry/offset pair
* for later lookup from userspace. Return 0 on failure.
*/
static int
add_sample(struct mm_struct *mm, struct op_sample *s, int in_kernel)
{
unsigned long cookie;
off_t offset;
if (in_kernel) {
add_sample_entry(s->eip, s->event);
return 1;
}
/* add userspace sample */
if (!mm) {
atomic_inc(&oprofile_stats.sample_lost_no_mm);
return 0;
}
cookie = lookup_dcookie(mm, s->eip, &offset);
if (cookie == INVALID_COOKIE) {
atomic_inc(&oprofile_stats.sample_lost_no_mapping);
return 0;
}
if (cookie != last_cookie) {
add_cookie_switch(cookie);
last_cookie = cookie;
}
add_sample_entry(offset, s->event);
return 1;
}
static void release_mm(struct mm_struct *mm)
{
if (!mm)
return;
up_read(&mm->mmap_sem);
mmput(mm);
}
static struct mm_struct *take_tasks_mm(struct task_struct *task)
{
struct mm_struct *mm = get_task_mm(task);
if (mm)
down_read(&mm->mmap_sem);
return mm;
}
static inline int is_code(unsigned long val)
{
return val == ESCAPE_CODE;
}
/* Move tasks along towards death. Any tasks on dead_tasks
* will definitely have no remaining references in any
* CPU buffers at this point, because we use two lists,
* and to have reached the list, it must have gone through
* one full sync already.
*/
static void process_task_mortuary(void)
{
unsigned long flags;
LIST_HEAD(local_dead_tasks);
struct task_struct *task;
struct task_struct *ttask;
spin_lock_irqsave(&task_mortuary, flags);
list_splice_init(&dead_tasks, &local_dead_tasks);
list_splice_init(&dying_tasks, &dead_tasks);
spin_unlock_irqrestore(&task_mortuary, flags);
list_for_each_entry_safe(task, ttask, &local_dead_tasks, tasks) {
list_del(&task->tasks);
free_task(task);
}
}
static void mark_done(int cpu)
{
int i;
cpumask_set_cpu(cpu, marked_cpus);
for_each_online_cpu(i) {
if (!cpumask_test_cpu(i, marked_cpus))
return;
}
/* All CPUs have been processed at least once,
* we can process the mortuary once
*/
process_task_mortuary();
cpumask_clear(marked_cpus);
}
/* FIXME: this is not sufficient if we implement syscall barrier backtrace
* traversal, the code switch to sb_sample_start at first kernel enter/exit
* switch so we need a fifth state and some special handling in sync_buffer()
*/
typedef enum {
sb_bt_ignore = -2,
sb_buffer_start,
sb_bt_start,
sb_sample_start,
} sync_buffer_state;
/* Sync one of the CPU's buffers into the global event buffer.
* Here we need to go through each batch of samples punctuated
* by context switch notes, taking the task's mmap_sem and doing
* lookup in task->mm->mmap to convert EIP into dcookie/offset
* value.
*/
void sync_buffer(int cpu)
{
struct mm_struct *mm = NULL;
struct mm_struct *oldmm;
unsigned long val;
struct task_struct *new;
unsigned long cookie = 0;
int in_kernel = 1;
sync_buffer_state state = sb_buffer_start;
unsigned int i;
unsigned long available;
unsigned long flags;
struct op_entry entry;
struct op_sample *sample;
mutex_lock(&buffer_mutex);
add_cpu_switch(cpu);
op_cpu_buffer_reset(cpu);
available = op_cpu_buffer_entries(cpu);
for (i = 0; i < available; ++i) {
sample = op_cpu_buffer_read_entry(&entry, cpu);
if (!sample)
break;
if (is_code(sample->eip)) {
flags = sample->event;
if (flags & TRACE_BEGIN) {
state = sb_bt_start;
add_trace_begin();
}
if (flags & KERNEL_CTX_SWITCH) {
/* kernel/userspace switch */
in_kernel = flags & IS_KERNEL;
if (state == sb_buffer_start)
state = sb_sample_start;
add_kernel_ctx_switch(flags & IS_KERNEL);
}
if (flags & USER_CTX_SWITCH
&& op_cpu_buffer_get_data(&entry, &val)) {
/* userspace context switch */
new = (struct task_struct *)val;
oldmm = mm;
release_mm(oldmm);
mm = take_tasks_mm(new);
if (mm != oldmm)
cookie = get_exec_dcookie(mm);
add_user_ctx_switch(new, cookie);
}
if (op_cpu_buffer_get_size(&entry))
add_data(&entry, mm);
continue;
}
if (state < sb_bt_start)
/* ignore sample */
continue;
if (add_sample(mm, sample, in_kernel))
continue;
/* ignore backtraces if failed to add a sample */
if (state == sb_bt_start) {
state = sb_bt_ignore;
atomic_inc(&oprofile_stats.bt_lost_no_mapping);
}
}
release_mm(mm);
mark_done(cpu);
mutex_unlock(&buffer_mutex);
}
/* The function can be used to add a buffer worth of data directly to
* the kernel buffer. The buffer is assumed to be a circular buffer.
* Take the entries from index start and end at index end, wrapping
* at max_entries.
*/
void oprofile_put_buff(unsigned long *buf, unsigned int start,
unsigned int stop, unsigned int max)
{
int i;
i = start;
mutex_lock(&buffer_mutex);
while (i != stop) {
add_event_entry(buf[i++]);
if (i >= max)
i = 0;
}
mutex_unlock(&buffer_mutex);
}
| gpl-2.0 |
Flemmard/akh8960_cm | drivers/ata/pata_hpt37x.c | 8039 | 26312 | /*
* Libata driver for the highpoint 37x and 30x UDMA66 ATA controllers.
*
* This driver is heavily based upon:
*
* linux/drivers/ide/pci/hpt366.c Version 0.36 April 25, 2003
*
* Copyright (C) 1999-2003 Andre Hedrick <andre@linux-ide.org>
* Portions Copyright (C) 2001 Sun Microsystems, Inc.
* Portions Copyright (C) 2003 Red Hat Inc
* Portions Copyright (C) 2005-2010 MontaVista Software, Inc.
*
* TODO
* Look into engine reset on timeout errors. Should not be required.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_hpt37x"
#define DRV_VERSION "0.6.23"
struct hpt_clock {
u8 xfer_speed;
u32 timing;
};
struct hpt_chip {
const char *name;
unsigned int base;
struct hpt_clock const *clocks[4];
};
/* key for bus clock timings
* bit
* 0:3 data_high_time. Inactive time of DIOW_/DIOR_ for PIO and MW DMA.
* cycles = value + 1
* 4:8 data_low_time. Active time of DIOW_/DIOR_ for PIO and MW DMA.
* cycles = value + 1
* 9:12 cmd_high_time. Inactive time of DIOW_/DIOR_ during task file
* register access.
* 13:17 cmd_low_time. Active time of DIOW_/DIOR_ during task file
* register access.
* 18:20 udma_cycle_time. Clock cycles for UDMA xfer.
* 21 CLK frequency for UDMA: 0=ATA clock, 1=dual ATA clock.
* 22:24 pre_high_time. Time to initialize 1st cycle for PIO and MW DMA xfer.
* 25:27 cmd_pre_high_time. Time to initialize 1st PIO cycle for task file
* register access.
* 28 UDMA enable.
* 29 DMA enable.
* 30 PIO_MST enable. If set, the chip is in bus master mode during
* PIO xfer.
* 31 FIFO enable. Only for PIO.
*/
static struct hpt_clock hpt37x_timings_33[] = {
{ XFER_UDMA_6, 0x12446231 }, /* 0x12646231 ?? */
{ XFER_UDMA_5, 0x12446231 },
{ XFER_UDMA_4, 0x12446231 },
{ XFER_UDMA_3, 0x126c6231 },
{ XFER_UDMA_2, 0x12486231 },
{ XFER_UDMA_1, 0x124c6233 },
{ XFER_UDMA_0, 0x12506297 },
{ XFER_MW_DMA_2, 0x22406c31 },
{ XFER_MW_DMA_1, 0x22406c33 },
{ XFER_MW_DMA_0, 0x22406c97 },
{ XFER_PIO_4, 0x06414e31 },
{ XFER_PIO_3, 0x06414e42 },
{ XFER_PIO_2, 0x06414e53 },
{ XFER_PIO_1, 0x06814e93 },
{ XFER_PIO_0, 0x06814ea7 }
};
static struct hpt_clock hpt37x_timings_50[] = {
{ XFER_UDMA_6, 0x12848242 },
{ XFER_UDMA_5, 0x12848242 },
{ XFER_UDMA_4, 0x12ac8242 },
{ XFER_UDMA_3, 0x128c8242 },
{ XFER_UDMA_2, 0x120c8242 },
{ XFER_UDMA_1, 0x12148254 },
{ XFER_UDMA_0, 0x121882ea },
{ XFER_MW_DMA_2, 0x22808242 },
{ XFER_MW_DMA_1, 0x22808254 },
{ XFER_MW_DMA_0, 0x228082ea },
{ XFER_PIO_4, 0x0a81f442 },
{ XFER_PIO_3, 0x0a81f443 },
{ XFER_PIO_2, 0x0a81f454 },
{ XFER_PIO_1, 0x0ac1f465 },
{ XFER_PIO_0, 0x0ac1f48a }
};
static struct hpt_clock hpt37x_timings_66[] = {
{ XFER_UDMA_6, 0x1c869c62 },
{ XFER_UDMA_5, 0x1cae9c62 }, /* 0x1c8a9c62 */
{ XFER_UDMA_4, 0x1c8a9c62 },
{ XFER_UDMA_3, 0x1c8e9c62 },
{ XFER_UDMA_2, 0x1c929c62 },
{ XFER_UDMA_1, 0x1c9a9c62 },
{ XFER_UDMA_0, 0x1c829c62 },
{ XFER_MW_DMA_2, 0x2c829c62 },
{ XFER_MW_DMA_1, 0x2c829c66 },
{ XFER_MW_DMA_0, 0x2c829d2e },
{ XFER_PIO_4, 0x0c829c62 },
{ XFER_PIO_3, 0x0c829c84 },
{ XFER_PIO_2, 0x0c829ca6 },
{ XFER_PIO_1, 0x0d029d26 },
{ XFER_PIO_0, 0x0d029d5e }
};
static const struct hpt_chip hpt370 = {
"HPT370",
48,
{
hpt37x_timings_33,
NULL,
NULL,
NULL
}
};
static const struct hpt_chip hpt370a = {
"HPT370A",
48,
{
hpt37x_timings_33,
NULL,
hpt37x_timings_50,
NULL
}
};
static const struct hpt_chip hpt372 = {
"HPT372",
55,
{
hpt37x_timings_33,
NULL,
hpt37x_timings_50,
hpt37x_timings_66
}
};
static const struct hpt_chip hpt302 = {
"HPT302",
66,
{
hpt37x_timings_33,
NULL,
hpt37x_timings_50,
hpt37x_timings_66
}
};
static const struct hpt_chip hpt371 = {
"HPT371",
66,
{
hpt37x_timings_33,
NULL,
hpt37x_timings_50,
hpt37x_timings_66
}
};
static const struct hpt_chip hpt372a = {
"HPT372A",
66,
{
hpt37x_timings_33,
NULL,
hpt37x_timings_50,
hpt37x_timings_66
}
};
static const struct hpt_chip hpt374 = {
"HPT374",
48,
{
hpt37x_timings_33,
NULL,
NULL,
NULL
}
};
/**
* hpt37x_find_mode - reset the hpt37x bus
* @ap: ATA port
* @speed: transfer mode
*
* Return the 32bit register programming information for this channel
* that matches the speed provided.
*/
static u32 hpt37x_find_mode(struct ata_port *ap, int speed)
{
struct hpt_clock *clocks = ap->host->private_data;
while (clocks->xfer_speed) {
if (clocks->xfer_speed == speed)
return clocks->timing;
clocks++;
}
BUG();
return 0xffffffffU; /* silence compiler warning */
}
static int hpt_dma_blacklisted(const struct ata_device *dev, char *modestr,
const char * const list[])
{
unsigned char model_num[ATA_ID_PROD_LEN + 1];
int i = 0;
ata_id_c_string(dev->id, model_num, ATA_ID_PROD, sizeof(model_num));
while (list[i] != NULL) {
if (!strcmp(list[i], model_num)) {
pr_warn("%s is not supported for %s\n",
modestr, list[i]);
return 1;
}
i++;
}
return 0;
}
static const char * const bad_ata33[] = {
"Maxtor 92720U8", "Maxtor 92040U6", "Maxtor 91360U4", "Maxtor 91020U3",
"Maxtor 90845U3", "Maxtor 90650U2",
"Maxtor 91360D8", "Maxtor 91190D7", "Maxtor 91020D6", "Maxtor 90845D5",
"Maxtor 90680D4", "Maxtor 90510D3", "Maxtor 90340D2",
"Maxtor 91152D8", "Maxtor 91008D7", "Maxtor 90845D6", "Maxtor 90840D6",
"Maxtor 90720D5", "Maxtor 90648D5", "Maxtor 90576D4",
"Maxtor 90510D4",
"Maxtor 90432D3", "Maxtor 90288D2", "Maxtor 90256D2",
"Maxtor 91000D8", "Maxtor 90910D8", "Maxtor 90875D7", "Maxtor 90840D7",
"Maxtor 90750D6", "Maxtor 90625D5", "Maxtor 90500D4",
"Maxtor 91728D8", "Maxtor 91512D7", "Maxtor 91303D6", "Maxtor 91080D5",
"Maxtor 90845D4", "Maxtor 90680D4", "Maxtor 90648D3", "Maxtor 90432D2",
NULL
};
static const char * const bad_ata100_5[] = {
"IBM-DTLA-307075",
"IBM-DTLA-307060",
"IBM-DTLA-307045",
"IBM-DTLA-307030",
"IBM-DTLA-307020",
"IBM-DTLA-307015",
"IBM-DTLA-305040",
"IBM-DTLA-305030",
"IBM-DTLA-305020",
"IC35L010AVER07-0",
"IC35L020AVER07-0",
"IC35L030AVER07-0",
"IC35L040AVER07-0",
"IC35L060AVER07-0",
"WDC AC310200R",
NULL
};
/**
* hpt370_filter - mode selection filter
* @adev: ATA device
*
* Block UDMA on devices that cause trouble with this controller.
*/
static unsigned long hpt370_filter(struct ata_device *adev, unsigned long mask)
{
if (adev->class == ATA_DEV_ATA) {
if (hpt_dma_blacklisted(adev, "UDMA", bad_ata33))
mask &= ~ATA_MASK_UDMA;
if (hpt_dma_blacklisted(adev, "UDMA100", bad_ata100_5))
mask &= ~(0xE0 << ATA_SHIFT_UDMA);
}
return mask;
}
/**
* hpt370a_filter - mode selection filter
* @adev: ATA device
*
* Block UDMA on devices that cause trouble with this controller.
*/
static unsigned long hpt370a_filter(struct ata_device *adev, unsigned long mask)
{
if (adev->class == ATA_DEV_ATA) {
if (hpt_dma_blacklisted(adev, "UDMA100", bad_ata100_5))
mask &= ~(0xE0 << ATA_SHIFT_UDMA);
}
return mask;
}
/**
* hpt372_filter - mode selection filter
* @adev: ATA device
* @mask: mode mask
*
* The Marvell bridge chips used on the HighPoint SATA cards do not seem
* to support the UltraDMA modes 1, 2, and 3 as well as any MWDMA modes...
*/
static unsigned long hpt372_filter(struct ata_device *adev, unsigned long mask)
{
if (ata_id_is_sata(adev->id))
mask &= ~((0xE << ATA_SHIFT_UDMA) | ATA_MASK_MWDMA);
return mask;
}
/**
* hpt37x_cable_detect - Detect the cable type
* @ap: ATA port to detect on
*
* Return the cable type attached to this port
*/
static int hpt37x_cable_detect(struct ata_port *ap)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
u8 scr2, ata66;
pci_read_config_byte(pdev, 0x5B, &scr2);
pci_write_config_byte(pdev, 0x5B, scr2 & ~0x01);
udelay(10); /* debounce */
/* Cable register now active */
pci_read_config_byte(pdev, 0x5A, &ata66);
/* Restore state */
pci_write_config_byte(pdev, 0x5B, scr2);
if (ata66 & (2 >> ap->port_no))
return ATA_CBL_PATA40;
else
return ATA_CBL_PATA80;
}
/**
* hpt374_fn1_cable_detect - Detect the cable type
* @ap: ATA port to detect on
*
* Return the cable type attached to this port
*/
static int hpt374_fn1_cable_detect(struct ata_port *ap)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
unsigned int mcrbase = 0x50 + 4 * ap->port_no;
u16 mcr3;
u8 ata66;
/* Do the extra channel work */
pci_read_config_word(pdev, mcrbase + 2, &mcr3);
/* Set bit 15 of 0x52 to enable TCBLID as input */
pci_write_config_word(pdev, mcrbase + 2, mcr3 | 0x8000);
pci_read_config_byte(pdev, 0x5A, &ata66);
/* Reset TCBLID/FCBLID to output */
pci_write_config_word(pdev, mcrbase + 2, mcr3);
if (ata66 & (2 >> ap->port_no))
return ATA_CBL_PATA40;
else
return ATA_CBL_PATA80;
}
/**
* hpt37x_pre_reset - reset the hpt37x bus
* @link: ATA link to reset
* @deadline: deadline jiffies for the operation
*
* Perform the initial reset handling for the HPT37x.
*/
static int hpt37x_pre_reset(struct ata_link *link, unsigned long deadline)
{
struct ata_port *ap = link->ap;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
static const struct pci_bits hpt37x_enable_bits[] = {
{ 0x50, 1, 0x04, 0x04 },
{ 0x54, 1, 0x04, 0x04 }
};
if (!pci_test_config_bits(pdev, &hpt37x_enable_bits[ap->port_no]))
return -ENOENT;
/* Reset the state machine */
pci_write_config_byte(pdev, 0x50 + 4 * ap->port_no, 0x37);
udelay(100);
return ata_sff_prereset(link, deadline);
}
static void hpt370_set_mode(struct ata_port *ap, struct ata_device *adev,
u8 mode)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
u32 addr1, addr2;
u32 reg, timing, mask;
u8 fast;
addr1 = 0x40 + 4 * (adev->devno + 2 * ap->port_no);
addr2 = 0x51 + 4 * ap->port_no;
/* Fast interrupt prediction disable, hold off interrupt disable */
pci_read_config_byte(pdev, addr2, &fast);
fast &= ~0x02;
fast |= 0x01;
pci_write_config_byte(pdev, addr2, fast);
/* Determine timing mask and find matching mode entry */
if (mode < XFER_MW_DMA_0)
mask = 0xcfc3ffff;
else if (mode < XFER_UDMA_0)
mask = 0x31c001ff;
else
mask = 0x303c0000;
timing = hpt37x_find_mode(ap, mode);
pci_read_config_dword(pdev, addr1, ®);
reg = (reg & ~mask) | (timing & mask);
pci_write_config_dword(pdev, addr1, reg);
}
/**
* hpt370_set_piomode - PIO setup
* @ap: ATA interface
* @adev: device on the interface
*
* Perform PIO mode setup.
*/
static void hpt370_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
hpt370_set_mode(ap, adev, adev->pio_mode);
}
/**
* hpt370_set_dmamode - DMA timing setup
* @ap: ATA interface
* @adev: Device being configured
*
* Set up the channel for MWDMA or UDMA modes.
*/
static void hpt370_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
hpt370_set_mode(ap, adev, adev->dma_mode);
}
/**
* hpt370_bmdma_end - DMA engine stop
* @qc: ATA command
*
* Work around the HPT370 DMA engine.
*/
static void hpt370_bmdma_stop(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
void __iomem *bmdma = ap->ioaddr.bmdma_addr;
u8 dma_stat = ioread8(bmdma + ATA_DMA_STATUS);
u8 dma_cmd;
if (dma_stat & ATA_DMA_ACTIVE) {
udelay(20);
dma_stat = ioread8(bmdma + ATA_DMA_STATUS);
}
if (dma_stat & ATA_DMA_ACTIVE) {
/* Clear the engine */
pci_write_config_byte(pdev, 0x50 + 4 * ap->port_no, 0x37);
udelay(10);
/* Stop DMA */
dma_cmd = ioread8(bmdma + ATA_DMA_CMD);
iowrite8(dma_cmd & ~ATA_DMA_START, bmdma + ATA_DMA_CMD);
/* Clear Error */
dma_stat = ioread8(bmdma + ATA_DMA_STATUS);
iowrite8(dma_stat | ATA_DMA_INTR | ATA_DMA_ERR,
bmdma + ATA_DMA_STATUS);
/* Clear the engine */
pci_write_config_byte(pdev, 0x50 + 4 * ap->port_no, 0x37);
udelay(10);
}
ata_bmdma_stop(qc);
}
static void hpt372_set_mode(struct ata_port *ap, struct ata_device *adev,
u8 mode)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
u32 addr1, addr2;
u32 reg, timing, mask;
u8 fast;
addr1 = 0x40 + 4 * (adev->devno + 2 * ap->port_no);
addr2 = 0x51 + 4 * ap->port_no;
/* Fast interrupt prediction disable, hold off interrupt disable */
pci_read_config_byte(pdev, addr2, &fast);
fast &= ~0x07;
pci_write_config_byte(pdev, addr2, fast);
/* Determine timing mask and find matching mode entry */
if (mode < XFER_MW_DMA_0)
mask = 0xcfc3ffff;
else if (mode < XFER_UDMA_0)
mask = 0x31c001ff;
else
mask = 0x303c0000;
timing = hpt37x_find_mode(ap, mode);
pci_read_config_dword(pdev, addr1, ®);
reg = (reg & ~mask) | (timing & mask);
pci_write_config_dword(pdev, addr1, reg);
}
/**
* hpt372_set_piomode - PIO setup
* @ap: ATA interface
* @adev: device on the interface
*
* Perform PIO mode setup.
*/
static void hpt372_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
hpt372_set_mode(ap, adev, adev->pio_mode);
}
/**
* hpt372_set_dmamode - DMA timing setup
* @ap: ATA interface
* @adev: Device being configured
*
* Set up the channel for MWDMA or UDMA modes.
*/
static void hpt372_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
hpt372_set_mode(ap, adev, adev->dma_mode);
}
/**
* hpt37x_bmdma_end - DMA engine stop
* @qc: ATA command
*
* Clean up after the HPT372 and later DMA engine
*/
static void hpt37x_bmdma_stop(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
int mscreg = 0x50 + 4 * ap->port_no;
u8 bwsr_stat, msc_stat;
pci_read_config_byte(pdev, 0x6A, &bwsr_stat);
pci_read_config_byte(pdev, mscreg, &msc_stat);
if (bwsr_stat & (1 << ap->port_no))
pci_write_config_byte(pdev, mscreg, msc_stat | 0x30);
ata_bmdma_stop(qc);
}
static struct scsi_host_template hpt37x_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
/*
* Configuration for HPT370
*/
static struct ata_port_operations hpt370_port_ops = {
.inherits = &ata_bmdma_port_ops,
.bmdma_stop = hpt370_bmdma_stop,
.mode_filter = hpt370_filter,
.cable_detect = hpt37x_cable_detect,
.set_piomode = hpt370_set_piomode,
.set_dmamode = hpt370_set_dmamode,
.prereset = hpt37x_pre_reset,
};
/*
* Configuration for HPT370A. Close to 370 but less filters
*/
static struct ata_port_operations hpt370a_port_ops = {
.inherits = &hpt370_port_ops,
.mode_filter = hpt370a_filter,
};
/*
* Configuration for HPT371 and HPT302. Slightly different PIO and DMA
* mode setting functionality.
*/
static struct ata_port_operations hpt302_port_ops = {
.inherits = &ata_bmdma_port_ops,
.bmdma_stop = hpt37x_bmdma_stop,
.cable_detect = hpt37x_cable_detect,
.set_piomode = hpt372_set_piomode,
.set_dmamode = hpt372_set_dmamode,
.prereset = hpt37x_pre_reset,
};
/*
* Configuration for HPT372. Mode setting works like 371 and 302
* but we have a mode filter.
*/
static struct ata_port_operations hpt372_port_ops = {
.inherits = &hpt302_port_ops,
.mode_filter = hpt372_filter,
};
/*
* Configuration for HPT374. Mode setting and filtering works like 372
* but we have a different cable detection procedure for function 1.
*/
static struct ata_port_operations hpt374_fn1_port_ops = {
.inherits = &hpt372_port_ops,
.cable_detect = hpt374_fn1_cable_detect,
};
/**
* hpt37x_clock_slot - Turn timing to PC clock entry
* @freq: Reported frequency timing
* @base: Base timing
*
* Turn the timing data intoa clock slot (0 for 33, 1 for 40, 2 for 50
* and 3 for 66Mhz)
*/
static int hpt37x_clock_slot(unsigned int freq, unsigned int base)
{
unsigned int f = (base * freq) / 192; /* Mhz */
if (f < 40)
return 0; /* 33Mhz slot */
if (f < 45)
return 1; /* 40Mhz slot */
if (f < 55)
return 2; /* 50Mhz slot */
return 3; /* 60Mhz slot */
}
/**
* hpt37x_calibrate_dpll - Calibrate the DPLL loop
* @dev: PCI device
*
* Perform a calibration cycle on the HPT37x DPLL. Returns 1 if this
* succeeds
*/
static int hpt37x_calibrate_dpll(struct pci_dev *dev)
{
u8 reg5b;
u32 reg5c;
int tries;
for (tries = 0; tries < 0x5000; tries++) {
udelay(50);
pci_read_config_byte(dev, 0x5b, ®5b);
if (reg5b & 0x80) {
/* See if it stays set */
for (tries = 0; tries < 0x1000; tries++) {
pci_read_config_byte(dev, 0x5b, ®5b);
/* Failed ? */
if ((reg5b & 0x80) == 0)
return 0;
}
/* Turn off tuning, we have the DPLL set */
pci_read_config_dword(dev, 0x5c, ®5c);
pci_write_config_dword(dev, 0x5c, reg5c & ~0x100);
return 1;
}
}
/* Never went stable */
return 0;
}
static u32 hpt374_read_freq(struct pci_dev *pdev)
{
u32 freq;
unsigned long io_base = pci_resource_start(pdev, 4);
if (PCI_FUNC(pdev->devfn) & 1) {
struct pci_dev *pdev_0;
pdev_0 = pci_get_slot(pdev->bus, pdev->devfn - 1);
/* Someone hot plugged the controller on us ? */
if (pdev_0 == NULL)
return 0;
io_base = pci_resource_start(pdev_0, 4);
freq = inl(io_base + 0x90);
pci_dev_put(pdev_0);
} else
freq = inl(io_base + 0x90);
return freq;
}
/**
* hpt37x_init_one - Initialise an HPT37X/302
* @dev: PCI device
* @id: Entry in match table
*
* Initialise an HPT37x device. There are some interesting complications
* here. Firstly the chip may report 366 and be one of several variants.
* Secondly all the timings depend on the clock for the chip which we must
* detect and look up
*
* This is the known chip mappings. It may be missing a couple of later
* releases.
*
* Chip version PCI Rev Notes
* HPT366 4 (HPT366) 0 Other driver
* HPT366 4 (HPT366) 1 Other driver
* HPT368 4 (HPT366) 2 Other driver
* HPT370 4 (HPT366) 3 UDMA100
* HPT370A 4 (HPT366) 4 UDMA100
* HPT372 4 (HPT366) 5 UDMA133 (1)
* HPT372N 4 (HPT366) 6 Other driver
* HPT372A 5 (HPT372) 1 UDMA133 (1)
* HPT372N 5 (HPT372) 2 Other driver
* HPT302 6 (HPT302) 1 UDMA133
* HPT302N 6 (HPT302) 2 Other driver
* HPT371 7 (HPT371) * UDMA133
* HPT374 8 (HPT374) * UDMA133 4 channel
* HPT372N 9 (HPT372N) * Other driver
*
* (1) UDMA133 support depends on the bus clock
*/
static int hpt37x_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
/* HPT370 - UDMA100 */
static const struct ata_port_info info_hpt370 = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &hpt370_port_ops
};
/* HPT370A - UDMA100 */
static const struct ata_port_info info_hpt370a = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &hpt370a_port_ops
};
/* HPT370 - UDMA66 */
static const struct ata_port_info info_hpt370_33 = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA4,
.port_ops = &hpt370_port_ops
};
/* HPT370A - UDMA66 */
static const struct ata_port_info info_hpt370a_33 = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA4,
.port_ops = &hpt370a_port_ops
};
/* HPT372 - UDMA133 */
static const struct ata_port_info info_hpt372 = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA6,
.port_ops = &hpt372_port_ops
};
/* HPT371, 302 - UDMA133 */
static const struct ata_port_info info_hpt302 = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA6,
.port_ops = &hpt302_port_ops
};
/* HPT374 - UDMA100, function 1 uses different cable_detect method */
static const struct ata_port_info info_hpt374_fn0 = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &hpt372_port_ops
};
static const struct ata_port_info info_hpt374_fn1 = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &hpt374_fn1_port_ops
};
static const int MHz[4] = { 33, 40, 50, 66 };
void *private_data = NULL;
const struct ata_port_info *ppi[] = { NULL, NULL };
u8 rev = dev->revision;
u8 irqmask;
u8 mcr1;
u32 freq;
int prefer_dpll = 1;
unsigned long iobase = pci_resource_start(dev, 4);
const struct hpt_chip *chip_table;
int clock_slot;
int rc;
rc = pcim_enable_device(dev);
if (rc)
return rc;
switch (dev->device) {
case PCI_DEVICE_ID_TTI_HPT366:
/* May be a later chip in disguise. Check */
/* Older chips are in the HPT366 driver. Ignore them */
if (rev < 3)
return -ENODEV;
/* N series chips have their own driver. Ignore */
if (rev == 6)
return -ENODEV;
switch (rev) {
case 3:
ppi[0] = &info_hpt370;
chip_table = &hpt370;
prefer_dpll = 0;
break;
case 4:
ppi[0] = &info_hpt370a;
chip_table = &hpt370a;
prefer_dpll = 0;
break;
case 5:
ppi[0] = &info_hpt372;
chip_table = &hpt372;
break;
default:
pr_err("Unknown HPT366 subtype, please report (%d)\n",
rev);
return -ENODEV;
}
break;
case PCI_DEVICE_ID_TTI_HPT372:
/* 372N if rev >= 2 */
if (rev >= 2)
return -ENODEV;
ppi[0] = &info_hpt372;
chip_table = &hpt372a;
break;
case PCI_DEVICE_ID_TTI_HPT302:
/* 302N if rev > 1 */
if (rev > 1)
return -ENODEV;
ppi[0] = &info_hpt302;
/* Check this */
chip_table = &hpt302;
break;
case PCI_DEVICE_ID_TTI_HPT371:
if (rev > 1)
return -ENODEV;
ppi[0] = &info_hpt302;
chip_table = &hpt371;
/*
* Single channel device, master is not present but the BIOS
* (or us for non x86) must mark it absent
*/
pci_read_config_byte(dev, 0x50, &mcr1);
mcr1 &= ~0x04;
pci_write_config_byte(dev, 0x50, mcr1);
break;
case PCI_DEVICE_ID_TTI_HPT374:
chip_table = &hpt374;
if (!(PCI_FUNC(dev->devfn) & 1))
*ppi = &info_hpt374_fn0;
else
*ppi = &info_hpt374_fn1;
break;
default:
pr_err("PCI table is bogus, please report (%d)\n", dev->device);
return -ENODEV;
}
/* Ok so this is a chip we support */
pci_write_config_byte(dev, PCI_CACHE_LINE_SIZE, (L1_CACHE_BYTES / 4));
pci_write_config_byte(dev, PCI_LATENCY_TIMER, 0x78);
pci_write_config_byte(dev, PCI_MIN_GNT, 0x08);
pci_write_config_byte(dev, PCI_MAX_LAT, 0x08);
pci_read_config_byte(dev, 0x5A, &irqmask);
irqmask &= ~0x10;
pci_write_config_byte(dev, 0x5a, irqmask);
/*
* default to pci clock. make sure MA15/16 are set to output
* to prevent drives having problems with 40-pin cables. Needed
* for some drives such as IBM-DTLA which will not enter ready
* state on reset when PDIAG is a input.
*/
pci_write_config_byte(dev, 0x5b, 0x23);
/*
* HighPoint does this for HPT372A.
* NOTE: This register is only writeable via I/O space.
*/
if (chip_table == &hpt372a)
outb(0x0e, iobase + 0x9c);
/*
* Some devices do not let this value be accessed via PCI space
* according to the old driver. In addition we must use the value
* from FN 0 on the HPT374.
*/
if (chip_table == &hpt374) {
freq = hpt374_read_freq(dev);
if (freq == 0)
return -ENODEV;
} else
freq = inl(iobase + 0x90);
if ((freq >> 12) != 0xABCDE) {
int i;
u8 sr;
u32 total = 0;
pr_warn("BIOS has not set timing clocks\n");
/* This is the process the HPT371 BIOS is reported to use */
for (i = 0; i < 128; i++) {
pci_read_config_byte(dev, 0x78, &sr);
total += sr & 0x1FF;
udelay(15);
}
freq = total / 128;
}
freq &= 0x1FF;
/*
* Turn the frequency check into a band and then find a timing
* table to match it.
*/
clock_slot = hpt37x_clock_slot(freq, chip_table->base);
if (chip_table->clocks[clock_slot] == NULL || prefer_dpll) {
/*
* We need to try PLL mode instead
*
* For non UDMA133 capable devices we should
* use a 50MHz DPLL by choice
*/
unsigned int f_low, f_high;
int dpll, adjust;
/* Compute DPLL */
dpll = (ppi[0]->udma_mask & 0xC0) ? 3 : 2;
f_low = (MHz[clock_slot] * 48) / MHz[dpll];
f_high = f_low + 2;
if (clock_slot > 1)
f_high += 2;
/* Select the DPLL clock. */
pci_write_config_byte(dev, 0x5b, 0x21);
pci_write_config_dword(dev, 0x5C,
(f_high << 16) | f_low | 0x100);
for (adjust = 0; adjust < 8; adjust++) {
if (hpt37x_calibrate_dpll(dev))
break;
/*
* See if it'll settle at a fractionally
* different clock
*/
if (adjust & 1)
f_low -= adjust >> 1;
else
f_high += adjust >> 1;
pci_write_config_dword(dev, 0x5C,
(f_high << 16) | f_low | 0x100);
}
if (adjust == 8) {
pr_err("DPLL did not stabilize!\n");
return -ENODEV;
}
if (dpll == 3)
private_data = (void *)hpt37x_timings_66;
else
private_data = (void *)hpt37x_timings_50;
pr_info("bus clock %dMHz, using %dMHz DPLL\n",
MHz[clock_slot], MHz[dpll]);
} else {
private_data = (void *)chip_table->clocks[clock_slot];
/*
* Perform a final fixup. Note that we will have used the
* DPLL on the HPT372 which means we don't have to worry
* about lack of UDMA133 support on lower clocks
*/
if (clock_slot < 2 && ppi[0] == &info_hpt370)
ppi[0] = &info_hpt370_33;
if (clock_slot < 2 && ppi[0] == &info_hpt370a)
ppi[0] = &info_hpt370a_33;
pr_info("%s using %dMHz bus clock\n",
chip_table->name, MHz[clock_slot]);
}
/* Now kick off ATA set up */
return ata_pci_bmdma_init_one(dev, ppi, &hpt37x_sht, private_data, 0);
}
static const struct pci_device_id hpt37x[] = {
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT366), },
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT371), },
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT372), },
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT374), },
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT302), },
{ },
};
static struct pci_driver hpt37x_pci_driver = {
.name = DRV_NAME,
.id_table = hpt37x,
.probe = hpt37x_init_one,
.remove = ata_pci_remove_one
};
static int __init hpt37x_init(void)
{
return pci_register_driver(&hpt37x_pci_driver);
}
static void __exit hpt37x_exit(void)
{
pci_unregister_driver(&hpt37x_pci_driver);
}
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("low-level driver for the Highpoint HPT37x/30x");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, hpt37x);
MODULE_VERSION(DRV_VERSION);
module_init(hpt37x_init);
module_exit(hpt37x_exit);
| gpl-2.0 |
hendrik42/odroid-linux | drivers/mtd/mtdconcat.c | 8295 | 23586 | /*
* MTD device concatenation layer
*
* Copyright © 2002 Robert Kaiser <rkaiser@sysgo.de>
* Copyright © 2002-2010 David Woodhouse <dwmw2@infradead.org>
*
* NAND support by Christian Gan <cgan@iders.ca>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/backing-dev.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/concat.h>
#include <asm/div64.h>
/*
* Our storage structure:
* Subdev points to an array of pointers to struct mtd_info objects
* which is allocated along with this structure
*
*/
struct mtd_concat {
struct mtd_info mtd;
int num_subdev;
struct mtd_info **subdev;
};
/*
* how to calculate the size required for the above structure,
* including the pointer array subdev points to:
*/
#define SIZEOF_STRUCT_MTD_CONCAT(num_subdev) \
((sizeof(struct mtd_concat) + (num_subdev) * sizeof(struct mtd_info *)))
/*
* Given a pointer to the MTD object in the mtd_concat structure,
* we can retrieve the pointer to that structure with this macro.
*/
#define CONCAT(x) ((struct mtd_concat *)(x))
/*
* MTD methods which look up the relevant subdevice, translate the
* effective address and pass through to the subdevice.
*/
static int
concat_read(struct mtd_info *mtd, loff_t from, size_t len,
size_t * retlen, u_char * buf)
{
struct mtd_concat *concat = CONCAT(mtd);
int ret = 0, err;
int i;
for (i = 0; i < concat->num_subdev; i++) {
struct mtd_info *subdev = concat->subdev[i];
size_t size, retsize;
if (from >= subdev->size) {
/* Not destined for this subdev */
size = 0;
from -= subdev->size;
continue;
}
if (from + len > subdev->size)
/* First part goes into this subdev */
size = subdev->size - from;
else
/* Entire transaction goes into this subdev */
size = len;
err = mtd_read(subdev, from, size, &retsize, buf);
/* Save information about bitflips! */
if (unlikely(err)) {
if (mtd_is_eccerr(err)) {
mtd->ecc_stats.failed++;
ret = err;
} else if (mtd_is_bitflip(err)) {
mtd->ecc_stats.corrected++;
/* Do not overwrite -EBADMSG !! */
if (!ret)
ret = err;
} else
return err;
}
*retlen += retsize;
len -= size;
if (len == 0)
return ret;
buf += size;
from = 0;
}
return -EINVAL;
}
static int
concat_write(struct mtd_info *mtd, loff_t to, size_t len,
size_t * retlen, const u_char * buf)
{
struct mtd_concat *concat = CONCAT(mtd);
int err = -EINVAL;
int i;
for (i = 0; i < concat->num_subdev; i++) {
struct mtd_info *subdev = concat->subdev[i];
size_t size, retsize;
if (to >= subdev->size) {
size = 0;
to -= subdev->size;
continue;
}
if (to + len > subdev->size)
size = subdev->size - to;
else
size = len;
err = mtd_write(subdev, to, size, &retsize, buf);
if (err)
break;
*retlen += retsize;
len -= size;
if (len == 0)
break;
err = -EINVAL;
buf += size;
to = 0;
}
return err;
}
static int
concat_writev(struct mtd_info *mtd, const struct kvec *vecs,
unsigned long count, loff_t to, size_t * retlen)
{
struct mtd_concat *concat = CONCAT(mtd);
struct kvec *vecs_copy;
unsigned long entry_low, entry_high;
size_t total_len = 0;
int i;
int err = -EINVAL;
/* Calculate total length of data */
for (i = 0; i < count; i++)
total_len += vecs[i].iov_len;
/* Check alignment */
if (mtd->writesize > 1) {
uint64_t __to = to;
if (do_div(__to, mtd->writesize) || (total_len % mtd->writesize))
return -EINVAL;
}
/* make a copy of vecs */
vecs_copy = kmemdup(vecs, sizeof(struct kvec) * count, GFP_KERNEL);
if (!vecs_copy)
return -ENOMEM;
entry_low = 0;
for (i = 0; i < concat->num_subdev; i++) {
struct mtd_info *subdev = concat->subdev[i];
size_t size, wsize, retsize, old_iov_len;
if (to >= subdev->size) {
to -= subdev->size;
continue;
}
size = min_t(uint64_t, total_len, subdev->size - to);
wsize = size; /* store for future use */
entry_high = entry_low;
while (entry_high < count) {
if (size <= vecs_copy[entry_high].iov_len)
break;
size -= vecs_copy[entry_high++].iov_len;
}
old_iov_len = vecs_copy[entry_high].iov_len;
vecs_copy[entry_high].iov_len = size;
err = mtd_writev(subdev, &vecs_copy[entry_low],
entry_high - entry_low + 1, to, &retsize);
vecs_copy[entry_high].iov_len = old_iov_len - size;
vecs_copy[entry_high].iov_base += size;
entry_low = entry_high;
if (err)
break;
*retlen += retsize;
total_len -= wsize;
if (total_len == 0)
break;
err = -EINVAL;
to = 0;
}
kfree(vecs_copy);
return err;
}
static int
concat_read_oob(struct mtd_info *mtd, loff_t from, struct mtd_oob_ops *ops)
{
struct mtd_concat *concat = CONCAT(mtd);
struct mtd_oob_ops devops = *ops;
int i, err, ret = 0;
ops->retlen = ops->oobretlen = 0;
for (i = 0; i < concat->num_subdev; i++) {
struct mtd_info *subdev = concat->subdev[i];
if (from >= subdev->size) {
from -= subdev->size;
continue;
}
/* partial read ? */
if (from + devops.len > subdev->size)
devops.len = subdev->size - from;
err = mtd_read_oob(subdev, from, &devops);
ops->retlen += devops.retlen;
ops->oobretlen += devops.oobretlen;
/* Save information about bitflips! */
if (unlikely(err)) {
if (mtd_is_eccerr(err)) {
mtd->ecc_stats.failed++;
ret = err;
} else if (mtd_is_bitflip(err)) {
mtd->ecc_stats.corrected++;
/* Do not overwrite -EBADMSG !! */
if (!ret)
ret = err;
} else
return err;
}
if (devops.datbuf) {
devops.len = ops->len - ops->retlen;
if (!devops.len)
return ret;
devops.datbuf += devops.retlen;
}
if (devops.oobbuf) {
devops.ooblen = ops->ooblen - ops->oobretlen;
if (!devops.ooblen)
return ret;
devops.oobbuf += ops->oobretlen;
}
from = 0;
}
return -EINVAL;
}
static int
concat_write_oob(struct mtd_info *mtd, loff_t to, struct mtd_oob_ops *ops)
{
struct mtd_concat *concat = CONCAT(mtd);
struct mtd_oob_ops devops = *ops;
int i, err;
if (!(mtd->flags & MTD_WRITEABLE))
return -EROFS;
ops->retlen = ops->oobretlen = 0;
for (i = 0; i < concat->num_subdev; i++) {
struct mtd_info *subdev = concat->subdev[i];
if (to >= subdev->size) {
to -= subdev->size;
continue;
}
/* partial write ? */
if (to + devops.len > subdev->size)
devops.len = subdev->size - to;
err = mtd_write_oob(subdev, to, &devops);
ops->retlen += devops.oobretlen;
if (err)
return err;
if (devops.datbuf) {
devops.len = ops->len - ops->retlen;
if (!devops.len)
return 0;
devops.datbuf += devops.retlen;
}
if (devops.oobbuf) {
devops.ooblen = ops->ooblen - ops->oobretlen;
if (!devops.ooblen)
return 0;
devops.oobbuf += devops.oobretlen;
}
to = 0;
}
return -EINVAL;
}
static void concat_erase_callback(struct erase_info *instr)
{
wake_up((wait_queue_head_t *) instr->priv);
}
static int concat_dev_erase(struct mtd_info *mtd, struct erase_info *erase)
{
int err;
wait_queue_head_t waitq;
DECLARE_WAITQUEUE(wait, current);
/*
* This code was stol^H^H^H^Hinspired by mtdchar.c
*/
init_waitqueue_head(&waitq);
erase->mtd = mtd;
erase->callback = concat_erase_callback;
erase->priv = (unsigned long) &waitq;
/*
* FIXME: Allow INTERRUPTIBLE. Which means
* not having the wait_queue head on the stack.
*/
err = mtd_erase(mtd, erase);
if (!err) {
set_current_state(TASK_UNINTERRUPTIBLE);
add_wait_queue(&waitq, &wait);
if (erase->state != MTD_ERASE_DONE
&& erase->state != MTD_ERASE_FAILED)
schedule();
remove_wait_queue(&waitq, &wait);
set_current_state(TASK_RUNNING);
err = (erase->state == MTD_ERASE_FAILED) ? -EIO : 0;
}
return err;
}
static int concat_erase(struct mtd_info *mtd, struct erase_info *instr)
{
struct mtd_concat *concat = CONCAT(mtd);
struct mtd_info *subdev;
int i, err;
uint64_t length, offset = 0;
struct erase_info *erase;
/*
* Check for proper erase block alignment of the to-be-erased area.
* It is easier to do this based on the super device's erase
* region info rather than looking at each particular sub-device
* in turn.
*/
if (!concat->mtd.numeraseregions) {
/* the easy case: device has uniform erase block size */
if (instr->addr & (concat->mtd.erasesize - 1))
return -EINVAL;
if (instr->len & (concat->mtd.erasesize - 1))
return -EINVAL;
} else {
/* device has variable erase size */
struct mtd_erase_region_info *erase_regions =
concat->mtd.eraseregions;
/*
* Find the erase region where the to-be-erased area begins:
*/
for (i = 0; i < concat->mtd.numeraseregions &&
instr->addr >= erase_regions[i].offset; i++) ;
--i;
/*
* Now erase_regions[i] is the region in which the
* to-be-erased area begins. Verify that the starting
* offset is aligned to this region's erase size:
*/
if (i < 0 || instr->addr & (erase_regions[i].erasesize - 1))
return -EINVAL;
/*
* now find the erase region where the to-be-erased area ends:
*/
for (; i < concat->mtd.numeraseregions &&
(instr->addr + instr->len) >= erase_regions[i].offset;
++i) ;
--i;
/*
* check if the ending offset is aligned to this region's erase size
*/
if (i < 0 || ((instr->addr + instr->len) &
(erase_regions[i].erasesize - 1)))
return -EINVAL;
}
/* make a local copy of instr to avoid modifying the caller's struct */
erase = kmalloc(sizeof (struct erase_info), GFP_KERNEL);
if (!erase)
return -ENOMEM;
*erase = *instr;
length = instr->len;
/*
* find the subdevice where the to-be-erased area begins, adjust
* starting offset to be relative to the subdevice start
*/
for (i = 0; i < concat->num_subdev; i++) {
subdev = concat->subdev[i];
if (subdev->size <= erase->addr) {
erase->addr -= subdev->size;
offset += subdev->size;
} else {
break;
}
}
/* must never happen since size limit has been verified above */
BUG_ON(i >= concat->num_subdev);
/* now do the erase: */
err = 0;
for (; length > 0; i++) {
/* loop for all subdevices affected by this request */
subdev = concat->subdev[i]; /* get current subdevice */
/* limit length to subdevice's size: */
if (erase->addr + length > subdev->size)
erase->len = subdev->size - erase->addr;
else
erase->len = length;
length -= erase->len;
if ((err = concat_dev_erase(subdev, erase))) {
/* sanity check: should never happen since
* block alignment has been checked above */
BUG_ON(err == -EINVAL);
if (erase->fail_addr != MTD_FAIL_ADDR_UNKNOWN)
instr->fail_addr = erase->fail_addr + offset;
break;
}
/*
* erase->addr specifies the offset of the area to be
* erased *within the current subdevice*. It can be
* non-zero only the first time through this loop, i.e.
* for the first subdevice where blocks need to be erased.
* All the following erases must begin at the start of the
* current subdevice, i.e. at offset zero.
*/
erase->addr = 0;
offset += subdev->size;
}
instr->state = erase->state;
kfree(erase);
if (err)
return err;
if (instr->callback)
instr->callback(instr);
return 0;
}
static int concat_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
{
struct mtd_concat *concat = CONCAT(mtd);
int i, err = -EINVAL;
for (i = 0; i < concat->num_subdev; i++) {
struct mtd_info *subdev = concat->subdev[i];
uint64_t size;
if (ofs >= subdev->size) {
size = 0;
ofs -= subdev->size;
continue;
}
if (ofs + len > subdev->size)
size = subdev->size - ofs;
else
size = len;
err = mtd_lock(subdev, ofs, size);
if (err)
break;
len -= size;
if (len == 0)
break;
err = -EINVAL;
ofs = 0;
}
return err;
}
static int concat_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
{
struct mtd_concat *concat = CONCAT(mtd);
int i, err = 0;
for (i = 0; i < concat->num_subdev; i++) {
struct mtd_info *subdev = concat->subdev[i];
uint64_t size;
if (ofs >= subdev->size) {
size = 0;
ofs -= subdev->size;
continue;
}
if (ofs + len > subdev->size)
size = subdev->size - ofs;
else
size = len;
err = mtd_unlock(subdev, ofs, size);
if (err)
break;
len -= size;
if (len == 0)
break;
err = -EINVAL;
ofs = 0;
}
return err;
}
static void concat_sync(struct mtd_info *mtd)
{
struct mtd_concat *concat = CONCAT(mtd);
int i;
for (i = 0; i < concat->num_subdev; i++) {
struct mtd_info *subdev = concat->subdev[i];
mtd_sync(subdev);
}
}
static int concat_suspend(struct mtd_info *mtd)
{
struct mtd_concat *concat = CONCAT(mtd);
int i, rc = 0;
for (i = 0; i < concat->num_subdev; i++) {
struct mtd_info *subdev = concat->subdev[i];
if ((rc = mtd_suspend(subdev)) < 0)
return rc;
}
return rc;
}
static void concat_resume(struct mtd_info *mtd)
{
struct mtd_concat *concat = CONCAT(mtd);
int i;
for (i = 0; i < concat->num_subdev; i++) {
struct mtd_info *subdev = concat->subdev[i];
mtd_resume(subdev);
}
}
static int concat_block_isbad(struct mtd_info *mtd, loff_t ofs)
{
struct mtd_concat *concat = CONCAT(mtd);
int i, res = 0;
if (!mtd_can_have_bb(concat->subdev[0]))
return res;
for (i = 0; i < concat->num_subdev; i++) {
struct mtd_info *subdev = concat->subdev[i];
if (ofs >= subdev->size) {
ofs -= subdev->size;
continue;
}
res = mtd_block_isbad(subdev, ofs);
break;
}
return res;
}
static int concat_block_markbad(struct mtd_info *mtd, loff_t ofs)
{
struct mtd_concat *concat = CONCAT(mtd);
int i, err = -EINVAL;
for (i = 0; i < concat->num_subdev; i++) {
struct mtd_info *subdev = concat->subdev[i];
if (ofs >= subdev->size) {
ofs -= subdev->size;
continue;
}
err = mtd_block_markbad(subdev, ofs);
if (!err)
mtd->ecc_stats.badblocks++;
break;
}
return err;
}
/*
* try to support NOMMU mmaps on concatenated devices
* - we don't support subdev spanning as we can't guarantee it'll work
*/
static unsigned long concat_get_unmapped_area(struct mtd_info *mtd,
unsigned long len,
unsigned long offset,
unsigned long flags)
{
struct mtd_concat *concat = CONCAT(mtd);
int i;
for (i = 0; i < concat->num_subdev; i++) {
struct mtd_info *subdev = concat->subdev[i];
if (offset >= subdev->size) {
offset -= subdev->size;
continue;
}
return mtd_get_unmapped_area(subdev, len, offset, flags);
}
return (unsigned long) -ENOSYS;
}
/*
* This function constructs a virtual MTD device by concatenating
* num_devs MTD devices. A pointer to the new device object is
* stored to *new_dev upon success. This function does _not_
* register any devices: this is the caller's responsibility.
*/
struct mtd_info *mtd_concat_create(struct mtd_info *subdev[], /* subdevices to concatenate */
int num_devs, /* number of subdevices */
const char *name)
{ /* name for the new device */
int i;
size_t size;
struct mtd_concat *concat;
uint32_t max_erasesize, curr_erasesize;
int num_erase_region;
int max_writebufsize = 0;
printk(KERN_NOTICE "Concatenating MTD devices:\n");
for (i = 0; i < num_devs; i++)
printk(KERN_NOTICE "(%d): \"%s\"\n", i, subdev[i]->name);
printk(KERN_NOTICE "into device \"%s\"\n", name);
/* allocate the device structure */
size = SIZEOF_STRUCT_MTD_CONCAT(num_devs);
concat = kzalloc(size, GFP_KERNEL);
if (!concat) {
printk
("memory allocation error while creating concatenated device \"%s\"\n",
name);
return NULL;
}
concat->subdev = (struct mtd_info **) (concat + 1);
/*
* Set up the new "super" device's MTD object structure, check for
* incompatibilities between the subdevices.
*/
concat->mtd.type = subdev[0]->type;
concat->mtd.flags = subdev[0]->flags;
concat->mtd.size = subdev[0]->size;
concat->mtd.erasesize = subdev[0]->erasesize;
concat->mtd.writesize = subdev[0]->writesize;
for (i = 0; i < num_devs; i++)
if (max_writebufsize < subdev[i]->writebufsize)
max_writebufsize = subdev[i]->writebufsize;
concat->mtd.writebufsize = max_writebufsize;
concat->mtd.subpage_sft = subdev[0]->subpage_sft;
concat->mtd.oobsize = subdev[0]->oobsize;
concat->mtd.oobavail = subdev[0]->oobavail;
if (subdev[0]->_writev)
concat->mtd._writev = concat_writev;
if (subdev[0]->_read_oob)
concat->mtd._read_oob = concat_read_oob;
if (subdev[0]->_write_oob)
concat->mtd._write_oob = concat_write_oob;
if (subdev[0]->_block_isbad)
concat->mtd._block_isbad = concat_block_isbad;
if (subdev[0]->_block_markbad)
concat->mtd._block_markbad = concat_block_markbad;
concat->mtd.ecc_stats.badblocks = subdev[0]->ecc_stats.badblocks;
concat->mtd.backing_dev_info = subdev[0]->backing_dev_info;
concat->subdev[0] = subdev[0];
for (i = 1; i < num_devs; i++) {
if (concat->mtd.type != subdev[i]->type) {
kfree(concat);
printk("Incompatible device type on \"%s\"\n",
subdev[i]->name);
return NULL;
}
if (concat->mtd.flags != subdev[i]->flags) {
/*
* Expect all flags except MTD_WRITEABLE to be
* equal on all subdevices.
*/
if ((concat->mtd.flags ^ subdev[i]->
flags) & ~MTD_WRITEABLE) {
kfree(concat);
printk("Incompatible device flags on \"%s\"\n",
subdev[i]->name);
return NULL;
} else
/* if writeable attribute differs,
make super device writeable */
concat->mtd.flags |=
subdev[i]->flags & MTD_WRITEABLE;
}
/* only permit direct mapping if the BDIs are all the same
* - copy-mapping is still permitted
*/
if (concat->mtd.backing_dev_info !=
subdev[i]->backing_dev_info)
concat->mtd.backing_dev_info =
&default_backing_dev_info;
concat->mtd.size += subdev[i]->size;
concat->mtd.ecc_stats.badblocks +=
subdev[i]->ecc_stats.badblocks;
if (concat->mtd.writesize != subdev[i]->writesize ||
concat->mtd.subpage_sft != subdev[i]->subpage_sft ||
concat->mtd.oobsize != subdev[i]->oobsize ||
!concat->mtd._read_oob != !subdev[i]->_read_oob ||
!concat->mtd._write_oob != !subdev[i]->_write_oob) {
kfree(concat);
printk("Incompatible OOB or ECC data on \"%s\"\n",
subdev[i]->name);
return NULL;
}
concat->subdev[i] = subdev[i];
}
concat->mtd.ecclayout = subdev[0]->ecclayout;
concat->num_subdev = num_devs;
concat->mtd.name = name;
concat->mtd._erase = concat_erase;
concat->mtd._read = concat_read;
concat->mtd._write = concat_write;
concat->mtd._sync = concat_sync;
concat->mtd._lock = concat_lock;
concat->mtd._unlock = concat_unlock;
concat->mtd._suspend = concat_suspend;
concat->mtd._resume = concat_resume;
concat->mtd._get_unmapped_area = concat_get_unmapped_area;
/*
* Combine the erase block size info of the subdevices:
*
* first, walk the map of the new device and see how
* many changes in erase size we have
*/
max_erasesize = curr_erasesize = subdev[0]->erasesize;
num_erase_region = 1;
for (i = 0; i < num_devs; i++) {
if (subdev[i]->numeraseregions == 0) {
/* current subdevice has uniform erase size */
if (subdev[i]->erasesize != curr_erasesize) {
/* if it differs from the last subdevice's erase size, count it */
++num_erase_region;
curr_erasesize = subdev[i]->erasesize;
if (curr_erasesize > max_erasesize)
max_erasesize = curr_erasesize;
}
} else {
/* current subdevice has variable erase size */
int j;
for (j = 0; j < subdev[i]->numeraseregions; j++) {
/* walk the list of erase regions, count any changes */
if (subdev[i]->eraseregions[j].erasesize !=
curr_erasesize) {
++num_erase_region;
curr_erasesize =
subdev[i]->eraseregions[j].
erasesize;
if (curr_erasesize > max_erasesize)
max_erasesize = curr_erasesize;
}
}
}
}
if (num_erase_region == 1) {
/*
* All subdevices have the same uniform erase size.
* This is easy:
*/
concat->mtd.erasesize = curr_erasesize;
concat->mtd.numeraseregions = 0;
} else {
uint64_t tmp64;
/*
* erase block size varies across the subdevices: allocate
* space to store the data describing the variable erase regions
*/
struct mtd_erase_region_info *erase_region_p;
uint64_t begin, position;
concat->mtd.erasesize = max_erasesize;
concat->mtd.numeraseregions = num_erase_region;
concat->mtd.eraseregions = erase_region_p =
kmalloc(num_erase_region *
sizeof (struct mtd_erase_region_info), GFP_KERNEL);
if (!erase_region_p) {
kfree(concat);
printk
("memory allocation error while creating erase region list"
" for device \"%s\"\n", name);
return NULL;
}
/*
* walk the map of the new device once more and fill in
* in erase region info:
*/
curr_erasesize = subdev[0]->erasesize;
begin = position = 0;
for (i = 0; i < num_devs; i++) {
if (subdev[i]->numeraseregions == 0) {
/* current subdevice has uniform erase size */
if (subdev[i]->erasesize != curr_erasesize) {
/*
* fill in an mtd_erase_region_info structure for the area
* we have walked so far:
*/
erase_region_p->offset = begin;
erase_region_p->erasesize =
curr_erasesize;
tmp64 = position - begin;
do_div(tmp64, curr_erasesize);
erase_region_p->numblocks = tmp64;
begin = position;
curr_erasesize = subdev[i]->erasesize;
++erase_region_p;
}
position += subdev[i]->size;
} else {
/* current subdevice has variable erase size */
int j;
for (j = 0; j < subdev[i]->numeraseregions; j++) {
/* walk the list of erase regions, count any changes */
if (subdev[i]->eraseregions[j].
erasesize != curr_erasesize) {
erase_region_p->offset = begin;
erase_region_p->erasesize =
curr_erasesize;
tmp64 = position - begin;
do_div(tmp64, curr_erasesize);
erase_region_p->numblocks = tmp64;
begin = position;
curr_erasesize =
subdev[i]->eraseregions[j].
erasesize;
++erase_region_p;
}
position +=
subdev[i]->eraseregions[j].
numblocks * (uint64_t)curr_erasesize;
}
}
}
/* Now write the final entry */
erase_region_p->offset = begin;
erase_region_p->erasesize = curr_erasesize;
tmp64 = position - begin;
do_div(tmp64, curr_erasesize);
erase_region_p->numblocks = tmp64;
}
return &concat->mtd;
}
/*
* This function destroys an MTD object obtained from concat_mtd_devs()
*/
void mtd_concat_destroy(struct mtd_info *mtd)
{
struct mtd_concat *concat = CONCAT(mtd);
if (concat->mtd.numeraseregions)
kfree(concat->mtd.eraseregions);
kfree(concat);
}
EXPORT_SYMBOL(mtd_concat_create);
EXPORT_SYMBOL(mtd_concat_destroy);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Robert Kaiser <rkaiser@sysgo.de>");
MODULE_DESCRIPTION("Generic support for concatenating of MTD devices");
| gpl-2.0 |
percy-g2/android_kernel_totoro | common/arch/m68knommu/platform/5307/nettel.c | 8551 | 4096 | /***************************************************************************/
/*
* nettel.c -- startup code support for the NETtel boards
*
* Copyright (C) 2009, Greg Ungerer (gerg@snapgear.com)
*/
/***************************************************************************/
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <asm/coldfire.h>
#include <asm/mcfsim.h>
#include <asm/nettel.h>
/***************************************************************************/
/*
* Define the IO and interrupt resources of the 2 SMC9196 interfaces.
*/
#define NETTEL_SMC0_ADDR 0x30600300
#define NETTEL_SMC0_IRQ 29
#define NETTEL_SMC1_ADDR 0x30600000
#define NETTEL_SMC1_IRQ 27
/*
* We need some access into the SMC9196 registers. Define those registers
* we will need here (including the smc91x.h doesn't seem to give us these
* in a simple form).
*/
#define SMC91xx_BANKSELECT 14
#define SMC91xx_BASEADDR 2
#define SMC91xx_BASEMAC 4
/***************************************************************************/
static struct resource nettel_smc91x_0_resources[] = {
{
.start = NETTEL_SMC0_ADDR,
.end = NETTEL_SMC0_ADDR + 0x20,
.flags = IORESOURCE_MEM,
},
{
.start = NETTEL_SMC0_IRQ,
.end = NETTEL_SMC0_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct resource nettel_smc91x_1_resources[] = {
{
.start = NETTEL_SMC1_ADDR,
.end = NETTEL_SMC1_ADDR + 0x20,
.flags = IORESOURCE_MEM,
},
{
.start = NETTEL_SMC1_IRQ,
.end = NETTEL_SMC1_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device nettel_smc91x[] = {
{
.name = "smc91x",
.id = 0,
.num_resources = ARRAY_SIZE(nettel_smc91x_0_resources),
.resource = nettel_smc91x_0_resources,
},
{
.name = "smc91x",
.id = 1,
.num_resources = ARRAY_SIZE(nettel_smc91x_1_resources),
.resource = nettel_smc91x_1_resources,
},
};
static struct platform_device *nettel_devices[] __initdata = {
&nettel_smc91x[0],
&nettel_smc91x[1],
};
/***************************************************************************/
static u8 nettel_macdefault[] __initdata = {
0x00, 0xd0, 0xcf, 0x00, 0x00, 0x01,
};
/*
* Set flash contained MAC address into SMC9196 core. Make sure the flash
* MAC address is sane, and not an empty flash. If no good use the Moreton
* Bay default MAC address instead.
*/
static void __init nettel_smc91x_setmac(unsigned int ioaddr, unsigned int flashaddr)
{
u16 *macp;
macp = (u16 *) flashaddr;
if ((macp[0] == 0xffff) && (macp[1] == 0xffff) && (macp[2] == 0xffff))
macp = (u16 *) &nettel_macdefault[0];
writew(1, NETTEL_SMC0_ADDR + SMC91xx_BANKSELECT);
writew(macp[0], ioaddr + SMC91xx_BASEMAC);
writew(macp[1], ioaddr + SMC91xx_BASEMAC + 2);
writew(macp[2], ioaddr + SMC91xx_BASEMAC + 4);
}
/***************************************************************************/
/*
* Re-map the address space of at least one of the SMC ethernet
* parts. Both parts power up decoding the same address, so we
* need to move one of them first, before doing anything else.
*/
static void __init nettel_smc91x_init(void)
{
writew(0x00ec, MCF_MBAR + MCFSIM_PADDR);
mcf_setppdata(0, 0x0080);
writew(1, NETTEL_SMC0_ADDR + SMC91xx_BANKSELECT);
writew(0x0067, NETTEL_SMC0_ADDR + SMC91xx_BASEADDR);
mcf_setppdata(0x0080, 0);
/* Set correct chip select timing for SMC9196 accesses */
writew(0x1180, MCF_MBAR + MCFSIM_CSCR3);
/* Set the SMC interrupts to be auto-vectored */
mcf_autovector(NETTEL_SMC0_IRQ);
mcf_autovector(NETTEL_SMC1_IRQ);
/* Set MAC addresses from flash for both interfaces */
nettel_smc91x_setmac(NETTEL_SMC0_ADDR, 0xf0006000);
nettel_smc91x_setmac(NETTEL_SMC1_ADDR, 0xf0006006);
}
/***************************************************************************/
static int __init init_nettel(void)
{
nettel_smc91x_init();
platform_add_devices(nettel_devices, ARRAY_SIZE(nettel_devices));
return 0;
}
arch_initcall(init_nettel);
/***************************************************************************/
| gpl-2.0 |
croniccorey/OnePlus2-Kernel | drivers/net/ethernet/chelsio/cxgb/vsc7326.c | 12391 | 19904 | /* $Date: 2006/04/28 19:20:06 $ $RCSfile: vsc7326.c,v $ $Revision: 1.19 $ */
/* Driver for Vitesse VSC7326 (Schaumburg) MAC */
#include "gmac.h"
#include "elmer0.h"
#include "vsc7326_reg.h"
/* Update fast changing statistics every 15 seconds */
#define STATS_TICK_SECS 15
/* 30 minutes for full statistics update */
#define MAJOR_UPDATE_TICKS (1800 / STATS_TICK_SECS)
#define MAX_MTU 9600
/* The egress WM value 0x01a01fff should be used only when the
* interface is down (MAC port disabled). This is a workaround
* for disabling the T2/MAC flow-control. When the interface is
* enabled, the WM value should be set to 0x014a03F0.
*/
#define WM_DISABLE 0x01a01fff
#define WM_ENABLE 0x014a03F0
struct init_table {
u32 addr;
u32 data;
};
struct _cmac_instance {
u32 index;
u32 ticks;
};
#define INITBLOCK_SLEEP 0xffffffff
static void vsc_read(adapter_t *adapter, u32 addr, u32 *val)
{
u32 status, vlo, vhi;
int i;
spin_lock_bh(&adapter->mac_lock);
t1_tpi_read(adapter, (addr << 2) + 4, &vlo);
i = 0;
do {
t1_tpi_read(adapter, (REG_LOCAL_STATUS << 2) + 4, &vlo);
t1_tpi_read(adapter, REG_LOCAL_STATUS << 2, &vhi);
status = (vhi << 16) | vlo;
i++;
} while (((status & 1) == 0) && (i < 50));
if (i == 50)
pr_err("Invalid tpi read from MAC, breaking loop.\n");
t1_tpi_read(adapter, (REG_LOCAL_DATA << 2) + 4, &vlo);
t1_tpi_read(adapter, REG_LOCAL_DATA << 2, &vhi);
*val = (vhi << 16) | vlo;
/* pr_err("rd: block: 0x%x sublock: 0x%x reg: 0x%x data: 0x%x\n",
((addr&0xe000)>>13), ((addr&0x1e00)>>9),
((addr&0x01fe)>>1), *val); */
spin_unlock_bh(&adapter->mac_lock);
}
static void vsc_write(adapter_t *adapter, u32 addr, u32 data)
{
spin_lock_bh(&adapter->mac_lock);
t1_tpi_write(adapter, (addr << 2) + 4, data & 0xFFFF);
t1_tpi_write(adapter, addr << 2, (data >> 16) & 0xFFFF);
/* pr_err("wr: block: 0x%x sublock: 0x%x reg: 0x%x data: 0x%x\n",
((addr&0xe000)>>13), ((addr&0x1e00)>>9),
((addr&0x01fe)>>1), data); */
spin_unlock_bh(&adapter->mac_lock);
}
/* Hard reset the MAC. This wipes out *all* configuration. */
static void vsc7326_full_reset(adapter_t* adapter)
{
u32 val;
u32 result = 0xffff;
t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~1;
t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(2);
val |= 0x1; /* Enable mac MAC itself */
val |= 0x800; /* Turn off the red LED */
t1_tpi_write(adapter, A_ELMER0_GPO, val);
mdelay(1);
vsc_write(adapter, REG_SW_RESET, 0x80000001);
do {
mdelay(1);
vsc_read(adapter, REG_SW_RESET, &result);
} while (result != 0x0);
}
static struct init_table vsc7326_reset[] = {
{ REG_IFACE_MODE, 0x00000000 },
{ REG_CRC_CFG, 0x00000020 },
{ REG_PLL_CLK_SPEED, 0x00050c00 },
{ REG_PLL_CLK_SPEED, 0x00050c00 },
{ REG_MSCH, 0x00002f14 },
{ REG_SPI4_MISC, 0x00040409 },
{ REG_SPI4_DESKEW, 0x00080000 },
{ REG_SPI4_ING_SETUP2, 0x08080004 },
{ REG_SPI4_ING_SETUP0, 0x04111004 },
{ REG_SPI4_EGR_SETUP0, 0x80001a04 },
{ REG_SPI4_ING_SETUP1, 0x02010000 },
{ REG_AGE_INC(0), 0x00000000 },
{ REG_AGE_INC(1), 0x00000000 },
{ REG_ING_CONTROL, 0x0a200011 },
{ REG_EGR_CONTROL, 0xa0010091 },
};
static struct init_table vsc7326_portinit[4][22] = {
{ /* Port 0 */
/* FIFO setup */
{ REG_DBG(0), 0x000004f0 },
{ REG_HDX(0), 0x00073101 },
{ REG_TEST(0,0), 0x00000022 },
{ REG_TEST(1,0), 0x00000022 },
{ REG_TOP_BOTTOM(0,0), 0x003f0000 },
{ REG_TOP_BOTTOM(1,0), 0x00120000 },
{ REG_HIGH_LOW_WM(0,0), 0x07460757 },
{ REG_HIGH_LOW_WM(1,0), WM_DISABLE },
{ REG_CT_THRHLD(0,0), 0x00000000 },
{ REG_CT_THRHLD(1,0), 0x00000000 },
{ REG_BUCKE(0), 0x0002ffff },
{ REG_BUCKI(0), 0x0002ffff },
{ REG_TEST(0,0), 0x00000020 },
{ REG_TEST(1,0), 0x00000020 },
/* Port config */
{ REG_MAX_LEN(0), 0x00002710 },
{ REG_PORT_FAIL(0), 0x00000002 },
{ REG_NORMALIZER(0), 0x00000a64 },
{ REG_DENORM(0), 0x00000010 },
{ REG_STICK_BIT(0), 0x03baa370 },
{ REG_DEV_SETUP(0), 0x00000083 },
{ REG_DEV_SETUP(0), 0x00000082 },
{ REG_MODE_CFG(0), 0x0200259f },
},
{ /* Port 1 */
/* FIFO setup */
{ REG_DBG(1), 0x000004f0 },
{ REG_HDX(1), 0x00073101 },
{ REG_TEST(0,1), 0x00000022 },
{ REG_TEST(1,1), 0x00000022 },
{ REG_TOP_BOTTOM(0,1), 0x007e003f },
{ REG_TOP_BOTTOM(1,1), 0x00240012 },
{ REG_HIGH_LOW_WM(0,1), 0x07460757 },
{ REG_HIGH_LOW_WM(1,1), WM_DISABLE },
{ REG_CT_THRHLD(0,1), 0x00000000 },
{ REG_CT_THRHLD(1,1), 0x00000000 },
{ REG_BUCKE(1), 0x0002ffff },
{ REG_BUCKI(1), 0x0002ffff },
{ REG_TEST(0,1), 0x00000020 },
{ REG_TEST(1,1), 0x00000020 },
/* Port config */
{ REG_MAX_LEN(1), 0x00002710 },
{ REG_PORT_FAIL(1), 0x00000002 },
{ REG_NORMALIZER(1), 0x00000a64 },
{ REG_DENORM(1), 0x00000010 },
{ REG_STICK_BIT(1), 0x03baa370 },
{ REG_DEV_SETUP(1), 0x00000083 },
{ REG_DEV_SETUP(1), 0x00000082 },
{ REG_MODE_CFG(1), 0x0200259f },
},
{ /* Port 2 */
/* FIFO setup */
{ REG_DBG(2), 0x000004f0 },
{ REG_HDX(2), 0x00073101 },
{ REG_TEST(0,2), 0x00000022 },
{ REG_TEST(1,2), 0x00000022 },
{ REG_TOP_BOTTOM(0,2), 0x00bd007e },
{ REG_TOP_BOTTOM(1,2), 0x00360024 },
{ REG_HIGH_LOW_WM(0,2), 0x07460757 },
{ REG_HIGH_LOW_WM(1,2), WM_DISABLE },
{ REG_CT_THRHLD(0,2), 0x00000000 },
{ REG_CT_THRHLD(1,2), 0x00000000 },
{ REG_BUCKE(2), 0x0002ffff },
{ REG_BUCKI(2), 0x0002ffff },
{ REG_TEST(0,2), 0x00000020 },
{ REG_TEST(1,2), 0x00000020 },
/* Port config */
{ REG_MAX_LEN(2), 0x00002710 },
{ REG_PORT_FAIL(2), 0x00000002 },
{ REG_NORMALIZER(2), 0x00000a64 },
{ REG_DENORM(2), 0x00000010 },
{ REG_STICK_BIT(2), 0x03baa370 },
{ REG_DEV_SETUP(2), 0x00000083 },
{ REG_DEV_SETUP(2), 0x00000082 },
{ REG_MODE_CFG(2), 0x0200259f },
},
{ /* Port 3 */
/* FIFO setup */
{ REG_DBG(3), 0x000004f0 },
{ REG_HDX(3), 0x00073101 },
{ REG_TEST(0,3), 0x00000022 },
{ REG_TEST(1,3), 0x00000022 },
{ REG_TOP_BOTTOM(0,3), 0x00fc00bd },
{ REG_TOP_BOTTOM(1,3), 0x00480036 },
{ REG_HIGH_LOW_WM(0,3), 0x07460757 },
{ REG_HIGH_LOW_WM(1,3), WM_DISABLE },
{ REG_CT_THRHLD(0,3), 0x00000000 },
{ REG_CT_THRHLD(1,3), 0x00000000 },
{ REG_BUCKE(3), 0x0002ffff },
{ REG_BUCKI(3), 0x0002ffff },
{ REG_TEST(0,3), 0x00000020 },
{ REG_TEST(1,3), 0x00000020 },
/* Port config */
{ REG_MAX_LEN(3), 0x00002710 },
{ REG_PORT_FAIL(3), 0x00000002 },
{ REG_NORMALIZER(3), 0x00000a64 },
{ REG_DENORM(3), 0x00000010 },
{ REG_STICK_BIT(3), 0x03baa370 },
{ REG_DEV_SETUP(3), 0x00000083 },
{ REG_DEV_SETUP(3), 0x00000082 },
{ REG_MODE_CFG(3), 0x0200259f },
},
};
static void run_table(adapter_t *adapter, struct init_table *ib, int len)
{
int i;
for (i = 0; i < len; i++) {
if (ib[i].addr == INITBLOCK_SLEEP) {
udelay( ib[i].data );
pr_err("sleep %d us\n",ib[i].data);
} else
vsc_write( adapter, ib[i].addr, ib[i].data );
}
}
static int bist_rd(adapter_t *adapter, int moduleid, int address)
{
int data = 0;
u32 result = 0;
if ((address != 0x0) &&
(address != 0x1) &&
(address != 0x2) &&
(address != 0xd) &&
(address != 0xe))
pr_err("No bist address: 0x%x\n", address);
data = ((0x00 << 24) | ((address & 0xff) << 16) | (0x00 << 8) |
((moduleid & 0xff) << 0));
vsc_write(adapter, REG_RAM_BIST_CMD, data);
udelay(10);
vsc_read(adapter, REG_RAM_BIST_RESULT, &result);
if ((result & (1 << 9)) != 0x0)
pr_err("Still in bist read: 0x%x\n", result);
else if ((result & (1 << 8)) != 0x0)
pr_err("bist read error: 0x%x\n", result);
return result & 0xff;
}
static int bist_wr(adapter_t *adapter, int moduleid, int address, int value)
{
int data = 0;
u32 result = 0;
if ((address != 0x0) &&
(address != 0x1) &&
(address != 0x2) &&
(address != 0xd) &&
(address != 0xe))
pr_err("No bist address: 0x%x\n", address);
if (value > 255)
pr_err("Suspicious write out of range value: 0x%x\n", value);
data = ((0x01 << 24) | ((address & 0xff) << 16) | (value << 8) |
((moduleid & 0xff) << 0));
vsc_write(adapter, REG_RAM_BIST_CMD, data);
udelay(5);
vsc_read(adapter, REG_RAM_BIST_CMD, &result);
if ((result & (1 << 27)) != 0x0)
pr_err("Still in bist write: 0x%x\n", result);
else if ((result & (1 << 26)) != 0x0)
pr_err("bist write error: 0x%x\n", result);
return 0;
}
static int run_bist(adapter_t *adapter, int moduleid)
{
/*run bist*/
(void) bist_wr(adapter,moduleid, 0x00, 0x02);
(void) bist_wr(adapter,moduleid, 0x01, 0x01);
return 0;
}
static int check_bist(adapter_t *adapter, int moduleid)
{
int result=0;
int column=0;
/*check bist*/
result = bist_rd(adapter,moduleid, 0x02);
column = ((bist_rd(adapter,moduleid, 0x0e)<<8) +
(bist_rd(adapter,moduleid, 0x0d)));
if ((result & 3) != 0x3)
pr_err("Result: 0x%x BIST error in ram %d, column: 0x%04x\n",
result, moduleid, column);
return 0;
}
static int enable_mem(adapter_t *adapter, int moduleid)
{
/*enable mem*/
(void) bist_wr(adapter,moduleid, 0x00, 0x00);
return 0;
}
static int run_bist_all(adapter_t *adapter)
{
int port = 0;
u32 val = 0;
vsc_write(adapter, REG_MEM_BIST, 0x5);
vsc_read(adapter, REG_MEM_BIST, &val);
for (port = 0; port < 12; port++)
vsc_write(adapter, REG_DEV_SETUP(port), 0x0);
udelay(300);
vsc_write(adapter, REG_SPI4_MISC, 0x00040409);
udelay(300);
(void) run_bist(adapter,13);
(void) run_bist(adapter,14);
(void) run_bist(adapter,20);
(void) run_bist(adapter,21);
mdelay(200);
(void) check_bist(adapter,13);
(void) check_bist(adapter,14);
(void) check_bist(adapter,20);
(void) check_bist(adapter,21);
udelay(100);
(void) enable_mem(adapter,13);
(void) enable_mem(adapter,14);
(void) enable_mem(adapter,20);
(void) enable_mem(adapter,21);
udelay(300);
vsc_write(adapter, REG_SPI4_MISC, 0x60040400);
udelay(300);
for (port = 0; port < 12; port++)
vsc_write(adapter, REG_DEV_SETUP(port), 0x1);
udelay(300);
vsc_write(adapter, REG_MEM_BIST, 0x0);
mdelay(10);
return 0;
}
static int mac_intr_handler(struct cmac *mac)
{
return 0;
}
static int mac_intr_enable(struct cmac *mac)
{
return 0;
}
static int mac_intr_disable(struct cmac *mac)
{
return 0;
}
static int mac_intr_clear(struct cmac *mac)
{
return 0;
}
/* Expect MAC address to be in network byte order. */
static int mac_set_address(struct cmac* mac, u8 addr[6])
{
u32 val;
int port = mac->instance->index;
vsc_write(mac->adapter, REG_MAC_LOW_ADDR(port),
(addr[3] << 16) | (addr[4] << 8) | addr[5]);
vsc_write(mac->adapter, REG_MAC_HIGH_ADDR(port),
(addr[0] << 16) | (addr[1] << 8) | addr[2]);
vsc_read(mac->adapter, REG_ING_FFILT_UM_EN, &val);
val &= ~0xf0000000;
vsc_write(mac->adapter, REG_ING_FFILT_UM_EN, val | (port << 28));
vsc_write(mac->adapter, REG_ING_FFILT_MASK0,
0xffff0000 | (addr[4] << 8) | addr[5]);
vsc_write(mac->adapter, REG_ING_FFILT_MASK1,
0xffff0000 | (addr[2] << 8) | addr[3]);
vsc_write(mac->adapter, REG_ING_FFILT_MASK2,
0xffff0000 | (addr[0] << 8) | addr[1]);
return 0;
}
static int mac_get_address(struct cmac *mac, u8 addr[6])
{
u32 addr_lo, addr_hi;
int port = mac->instance->index;
vsc_read(mac->adapter, REG_MAC_LOW_ADDR(port), &addr_lo);
vsc_read(mac->adapter, REG_MAC_HIGH_ADDR(port), &addr_hi);
addr[0] = (u8) (addr_hi >> 16);
addr[1] = (u8) (addr_hi >> 8);
addr[2] = (u8) addr_hi;
addr[3] = (u8) (addr_lo >> 16);
addr[4] = (u8) (addr_lo >> 8);
addr[5] = (u8) addr_lo;
return 0;
}
/* This is intended to reset a port, not the whole MAC */
static int mac_reset(struct cmac *mac)
{
int index = mac->instance->index;
run_table(mac->adapter, vsc7326_portinit[index],
ARRAY_SIZE(vsc7326_portinit[index]));
return 0;
}
static int mac_set_rx_mode(struct cmac *mac, struct t1_rx_mode *rm)
{
u32 v;
int port = mac->instance->index;
vsc_read(mac->adapter, REG_ING_FFILT_UM_EN, &v);
v |= 1 << 12;
if (t1_rx_mode_promisc(rm))
v &= ~(1 << (port + 16));
else
v |= 1 << (port + 16);
vsc_write(mac->adapter, REG_ING_FFILT_UM_EN, v);
return 0;
}
static int mac_set_mtu(struct cmac *mac, int mtu)
{
int port = mac->instance->index;
if (mtu > MAX_MTU)
return -EINVAL;
/* max_len includes header and FCS */
vsc_write(mac->adapter, REG_MAX_LEN(port), mtu + 14 + 4);
return 0;
}
static int mac_set_speed_duplex_fc(struct cmac *mac, int speed, int duplex,
int fc)
{
u32 v;
int enable, port = mac->instance->index;
if (speed >= 0 && speed != SPEED_10 && speed != SPEED_100 &&
speed != SPEED_1000)
return -1;
if (duplex > 0 && duplex != DUPLEX_FULL)
return -1;
if (speed >= 0) {
vsc_read(mac->adapter, REG_MODE_CFG(port), &v);
enable = v & 3; /* save tx/rx enables */
v &= ~0xf;
v |= 4; /* full duplex */
if (speed == SPEED_1000)
v |= 8; /* GigE */
enable |= v;
vsc_write(mac->adapter, REG_MODE_CFG(port), v);
if (speed == SPEED_1000)
v = 0x82;
else if (speed == SPEED_100)
v = 0x84;
else /* SPEED_10 */
v = 0x86;
vsc_write(mac->adapter, REG_DEV_SETUP(port), v | 1); /* reset */
vsc_write(mac->adapter, REG_DEV_SETUP(port), v);
vsc_read(mac->adapter, REG_DBG(port), &v);
v &= ~0xff00;
if (speed == SPEED_1000)
v |= 0x400;
else if (speed == SPEED_100)
v |= 0x2000;
else /* SPEED_10 */
v |= 0xff00;
vsc_write(mac->adapter, REG_DBG(port), v);
vsc_write(mac->adapter, REG_TX_IFG(port),
speed == SPEED_1000 ? 5 : 0x11);
if (duplex == DUPLEX_HALF)
enable = 0x0; /* 100 or 10 */
else if (speed == SPEED_1000)
enable = 0xc;
else /* SPEED_100 or 10 */
enable = 0x4;
enable |= 0x9 << 10; /* IFG1 */
enable |= 0x6 << 6; /* IFG2 */
enable |= 0x1 << 4; /* VLAN */
enable |= 0x3; /* RX/TX EN */
vsc_write(mac->adapter, REG_MODE_CFG(port), enable);
}
vsc_read(mac->adapter, REG_PAUSE_CFG(port), &v);
v &= 0xfff0ffff;
v |= 0x20000; /* xon/xoff */
if (fc & PAUSE_RX)
v |= 0x40000;
if (fc & PAUSE_TX)
v |= 0x80000;
if (fc == (PAUSE_RX | PAUSE_TX))
v |= 0x10000;
vsc_write(mac->adapter, REG_PAUSE_CFG(port), v);
return 0;
}
static int mac_enable(struct cmac *mac, int which)
{
u32 val;
int port = mac->instance->index;
/* Write the correct WM value when the port is enabled. */
vsc_write(mac->adapter, REG_HIGH_LOW_WM(1,port), WM_ENABLE);
vsc_read(mac->adapter, REG_MODE_CFG(port), &val);
if (which & MAC_DIRECTION_RX)
val |= 0x2;
if (which & MAC_DIRECTION_TX)
val |= 1;
vsc_write(mac->adapter, REG_MODE_CFG(port), val);
return 0;
}
static int mac_disable(struct cmac *mac, int which)
{
u32 val;
int i, port = mac->instance->index;
/* Reset the port, this also writes the correct WM value */
mac_reset(mac);
vsc_read(mac->adapter, REG_MODE_CFG(port), &val);
if (which & MAC_DIRECTION_RX)
val &= ~0x2;
if (which & MAC_DIRECTION_TX)
val &= ~0x1;
vsc_write(mac->adapter, REG_MODE_CFG(port), val);
vsc_read(mac->adapter, REG_MODE_CFG(port), &val);
/* Clear stats */
for (i = 0; i <= 0x3a; ++i)
vsc_write(mac->adapter, CRA(4, port, i), 0);
/* Clear software counters */
memset(&mac->stats, 0, sizeof(struct cmac_statistics));
return 0;
}
static void rmon_update(struct cmac *mac, unsigned int addr, u64 *stat)
{
u32 v, lo;
vsc_read(mac->adapter, addr, &v);
lo = *stat;
*stat = *stat - lo + v;
if (v == 0)
return;
if (v < lo)
*stat += (1ULL << 32);
}
static void port_stats_update(struct cmac *mac)
{
struct {
unsigned int reg;
unsigned int offset;
} hw_stats[] = {
#define HW_STAT(reg, stat_name) \
{ reg, (&((struct cmac_statistics *)NULL)->stat_name) - (u64 *)NULL }
/* Rx stats */
HW_STAT(RxUnicast, RxUnicastFramesOK),
HW_STAT(RxMulticast, RxMulticastFramesOK),
HW_STAT(RxBroadcast, RxBroadcastFramesOK),
HW_STAT(Crc, RxFCSErrors),
HW_STAT(RxAlignment, RxAlignErrors),
HW_STAT(RxOversize, RxFrameTooLongErrors),
HW_STAT(RxPause, RxPauseFrames),
HW_STAT(RxJabbers, RxJabberErrors),
HW_STAT(RxFragments, RxRuntErrors),
HW_STAT(RxUndersize, RxRuntErrors),
HW_STAT(RxSymbolCarrier, RxSymbolErrors),
HW_STAT(RxSize1519ToMax, RxJumboFramesOK),
/* Tx stats (skip collision stats as we are full-duplex only) */
HW_STAT(TxUnicast, TxUnicastFramesOK),
HW_STAT(TxMulticast, TxMulticastFramesOK),
HW_STAT(TxBroadcast, TxBroadcastFramesOK),
HW_STAT(TxPause, TxPauseFrames),
HW_STAT(TxUnderrun, TxUnderrun),
HW_STAT(TxSize1519ToMax, TxJumboFramesOK),
}, *p = hw_stats;
unsigned int port = mac->instance->index;
u64 *stats = (u64 *)&mac->stats;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(hw_stats); i++)
rmon_update(mac, CRA(0x4, port, p->reg), stats + p->offset);
rmon_update(mac, REG_TX_OK_BYTES(port), &mac->stats.TxOctetsOK);
rmon_update(mac, REG_RX_OK_BYTES(port), &mac->stats.RxOctetsOK);
rmon_update(mac, REG_RX_BAD_BYTES(port), &mac->stats.RxOctetsBad);
}
/*
* This function is called periodically to accumulate the current values of the
* RMON counters into the port statistics. Since the counters are only 32 bits
* some of them can overflow in less than a minute at GigE speeds, so this
* function should be called every 30 seconds or so.
*
* To cut down on reading costs we update only the octet counters at each tick
* and do a full update at major ticks, which can be every 30 minutes or more.
*/
static const struct cmac_statistics *mac_update_statistics(struct cmac *mac,
int flag)
{
if (flag == MAC_STATS_UPDATE_FULL ||
mac->instance->ticks >= MAJOR_UPDATE_TICKS) {
port_stats_update(mac);
mac->instance->ticks = 0;
} else {
int port = mac->instance->index;
rmon_update(mac, REG_RX_OK_BYTES(port),
&mac->stats.RxOctetsOK);
rmon_update(mac, REG_RX_BAD_BYTES(port),
&mac->stats.RxOctetsBad);
rmon_update(mac, REG_TX_OK_BYTES(port),
&mac->stats.TxOctetsOK);
mac->instance->ticks++;
}
return &mac->stats;
}
static void mac_destroy(struct cmac *mac)
{
kfree(mac);
}
static struct cmac_ops vsc7326_ops = {
.destroy = mac_destroy,
.reset = mac_reset,
.interrupt_handler = mac_intr_handler,
.interrupt_enable = mac_intr_enable,
.interrupt_disable = mac_intr_disable,
.interrupt_clear = mac_intr_clear,
.enable = mac_enable,
.disable = mac_disable,
.set_mtu = mac_set_mtu,
.set_rx_mode = mac_set_rx_mode,
.set_speed_duplex_fc = mac_set_speed_duplex_fc,
.statistics_update = mac_update_statistics,
.macaddress_get = mac_get_address,
.macaddress_set = mac_set_address,
};
static struct cmac *vsc7326_mac_create(adapter_t *adapter, int index)
{
struct cmac *mac;
u32 val;
int i;
mac = kzalloc(sizeof(*mac) + sizeof(cmac_instance), GFP_KERNEL);
if (!mac)
return NULL;
mac->ops = &vsc7326_ops;
mac->instance = (cmac_instance *)(mac + 1);
mac->adapter = adapter;
mac->instance->index = index;
mac->instance->ticks = 0;
i = 0;
do {
u32 vhi, vlo;
vhi = vlo = 0;
t1_tpi_read(adapter, (REG_LOCAL_STATUS << 2) + 4, &vlo);
udelay(1);
t1_tpi_read(adapter, REG_LOCAL_STATUS << 2, &vhi);
udelay(5);
val = (vhi << 16) | vlo;
} while ((++i < 10000) && (val == 0xffffffff));
return mac;
}
static int vsc7326_mac_reset(adapter_t *adapter)
{
vsc7326_full_reset(adapter);
(void) run_bist_all(adapter);
run_table(adapter, vsc7326_reset, ARRAY_SIZE(vsc7326_reset));
return 0;
}
const struct gmac t1_vsc7326_ops = {
.stats_update_period = STATS_TICK_SECS,
.create = vsc7326_mac_create,
.reset = vsc7326_mac_reset,
};
| gpl-2.0 |
hiikezoe/android_kernel_asus_tf300t | fs/hfs/attr.c | 13671 | 2666 | /*
* linux/fs/hfs/attr.c
*
* (C) 2003 Ardis Technologies <roman@ardistech.com>
*
* Export hfs data via xattr
*/
#include <linux/fs.h>
#include <linux/xattr.h>
#include "hfs_fs.h"
#include "btree.h"
int hfs_setxattr(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags)
{
struct inode *inode = dentry->d_inode;
struct hfs_find_data fd;
hfs_cat_rec rec;
struct hfs_cat_file *file;
int res;
if (!S_ISREG(inode->i_mode) || HFS_IS_RSRC(inode))
return -EOPNOTSUPP;
res = hfs_find_init(HFS_SB(inode->i_sb)->cat_tree, &fd);
if (res)
return res;
fd.search_key->cat = HFS_I(inode)->cat_key;
res = hfs_brec_find(&fd);
if (res)
goto out;
hfs_bnode_read(fd.bnode, &rec, fd.entryoffset,
sizeof(struct hfs_cat_file));
file = &rec.file;
if (!strcmp(name, "hfs.type")) {
if (size == 4)
memcpy(&file->UsrWds.fdType, value, 4);
else
res = -ERANGE;
} else if (!strcmp(name, "hfs.creator")) {
if (size == 4)
memcpy(&file->UsrWds.fdCreator, value, 4);
else
res = -ERANGE;
} else
res = -EOPNOTSUPP;
if (!res)
hfs_bnode_write(fd.bnode, &rec, fd.entryoffset,
sizeof(struct hfs_cat_file));
out:
hfs_find_exit(&fd);
return res;
}
ssize_t hfs_getxattr(struct dentry *dentry, const char *name,
void *value, size_t size)
{
struct inode *inode = dentry->d_inode;
struct hfs_find_data fd;
hfs_cat_rec rec;
struct hfs_cat_file *file;
ssize_t res = 0;
if (!S_ISREG(inode->i_mode) || HFS_IS_RSRC(inode))
return -EOPNOTSUPP;
if (size) {
res = hfs_find_init(HFS_SB(inode->i_sb)->cat_tree, &fd);
if (res)
return res;
fd.search_key->cat = HFS_I(inode)->cat_key;
res = hfs_brec_find(&fd);
if (res)
goto out;
hfs_bnode_read(fd.bnode, &rec, fd.entryoffset,
sizeof(struct hfs_cat_file));
}
file = &rec.file;
if (!strcmp(name, "hfs.type")) {
if (size >= 4) {
memcpy(value, &file->UsrWds.fdType, 4);
res = 4;
} else
res = size ? -ERANGE : 4;
} else if (!strcmp(name, "hfs.creator")) {
if (size >= 4) {
memcpy(value, &file->UsrWds.fdCreator, 4);
res = 4;
} else
res = size ? -ERANGE : 4;
} else
res = -ENODATA;
out:
if (size)
hfs_find_exit(&fd);
return res;
}
#define HFS_ATTRLIST_SIZE (sizeof("hfs.creator")+sizeof("hfs.type"))
ssize_t hfs_listxattr(struct dentry *dentry, char *buffer, size_t size)
{
struct inode *inode = dentry->d_inode;
if (!S_ISREG(inode->i_mode) || HFS_IS_RSRC(inode))
return -EOPNOTSUPP;
if (!buffer || !size)
return HFS_ATTRLIST_SIZE;
if (size < HFS_ATTRLIST_SIZE)
return -ERANGE;
strcpy(buffer, "hfs.type");
strcpy(buffer + sizeof("hfs.type"), "hfs.creator");
return HFS_ATTRLIST_SIZE;
}
| gpl-2.0 |
MasterSS/linux | fs/ntfs/unistr.c | 14951 | 12445 | /*
* unistr.c - NTFS Unicode string handling. Part of the Linux-NTFS project.
*
* Copyright (c) 2001-2006 Anton Altaparmakov
*
* This program/include file 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/include file 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 (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/slab.h>
#include "types.h"
#include "debug.h"
#include "ntfs.h"
/*
* IMPORTANT
* =========
*
* All these routines assume that the Unicode characters are in little endian
* encoding inside the strings!!!
*/
/*
* This is used by the name collation functions to quickly determine what
* characters are (in)valid.
*/
static const u8 legal_ansi_char_array[0x40] = {
0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x17, 0x07, 0x18, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x18, 0x16, 0x16, 0x17, 0x07, 0x00,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x04, 0x16, 0x18, 0x16, 0x18, 0x18,
};
/**
* ntfs_are_names_equal - compare two Unicode names for equality
* @s1: name to compare to @s2
* @s1_len: length in Unicode characters of @s1
* @s2: name to compare to @s1
* @s2_len: length in Unicode characters of @s2
* @ic: ignore case bool
* @upcase: upcase table (only if @ic == IGNORE_CASE)
* @upcase_size: length in Unicode characters of @upcase (if present)
*
* Compare the names @s1 and @s2 and return 'true' (1) if the names are
* identical, or 'false' (0) if they are not identical. If @ic is IGNORE_CASE,
* the @upcase table is used to performa a case insensitive comparison.
*/
bool ntfs_are_names_equal(const ntfschar *s1, size_t s1_len,
const ntfschar *s2, size_t s2_len, const IGNORE_CASE_BOOL ic,
const ntfschar *upcase, const u32 upcase_size)
{
if (s1_len != s2_len)
return false;
if (ic == CASE_SENSITIVE)
return !ntfs_ucsncmp(s1, s2, s1_len);
return !ntfs_ucsncasecmp(s1, s2, s1_len, upcase, upcase_size);
}
/**
* ntfs_collate_names - collate two Unicode names
* @name1: first Unicode name to compare
* @name2: second Unicode name to compare
* @err_val: if @name1 contains an invalid character return this value
* @ic: either CASE_SENSITIVE or IGNORE_CASE
* @upcase: upcase table (ignored if @ic is CASE_SENSITIVE)
* @upcase_len: upcase table size (ignored if @ic is CASE_SENSITIVE)
*
* ntfs_collate_names collates two Unicode names and returns:
*
* -1 if the first name collates before the second one,
* 0 if the names match,
* 1 if the second name collates before the first one, or
* @err_val if an invalid character is found in @name1 during the comparison.
*
* The following characters are considered invalid: '"', '*', '<', '>' and '?'.
*/
int ntfs_collate_names(const ntfschar *name1, const u32 name1_len,
const ntfschar *name2, const u32 name2_len,
const int err_val, const IGNORE_CASE_BOOL ic,
const ntfschar *upcase, const u32 upcase_len)
{
u32 cnt, min_len;
u16 c1, c2;
min_len = name1_len;
if (name1_len > name2_len)
min_len = name2_len;
for (cnt = 0; cnt < min_len; ++cnt) {
c1 = le16_to_cpu(*name1++);
c2 = le16_to_cpu(*name2++);
if (ic) {
if (c1 < upcase_len)
c1 = le16_to_cpu(upcase[c1]);
if (c2 < upcase_len)
c2 = le16_to_cpu(upcase[c2]);
}
if (c1 < 64 && legal_ansi_char_array[c1] & 8)
return err_val;
if (c1 < c2)
return -1;
if (c1 > c2)
return 1;
}
if (name1_len < name2_len)
return -1;
if (name1_len == name2_len)
return 0;
/* name1_len > name2_len */
c1 = le16_to_cpu(*name1);
if (c1 < 64 && legal_ansi_char_array[c1] & 8)
return err_val;
return 1;
}
/**
* ntfs_ucsncmp - compare two little endian Unicode strings
* @s1: first string
* @s2: second string
* @n: maximum unicode characters to compare
*
* Compare the first @n characters of the Unicode strings @s1 and @s2,
* The strings in little endian format and appropriate le16_to_cpu()
* conversion is performed on non-little endian machines.
*
* The function returns an integer less than, equal to, or greater than zero
* if @s1 (or the first @n Unicode characters thereof) is found, respectively,
* to be less than, to match, or be greater than @s2.
*/
int ntfs_ucsncmp(const ntfschar *s1, const ntfschar *s2, size_t n)
{
u16 c1, c2;
size_t i;
for (i = 0; i < n; ++i) {
c1 = le16_to_cpu(s1[i]);
c2 = le16_to_cpu(s2[i]);
if (c1 < c2)
return -1;
if (c1 > c2)
return 1;
if (!c1)
break;
}
return 0;
}
/**
* ntfs_ucsncasecmp - compare two little endian Unicode strings, ignoring case
* @s1: first string
* @s2: second string
* @n: maximum unicode characters to compare
* @upcase: upcase table
* @upcase_size: upcase table size in Unicode characters
*
* Compare the first @n characters of the Unicode strings @s1 and @s2,
* ignoring case. The strings in little endian format and appropriate
* le16_to_cpu() conversion is performed on non-little endian machines.
*
* Each character is uppercased using the @upcase table before the comparison.
*
* The function returns an integer less than, equal to, or greater than zero
* if @s1 (or the first @n Unicode characters thereof) is found, respectively,
* to be less than, to match, or be greater than @s2.
*/
int ntfs_ucsncasecmp(const ntfschar *s1, const ntfschar *s2, size_t n,
const ntfschar *upcase, const u32 upcase_size)
{
size_t i;
u16 c1, c2;
for (i = 0; i < n; ++i) {
if ((c1 = le16_to_cpu(s1[i])) < upcase_size)
c1 = le16_to_cpu(upcase[c1]);
if ((c2 = le16_to_cpu(s2[i])) < upcase_size)
c2 = le16_to_cpu(upcase[c2]);
if (c1 < c2)
return -1;
if (c1 > c2)
return 1;
if (!c1)
break;
}
return 0;
}
void ntfs_upcase_name(ntfschar *name, u32 name_len, const ntfschar *upcase,
const u32 upcase_len)
{
u32 i;
u16 u;
for (i = 0; i < name_len; i++)
if ((u = le16_to_cpu(name[i])) < upcase_len)
name[i] = upcase[u];
}
void ntfs_file_upcase_value(FILE_NAME_ATTR *file_name_attr,
const ntfschar *upcase, const u32 upcase_len)
{
ntfs_upcase_name((ntfschar*)&file_name_attr->file_name,
file_name_attr->file_name_length, upcase, upcase_len);
}
int ntfs_file_compare_values(FILE_NAME_ATTR *file_name_attr1,
FILE_NAME_ATTR *file_name_attr2,
const int err_val, const IGNORE_CASE_BOOL ic,
const ntfschar *upcase, const u32 upcase_len)
{
return ntfs_collate_names((ntfschar*)&file_name_attr1->file_name,
file_name_attr1->file_name_length,
(ntfschar*)&file_name_attr2->file_name,
file_name_attr2->file_name_length,
err_val, ic, upcase, upcase_len);
}
/**
* ntfs_nlstoucs - convert NLS string to little endian Unicode string
* @vol: ntfs volume which we are working with
* @ins: input NLS string buffer
* @ins_len: length of input string in bytes
* @outs: on return contains the allocated output Unicode string buffer
*
* Convert the input string @ins, which is in whatever format the loaded NLS
* map dictates, into a little endian, 2-byte Unicode string.
*
* This function allocates the string and the caller is responsible for
* calling kmem_cache_free(ntfs_name_cache, *@outs); when finished with it.
*
* On success the function returns the number of Unicode characters written to
* the output string *@outs (>= 0), not counting the terminating Unicode NULL
* character. *@outs is set to the allocated output string buffer.
*
* On error, a negative number corresponding to the error code is returned. In
* that case the output string is not allocated. Both *@outs and *@outs_len
* are then undefined.
*
* This might look a bit odd due to fast path optimization...
*/
int ntfs_nlstoucs(const ntfs_volume *vol, const char *ins,
const int ins_len, ntfschar **outs)
{
struct nls_table *nls = vol->nls_map;
ntfschar *ucs;
wchar_t wc;
int i, o, wc_len;
/* We do not trust outside sources. */
if (likely(ins)) {
ucs = kmem_cache_alloc(ntfs_name_cache, GFP_NOFS);
if (likely(ucs)) {
for (i = o = 0; i < ins_len; i += wc_len) {
wc_len = nls->char2uni(ins + i, ins_len - i,
&wc);
if (likely(wc_len >= 0 &&
o < NTFS_MAX_NAME_LEN)) {
if (likely(wc)) {
ucs[o++] = cpu_to_le16(wc);
continue;
} /* else if (!wc) */
break;
} /* else if (wc_len < 0 ||
o >= NTFS_MAX_NAME_LEN) */
goto name_err;
}
ucs[o] = 0;
*outs = ucs;
return o;
} /* else if (!ucs) */
ntfs_error(vol->sb, "Failed to allocate buffer for converted "
"name from ntfs_name_cache.");
return -ENOMEM;
} /* else if (!ins) */
ntfs_error(vol->sb, "Received NULL pointer.");
return -EINVAL;
name_err:
kmem_cache_free(ntfs_name_cache, ucs);
if (wc_len < 0) {
ntfs_error(vol->sb, "Name using character set %s contains "
"characters that cannot be converted to "
"Unicode.", nls->charset);
i = -EILSEQ;
} else /* if (o >= NTFS_MAX_NAME_LEN) */ {
ntfs_error(vol->sb, "Name is too long (maximum length for a "
"name on NTFS is %d Unicode characters.",
NTFS_MAX_NAME_LEN);
i = -ENAMETOOLONG;
}
return i;
}
/**
* ntfs_ucstonls - convert little endian Unicode string to NLS string
* @vol: ntfs volume which we are working with
* @ins: input Unicode string buffer
* @ins_len: length of input string in Unicode characters
* @outs: on return contains the (allocated) output NLS string buffer
* @outs_len: length of output string buffer in bytes
*
* Convert the input little endian, 2-byte Unicode string @ins, of length
* @ins_len into the string format dictated by the loaded NLS.
*
* If *@outs is NULL, this function allocates the string and the caller is
* responsible for calling kfree(*@outs); when finished with it. In this case
* @outs_len is ignored and can be 0.
*
* On success the function returns the number of bytes written to the output
* string *@outs (>= 0), not counting the terminating NULL byte. If the output
* string buffer was allocated, *@outs is set to it.
*
* On error, a negative number corresponding to the error code is returned. In
* that case the output string is not allocated. The contents of *@outs are
* then undefined.
*
* This might look a bit odd due to fast path optimization...
*/
int ntfs_ucstonls(const ntfs_volume *vol, const ntfschar *ins,
const int ins_len, unsigned char **outs, int outs_len)
{
struct nls_table *nls = vol->nls_map;
unsigned char *ns;
int i, o, ns_len, wc;
/* We don't trust outside sources. */
if (ins) {
ns = *outs;
ns_len = outs_len;
if (ns && !ns_len) {
wc = -ENAMETOOLONG;
goto conversion_err;
}
if (!ns) {
ns_len = ins_len * NLS_MAX_CHARSET_SIZE;
ns = kmalloc(ns_len + 1, GFP_NOFS);
if (!ns)
goto mem_err_out;
}
for (i = o = 0; i < ins_len; i++) {
retry: wc = nls->uni2char(le16_to_cpu(ins[i]), ns + o,
ns_len - o);
if (wc > 0) {
o += wc;
continue;
} else if (!wc)
break;
else if (wc == -ENAMETOOLONG && ns != *outs) {
unsigned char *tc;
/* Grow in multiples of 64 bytes. */
tc = kmalloc((ns_len + 64) &
~63, GFP_NOFS);
if (tc) {
memcpy(tc, ns, ns_len);
ns_len = ((ns_len + 64) & ~63) - 1;
kfree(ns);
ns = tc;
goto retry;
} /* No memory so goto conversion_error; */
} /* wc < 0, real error. */
goto conversion_err;
}
ns[o] = 0;
*outs = ns;
return o;
} /* else (!ins) */
ntfs_error(vol->sb, "Received NULL pointer.");
return -EINVAL;
conversion_err:
ntfs_error(vol->sb, "Unicode name contains characters that cannot be "
"converted to character set %s. You might want to "
"try to use the mount option nls=utf8.", nls->charset);
if (ns != *outs)
kfree(ns);
if (wc != -ENAMETOOLONG)
wc = -EILSEQ;
return wc;
mem_err_out:
ntfs_error(vol->sb, "Failed to allocate name!");
return -ENOMEM;
}
| gpl-2.0 |
digetx/picasso-kernel | drivers/firewire/ohci.c | 104 | 108281 | /*
* Driver for OHCI 1394 controllers
*
* Copyright (C) 2003-2006 Kristian Hoegsberg <krh@bitplanet.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/bitops.h>
#include <linux/bug.h>
#include <linux/compiler.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/firewire.h>
#include <linux/firewire-constants.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/mutex.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/time.h>
#include <linux/vmalloc.h>
#include <linux/workqueue.h>
#include <asm/byteorder.h>
#include <asm/page.h>
#ifdef CONFIG_PPC_PMAC
#include <asm/pmac_feature.h>
#endif
#include "core.h"
#include "ohci.h"
#define ohci_info(ohci, f, args...) dev_info(ohci->card.device, f, ##args)
#define ohci_notice(ohci, f, args...) dev_notice(ohci->card.device, f, ##args)
#define ohci_err(ohci, f, args...) dev_err(ohci->card.device, f, ##args)
#define DESCRIPTOR_OUTPUT_MORE 0
#define DESCRIPTOR_OUTPUT_LAST (1 << 12)
#define DESCRIPTOR_INPUT_MORE (2 << 12)
#define DESCRIPTOR_INPUT_LAST (3 << 12)
#define DESCRIPTOR_STATUS (1 << 11)
#define DESCRIPTOR_KEY_IMMEDIATE (2 << 8)
#define DESCRIPTOR_PING (1 << 7)
#define DESCRIPTOR_YY (1 << 6)
#define DESCRIPTOR_NO_IRQ (0 << 4)
#define DESCRIPTOR_IRQ_ERROR (1 << 4)
#define DESCRIPTOR_IRQ_ALWAYS (3 << 4)
#define DESCRIPTOR_BRANCH_ALWAYS (3 << 2)
#define DESCRIPTOR_WAIT (3 << 0)
#define DESCRIPTOR_CMD (0xf << 12)
struct descriptor {
__le16 req_count;
__le16 control;
__le32 data_address;
__le32 branch_address;
__le16 res_count;
__le16 transfer_status;
} __attribute__((aligned(16)));
#define CONTROL_SET(regs) (regs)
#define CONTROL_CLEAR(regs) ((regs) + 4)
#define COMMAND_PTR(regs) ((regs) + 12)
#define CONTEXT_MATCH(regs) ((regs) + 16)
#define AR_BUFFER_SIZE (32*1024)
#define AR_BUFFERS_MIN DIV_ROUND_UP(AR_BUFFER_SIZE, PAGE_SIZE)
/* we need at least two pages for proper list management */
#define AR_BUFFERS (AR_BUFFERS_MIN >= 2 ? AR_BUFFERS_MIN : 2)
#define MAX_ASYNC_PAYLOAD 4096
#define MAX_AR_PACKET_SIZE (16 + MAX_ASYNC_PAYLOAD + 4)
#define AR_WRAPAROUND_PAGES DIV_ROUND_UP(MAX_AR_PACKET_SIZE, PAGE_SIZE)
struct ar_context {
struct fw_ohci *ohci;
struct page *pages[AR_BUFFERS];
void *buffer;
struct descriptor *descriptors;
dma_addr_t descriptors_bus;
void *pointer;
unsigned int last_buffer_index;
u32 regs;
struct tasklet_struct tasklet;
};
struct context;
typedef int (*descriptor_callback_t)(struct context *ctx,
struct descriptor *d,
struct descriptor *last);
/*
* A buffer that contains a block of DMA-able coherent memory used for
* storing a portion of a DMA descriptor program.
*/
struct descriptor_buffer {
struct list_head list;
dma_addr_t buffer_bus;
size_t buffer_size;
size_t used;
struct descriptor buffer[0];
};
struct context {
struct fw_ohci *ohci;
u32 regs;
int total_allocation;
u32 current_bus;
bool running;
bool flushing;
/*
* List of page-sized buffers for storing DMA descriptors.
* Head of list contains buffers in use and tail of list contains
* free buffers.
*/
struct list_head buffer_list;
/*
* Pointer to a buffer inside buffer_list that contains the tail
* end of the current DMA program.
*/
struct descriptor_buffer *buffer_tail;
/*
* The descriptor containing the branch address of the first
* descriptor that has not yet been filled by the device.
*/
struct descriptor *last;
/*
* The last descriptor block in the DMA program. It contains the branch
* address that must be updated upon appending a new descriptor.
*/
struct descriptor *prev;
int prev_z;
descriptor_callback_t callback;
struct tasklet_struct tasklet;
};
#define IT_HEADER_SY(v) ((v) << 0)
#define IT_HEADER_TCODE(v) ((v) << 4)
#define IT_HEADER_CHANNEL(v) ((v) << 8)
#define IT_HEADER_TAG(v) ((v) << 14)
#define IT_HEADER_SPEED(v) ((v) << 16)
#define IT_HEADER_DATA_LENGTH(v) ((v) << 16)
struct iso_context {
struct fw_iso_context base;
struct context context;
void *header;
size_t header_length;
unsigned long flushing_completions;
u32 mc_buffer_bus;
u16 mc_completed;
u16 last_timestamp;
u8 sync;
u8 tags;
};
#define CONFIG_ROM_SIZE 1024
struct fw_ohci {
struct fw_card card;
__iomem char *registers;
int node_id;
int generation;
int request_generation; /* for timestamping incoming requests */
unsigned quirks;
unsigned int pri_req_max;
u32 bus_time;
bool bus_time_running;
bool is_root;
bool csr_state_setclear_abdicate;
int n_ir;
int n_it;
/*
* Spinlock for accessing fw_ohci data. Never call out of
* this driver with this lock held.
*/
spinlock_t lock;
struct mutex phy_reg_mutex;
void *misc_buffer;
dma_addr_t misc_buffer_bus;
struct ar_context ar_request_ctx;
struct ar_context ar_response_ctx;
struct context at_request_ctx;
struct context at_response_ctx;
u32 it_context_support;
u32 it_context_mask; /* unoccupied IT contexts */
struct iso_context *it_context_list;
u64 ir_context_channels; /* unoccupied channels */
u32 ir_context_support;
u32 ir_context_mask; /* unoccupied IR contexts */
struct iso_context *ir_context_list;
u64 mc_channels; /* channels in use by the multichannel IR context */
bool mc_allocated;
__be32 *config_rom;
dma_addr_t config_rom_bus;
__be32 *next_config_rom;
dma_addr_t next_config_rom_bus;
__be32 next_header;
__le32 *self_id;
dma_addr_t self_id_bus;
struct work_struct bus_reset_work;
u32 self_id_buffer[512];
};
static struct workqueue_struct *selfid_workqueue;
static inline struct fw_ohci *fw_ohci(struct fw_card *card)
{
return container_of(card, struct fw_ohci, card);
}
#define IT_CONTEXT_CYCLE_MATCH_ENABLE 0x80000000
#define IR_CONTEXT_BUFFER_FILL 0x80000000
#define IR_CONTEXT_ISOCH_HEADER 0x40000000
#define IR_CONTEXT_CYCLE_MATCH_ENABLE 0x20000000
#define IR_CONTEXT_MULTI_CHANNEL_MODE 0x10000000
#define IR_CONTEXT_DUAL_BUFFER_MODE 0x08000000
#define CONTEXT_RUN 0x8000
#define CONTEXT_WAKE 0x1000
#define CONTEXT_DEAD 0x0800
#define CONTEXT_ACTIVE 0x0400
#define OHCI1394_MAX_AT_REQ_RETRIES 0xf
#define OHCI1394_MAX_AT_RESP_RETRIES 0x2
#define OHCI1394_MAX_PHYS_RESP_RETRIES 0x8
#define OHCI1394_REGISTER_SIZE 0x800
#define OHCI1394_PCI_HCI_Control 0x40
#define SELF_ID_BUF_SIZE 0x800
#define OHCI_TCODE_PHY_PACKET 0x0e
#define OHCI_VERSION_1_1 0x010010
static char ohci_driver_name[] = KBUILD_MODNAME;
#define PCI_VENDOR_ID_PINNACLE_SYSTEMS 0x11bd
#define PCI_DEVICE_ID_AGERE_FW643 0x5901
#define PCI_DEVICE_ID_CREATIVE_SB1394 0x4001
#define PCI_DEVICE_ID_JMICRON_JMB38X_FW 0x2380
#define PCI_DEVICE_ID_TI_TSB12LV22 0x8009
#define PCI_DEVICE_ID_TI_TSB12LV26 0x8020
#define PCI_DEVICE_ID_TI_TSB82AA2 0x8025
#define PCI_DEVICE_ID_VIA_VT630X 0x3044
#define PCI_REV_ID_VIA_VT6306 0x46
#define PCI_DEVICE_ID_VIA_VT6315 0x3403
#define QUIRK_CYCLE_TIMER 0x1
#define QUIRK_RESET_PACKET 0x2
#define QUIRK_BE_HEADERS 0x4
#define QUIRK_NO_1394A 0x8
#define QUIRK_NO_MSI 0x10
#define QUIRK_TI_SLLZ059 0x20
#define QUIRK_IR_WAKE 0x40
/* In case of multiple matches in ohci_quirks[], only the first one is used. */
static const struct {
unsigned short vendor, device, revision, flags;
} ohci_quirks[] = {
{PCI_VENDOR_ID_AL, PCI_ANY_ID, PCI_ANY_ID,
QUIRK_CYCLE_TIMER},
{PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_UNI_N_FW, PCI_ANY_ID,
QUIRK_BE_HEADERS},
{PCI_VENDOR_ID_ATT, PCI_DEVICE_ID_AGERE_FW643, 6,
QUIRK_NO_MSI},
{PCI_VENDOR_ID_CREATIVE, PCI_DEVICE_ID_CREATIVE_SB1394, PCI_ANY_ID,
QUIRK_RESET_PACKET},
{PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB38X_FW, PCI_ANY_ID,
QUIRK_NO_MSI},
{PCI_VENDOR_ID_NEC, PCI_ANY_ID, PCI_ANY_ID,
QUIRK_CYCLE_TIMER},
{PCI_VENDOR_ID_O2, PCI_ANY_ID, PCI_ANY_ID,
QUIRK_NO_MSI},
{PCI_VENDOR_ID_RICOH, PCI_ANY_ID, PCI_ANY_ID,
QUIRK_CYCLE_TIMER | QUIRK_NO_MSI},
{PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_TSB12LV22, PCI_ANY_ID,
QUIRK_CYCLE_TIMER | QUIRK_RESET_PACKET | QUIRK_NO_1394A},
{PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_TSB12LV26, PCI_ANY_ID,
QUIRK_RESET_PACKET | QUIRK_TI_SLLZ059},
{PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_TSB82AA2, PCI_ANY_ID,
QUIRK_RESET_PACKET | QUIRK_TI_SLLZ059},
{PCI_VENDOR_ID_TI, PCI_ANY_ID, PCI_ANY_ID,
QUIRK_RESET_PACKET},
{PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_VT630X, PCI_REV_ID_VIA_VT6306,
QUIRK_CYCLE_TIMER | QUIRK_IR_WAKE},
{PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_VT6315, 0,
QUIRK_CYCLE_TIMER /* FIXME: necessary? */ | QUIRK_NO_MSI},
{PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_VT6315, PCI_ANY_ID,
QUIRK_NO_MSI},
{PCI_VENDOR_ID_VIA, PCI_ANY_ID, PCI_ANY_ID,
QUIRK_CYCLE_TIMER | QUIRK_NO_MSI},
};
/* This overrides anything that was found in ohci_quirks[]. */
static int param_quirks;
module_param_named(quirks, param_quirks, int, 0644);
MODULE_PARM_DESC(quirks, "Chip quirks (default = 0"
", nonatomic cycle timer = " __stringify(QUIRK_CYCLE_TIMER)
", reset packet generation = " __stringify(QUIRK_RESET_PACKET)
", AR/selfID endianness = " __stringify(QUIRK_BE_HEADERS)
", no 1394a enhancements = " __stringify(QUIRK_NO_1394A)
", disable MSI = " __stringify(QUIRK_NO_MSI)
", TI SLLZ059 erratum = " __stringify(QUIRK_TI_SLLZ059)
", IR wake unreliable = " __stringify(QUIRK_IR_WAKE)
")");
#define OHCI_PARAM_DEBUG_AT_AR 1
#define OHCI_PARAM_DEBUG_SELFIDS 2
#define OHCI_PARAM_DEBUG_IRQS 4
#define OHCI_PARAM_DEBUG_BUSRESETS 8 /* only effective before chip init */
static int param_debug;
module_param_named(debug, param_debug, int, 0644);
MODULE_PARM_DESC(debug, "Verbose logging (default = 0"
", AT/AR events = " __stringify(OHCI_PARAM_DEBUG_AT_AR)
", self-IDs = " __stringify(OHCI_PARAM_DEBUG_SELFIDS)
", IRQs = " __stringify(OHCI_PARAM_DEBUG_IRQS)
", busReset events = " __stringify(OHCI_PARAM_DEBUG_BUSRESETS)
", or a combination, or all = -1)");
static bool param_remote_dma;
module_param_named(remote_dma, param_remote_dma, bool, 0444);
MODULE_PARM_DESC(remote_dma, "Enable unfiltered remote DMA (default = N)");
static void log_irqs(struct fw_ohci *ohci, u32 evt)
{
if (likely(!(param_debug &
(OHCI_PARAM_DEBUG_IRQS | OHCI_PARAM_DEBUG_BUSRESETS))))
return;
if (!(param_debug & OHCI_PARAM_DEBUG_IRQS) &&
!(evt & OHCI1394_busReset))
return;
ohci_notice(ohci, "IRQ %08x%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n", evt,
evt & OHCI1394_selfIDComplete ? " selfID" : "",
evt & OHCI1394_RQPkt ? " AR_req" : "",
evt & OHCI1394_RSPkt ? " AR_resp" : "",
evt & OHCI1394_reqTxComplete ? " AT_req" : "",
evt & OHCI1394_respTxComplete ? " AT_resp" : "",
evt & OHCI1394_isochRx ? " IR" : "",
evt & OHCI1394_isochTx ? " IT" : "",
evt & OHCI1394_postedWriteErr ? " postedWriteErr" : "",
evt & OHCI1394_cycleTooLong ? " cycleTooLong" : "",
evt & OHCI1394_cycle64Seconds ? " cycle64Seconds" : "",
evt & OHCI1394_cycleInconsistent ? " cycleInconsistent" : "",
evt & OHCI1394_regAccessFail ? " regAccessFail" : "",
evt & OHCI1394_unrecoverableError ? " unrecoverableError" : "",
evt & OHCI1394_busReset ? " busReset" : "",
evt & ~(OHCI1394_selfIDComplete | OHCI1394_RQPkt |
OHCI1394_RSPkt | OHCI1394_reqTxComplete |
OHCI1394_respTxComplete | OHCI1394_isochRx |
OHCI1394_isochTx | OHCI1394_postedWriteErr |
OHCI1394_cycleTooLong | OHCI1394_cycle64Seconds |
OHCI1394_cycleInconsistent |
OHCI1394_regAccessFail | OHCI1394_busReset)
? " ?" : "");
}
static const char *speed[] = {
[0] = "S100", [1] = "S200", [2] = "S400", [3] = "beta",
};
static const char *power[] = {
[0] = "+0W", [1] = "+15W", [2] = "+30W", [3] = "+45W",
[4] = "-3W", [5] = " ?W", [6] = "-3..-6W", [7] = "-3..-10W",
};
static const char port[] = { '.', '-', 'p', 'c', };
static char _p(u32 *s, int shift)
{
return port[*s >> shift & 3];
}
static void log_selfids(struct fw_ohci *ohci, int generation, int self_id_count)
{
u32 *s;
if (likely(!(param_debug & OHCI_PARAM_DEBUG_SELFIDS)))
return;
ohci_notice(ohci, "%d selfIDs, generation %d, local node ID %04x\n",
self_id_count, generation, ohci->node_id);
for (s = ohci->self_id_buffer; self_id_count--; ++s)
if ((*s & 1 << 23) == 0)
ohci_notice(ohci,
"selfID 0: %08x, phy %d [%c%c%c] %s gc=%d %s %s%s%s\n",
*s, *s >> 24 & 63, _p(s, 6), _p(s, 4), _p(s, 2),
speed[*s >> 14 & 3], *s >> 16 & 63,
power[*s >> 8 & 7], *s >> 22 & 1 ? "L" : "",
*s >> 11 & 1 ? "c" : "", *s & 2 ? "i" : "");
else
ohci_notice(ohci,
"selfID n: %08x, phy %d [%c%c%c%c%c%c%c%c]\n",
*s, *s >> 24 & 63,
_p(s, 16), _p(s, 14), _p(s, 12), _p(s, 10),
_p(s, 8), _p(s, 6), _p(s, 4), _p(s, 2));
}
static const char *evts[] = {
[0x00] = "evt_no_status", [0x01] = "-reserved-",
[0x02] = "evt_long_packet", [0x03] = "evt_missing_ack",
[0x04] = "evt_underrun", [0x05] = "evt_overrun",
[0x06] = "evt_descriptor_read", [0x07] = "evt_data_read",
[0x08] = "evt_data_write", [0x09] = "evt_bus_reset",
[0x0a] = "evt_timeout", [0x0b] = "evt_tcode_err",
[0x0c] = "-reserved-", [0x0d] = "-reserved-",
[0x0e] = "evt_unknown", [0x0f] = "evt_flushed",
[0x10] = "-reserved-", [0x11] = "ack_complete",
[0x12] = "ack_pending ", [0x13] = "-reserved-",
[0x14] = "ack_busy_X", [0x15] = "ack_busy_A",
[0x16] = "ack_busy_B", [0x17] = "-reserved-",
[0x18] = "-reserved-", [0x19] = "-reserved-",
[0x1a] = "-reserved-", [0x1b] = "ack_tardy",
[0x1c] = "-reserved-", [0x1d] = "ack_data_error",
[0x1e] = "ack_type_error", [0x1f] = "-reserved-",
[0x20] = "pending/cancelled",
};
static const char *tcodes[] = {
[0x0] = "QW req", [0x1] = "BW req",
[0x2] = "W resp", [0x3] = "-reserved-",
[0x4] = "QR req", [0x5] = "BR req",
[0x6] = "QR resp", [0x7] = "BR resp",
[0x8] = "cycle start", [0x9] = "Lk req",
[0xa] = "async stream packet", [0xb] = "Lk resp",
[0xc] = "-reserved-", [0xd] = "-reserved-",
[0xe] = "link internal", [0xf] = "-reserved-",
};
static void log_ar_at_event(struct fw_ohci *ohci,
char dir, int speed, u32 *header, int evt)
{
int tcode = header[0] >> 4 & 0xf;
char specific[12];
if (likely(!(param_debug & OHCI_PARAM_DEBUG_AT_AR)))
return;
if (unlikely(evt >= ARRAY_SIZE(evts)))
evt = 0x1f;
if (evt == OHCI1394_evt_bus_reset) {
ohci_notice(ohci, "A%c evt_bus_reset, generation %d\n",
dir, (header[2] >> 16) & 0xff);
return;
}
switch (tcode) {
case 0x0: case 0x6: case 0x8:
snprintf(specific, sizeof(specific), " = %08x",
be32_to_cpu((__force __be32)header[3]));
break;
case 0x1: case 0x5: case 0x7: case 0x9: case 0xb:
snprintf(specific, sizeof(specific), " %x,%x",
header[3] >> 16, header[3] & 0xffff);
break;
default:
specific[0] = '\0';
}
switch (tcode) {
case 0xa:
ohci_notice(ohci, "A%c %s, %s\n",
dir, evts[evt], tcodes[tcode]);
break;
case 0xe:
ohci_notice(ohci, "A%c %s, PHY %08x %08x\n",
dir, evts[evt], header[1], header[2]);
break;
case 0x0: case 0x1: case 0x4: case 0x5: case 0x9:
ohci_notice(ohci,
"A%c spd %x tl %02x, %04x -> %04x, %s, %s, %04x%08x%s\n",
dir, speed, header[0] >> 10 & 0x3f,
header[1] >> 16, header[0] >> 16, evts[evt],
tcodes[tcode], header[1] & 0xffff, header[2], specific);
break;
default:
ohci_notice(ohci,
"A%c spd %x tl %02x, %04x -> %04x, %s, %s%s\n",
dir, speed, header[0] >> 10 & 0x3f,
header[1] >> 16, header[0] >> 16, evts[evt],
tcodes[tcode], specific);
}
}
static inline void reg_write(const struct fw_ohci *ohci, int offset, u32 data)
{
writel(data, ohci->registers + offset);
}
static inline u32 reg_read(const struct fw_ohci *ohci, int offset)
{
return readl(ohci->registers + offset);
}
static inline void flush_writes(const struct fw_ohci *ohci)
{
/* Do a dummy read to flush writes. */
reg_read(ohci, OHCI1394_Version);
}
/*
* Beware! read_phy_reg(), write_phy_reg(), update_phy_reg(), and
* read_paged_phy_reg() require the caller to hold ohci->phy_reg_mutex.
* In other words, only use ohci_read_phy_reg() and ohci_update_phy_reg()
* directly. Exceptions are intrinsically serialized contexts like pci_probe.
*/
static int read_phy_reg(struct fw_ohci *ohci, int addr)
{
u32 val;
int i;
reg_write(ohci, OHCI1394_PhyControl, OHCI1394_PhyControl_Read(addr));
for (i = 0; i < 3 + 100; i++) {
val = reg_read(ohci, OHCI1394_PhyControl);
if (!~val)
return -ENODEV; /* Card was ejected. */
if (val & OHCI1394_PhyControl_ReadDone)
return OHCI1394_PhyControl_ReadData(val);
/*
* Try a few times without waiting. Sleeping is necessary
* only when the link/PHY interface is busy.
*/
if (i >= 3)
msleep(1);
}
ohci_err(ohci, "failed to read phy reg %d\n", addr);
dump_stack();
return -EBUSY;
}
static int write_phy_reg(const struct fw_ohci *ohci, int addr, u32 val)
{
int i;
reg_write(ohci, OHCI1394_PhyControl,
OHCI1394_PhyControl_Write(addr, val));
for (i = 0; i < 3 + 100; i++) {
val = reg_read(ohci, OHCI1394_PhyControl);
if (!~val)
return -ENODEV; /* Card was ejected. */
if (!(val & OHCI1394_PhyControl_WritePending))
return 0;
if (i >= 3)
msleep(1);
}
ohci_err(ohci, "failed to write phy reg %d, val %u\n", addr, val);
dump_stack();
return -EBUSY;
}
static int update_phy_reg(struct fw_ohci *ohci, int addr,
int clear_bits, int set_bits)
{
int ret = read_phy_reg(ohci, addr);
if (ret < 0)
return ret;
/*
* The interrupt status bits are cleared by writing a one bit.
* Avoid clearing them unless explicitly requested in set_bits.
*/
if (addr == 5)
clear_bits |= PHY_INT_STATUS_BITS;
return write_phy_reg(ohci, addr, (ret & ~clear_bits) | set_bits);
}
static int read_paged_phy_reg(struct fw_ohci *ohci, int page, int addr)
{
int ret;
ret = update_phy_reg(ohci, 7, PHY_PAGE_SELECT, page << 5);
if (ret < 0)
return ret;
return read_phy_reg(ohci, addr);
}
static int ohci_read_phy_reg(struct fw_card *card, int addr)
{
struct fw_ohci *ohci = fw_ohci(card);
int ret;
mutex_lock(&ohci->phy_reg_mutex);
ret = read_phy_reg(ohci, addr);
mutex_unlock(&ohci->phy_reg_mutex);
return ret;
}
static int ohci_update_phy_reg(struct fw_card *card, int addr,
int clear_bits, int set_bits)
{
struct fw_ohci *ohci = fw_ohci(card);
int ret;
mutex_lock(&ohci->phy_reg_mutex);
ret = update_phy_reg(ohci, addr, clear_bits, set_bits);
mutex_unlock(&ohci->phy_reg_mutex);
return ret;
}
static inline dma_addr_t ar_buffer_bus(struct ar_context *ctx, unsigned int i)
{
return page_private(ctx->pages[i]);
}
static void ar_context_link_page(struct ar_context *ctx, unsigned int index)
{
struct descriptor *d;
d = &ctx->descriptors[index];
d->branch_address &= cpu_to_le32(~0xf);
d->res_count = cpu_to_le16(PAGE_SIZE);
d->transfer_status = 0;
wmb(); /* finish init of new descriptors before branch_address update */
d = &ctx->descriptors[ctx->last_buffer_index];
d->branch_address |= cpu_to_le32(1);
ctx->last_buffer_index = index;
reg_write(ctx->ohci, CONTROL_SET(ctx->regs), CONTEXT_WAKE);
}
static void ar_context_release(struct ar_context *ctx)
{
unsigned int i;
if (ctx->buffer)
vm_unmap_ram(ctx->buffer, AR_BUFFERS + AR_WRAPAROUND_PAGES);
for (i = 0; i < AR_BUFFERS; i++)
if (ctx->pages[i]) {
dma_unmap_page(ctx->ohci->card.device,
ar_buffer_bus(ctx, i),
PAGE_SIZE, DMA_FROM_DEVICE);
__free_page(ctx->pages[i]);
}
}
static void ar_context_abort(struct ar_context *ctx, const char *error_msg)
{
struct fw_ohci *ohci = ctx->ohci;
if (reg_read(ohci, CONTROL_CLEAR(ctx->regs)) & CONTEXT_RUN) {
reg_write(ohci, CONTROL_CLEAR(ctx->regs), CONTEXT_RUN);
flush_writes(ohci);
ohci_err(ohci, "AR error: %s; DMA stopped\n", error_msg);
}
/* FIXME: restart? */
}
static inline unsigned int ar_next_buffer_index(unsigned int index)
{
return (index + 1) % AR_BUFFERS;
}
static inline unsigned int ar_prev_buffer_index(unsigned int index)
{
return (index - 1 + AR_BUFFERS) % AR_BUFFERS;
}
static inline unsigned int ar_first_buffer_index(struct ar_context *ctx)
{
return ar_next_buffer_index(ctx->last_buffer_index);
}
/*
* We search for the buffer that contains the last AR packet DMA data written
* by the controller.
*/
static unsigned int ar_search_last_active_buffer(struct ar_context *ctx,
unsigned int *buffer_offset)
{
unsigned int i, next_i, last = ctx->last_buffer_index;
__le16 res_count, next_res_count;
i = ar_first_buffer_index(ctx);
res_count = ACCESS_ONCE(ctx->descriptors[i].res_count);
/* A buffer that is not yet completely filled must be the last one. */
while (i != last && res_count == 0) {
/* Peek at the next descriptor. */
next_i = ar_next_buffer_index(i);
rmb(); /* read descriptors in order */
next_res_count = ACCESS_ONCE(
ctx->descriptors[next_i].res_count);
/*
* If the next descriptor is still empty, we must stop at this
* descriptor.
*/
if (next_res_count == cpu_to_le16(PAGE_SIZE)) {
/*
* The exception is when the DMA data for one packet is
* split over three buffers; in this case, the middle
* buffer's descriptor might be never updated by the
* controller and look still empty, and we have to peek
* at the third one.
*/
if (MAX_AR_PACKET_SIZE > PAGE_SIZE && i != last) {
next_i = ar_next_buffer_index(next_i);
rmb();
next_res_count = ACCESS_ONCE(
ctx->descriptors[next_i].res_count);
if (next_res_count != cpu_to_le16(PAGE_SIZE))
goto next_buffer_is_active;
}
break;
}
next_buffer_is_active:
i = next_i;
res_count = next_res_count;
}
rmb(); /* read res_count before the DMA data */
*buffer_offset = PAGE_SIZE - le16_to_cpu(res_count);
if (*buffer_offset > PAGE_SIZE) {
*buffer_offset = 0;
ar_context_abort(ctx, "corrupted descriptor");
}
return i;
}
static void ar_sync_buffers_for_cpu(struct ar_context *ctx,
unsigned int end_buffer_index,
unsigned int end_buffer_offset)
{
unsigned int i;
i = ar_first_buffer_index(ctx);
while (i != end_buffer_index) {
dma_sync_single_for_cpu(ctx->ohci->card.device,
ar_buffer_bus(ctx, i),
PAGE_SIZE, DMA_FROM_DEVICE);
i = ar_next_buffer_index(i);
}
if (end_buffer_offset > 0)
dma_sync_single_for_cpu(ctx->ohci->card.device,
ar_buffer_bus(ctx, i),
end_buffer_offset, DMA_FROM_DEVICE);
}
#if defined(CONFIG_PPC_PMAC) && defined(CONFIG_PPC32)
#define cond_le32_to_cpu(v) \
(ohci->quirks & QUIRK_BE_HEADERS ? (__force __u32)(v) : le32_to_cpu(v))
#else
#define cond_le32_to_cpu(v) le32_to_cpu(v)
#endif
static __le32 *handle_ar_packet(struct ar_context *ctx, __le32 *buffer)
{
struct fw_ohci *ohci = ctx->ohci;
struct fw_packet p;
u32 status, length, tcode;
int evt;
p.header[0] = cond_le32_to_cpu(buffer[0]);
p.header[1] = cond_le32_to_cpu(buffer[1]);
p.header[2] = cond_le32_to_cpu(buffer[2]);
tcode = (p.header[0] >> 4) & 0x0f;
switch (tcode) {
case TCODE_WRITE_QUADLET_REQUEST:
case TCODE_READ_QUADLET_RESPONSE:
p.header[3] = (__force __u32) buffer[3];
p.header_length = 16;
p.payload_length = 0;
break;
case TCODE_READ_BLOCK_REQUEST :
p.header[3] = cond_le32_to_cpu(buffer[3]);
p.header_length = 16;
p.payload_length = 0;
break;
case TCODE_WRITE_BLOCK_REQUEST:
case TCODE_READ_BLOCK_RESPONSE:
case TCODE_LOCK_REQUEST:
case TCODE_LOCK_RESPONSE:
p.header[3] = cond_le32_to_cpu(buffer[3]);
p.header_length = 16;
p.payload_length = p.header[3] >> 16;
if (p.payload_length > MAX_ASYNC_PAYLOAD) {
ar_context_abort(ctx, "invalid packet length");
return NULL;
}
break;
case TCODE_WRITE_RESPONSE:
case TCODE_READ_QUADLET_REQUEST:
case OHCI_TCODE_PHY_PACKET:
p.header_length = 12;
p.payload_length = 0;
break;
default:
ar_context_abort(ctx, "invalid tcode");
return NULL;
}
p.payload = (void *) buffer + p.header_length;
/* FIXME: What to do about evt_* errors? */
length = (p.header_length + p.payload_length + 3) / 4;
status = cond_le32_to_cpu(buffer[length]);
evt = (status >> 16) & 0x1f;
p.ack = evt - 16;
p.speed = (status >> 21) & 0x7;
p.timestamp = status & 0xffff;
p.generation = ohci->request_generation;
log_ar_at_event(ohci, 'R', p.speed, p.header, evt);
/*
* Several controllers, notably from NEC and VIA, forget to
* write ack_complete status at PHY packet reception.
*/
if (evt == OHCI1394_evt_no_status &&
(p.header[0] & 0xff) == (OHCI1394_phy_tcode << 4))
p.ack = ACK_COMPLETE;
/*
* The OHCI bus reset handler synthesizes a PHY packet with
* the new generation number when a bus reset happens (see
* section 8.4.2.3). This helps us determine when a request
* was received and make sure we send the response in the same
* generation. We only need this for requests; for responses
* we use the unique tlabel for finding the matching
* request.
*
* Alas some chips sometimes emit bus reset packets with a
* wrong generation. We set the correct generation for these
* at a slightly incorrect time (in bus_reset_work).
*/
if (evt == OHCI1394_evt_bus_reset) {
if (!(ohci->quirks & QUIRK_RESET_PACKET))
ohci->request_generation = (p.header[2] >> 16) & 0xff;
} else if (ctx == &ohci->ar_request_ctx) {
fw_core_handle_request(&ohci->card, &p);
} else {
fw_core_handle_response(&ohci->card, &p);
}
return buffer + length + 1;
}
static void *handle_ar_packets(struct ar_context *ctx, void *p, void *end)
{
void *next;
while (p < end) {
next = handle_ar_packet(ctx, p);
if (!next)
return p;
p = next;
}
return p;
}
static void ar_recycle_buffers(struct ar_context *ctx, unsigned int end_buffer)
{
unsigned int i;
i = ar_first_buffer_index(ctx);
while (i != end_buffer) {
dma_sync_single_for_device(ctx->ohci->card.device,
ar_buffer_bus(ctx, i),
PAGE_SIZE, DMA_FROM_DEVICE);
ar_context_link_page(ctx, i);
i = ar_next_buffer_index(i);
}
}
static void ar_context_tasklet(unsigned long data)
{
struct ar_context *ctx = (struct ar_context *)data;
unsigned int end_buffer_index, end_buffer_offset;
void *p, *end;
p = ctx->pointer;
if (!p)
return;
end_buffer_index = ar_search_last_active_buffer(ctx,
&end_buffer_offset);
ar_sync_buffers_for_cpu(ctx, end_buffer_index, end_buffer_offset);
end = ctx->buffer + end_buffer_index * PAGE_SIZE + end_buffer_offset;
if (end_buffer_index < ar_first_buffer_index(ctx)) {
/*
* The filled part of the overall buffer wraps around; handle
* all packets up to the buffer end here. If the last packet
* wraps around, its tail will be visible after the buffer end
* because the buffer start pages are mapped there again.
*/
void *buffer_end = ctx->buffer + AR_BUFFERS * PAGE_SIZE;
p = handle_ar_packets(ctx, p, buffer_end);
if (p < buffer_end)
goto error;
/* adjust p to point back into the actual buffer */
p -= AR_BUFFERS * PAGE_SIZE;
}
p = handle_ar_packets(ctx, p, end);
if (p != end) {
if (p > end)
ar_context_abort(ctx, "inconsistent descriptor");
goto error;
}
ctx->pointer = p;
ar_recycle_buffers(ctx, end_buffer_index);
return;
error:
ctx->pointer = NULL;
}
static int ar_context_init(struct ar_context *ctx, struct fw_ohci *ohci,
unsigned int descriptors_offset, u32 regs)
{
unsigned int i;
dma_addr_t dma_addr;
struct page *pages[AR_BUFFERS + AR_WRAPAROUND_PAGES];
struct descriptor *d;
ctx->regs = regs;
ctx->ohci = ohci;
tasklet_init(&ctx->tasklet, ar_context_tasklet, (unsigned long)ctx);
for (i = 0; i < AR_BUFFERS; i++) {
ctx->pages[i] = alloc_page(GFP_KERNEL | GFP_DMA32);
if (!ctx->pages[i])
goto out_of_memory;
dma_addr = dma_map_page(ohci->card.device, ctx->pages[i],
0, PAGE_SIZE, DMA_FROM_DEVICE);
if (dma_mapping_error(ohci->card.device, dma_addr)) {
__free_page(ctx->pages[i]);
ctx->pages[i] = NULL;
goto out_of_memory;
}
set_page_private(ctx->pages[i], dma_addr);
}
for (i = 0; i < AR_BUFFERS; i++)
pages[i] = ctx->pages[i];
for (i = 0; i < AR_WRAPAROUND_PAGES; i++)
pages[AR_BUFFERS + i] = ctx->pages[i];
ctx->buffer = vm_map_ram(pages, AR_BUFFERS + AR_WRAPAROUND_PAGES,
-1, PAGE_KERNEL);
if (!ctx->buffer)
goto out_of_memory;
ctx->descriptors = ohci->misc_buffer + descriptors_offset;
ctx->descriptors_bus = ohci->misc_buffer_bus + descriptors_offset;
for (i = 0; i < AR_BUFFERS; i++) {
d = &ctx->descriptors[i];
d->req_count = cpu_to_le16(PAGE_SIZE);
d->control = cpu_to_le16(DESCRIPTOR_INPUT_MORE |
DESCRIPTOR_STATUS |
DESCRIPTOR_BRANCH_ALWAYS);
d->data_address = cpu_to_le32(ar_buffer_bus(ctx, i));
d->branch_address = cpu_to_le32(ctx->descriptors_bus +
ar_next_buffer_index(i) * sizeof(struct descriptor));
}
return 0;
out_of_memory:
ar_context_release(ctx);
return -ENOMEM;
}
static void ar_context_run(struct ar_context *ctx)
{
unsigned int i;
for (i = 0; i < AR_BUFFERS; i++)
ar_context_link_page(ctx, i);
ctx->pointer = ctx->buffer;
reg_write(ctx->ohci, COMMAND_PTR(ctx->regs), ctx->descriptors_bus | 1);
reg_write(ctx->ohci, CONTROL_SET(ctx->regs), CONTEXT_RUN);
}
static struct descriptor *find_branch_descriptor(struct descriptor *d, int z)
{
__le16 branch;
branch = d->control & cpu_to_le16(DESCRIPTOR_BRANCH_ALWAYS);
/* figure out which descriptor the branch address goes in */
if (z == 2 && branch == cpu_to_le16(DESCRIPTOR_BRANCH_ALWAYS))
return d;
else
return d + z - 1;
}
static void context_tasklet(unsigned long data)
{
struct context *ctx = (struct context *) data;
struct descriptor *d, *last;
u32 address;
int z;
struct descriptor_buffer *desc;
desc = list_entry(ctx->buffer_list.next,
struct descriptor_buffer, list);
last = ctx->last;
while (last->branch_address != 0) {
struct descriptor_buffer *old_desc = desc;
address = le32_to_cpu(last->branch_address);
z = address & 0xf;
address &= ~0xf;
ctx->current_bus = address;
/* If the branch address points to a buffer outside of the
* current buffer, advance to the next buffer. */
if (address < desc->buffer_bus ||
address >= desc->buffer_bus + desc->used)
desc = list_entry(desc->list.next,
struct descriptor_buffer, list);
d = desc->buffer + (address - desc->buffer_bus) / sizeof(*d);
last = find_branch_descriptor(d, z);
if (!ctx->callback(ctx, d, last))
break;
if (old_desc != desc) {
/* If we've advanced to the next buffer, move the
* previous buffer to the free list. */
unsigned long flags;
old_desc->used = 0;
spin_lock_irqsave(&ctx->ohci->lock, flags);
list_move_tail(&old_desc->list, &ctx->buffer_list);
spin_unlock_irqrestore(&ctx->ohci->lock, flags);
}
ctx->last = last;
}
}
/*
* Allocate a new buffer and add it to the list of free buffers for this
* context. Must be called with ohci->lock held.
*/
static int context_add_buffer(struct context *ctx)
{
struct descriptor_buffer *desc;
dma_addr_t uninitialized_var(bus_addr);
int offset;
/*
* 16MB of descriptors should be far more than enough for any DMA
* program. This will catch run-away userspace or DoS attacks.
*/
if (ctx->total_allocation >= 16*1024*1024)
return -ENOMEM;
desc = dma_alloc_coherent(ctx->ohci->card.device, PAGE_SIZE,
&bus_addr, GFP_ATOMIC);
if (!desc)
return -ENOMEM;
offset = (void *)&desc->buffer - (void *)desc;
desc->buffer_size = PAGE_SIZE - offset;
desc->buffer_bus = bus_addr + offset;
desc->used = 0;
list_add_tail(&desc->list, &ctx->buffer_list);
ctx->total_allocation += PAGE_SIZE;
return 0;
}
static int context_init(struct context *ctx, struct fw_ohci *ohci,
u32 regs, descriptor_callback_t callback)
{
ctx->ohci = ohci;
ctx->regs = regs;
ctx->total_allocation = 0;
INIT_LIST_HEAD(&ctx->buffer_list);
if (context_add_buffer(ctx) < 0)
return -ENOMEM;
ctx->buffer_tail = list_entry(ctx->buffer_list.next,
struct descriptor_buffer, list);
tasklet_init(&ctx->tasklet, context_tasklet, (unsigned long)ctx);
ctx->callback = callback;
/*
* We put a dummy descriptor in the buffer that has a NULL
* branch address and looks like it's been sent. That way we
* have a descriptor to append DMA programs to.
*/
memset(ctx->buffer_tail->buffer, 0, sizeof(*ctx->buffer_tail->buffer));
ctx->buffer_tail->buffer->control = cpu_to_le16(DESCRIPTOR_OUTPUT_LAST);
ctx->buffer_tail->buffer->transfer_status = cpu_to_le16(0x8011);
ctx->buffer_tail->used += sizeof(*ctx->buffer_tail->buffer);
ctx->last = ctx->buffer_tail->buffer;
ctx->prev = ctx->buffer_tail->buffer;
ctx->prev_z = 1;
return 0;
}
static void context_release(struct context *ctx)
{
struct fw_card *card = &ctx->ohci->card;
struct descriptor_buffer *desc, *tmp;
list_for_each_entry_safe(desc, tmp, &ctx->buffer_list, list)
dma_free_coherent(card->device, PAGE_SIZE, desc,
desc->buffer_bus -
((void *)&desc->buffer - (void *)desc));
}
/* Must be called with ohci->lock held */
static struct descriptor *context_get_descriptors(struct context *ctx,
int z, dma_addr_t *d_bus)
{
struct descriptor *d = NULL;
struct descriptor_buffer *desc = ctx->buffer_tail;
if (z * sizeof(*d) > desc->buffer_size)
return NULL;
if (z * sizeof(*d) > desc->buffer_size - desc->used) {
/* No room for the descriptor in this buffer, so advance to the
* next one. */
if (desc->list.next == &ctx->buffer_list) {
/* If there is no free buffer next in the list,
* allocate one. */
if (context_add_buffer(ctx) < 0)
return NULL;
}
desc = list_entry(desc->list.next,
struct descriptor_buffer, list);
ctx->buffer_tail = desc;
}
d = desc->buffer + desc->used / sizeof(*d);
memset(d, 0, z * sizeof(*d));
*d_bus = desc->buffer_bus + desc->used;
return d;
}
static void context_run(struct context *ctx, u32 extra)
{
struct fw_ohci *ohci = ctx->ohci;
reg_write(ohci, COMMAND_PTR(ctx->regs),
le32_to_cpu(ctx->last->branch_address));
reg_write(ohci, CONTROL_CLEAR(ctx->regs), ~0);
reg_write(ohci, CONTROL_SET(ctx->regs), CONTEXT_RUN | extra);
ctx->running = true;
flush_writes(ohci);
}
static void context_append(struct context *ctx,
struct descriptor *d, int z, int extra)
{
dma_addr_t d_bus;
struct descriptor_buffer *desc = ctx->buffer_tail;
struct descriptor *d_branch;
d_bus = desc->buffer_bus + (d - desc->buffer) * sizeof(*d);
desc->used += (z + extra) * sizeof(*d);
wmb(); /* finish init of new descriptors before branch_address update */
d_branch = find_branch_descriptor(ctx->prev, ctx->prev_z);
d_branch->branch_address = cpu_to_le32(d_bus | z);
/*
* VT6306 incorrectly checks only the single descriptor at the
* CommandPtr when the wake bit is written, so if it's a
* multi-descriptor block starting with an INPUT_MORE, put a copy of
* the branch address in the first descriptor.
*
* Not doing this for transmit contexts since not sure how it interacts
* with skip addresses.
*/
if (unlikely(ctx->ohci->quirks & QUIRK_IR_WAKE) &&
d_branch != ctx->prev &&
(ctx->prev->control & cpu_to_le16(DESCRIPTOR_CMD)) ==
cpu_to_le16(DESCRIPTOR_INPUT_MORE)) {
ctx->prev->branch_address = cpu_to_le32(d_bus | z);
}
ctx->prev = d;
ctx->prev_z = z;
}
static void context_stop(struct context *ctx)
{
struct fw_ohci *ohci = ctx->ohci;
u32 reg;
int i;
reg_write(ohci, CONTROL_CLEAR(ctx->regs), CONTEXT_RUN);
ctx->running = false;
for (i = 0; i < 1000; i++) {
reg = reg_read(ohci, CONTROL_SET(ctx->regs));
if ((reg & CONTEXT_ACTIVE) == 0)
return;
if (i)
udelay(10);
}
ohci_err(ohci, "DMA context still active (0x%08x)\n", reg);
}
struct driver_data {
u8 inline_data[8];
struct fw_packet *packet;
};
/*
* This function apppends a packet to the DMA queue for transmission.
* Must always be called with the ochi->lock held to ensure proper
* generation handling and locking around packet queue manipulation.
*/
static int at_context_queue_packet(struct context *ctx,
struct fw_packet *packet)
{
struct fw_ohci *ohci = ctx->ohci;
dma_addr_t d_bus, uninitialized_var(payload_bus);
struct driver_data *driver_data;
struct descriptor *d, *last;
__le32 *header;
int z, tcode;
d = context_get_descriptors(ctx, 4, &d_bus);
if (d == NULL) {
packet->ack = RCODE_SEND_ERROR;
return -1;
}
d[0].control = cpu_to_le16(DESCRIPTOR_KEY_IMMEDIATE);
d[0].res_count = cpu_to_le16(packet->timestamp);
/*
* The DMA format for asynchronous link packets is different
* from the IEEE1394 layout, so shift the fields around
* accordingly.
*/
tcode = (packet->header[0] >> 4) & 0x0f;
header = (__le32 *) &d[1];
switch (tcode) {
case TCODE_WRITE_QUADLET_REQUEST:
case TCODE_WRITE_BLOCK_REQUEST:
case TCODE_WRITE_RESPONSE:
case TCODE_READ_QUADLET_REQUEST:
case TCODE_READ_BLOCK_REQUEST:
case TCODE_READ_QUADLET_RESPONSE:
case TCODE_READ_BLOCK_RESPONSE:
case TCODE_LOCK_REQUEST:
case TCODE_LOCK_RESPONSE:
header[0] = cpu_to_le32((packet->header[0] & 0xffff) |
(packet->speed << 16));
header[1] = cpu_to_le32((packet->header[1] & 0xffff) |
(packet->header[0] & 0xffff0000));
header[2] = cpu_to_le32(packet->header[2]);
if (TCODE_IS_BLOCK_PACKET(tcode))
header[3] = cpu_to_le32(packet->header[3]);
else
header[3] = (__force __le32) packet->header[3];
d[0].req_count = cpu_to_le16(packet->header_length);
break;
case TCODE_LINK_INTERNAL:
header[0] = cpu_to_le32((OHCI1394_phy_tcode << 4) |
(packet->speed << 16));
header[1] = cpu_to_le32(packet->header[1]);
header[2] = cpu_to_le32(packet->header[2]);
d[0].req_count = cpu_to_le16(12);
if (is_ping_packet(&packet->header[1]))
d[0].control |= cpu_to_le16(DESCRIPTOR_PING);
break;
case TCODE_STREAM_DATA:
header[0] = cpu_to_le32((packet->header[0] & 0xffff) |
(packet->speed << 16));
header[1] = cpu_to_le32(packet->header[0] & 0xffff0000);
d[0].req_count = cpu_to_le16(8);
break;
default:
/* BUG(); */
packet->ack = RCODE_SEND_ERROR;
return -1;
}
BUILD_BUG_ON(sizeof(struct driver_data) > sizeof(struct descriptor));
driver_data = (struct driver_data *) &d[3];
driver_data->packet = packet;
packet->driver_data = driver_data;
if (packet->payload_length > 0) {
if (packet->payload_length > sizeof(driver_data->inline_data)) {
payload_bus = dma_map_single(ohci->card.device,
packet->payload,
packet->payload_length,
DMA_TO_DEVICE);
if (dma_mapping_error(ohci->card.device, payload_bus)) {
packet->ack = RCODE_SEND_ERROR;
return -1;
}
packet->payload_bus = payload_bus;
packet->payload_mapped = true;
} else {
memcpy(driver_data->inline_data, packet->payload,
packet->payload_length);
payload_bus = d_bus + 3 * sizeof(*d);
}
d[2].req_count = cpu_to_le16(packet->payload_length);
d[2].data_address = cpu_to_le32(payload_bus);
last = &d[2];
z = 3;
} else {
last = &d[0];
z = 2;
}
last->control |= cpu_to_le16(DESCRIPTOR_OUTPUT_LAST |
DESCRIPTOR_IRQ_ALWAYS |
DESCRIPTOR_BRANCH_ALWAYS);
/* FIXME: Document how the locking works. */
if (ohci->generation != packet->generation) {
if (packet->payload_mapped)
dma_unmap_single(ohci->card.device, payload_bus,
packet->payload_length, DMA_TO_DEVICE);
packet->ack = RCODE_GENERATION;
return -1;
}
context_append(ctx, d, z, 4 - z);
if (ctx->running)
reg_write(ohci, CONTROL_SET(ctx->regs), CONTEXT_WAKE);
else
context_run(ctx, 0);
return 0;
}
static void at_context_flush(struct context *ctx)
{
tasklet_disable(&ctx->tasklet);
ctx->flushing = true;
context_tasklet((unsigned long)ctx);
ctx->flushing = false;
tasklet_enable(&ctx->tasklet);
}
static int handle_at_packet(struct context *context,
struct descriptor *d,
struct descriptor *last)
{
struct driver_data *driver_data;
struct fw_packet *packet;
struct fw_ohci *ohci = context->ohci;
int evt;
if (last->transfer_status == 0 && !context->flushing)
/* This descriptor isn't done yet, stop iteration. */
return 0;
driver_data = (struct driver_data *) &d[3];
packet = driver_data->packet;
if (packet == NULL)
/* This packet was cancelled, just continue. */
return 1;
if (packet->payload_mapped)
dma_unmap_single(ohci->card.device, packet->payload_bus,
packet->payload_length, DMA_TO_DEVICE);
evt = le16_to_cpu(last->transfer_status) & 0x1f;
packet->timestamp = le16_to_cpu(last->res_count);
log_ar_at_event(ohci, 'T', packet->speed, packet->header, evt);
switch (evt) {
case OHCI1394_evt_timeout:
/* Async response transmit timed out. */
packet->ack = RCODE_CANCELLED;
break;
case OHCI1394_evt_flushed:
/*
* The packet was flushed should give same error as
* when we try to use a stale generation count.
*/
packet->ack = RCODE_GENERATION;
break;
case OHCI1394_evt_missing_ack:
if (context->flushing)
packet->ack = RCODE_GENERATION;
else {
/*
* Using a valid (current) generation count, but the
* node is not on the bus or not sending acks.
*/
packet->ack = RCODE_NO_ACK;
}
break;
case ACK_COMPLETE + 0x10:
case ACK_PENDING + 0x10:
case ACK_BUSY_X + 0x10:
case ACK_BUSY_A + 0x10:
case ACK_BUSY_B + 0x10:
case ACK_DATA_ERROR + 0x10:
case ACK_TYPE_ERROR + 0x10:
packet->ack = evt - 0x10;
break;
case OHCI1394_evt_no_status:
if (context->flushing) {
packet->ack = RCODE_GENERATION;
break;
}
/* fall through */
default:
packet->ack = RCODE_SEND_ERROR;
break;
}
packet->callback(packet, &ohci->card, packet->ack);
return 1;
}
#define HEADER_GET_DESTINATION(q) (((q) >> 16) & 0xffff)
#define HEADER_GET_TCODE(q) (((q) >> 4) & 0x0f)
#define HEADER_GET_OFFSET_HIGH(q) (((q) >> 0) & 0xffff)
#define HEADER_GET_DATA_LENGTH(q) (((q) >> 16) & 0xffff)
#define HEADER_GET_EXTENDED_TCODE(q) (((q) >> 0) & 0xffff)
static void handle_local_rom(struct fw_ohci *ohci,
struct fw_packet *packet, u32 csr)
{
struct fw_packet response;
int tcode, length, i;
tcode = HEADER_GET_TCODE(packet->header[0]);
if (TCODE_IS_BLOCK_PACKET(tcode))
length = HEADER_GET_DATA_LENGTH(packet->header[3]);
else
length = 4;
i = csr - CSR_CONFIG_ROM;
if (i + length > CONFIG_ROM_SIZE) {
fw_fill_response(&response, packet->header,
RCODE_ADDRESS_ERROR, NULL, 0);
} else if (!TCODE_IS_READ_REQUEST(tcode)) {
fw_fill_response(&response, packet->header,
RCODE_TYPE_ERROR, NULL, 0);
} else {
fw_fill_response(&response, packet->header, RCODE_COMPLETE,
(void *) ohci->config_rom + i, length);
}
fw_core_handle_response(&ohci->card, &response);
}
static void handle_local_lock(struct fw_ohci *ohci,
struct fw_packet *packet, u32 csr)
{
struct fw_packet response;
int tcode, length, ext_tcode, sel, try;
__be32 *payload, lock_old;
u32 lock_arg, lock_data;
tcode = HEADER_GET_TCODE(packet->header[0]);
length = HEADER_GET_DATA_LENGTH(packet->header[3]);
payload = packet->payload;
ext_tcode = HEADER_GET_EXTENDED_TCODE(packet->header[3]);
if (tcode == TCODE_LOCK_REQUEST &&
ext_tcode == EXTCODE_COMPARE_SWAP && length == 8) {
lock_arg = be32_to_cpu(payload[0]);
lock_data = be32_to_cpu(payload[1]);
} else if (tcode == TCODE_READ_QUADLET_REQUEST) {
lock_arg = 0;
lock_data = 0;
} else {
fw_fill_response(&response, packet->header,
RCODE_TYPE_ERROR, NULL, 0);
goto out;
}
sel = (csr - CSR_BUS_MANAGER_ID) / 4;
reg_write(ohci, OHCI1394_CSRData, lock_data);
reg_write(ohci, OHCI1394_CSRCompareData, lock_arg);
reg_write(ohci, OHCI1394_CSRControl, sel);
for (try = 0; try < 20; try++)
if (reg_read(ohci, OHCI1394_CSRControl) & 0x80000000) {
lock_old = cpu_to_be32(reg_read(ohci,
OHCI1394_CSRData));
fw_fill_response(&response, packet->header,
RCODE_COMPLETE,
&lock_old, sizeof(lock_old));
goto out;
}
ohci_err(ohci, "swap not done (CSR lock timeout)\n");
fw_fill_response(&response, packet->header, RCODE_BUSY, NULL, 0);
out:
fw_core_handle_response(&ohci->card, &response);
}
static void handle_local_request(struct context *ctx, struct fw_packet *packet)
{
u64 offset, csr;
if (ctx == &ctx->ohci->at_request_ctx) {
packet->ack = ACK_PENDING;
packet->callback(packet, &ctx->ohci->card, packet->ack);
}
offset =
((unsigned long long)
HEADER_GET_OFFSET_HIGH(packet->header[1]) << 32) |
packet->header[2];
csr = offset - CSR_REGISTER_BASE;
/* Handle config rom reads. */
if (csr >= CSR_CONFIG_ROM && csr < CSR_CONFIG_ROM_END)
handle_local_rom(ctx->ohci, packet, csr);
else switch (csr) {
case CSR_BUS_MANAGER_ID:
case CSR_BANDWIDTH_AVAILABLE:
case CSR_CHANNELS_AVAILABLE_HI:
case CSR_CHANNELS_AVAILABLE_LO:
handle_local_lock(ctx->ohci, packet, csr);
break;
default:
if (ctx == &ctx->ohci->at_request_ctx)
fw_core_handle_request(&ctx->ohci->card, packet);
else
fw_core_handle_response(&ctx->ohci->card, packet);
break;
}
if (ctx == &ctx->ohci->at_response_ctx) {
packet->ack = ACK_COMPLETE;
packet->callback(packet, &ctx->ohci->card, packet->ack);
}
}
static void at_context_transmit(struct context *ctx, struct fw_packet *packet)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&ctx->ohci->lock, flags);
if (HEADER_GET_DESTINATION(packet->header[0]) == ctx->ohci->node_id &&
ctx->ohci->generation == packet->generation) {
spin_unlock_irqrestore(&ctx->ohci->lock, flags);
handle_local_request(ctx, packet);
return;
}
ret = at_context_queue_packet(ctx, packet);
spin_unlock_irqrestore(&ctx->ohci->lock, flags);
if (ret < 0)
packet->callback(packet, &ctx->ohci->card, packet->ack);
}
static void detect_dead_context(struct fw_ohci *ohci,
const char *name, unsigned int regs)
{
u32 ctl;
ctl = reg_read(ohci, CONTROL_SET(regs));
if (ctl & CONTEXT_DEAD)
ohci_err(ohci, "DMA context %s has stopped, error code: %s\n",
name, evts[ctl & 0x1f]);
}
static void handle_dead_contexts(struct fw_ohci *ohci)
{
unsigned int i;
char name[8];
detect_dead_context(ohci, "ATReq", OHCI1394_AsReqTrContextBase);
detect_dead_context(ohci, "ATRsp", OHCI1394_AsRspTrContextBase);
detect_dead_context(ohci, "ARReq", OHCI1394_AsReqRcvContextBase);
detect_dead_context(ohci, "ARRsp", OHCI1394_AsRspRcvContextBase);
for (i = 0; i < 32; ++i) {
if (!(ohci->it_context_support & (1 << i)))
continue;
sprintf(name, "IT%u", i);
detect_dead_context(ohci, name, OHCI1394_IsoXmitContextBase(i));
}
for (i = 0; i < 32; ++i) {
if (!(ohci->ir_context_support & (1 << i)))
continue;
sprintf(name, "IR%u", i);
detect_dead_context(ohci, name, OHCI1394_IsoRcvContextBase(i));
}
/* TODO: maybe try to flush and restart the dead contexts */
}
static u32 cycle_timer_ticks(u32 cycle_timer)
{
u32 ticks;
ticks = cycle_timer & 0xfff;
ticks += 3072 * ((cycle_timer >> 12) & 0x1fff);
ticks += (3072 * 8000) * (cycle_timer >> 25);
return ticks;
}
/*
* Some controllers exhibit one or more of the following bugs when updating the
* iso cycle timer register:
* - When the lowest six bits are wrapping around to zero, a read that happens
* at the same time will return garbage in the lowest ten bits.
* - When the cycleOffset field wraps around to zero, the cycleCount field is
* not incremented for about 60 ns.
* - Occasionally, the entire register reads zero.
*
* To catch these, we read the register three times and ensure that the
* difference between each two consecutive reads is approximately the same, i.e.
* less than twice the other. Furthermore, any negative difference indicates an
* error. (A PCI read should take at least 20 ticks of the 24.576 MHz timer to
* execute, so we have enough precision to compute the ratio of the differences.)
*/
static u32 get_cycle_time(struct fw_ohci *ohci)
{
u32 c0, c1, c2;
u32 t0, t1, t2;
s32 diff01, diff12;
int i;
c2 = reg_read(ohci, OHCI1394_IsochronousCycleTimer);
if (ohci->quirks & QUIRK_CYCLE_TIMER) {
i = 0;
c1 = c2;
c2 = reg_read(ohci, OHCI1394_IsochronousCycleTimer);
do {
c0 = c1;
c1 = c2;
c2 = reg_read(ohci, OHCI1394_IsochronousCycleTimer);
t0 = cycle_timer_ticks(c0);
t1 = cycle_timer_ticks(c1);
t2 = cycle_timer_ticks(c2);
diff01 = t1 - t0;
diff12 = t2 - t1;
} while ((diff01 <= 0 || diff12 <= 0 ||
diff01 / diff12 >= 2 || diff12 / diff01 >= 2)
&& i++ < 20);
}
return c2;
}
/*
* This function has to be called at least every 64 seconds. The bus_time
* field stores not only the upper 25 bits of the BUS_TIME register but also
* the most significant bit of the cycle timer in bit 6 so that we can detect
* changes in this bit.
*/
static u32 update_bus_time(struct fw_ohci *ohci)
{
u32 cycle_time_seconds = get_cycle_time(ohci) >> 25;
if (unlikely(!ohci->bus_time_running)) {
reg_write(ohci, OHCI1394_IntMaskSet, OHCI1394_cycle64Seconds);
ohci->bus_time = (lower_32_bits(get_seconds()) & ~0x7f) |
(cycle_time_seconds & 0x40);
ohci->bus_time_running = true;
}
if ((ohci->bus_time & 0x40) != (cycle_time_seconds & 0x40))
ohci->bus_time += 0x40;
return ohci->bus_time | cycle_time_seconds;
}
static int get_status_for_port(struct fw_ohci *ohci, int port_index)
{
int reg;
mutex_lock(&ohci->phy_reg_mutex);
reg = write_phy_reg(ohci, 7, port_index);
if (reg >= 0)
reg = read_phy_reg(ohci, 8);
mutex_unlock(&ohci->phy_reg_mutex);
if (reg < 0)
return reg;
switch (reg & 0x0f) {
case 0x06:
return 2; /* is child node (connected to parent node) */
case 0x0e:
return 3; /* is parent node (connected to child node) */
}
return 1; /* not connected */
}
static int get_self_id_pos(struct fw_ohci *ohci, u32 self_id,
int self_id_count)
{
int i;
u32 entry;
for (i = 0; i < self_id_count; i++) {
entry = ohci->self_id_buffer[i];
if ((self_id & 0xff000000) == (entry & 0xff000000))
return -1;
if ((self_id & 0xff000000) < (entry & 0xff000000))
return i;
}
return i;
}
static int initiated_reset(struct fw_ohci *ohci)
{
int reg;
int ret = 0;
mutex_lock(&ohci->phy_reg_mutex);
reg = write_phy_reg(ohci, 7, 0xe0); /* Select page 7 */
if (reg >= 0) {
reg = read_phy_reg(ohci, 8);
reg |= 0x40;
reg = write_phy_reg(ohci, 8, reg); /* set PMODE bit */
if (reg >= 0) {
reg = read_phy_reg(ohci, 12); /* read register 12 */
if (reg >= 0) {
if ((reg & 0x08) == 0x08) {
/* bit 3 indicates "initiated reset" */
ret = 0x2;
}
}
}
}
mutex_unlock(&ohci->phy_reg_mutex);
return ret;
}
/*
* TI TSB82AA2B and TSB12LV26 do not receive the selfID of a locally
* attached TSB41BA3D phy; see http://www.ti.com/litv/pdf/sllz059.
* Construct the selfID from phy register contents.
*/
static int find_and_insert_self_id(struct fw_ohci *ohci, int self_id_count)
{
int reg, i, pos, status;
/* link active 1, speed 3, bridge 0, contender 1, more packets 0 */
u32 self_id = 0x8040c800;
reg = reg_read(ohci, OHCI1394_NodeID);
if (!(reg & OHCI1394_NodeID_idValid)) {
ohci_notice(ohci,
"node ID not valid, new bus reset in progress\n");
return -EBUSY;
}
self_id |= ((reg & 0x3f) << 24); /* phy ID */
reg = ohci_read_phy_reg(&ohci->card, 4);
if (reg < 0)
return reg;
self_id |= ((reg & 0x07) << 8); /* power class */
reg = ohci_read_phy_reg(&ohci->card, 1);
if (reg < 0)
return reg;
self_id |= ((reg & 0x3f) << 16); /* gap count */
for (i = 0; i < 3; i++) {
status = get_status_for_port(ohci, i);
if (status < 0)
return status;
self_id |= ((status & 0x3) << (6 - (i * 2)));
}
self_id |= initiated_reset(ohci);
pos = get_self_id_pos(ohci, self_id, self_id_count);
if (pos >= 0) {
memmove(&(ohci->self_id_buffer[pos+1]),
&(ohci->self_id_buffer[pos]),
(self_id_count - pos) * sizeof(*ohci->self_id_buffer));
ohci->self_id_buffer[pos] = self_id;
self_id_count++;
}
return self_id_count;
}
static void bus_reset_work(struct work_struct *work)
{
struct fw_ohci *ohci =
container_of(work, struct fw_ohci, bus_reset_work);
int self_id_count, generation, new_generation, i, j;
u32 reg;
void *free_rom = NULL;
dma_addr_t free_rom_bus = 0;
bool is_new_root;
reg = reg_read(ohci, OHCI1394_NodeID);
if (!(reg & OHCI1394_NodeID_idValid)) {
ohci_notice(ohci,
"node ID not valid, new bus reset in progress\n");
return;
}
if ((reg & OHCI1394_NodeID_nodeNumber) == 63) {
ohci_notice(ohci, "malconfigured bus\n");
return;
}
ohci->node_id = reg & (OHCI1394_NodeID_busNumber |
OHCI1394_NodeID_nodeNumber);
is_new_root = (reg & OHCI1394_NodeID_root) != 0;
if (!(ohci->is_root && is_new_root))
reg_write(ohci, OHCI1394_LinkControlSet,
OHCI1394_LinkControl_cycleMaster);
ohci->is_root = is_new_root;
reg = reg_read(ohci, OHCI1394_SelfIDCount);
if (reg & OHCI1394_SelfIDCount_selfIDError) {
ohci_notice(ohci, "self ID receive error\n");
return;
}
/*
* The count in the SelfIDCount register is the number of
* bytes in the self ID receive buffer. Since we also receive
* the inverted quadlets and a header quadlet, we shift one
* bit extra to get the actual number of self IDs.
*/
self_id_count = (reg >> 3) & 0xff;
if (self_id_count > 252) {
ohci_notice(ohci, "bad selfIDSize (%08x)\n", reg);
return;
}
generation = (cond_le32_to_cpu(ohci->self_id[0]) >> 16) & 0xff;
rmb();
for (i = 1, j = 0; j < self_id_count; i += 2, j++) {
u32 id = cond_le32_to_cpu(ohci->self_id[i]);
u32 id2 = cond_le32_to_cpu(ohci->self_id[i + 1]);
if (id != ~id2) {
/*
* If the invalid data looks like a cycle start packet,
* it's likely to be the result of the cycle master
* having a wrong gap count. In this case, the self IDs
* so far are valid and should be processed so that the
* bus manager can then correct the gap count.
*/
if (id == 0xffff008f) {
ohci_notice(ohci, "ignoring spurious self IDs\n");
self_id_count = j;
break;
}
ohci_notice(ohci, "bad self ID %d/%d (%08x != ~%08x)\n",
j, self_id_count, id, id2);
return;
}
ohci->self_id_buffer[j] = id;
}
if (ohci->quirks & QUIRK_TI_SLLZ059) {
self_id_count = find_and_insert_self_id(ohci, self_id_count);
if (self_id_count < 0) {
ohci_notice(ohci,
"could not construct local self ID\n");
return;
}
}
if (self_id_count == 0) {
ohci_notice(ohci, "no self IDs\n");
return;
}
rmb();
/*
* Check the consistency of the self IDs we just read. The
* problem we face is that a new bus reset can start while we
* read out the self IDs from the DMA buffer. If this happens,
* the DMA buffer will be overwritten with new self IDs and we
* will read out inconsistent data. The OHCI specification
* (section 11.2) recommends a technique similar to
* linux/seqlock.h, where we remember the generation of the
* self IDs in the buffer before reading them out and compare
* it to the current generation after reading them out. If
* the two generations match we know we have a consistent set
* of self IDs.
*/
new_generation = (reg_read(ohci, OHCI1394_SelfIDCount) >> 16) & 0xff;
if (new_generation != generation) {
ohci_notice(ohci, "new bus reset, discarding self ids\n");
return;
}
/* FIXME: Document how the locking works. */
spin_lock_irq(&ohci->lock);
ohci->generation = -1; /* prevent AT packet queueing */
context_stop(&ohci->at_request_ctx);
context_stop(&ohci->at_response_ctx);
spin_unlock_irq(&ohci->lock);
/*
* Per OHCI 1.2 draft, clause 7.2.3.3, hardware may leave unsent
* packets in the AT queues and software needs to drain them.
* Some OHCI 1.1 controllers (JMicron) apparently require this too.
*/
at_context_flush(&ohci->at_request_ctx);
at_context_flush(&ohci->at_response_ctx);
spin_lock_irq(&ohci->lock);
ohci->generation = generation;
reg_write(ohci, OHCI1394_IntEventClear, OHCI1394_busReset);
if (ohci->quirks & QUIRK_RESET_PACKET)
ohci->request_generation = generation;
/*
* This next bit is unrelated to the AT context stuff but we
* have to do it under the spinlock also. If a new config rom
* was set up before this reset, the old one is now no longer
* in use and we can free it. Update the config rom pointers
* to point to the current config rom and clear the
* next_config_rom pointer so a new update can take place.
*/
if (ohci->next_config_rom != NULL) {
if (ohci->next_config_rom != ohci->config_rom) {
free_rom = ohci->config_rom;
free_rom_bus = ohci->config_rom_bus;
}
ohci->config_rom = ohci->next_config_rom;
ohci->config_rom_bus = ohci->next_config_rom_bus;
ohci->next_config_rom = NULL;
/*
* Restore config_rom image and manually update
* config_rom registers. Writing the header quadlet
* will indicate that the config rom is ready, so we
* do that last.
*/
reg_write(ohci, OHCI1394_BusOptions,
be32_to_cpu(ohci->config_rom[2]));
ohci->config_rom[0] = ohci->next_header;
reg_write(ohci, OHCI1394_ConfigROMhdr,
be32_to_cpu(ohci->next_header));
}
if (param_remote_dma) {
reg_write(ohci, OHCI1394_PhyReqFilterHiSet, ~0);
reg_write(ohci, OHCI1394_PhyReqFilterLoSet, ~0);
}
spin_unlock_irq(&ohci->lock);
if (free_rom)
dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
free_rom, free_rom_bus);
log_selfids(ohci, generation, self_id_count);
fw_core_handle_bus_reset(&ohci->card, ohci->node_id, generation,
self_id_count, ohci->self_id_buffer,
ohci->csr_state_setclear_abdicate);
ohci->csr_state_setclear_abdicate = false;
}
static irqreturn_t irq_handler(int irq, void *data)
{
struct fw_ohci *ohci = data;
u32 event, iso_event;
int i;
event = reg_read(ohci, OHCI1394_IntEventClear);
if (!event || !~event)
return IRQ_NONE;
/*
* busReset and postedWriteErr must not be cleared yet
* (OHCI 1.1 clauses 7.2.3.2 and 13.2.8.1)
*/
reg_write(ohci, OHCI1394_IntEventClear,
event & ~(OHCI1394_busReset | OHCI1394_postedWriteErr));
log_irqs(ohci, event);
if (event & OHCI1394_selfIDComplete)
queue_work(selfid_workqueue, &ohci->bus_reset_work);
if (event & OHCI1394_RQPkt)
tasklet_schedule(&ohci->ar_request_ctx.tasklet);
if (event & OHCI1394_RSPkt)
tasklet_schedule(&ohci->ar_response_ctx.tasklet);
if (event & OHCI1394_reqTxComplete)
tasklet_schedule(&ohci->at_request_ctx.tasklet);
if (event & OHCI1394_respTxComplete)
tasklet_schedule(&ohci->at_response_ctx.tasklet);
if (event & OHCI1394_isochRx) {
iso_event = reg_read(ohci, OHCI1394_IsoRecvIntEventClear);
reg_write(ohci, OHCI1394_IsoRecvIntEventClear, iso_event);
while (iso_event) {
i = ffs(iso_event) - 1;
tasklet_schedule(
&ohci->ir_context_list[i].context.tasklet);
iso_event &= ~(1 << i);
}
}
if (event & OHCI1394_isochTx) {
iso_event = reg_read(ohci, OHCI1394_IsoXmitIntEventClear);
reg_write(ohci, OHCI1394_IsoXmitIntEventClear, iso_event);
while (iso_event) {
i = ffs(iso_event) - 1;
tasklet_schedule(
&ohci->it_context_list[i].context.tasklet);
iso_event &= ~(1 << i);
}
}
if (unlikely(event & OHCI1394_regAccessFail))
ohci_err(ohci, "register access failure\n");
if (unlikely(event & OHCI1394_postedWriteErr)) {
reg_read(ohci, OHCI1394_PostedWriteAddressHi);
reg_read(ohci, OHCI1394_PostedWriteAddressLo);
reg_write(ohci, OHCI1394_IntEventClear,
OHCI1394_postedWriteErr);
if (printk_ratelimit())
ohci_err(ohci, "PCI posted write error\n");
}
if (unlikely(event & OHCI1394_cycleTooLong)) {
if (printk_ratelimit())
ohci_notice(ohci, "isochronous cycle too long\n");
reg_write(ohci, OHCI1394_LinkControlSet,
OHCI1394_LinkControl_cycleMaster);
}
if (unlikely(event & OHCI1394_cycleInconsistent)) {
/*
* We need to clear this event bit in order to make
* cycleMatch isochronous I/O work. In theory we should
* stop active cycleMatch iso contexts now and restart
* them at least two cycles later. (FIXME?)
*/
if (printk_ratelimit())
ohci_notice(ohci, "isochronous cycle inconsistent\n");
}
if (unlikely(event & OHCI1394_unrecoverableError))
handle_dead_contexts(ohci);
if (event & OHCI1394_cycle64Seconds) {
spin_lock(&ohci->lock);
update_bus_time(ohci);
spin_unlock(&ohci->lock);
} else
flush_writes(ohci);
return IRQ_HANDLED;
}
static int software_reset(struct fw_ohci *ohci)
{
u32 val;
int i;
reg_write(ohci, OHCI1394_HCControlSet, OHCI1394_HCControl_softReset);
for (i = 0; i < 500; i++) {
val = reg_read(ohci, OHCI1394_HCControlSet);
if (!~val)
return -ENODEV; /* Card was ejected. */
if (!(val & OHCI1394_HCControl_softReset))
return 0;
msleep(1);
}
return -EBUSY;
}
static void copy_config_rom(__be32 *dest, const __be32 *src, size_t length)
{
size_t size = length * 4;
memcpy(dest, src, size);
if (size < CONFIG_ROM_SIZE)
memset(&dest[length], 0, CONFIG_ROM_SIZE - size);
}
static int configure_1394a_enhancements(struct fw_ohci *ohci)
{
bool enable_1394a;
int ret, clear, set, offset;
/* Check if the driver should configure link and PHY. */
if (!(reg_read(ohci, OHCI1394_HCControlSet) &
OHCI1394_HCControl_programPhyEnable))
return 0;
/* Paranoia: check whether the PHY supports 1394a, too. */
enable_1394a = false;
ret = read_phy_reg(ohci, 2);
if (ret < 0)
return ret;
if ((ret & PHY_EXTENDED_REGISTERS) == PHY_EXTENDED_REGISTERS) {
ret = read_paged_phy_reg(ohci, 1, 8);
if (ret < 0)
return ret;
if (ret >= 1)
enable_1394a = true;
}
if (ohci->quirks & QUIRK_NO_1394A)
enable_1394a = false;
/* Configure PHY and link consistently. */
if (enable_1394a) {
clear = 0;
set = PHY_ENABLE_ACCEL | PHY_ENABLE_MULTI;
} else {
clear = PHY_ENABLE_ACCEL | PHY_ENABLE_MULTI;
set = 0;
}
ret = update_phy_reg(ohci, 5, clear, set);
if (ret < 0)
return ret;
if (enable_1394a)
offset = OHCI1394_HCControlSet;
else
offset = OHCI1394_HCControlClear;
reg_write(ohci, offset, OHCI1394_HCControl_aPhyEnhanceEnable);
/* Clean up: configuration has been taken care of. */
reg_write(ohci, OHCI1394_HCControlClear,
OHCI1394_HCControl_programPhyEnable);
return 0;
}
static int probe_tsb41ba3d(struct fw_ohci *ohci)
{
/* TI vendor ID = 0x080028, TSB41BA3D product ID = 0x833005 (sic) */
static const u8 id[] = { 0x08, 0x00, 0x28, 0x83, 0x30, 0x05, };
int reg, i;
reg = read_phy_reg(ohci, 2);
if (reg < 0)
return reg;
if ((reg & PHY_EXTENDED_REGISTERS) != PHY_EXTENDED_REGISTERS)
return 0;
for (i = ARRAY_SIZE(id) - 1; i >= 0; i--) {
reg = read_paged_phy_reg(ohci, 1, i + 10);
if (reg < 0)
return reg;
if (reg != id[i])
return 0;
}
return 1;
}
static int ohci_enable(struct fw_card *card,
const __be32 *config_rom, size_t length)
{
struct fw_ohci *ohci = fw_ohci(card);
u32 lps, version, irqs;
int i, ret;
if (software_reset(ohci)) {
ohci_err(ohci, "failed to reset ohci card\n");
return -EBUSY;
}
/*
* Now enable LPS, which we need in order to start accessing
* most of the registers. In fact, on some cards (ALI M5251),
* accessing registers in the SClk domain without LPS enabled
* will lock up the machine. Wait 50msec to make sure we have
* full link enabled. However, with some cards (well, at least
* a JMicron PCIe card), we have to try again sometimes.
*
* TI TSB82AA2 + TSB81BA3(A) cards signal LPS enabled early but
* cannot actually use the phy at that time. These need tens of
* millisecods pause between LPS write and first phy access too.
*/
reg_write(ohci, OHCI1394_HCControlSet,
OHCI1394_HCControl_LPS |
OHCI1394_HCControl_postedWriteEnable);
flush_writes(ohci);
for (lps = 0, i = 0; !lps && i < 3; i++) {
msleep(50);
lps = reg_read(ohci, OHCI1394_HCControlSet) &
OHCI1394_HCControl_LPS;
}
if (!lps) {
ohci_err(ohci, "failed to set Link Power Status\n");
return -EIO;
}
if (ohci->quirks & QUIRK_TI_SLLZ059) {
ret = probe_tsb41ba3d(ohci);
if (ret < 0)
return ret;
if (ret)
ohci_notice(ohci, "local TSB41BA3D phy\n");
else
ohci->quirks &= ~QUIRK_TI_SLLZ059;
}
reg_write(ohci, OHCI1394_HCControlClear,
OHCI1394_HCControl_noByteSwapData);
reg_write(ohci, OHCI1394_SelfIDBuffer, ohci->self_id_bus);
reg_write(ohci, OHCI1394_LinkControlSet,
OHCI1394_LinkControl_cycleTimerEnable |
OHCI1394_LinkControl_cycleMaster);
reg_write(ohci, OHCI1394_ATRetries,
OHCI1394_MAX_AT_REQ_RETRIES |
(OHCI1394_MAX_AT_RESP_RETRIES << 4) |
(OHCI1394_MAX_PHYS_RESP_RETRIES << 8) |
(200 << 16));
ohci->bus_time_running = false;
for (i = 0; i < 32; i++)
if (ohci->ir_context_support & (1 << i))
reg_write(ohci, OHCI1394_IsoRcvContextControlClear(i),
IR_CONTEXT_MULTI_CHANNEL_MODE);
version = reg_read(ohci, OHCI1394_Version) & 0x00ff00ff;
if (version >= OHCI_VERSION_1_1) {
reg_write(ohci, OHCI1394_InitialChannelsAvailableHi,
0xfffffffe);
card->broadcast_channel_auto_allocated = true;
}
/* Get implemented bits of the priority arbitration request counter. */
reg_write(ohci, OHCI1394_FairnessControl, 0x3f);
ohci->pri_req_max = reg_read(ohci, OHCI1394_FairnessControl) & 0x3f;
reg_write(ohci, OHCI1394_FairnessControl, 0);
card->priority_budget_implemented = ohci->pri_req_max != 0;
reg_write(ohci, OHCI1394_PhyUpperBound, FW_MAX_PHYSICAL_RANGE >> 16);
reg_write(ohci, OHCI1394_IntEventClear, ~0);
reg_write(ohci, OHCI1394_IntMaskClear, ~0);
ret = configure_1394a_enhancements(ohci);
if (ret < 0)
return ret;
/* Activate link_on bit and contender bit in our self ID packets.*/
ret = ohci_update_phy_reg(card, 4, 0, PHY_LINK_ACTIVE | PHY_CONTENDER);
if (ret < 0)
return ret;
/*
* When the link is not yet enabled, the atomic config rom
* update mechanism described below in ohci_set_config_rom()
* is not active. We have to update ConfigRomHeader and
* BusOptions manually, and the write to ConfigROMmap takes
* effect immediately. We tie this to the enabling of the
* link, so we have a valid config rom before enabling - the
* OHCI requires that ConfigROMhdr and BusOptions have valid
* values before enabling.
*
* However, when the ConfigROMmap is written, some controllers
* always read back quadlets 0 and 2 from the config rom to
* the ConfigRomHeader and BusOptions registers on bus reset.
* They shouldn't do that in this initial case where the link
* isn't enabled. This means we have to use the same
* workaround here, setting the bus header to 0 and then write
* the right values in the bus reset tasklet.
*/
if (config_rom) {
ohci->next_config_rom =
dma_alloc_coherent(ohci->card.device, CONFIG_ROM_SIZE,
&ohci->next_config_rom_bus,
GFP_KERNEL);
if (ohci->next_config_rom == NULL)
return -ENOMEM;
copy_config_rom(ohci->next_config_rom, config_rom, length);
} else {
/*
* In the suspend case, config_rom is NULL, which
* means that we just reuse the old config rom.
*/
ohci->next_config_rom = ohci->config_rom;
ohci->next_config_rom_bus = ohci->config_rom_bus;
}
ohci->next_header = ohci->next_config_rom[0];
ohci->next_config_rom[0] = 0;
reg_write(ohci, OHCI1394_ConfigROMhdr, 0);
reg_write(ohci, OHCI1394_BusOptions,
be32_to_cpu(ohci->next_config_rom[2]));
reg_write(ohci, OHCI1394_ConfigROMmap, ohci->next_config_rom_bus);
reg_write(ohci, OHCI1394_AsReqFilterHiSet, 0x80000000);
irqs = OHCI1394_reqTxComplete | OHCI1394_respTxComplete |
OHCI1394_RQPkt | OHCI1394_RSPkt |
OHCI1394_isochTx | OHCI1394_isochRx |
OHCI1394_postedWriteErr |
OHCI1394_selfIDComplete |
OHCI1394_regAccessFail |
OHCI1394_cycleInconsistent |
OHCI1394_unrecoverableError |
OHCI1394_cycleTooLong |
OHCI1394_masterIntEnable;
if (param_debug & OHCI_PARAM_DEBUG_BUSRESETS)
irqs |= OHCI1394_busReset;
reg_write(ohci, OHCI1394_IntMaskSet, irqs);
reg_write(ohci, OHCI1394_HCControlSet,
OHCI1394_HCControl_linkEnable |
OHCI1394_HCControl_BIBimageValid);
reg_write(ohci, OHCI1394_LinkControlSet,
OHCI1394_LinkControl_rcvSelfID |
OHCI1394_LinkControl_rcvPhyPkt);
ar_context_run(&ohci->ar_request_ctx);
ar_context_run(&ohci->ar_response_ctx);
flush_writes(ohci);
/* We are ready to go, reset bus to finish initialization. */
fw_schedule_bus_reset(&ohci->card, false, true);
return 0;
}
static int ohci_set_config_rom(struct fw_card *card,
const __be32 *config_rom, size_t length)
{
struct fw_ohci *ohci;
__be32 *next_config_rom;
dma_addr_t uninitialized_var(next_config_rom_bus);
ohci = fw_ohci(card);
/*
* When the OHCI controller is enabled, the config rom update
* mechanism is a bit tricky, but easy enough to use. See
* section 5.5.6 in the OHCI specification.
*
* The OHCI controller caches the new config rom address in a
* shadow register (ConfigROMmapNext) and needs a bus reset
* for the changes to take place. When the bus reset is
* detected, the controller loads the new values for the
* ConfigRomHeader and BusOptions registers from the specified
* config rom and loads ConfigROMmap from the ConfigROMmapNext
* shadow register. All automatically and atomically.
*
* Now, there's a twist to this story. The automatic load of
* ConfigRomHeader and BusOptions doesn't honor the
* noByteSwapData bit, so with a be32 config rom, the
* controller will load be32 values in to these registers
* during the atomic update, even on litte endian
* architectures. The workaround we use is to put a 0 in the
* header quadlet; 0 is endian agnostic and means that the
* config rom isn't ready yet. In the bus reset tasklet we
* then set up the real values for the two registers.
*
* We use ohci->lock to avoid racing with the code that sets
* ohci->next_config_rom to NULL (see bus_reset_work).
*/
next_config_rom =
dma_alloc_coherent(ohci->card.device, CONFIG_ROM_SIZE,
&next_config_rom_bus, GFP_KERNEL);
if (next_config_rom == NULL)
return -ENOMEM;
spin_lock_irq(&ohci->lock);
/*
* If there is not an already pending config_rom update,
* push our new allocation into the ohci->next_config_rom
* and then mark the local variable as null so that we
* won't deallocate the new buffer.
*
* OTOH, if there is a pending config_rom update, just
* use that buffer with the new config_rom data, and
* let this routine free the unused DMA allocation.
*/
if (ohci->next_config_rom == NULL) {
ohci->next_config_rom = next_config_rom;
ohci->next_config_rom_bus = next_config_rom_bus;
next_config_rom = NULL;
}
copy_config_rom(ohci->next_config_rom, config_rom, length);
ohci->next_header = config_rom[0];
ohci->next_config_rom[0] = 0;
reg_write(ohci, OHCI1394_ConfigROMmap, ohci->next_config_rom_bus);
spin_unlock_irq(&ohci->lock);
/* If we didn't use the DMA allocation, delete it. */
if (next_config_rom != NULL)
dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
next_config_rom, next_config_rom_bus);
/*
* Now initiate a bus reset to have the changes take
* effect. We clean up the old config rom memory and DMA
* mappings in the bus reset tasklet, since the OHCI
* controller could need to access it before the bus reset
* takes effect.
*/
fw_schedule_bus_reset(&ohci->card, true, true);
return 0;
}
static void ohci_send_request(struct fw_card *card, struct fw_packet *packet)
{
struct fw_ohci *ohci = fw_ohci(card);
at_context_transmit(&ohci->at_request_ctx, packet);
}
static void ohci_send_response(struct fw_card *card, struct fw_packet *packet)
{
struct fw_ohci *ohci = fw_ohci(card);
at_context_transmit(&ohci->at_response_ctx, packet);
}
static int ohci_cancel_packet(struct fw_card *card, struct fw_packet *packet)
{
struct fw_ohci *ohci = fw_ohci(card);
struct context *ctx = &ohci->at_request_ctx;
struct driver_data *driver_data = packet->driver_data;
int ret = -ENOENT;
tasklet_disable(&ctx->tasklet);
if (packet->ack != 0)
goto out;
if (packet->payload_mapped)
dma_unmap_single(ohci->card.device, packet->payload_bus,
packet->payload_length, DMA_TO_DEVICE);
log_ar_at_event(ohci, 'T', packet->speed, packet->header, 0x20);
driver_data->packet = NULL;
packet->ack = RCODE_CANCELLED;
packet->callback(packet, &ohci->card, packet->ack);
ret = 0;
out:
tasklet_enable(&ctx->tasklet);
return ret;
}
static int ohci_enable_phys_dma(struct fw_card *card,
int node_id, int generation)
{
struct fw_ohci *ohci = fw_ohci(card);
unsigned long flags;
int n, ret = 0;
if (param_remote_dma)
return 0;
/*
* FIXME: Make sure this bitmask is cleared when we clear the busReset
* interrupt bit. Clear physReqResourceAllBuses on bus reset.
*/
spin_lock_irqsave(&ohci->lock, flags);
if (ohci->generation != generation) {
ret = -ESTALE;
goto out;
}
/*
* Note, if the node ID contains a non-local bus ID, physical DMA is
* enabled for _all_ nodes on remote buses.
*/
n = (node_id & 0xffc0) == LOCAL_BUS ? node_id & 0x3f : 63;
if (n < 32)
reg_write(ohci, OHCI1394_PhyReqFilterLoSet, 1 << n);
else
reg_write(ohci, OHCI1394_PhyReqFilterHiSet, 1 << (n - 32));
flush_writes(ohci);
out:
spin_unlock_irqrestore(&ohci->lock, flags);
return ret;
}
static u32 ohci_read_csr(struct fw_card *card, int csr_offset)
{
struct fw_ohci *ohci = fw_ohci(card);
unsigned long flags;
u32 value;
switch (csr_offset) {
case CSR_STATE_CLEAR:
case CSR_STATE_SET:
if (ohci->is_root &&
(reg_read(ohci, OHCI1394_LinkControlSet) &
OHCI1394_LinkControl_cycleMaster))
value = CSR_STATE_BIT_CMSTR;
else
value = 0;
if (ohci->csr_state_setclear_abdicate)
value |= CSR_STATE_BIT_ABDICATE;
return value;
case CSR_NODE_IDS:
return reg_read(ohci, OHCI1394_NodeID) << 16;
case CSR_CYCLE_TIME:
return get_cycle_time(ohci);
case CSR_BUS_TIME:
/*
* We might be called just after the cycle timer has wrapped
* around but just before the cycle64Seconds handler, so we
* better check here, too, if the bus time needs to be updated.
*/
spin_lock_irqsave(&ohci->lock, flags);
value = update_bus_time(ohci);
spin_unlock_irqrestore(&ohci->lock, flags);
return value;
case CSR_BUSY_TIMEOUT:
value = reg_read(ohci, OHCI1394_ATRetries);
return (value >> 4) & 0x0ffff00f;
case CSR_PRIORITY_BUDGET:
return (reg_read(ohci, OHCI1394_FairnessControl) & 0x3f) |
(ohci->pri_req_max << 8);
default:
WARN_ON(1);
return 0;
}
}
static void ohci_write_csr(struct fw_card *card, int csr_offset, u32 value)
{
struct fw_ohci *ohci = fw_ohci(card);
unsigned long flags;
switch (csr_offset) {
case CSR_STATE_CLEAR:
if ((value & CSR_STATE_BIT_CMSTR) && ohci->is_root) {
reg_write(ohci, OHCI1394_LinkControlClear,
OHCI1394_LinkControl_cycleMaster);
flush_writes(ohci);
}
if (value & CSR_STATE_BIT_ABDICATE)
ohci->csr_state_setclear_abdicate = false;
break;
case CSR_STATE_SET:
if ((value & CSR_STATE_BIT_CMSTR) && ohci->is_root) {
reg_write(ohci, OHCI1394_LinkControlSet,
OHCI1394_LinkControl_cycleMaster);
flush_writes(ohci);
}
if (value & CSR_STATE_BIT_ABDICATE)
ohci->csr_state_setclear_abdicate = true;
break;
case CSR_NODE_IDS:
reg_write(ohci, OHCI1394_NodeID, value >> 16);
flush_writes(ohci);
break;
case CSR_CYCLE_TIME:
reg_write(ohci, OHCI1394_IsochronousCycleTimer, value);
reg_write(ohci, OHCI1394_IntEventSet,
OHCI1394_cycleInconsistent);
flush_writes(ohci);
break;
case CSR_BUS_TIME:
spin_lock_irqsave(&ohci->lock, flags);
ohci->bus_time = (update_bus_time(ohci) & 0x40) |
(value & ~0x7f);
spin_unlock_irqrestore(&ohci->lock, flags);
break;
case CSR_BUSY_TIMEOUT:
value = (value & 0xf) | ((value & 0xf) << 4) |
((value & 0xf) << 8) | ((value & 0x0ffff000) << 4);
reg_write(ohci, OHCI1394_ATRetries, value);
flush_writes(ohci);
break;
case CSR_PRIORITY_BUDGET:
reg_write(ohci, OHCI1394_FairnessControl, value & 0x3f);
flush_writes(ohci);
break;
default:
WARN_ON(1);
break;
}
}
static void flush_iso_completions(struct iso_context *ctx)
{
ctx->base.callback.sc(&ctx->base, ctx->last_timestamp,
ctx->header_length, ctx->header,
ctx->base.callback_data);
ctx->header_length = 0;
}
static void copy_iso_headers(struct iso_context *ctx, const u32 *dma_hdr)
{
u32 *ctx_hdr;
if (ctx->header_length + ctx->base.header_size > PAGE_SIZE) {
if (ctx->base.drop_overflow_headers)
return;
flush_iso_completions(ctx);
}
ctx_hdr = ctx->header + ctx->header_length;
ctx->last_timestamp = (u16)le32_to_cpu((__force __le32)dma_hdr[0]);
/*
* The two iso header quadlets are byteswapped to little
* endian by the controller, but we want to present them
* as big endian for consistency with the bus endianness.
*/
if (ctx->base.header_size > 0)
ctx_hdr[0] = swab32(dma_hdr[1]); /* iso packet header */
if (ctx->base.header_size > 4)
ctx_hdr[1] = swab32(dma_hdr[0]); /* timestamp */
if (ctx->base.header_size > 8)
memcpy(&ctx_hdr[2], &dma_hdr[2], ctx->base.header_size - 8);
ctx->header_length += ctx->base.header_size;
}
static int handle_ir_packet_per_buffer(struct context *context,
struct descriptor *d,
struct descriptor *last)
{
struct iso_context *ctx =
container_of(context, struct iso_context, context);
struct descriptor *pd;
u32 buffer_dma;
for (pd = d; pd <= last; pd++)
if (pd->transfer_status)
break;
if (pd > last)
/* Descriptor(s) not done yet, stop iteration */
return 0;
while (!(d->control & cpu_to_le16(DESCRIPTOR_BRANCH_ALWAYS))) {
d++;
buffer_dma = le32_to_cpu(d->data_address);
dma_sync_single_range_for_cpu(context->ohci->card.device,
buffer_dma & PAGE_MASK,
buffer_dma & ~PAGE_MASK,
le16_to_cpu(d->req_count),
DMA_FROM_DEVICE);
}
copy_iso_headers(ctx, (u32 *) (last + 1));
if (last->control & cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS))
flush_iso_completions(ctx);
return 1;
}
/* d == last because each descriptor block is only a single descriptor. */
static int handle_ir_buffer_fill(struct context *context,
struct descriptor *d,
struct descriptor *last)
{
struct iso_context *ctx =
container_of(context, struct iso_context, context);
unsigned int req_count, res_count, completed;
u32 buffer_dma;
req_count = le16_to_cpu(last->req_count);
res_count = le16_to_cpu(ACCESS_ONCE(last->res_count));
completed = req_count - res_count;
buffer_dma = le32_to_cpu(last->data_address);
if (completed > 0) {
ctx->mc_buffer_bus = buffer_dma;
ctx->mc_completed = completed;
}
if (res_count != 0)
/* Descriptor(s) not done yet, stop iteration */
return 0;
dma_sync_single_range_for_cpu(context->ohci->card.device,
buffer_dma & PAGE_MASK,
buffer_dma & ~PAGE_MASK,
completed, DMA_FROM_DEVICE);
if (last->control & cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS)) {
ctx->base.callback.mc(&ctx->base,
buffer_dma + completed,
ctx->base.callback_data);
ctx->mc_completed = 0;
}
return 1;
}
static void flush_ir_buffer_fill(struct iso_context *ctx)
{
dma_sync_single_range_for_cpu(ctx->context.ohci->card.device,
ctx->mc_buffer_bus & PAGE_MASK,
ctx->mc_buffer_bus & ~PAGE_MASK,
ctx->mc_completed, DMA_FROM_DEVICE);
ctx->base.callback.mc(&ctx->base,
ctx->mc_buffer_bus + ctx->mc_completed,
ctx->base.callback_data);
ctx->mc_completed = 0;
}
static inline void sync_it_packet_for_cpu(struct context *context,
struct descriptor *pd)
{
__le16 control;
u32 buffer_dma;
/* only packets beginning with OUTPUT_MORE* have data buffers */
if (pd->control & cpu_to_le16(DESCRIPTOR_BRANCH_ALWAYS))
return;
/* skip over the OUTPUT_MORE_IMMEDIATE descriptor */
pd += 2;
/*
* If the packet has a header, the first OUTPUT_MORE/LAST descriptor's
* data buffer is in the context program's coherent page and must not
* be synced.
*/
if ((le32_to_cpu(pd->data_address) & PAGE_MASK) ==
(context->current_bus & PAGE_MASK)) {
if (pd->control & cpu_to_le16(DESCRIPTOR_BRANCH_ALWAYS))
return;
pd++;
}
do {
buffer_dma = le32_to_cpu(pd->data_address);
dma_sync_single_range_for_cpu(context->ohci->card.device,
buffer_dma & PAGE_MASK,
buffer_dma & ~PAGE_MASK,
le16_to_cpu(pd->req_count),
DMA_TO_DEVICE);
control = pd->control;
pd++;
} while (!(control & cpu_to_le16(DESCRIPTOR_BRANCH_ALWAYS)));
}
static int handle_it_packet(struct context *context,
struct descriptor *d,
struct descriptor *last)
{
struct iso_context *ctx =
container_of(context, struct iso_context, context);
struct descriptor *pd;
__be32 *ctx_hdr;
for (pd = d; pd <= last; pd++)
if (pd->transfer_status)
break;
if (pd > last)
/* Descriptor(s) not done yet, stop iteration */
return 0;
sync_it_packet_for_cpu(context, d);
if (ctx->header_length + 4 > PAGE_SIZE) {
if (ctx->base.drop_overflow_headers)
return 1;
flush_iso_completions(ctx);
}
ctx_hdr = ctx->header + ctx->header_length;
ctx->last_timestamp = le16_to_cpu(last->res_count);
/* Present this value as big-endian to match the receive code */
*ctx_hdr = cpu_to_be32((le16_to_cpu(pd->transfer_status) << 16) |
le16_to_cpu(pd->res_count));
ctx->header_length += 4;
if (last->control & cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS))
flush_iso_completions(ctx);
return 1;
}
static void set_multichannel_mask(struct fw_ohci *ohci, u64 channels)
{
u32 hi = channels >> 32, lo = channels;
reg_write(ohci, OHCI1394_IRMultiChanMaskHiClear, ~hi);
reg_write(ohci, OHCI1394_IRMultiChanMaskLoClear, ~lo);
reg_write(ohci, OHCI1394_IRMultiChanMaskHiSet, hi);
reg_write(ohci, OHCI1394_IRMultiChanMaskLoSet, lo);
mmiowb();
ohci->mc_channels = channels;
}
static struct fw_iso_context *ohci_allocate_iso_context(struct fw_card *card,
int type, int channel, size_t header_size)
{
struct fw_ohci *ohci = fw_ohci(card);
struct iso_context *uninitialized_var(ctx);
descriptor_callback_t uninitialized_var(callback);
u64 *uninitialized_var(channels);
u32 *uninitialized_var(mask), uninitialized_var(regs);
int index, ret = -EBUSY;
spin_lock_irq(&ohci->lock);
switch (type) {
case FW_ISO_CONTEXT_TRANSMIT:
mask = &ohci->it_context_mask;
callback = handle_it_packet;
index = ffs(*mask) - 1;
if (index >= 0) {
*mask &= ~(1 << index);
regs = OHCI1394_IsoXmitContextBase(index);
ctx = &ohci->it_context_list[index];
}
break;
case FW_ISO_CONTEXT_RECEIVE:
channels = &ohci->ir_context_channels;
mask = &ohci->ir_context_mask;
callback = handle_ir_packet_per_buffer;
index = *channels & 1ULL << channel ? ffs(*mask) - 1 : -1;
if (index >= 0) {
*channels &= ~(1ULL << channel);
*mask &= ~(1 << index);
regs = OHCI1394_IsoRcvContextBase(index);
ctx = &ohci->ir_context_list[index];
}
break;
case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
mask = &ohci->ir_context_mask;
callback = handle_ir_buffer_fill;
index = !ohci->mc_allocated ? ffs(*mask) - 1 : -1;
if (index >= 0) {
ohci->mc_allocated = true;
*mask &= ~(1 << index);
regs = OHCI1394_IsoRcvContextBase(index);
ctx = &ohci->ir_context_list[index];
}
break;
default:
index = -1;
ret = -ENOSYS;
}
spin_unlock_irq(&ohci->lock);
if (index < 0)
return ERR_PTR(ret);
memset(ctx, 0, sizeof(*ctx));
ctx->header_length = 0;
ctx->header = (void *) __get_free_page(GFP_KERNEL);
if (ctx->header == NULL) {
ret = -ENOMEM;
goto out;
}
ret = context_init(&ctx->context, ohci, regs, callback);
if (ret < 0)
goto out_with_header;
if (type == FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL) {
set_multichannel_mask(ohci, 0);
ctx->mc_completed = 0;
}
return &ctx->base;
out_with_header:
free_page((unsigned long)ctx->header);
out:
spin_lock_irq(&ohci->lock);
switch (type) {
case FW_ISO_CONTEXT_RECEIVE:
*channels |= 1ULL << channel;
break;
case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
ohci->mc_allocated = false;
break;
}
*mask |= 1 << index;
spin_unlock_irq(&ohci->lock);
return ERR_PTR(ret);
}
static int ohci_start_iso(struct fw_iso_context *base,
s32 cycle, u32 sync, u32 tags)
{
struct iso_context *ctx = container_of(base, struct iso_context, base);
struct fw_ohci *ohci = ctx->context.ohci;
u32 control = IR_CONTEXT_ISOCH_HEADER, match;
int index;
/* the controller cannot start without any queued packets */
if (ctx->context.last->branch_address == 0)
return -ENODATA;
switch (ctx->base.type) {
case FW_ISO_CONTEXT_TRANSMIT:
index = ctx - ohci->it_context_list;
match = 0;
if (cycle >= 0)
match = IT_CONTEXT_CYCLE_MATCH_ENABLE |
(cycle & 0x7fff) << 16;
reg_write(ohci, OHCI1394_IsoXmitIntEventClear, 1 << index);
reg_write(ohci, OHCI1394_IsoXmitIntMaskSet, 1 << index);
context_run(&ctx->context, match);
break;
case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
control |= IR_CONTEXT_BUFFER_FILL|IR_CONTEXT_MULTI_CHANNEL_MODE;
/* fall through */
case FW_ISO_CONTEXT_RECEIVE:
index = ctx - ohci->ir_context_list;
match = (tags << 28) | (sync << 8) | ctx->base.channel;
if (cycle >= 0) {
match |= (cycle & 0x07fff) << 12;
control |= IR_CONTEXT_CYCLE_MATCH_ENABLE;
}
reg_write(ohci, OHCI1394_IsoRecvIntEventClear, 1 << index);
reg_write(ohci, OHCI1394_IsoRecvIntMaskSet, 1 << index);
reg_write(ohci, CONTEXT_MATCH(ctx->context.regs), match);
context_run(&ctx->context, control);
ctx->sync = sync;
ctx->tags = tags;
break;
}
return 0;
}
static int ohci_stop_iso(struct fw_iso_context *base)
{
struct fw_ohci *ohci = fw_ohci(base->card);
struct iso_context *ctx = container_of(base, struct iso_context, base);
int index;
switch (ctx->base.type) {
case FW_ISO_CONTEXT_TRANSMIT:
index = ctx - ohci->it_context_list;
reg_write(ohci, OHCI1394_IsoXmitIntMaskClear, 1 << index);
break;
case FW_ISO_CONTEXT_RECEIVE:
case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
index = ctx - ohci->ir_context_list;
reg_write(ohci, OHCI1394_IsoRecvIntMaskClear, 1 << index);
break;
}
flush_writes(ohci);
context_stop(&ctx->context);
tasklet_kill(&ctx->context.tasklet);
return 0;
}
static void ohci_free_iso_context(struct fw_iso_context *base)
{
struct fw_ohci *ohci = fw_ohci(base->card);
struct iso_context *ctx = container_of(base, struct iso_context, base);
unsigned long flags;
int index;
ohci_stop_iso(base);
context_release(&ctx->context);
free_page((unsigned long)ctx->header);
spin_lock_irqsave(&ohci->lock, flags);
switch (base->type) {
case FW_ISO_CONTEXT_TRANSMIT:
index = ctx - ohci->it_context_list;
ohci->it_context_mask |= 1 << index;
break;
case FW_ISO_CONTEXT_RECEIVE:
index = ctx - ohci->ir_context_list;
ohci->ir_context_mask |= 1 << index;
ohci->ir_context_channels |= 1ULL << base->channel;
break;
case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
index = ctx - ohci->ir_context_list;
ohci->ir_context_mask |= 1 << index;
ohci->ir_context_channels |= ohci->mc_channels;
ohci->mc_channels = 0;
ohci->mc_allocated = false;
break;
}
spin_unlock_irqrestore(&ohci->lock, flags);
}
static int ohci_set_iso_channels(struct fw_iso_context *base, u64 *channels)
{
struct fw_ohci *ohci = fw_ohci(base->card);
unsigned long flags;
int ret;
switch (base->type) {
case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
spin_lock_irqsave(&ohci->lock, flags);
/* Don't allow multichannel to grab other contexts' channels. */
if (~ohci->ir_context_channels & ~ohci->mc_channels & *channels) {
*channels = ohci->ir_context_channels;
ret = -EBUSY;
} else {
set_multichannel_mask(ohci, *channels);
ret = 0;
}
spin_unlock_irqrestore(&ohci->lock, flags);
break;
default:
ret = -EINVAL;
}
return ret;
}
#ifdef CONFIG_PM
static void ohci_resume_iso_dma(struct fw_ohci *ohci)
{
int i;
struct iso_context *ctx;
for (i = 0 ; i < ohci->n_ir ; i++) {
ctx = &ohci->ir_context_list[i];
if (ctx->context.running)
ohci_start_iso(&ctx->base, 0, ctx->sync, ctx->tags);
}
for (i = 0 ; i < ohci->n_it ; i++) {
ctx = &ohci->it_context_list[i];
if (ctx->context.running)
ohci_start_iso(&ctx->base, 0, ctx->sync, ctx->tags);
}
}
#endif
static int queue_iso_transmit(struct iso_context *ctx,
struct fw_iso_packet *packet,
struct fw_iso_buffer *buffer,
unsigned long payload)
{
struct descriptor *d, *last, *pd;
struct fw_iso_packet *p;
__le32 *header;
dma_addr_t d_bus, page_bus;
u32 z, header_z, payload_z, irq;
u32 payload_index, payload_end_index, next_page_index;
int page, end_page, i, length, offset;
p = packet;
payload_index = payload;
if (p->skip)
z = 1;
else
z = 2;
if (p->header_length > 0)
z++;
/* Determine the first page the payload isn't contained in. */
end_page = PAGE_ALIGN(payload_index + p->payload_length) >> PAGE_SHIFT;
if (p->payload_length > 0)
payload_z = end_page - (payload_index >> PAGE_SHIFT);
else
payload_z = 0;
z += payload_z;
/* Get header size in number of descriptors. */
header_z = DIV_ROUND_UP(p->header_length, sizeof(*d));
d = context_get_descriptors(&ctx->context, z + header_z, &d_bus);
if (d == NULL)
return -ENOMEM;
if (!p->skip) {
d[0].control = cpu_to_le16(DESCRIPTOR_KEY_IMMEDIATE);
d[0].req_count = cpu_to_le16(8);
/*
* Link the skip address to this descriptor itself. This causes
* a context to skip a cycle whenever lost cycles or FIFO
* overruns occur, without dropping the data. The application
* should then decide whether this is an error condition or not.
* FIXME: Make the context's cycle-lost behaviour configurable?
*/
d[0].branch_address = cpu_to_le32(d_bus | z);
header = (__le32 *) &d[1];
header[0] = cpu_to_le32(IT_HEADER_SY(p->sy) |
IT_HEADER_TAG(p->tag) |
IT_HEADER_TCODE(TCODE_STREAM_DATA) |
IT_HEADER_CHANNEL(ctx->base.channel) |
IT_HEADER_SPEED(ctx->base.speed));
header[1] =
cpu_to_le32(IT_HEADER_DATA_LENGTH(p->header_length +
p->payload_length));
}
if (p->header_length > 0) {
d[2].req_count = cpu_to_le16(p->header_length);
d[2].data_address = cpu_to_le32(d_bus + z * sizeof(*d));
memcpy(&d[z], p->header, p->header_length);
}
pd = d + z - payload_z;
payload_end_index = payload_index + p->payload_length;
for (i = 0; i < payload_z; i++) {
page = payload_index >> PAGE_SHIFT;
offset = payload_index & ~PAGE_MASK;
next_page_index = (page + 1) << PAGE_SHIFT;
length =
min(next_page_index, payload_end_index) - payload_index;
pd[i].req_count = cpu_to_le16(length);
page_bus = page_private(buffer->pages[page]);
pd[i].data_address = cpu_to_le32(page_bus + offset);
dma_sync_single_range_for_device(ctx->context.ohci->card.device,
page_bus, offset, length,
DMA_TO_DEVICE);
payload_index += length;
}
if (p->interrupt)
irq = DESCRIPTOR_IRQ_ALWAYS;
else
irq = DESCRIPTOR_NO_IRQ;
last = z == 2 ? d : d + z - 1;
last->control |= cpu_to_le16(DESCRIPTOR_OUTPUT_LAST |
DESCRIPTOR_STATUS |
DESCRIPTOR_BRANCH_ALWAYS |
irq);
context_append(&ctx->context, d, z, header_z);
return 0;
}
static int queue_iso_packet_per_buffer(struct iso_context *ctx,
struct fw_iso_packet *packet,
struct fw_iso_buffer *buffer,
unsigned long payload)
{
struct device *device = ctx->context.ohci->card.device;
struct descriptor *d, *pd;
dma_addr_t d_bus, page_bus;
u32 z, header_z, rest;
int i, j, length;
int page, offset, packet_count, header_size, payload_per_buffer;
/*
* The OHCI controller puts the isochronous header and trailer in the
* buffer, so we need at least 8 bytes.
*/
packet_count = packet->header_length / ctx->base.header_size;
header_size = max(ctx->base.header_size, (size_t)8);
/* Get header size in number of descriptors. */
header_z = DIV_ROUND_UP(header_size, sizeof(*d));
page = payload >> PAGE_SHIFT;
offset = payload & ~PAGE_MASK;
payload_per_buffer = packet->payload_length / packet_count;
for (i = 0; i < packet_count; i++) {
/* d points to the header descriptor */
z = DIV_ROUND_UP(payload_per_buffer + offset, PAGE_SIZE) + 1;
d = context_get_descriptors(&ctx->context,
z + header_z, &d_bus);
if (d == NULL)
return -ENOMEM;
d->control = cpu_to_le16(DESCRIPTOR_STATUS |
DESCRIPTOR_INPUT_MORE);
if (packet->skip && i == 0)
d->control |= cpu_to_le16(DESCRIPTOR_WAIT);
d->req_count = cpu_to_le16(header_size);
d->res_count = d->req_count;
d->transfer_status = 0;
d->data_address = cpu_to_le32(d_bus + (z * sizeof(*d)));
rest = payload_per_buffer;
pd = d;
for (j = 1; j < z; j++) {
pd++;
pd->control = cpu_to_le16(DESCRIPTOR_STATUS |
DESCRIPTOR_INPUT_MORE);
if (offset + rest < PAGE_SIZE)
length = rest;
else
length = PAGE_SIZE - offset;
pd->req_count = cpu_to_le16(length);
pd->res_count = pd->req_count;
pd->transfer_status = 0;
page_bus = page_private(buffer->pages[page]);
pd->data_address = cpu_to_le32(page_bus + offset);
dma_sync_single_range_for_device(device, page_bus,
offset, length,
DMA_FROM_DEVICE);
offset = (offset + length) & ~PAGE_MASK;
rest -= length;
if (offset == 0)
page++;
}
pd->control = cpu_to_le16(DESCRIPTOR_STATUS |
DESCRIPTOR_INPUT_LAST |
DESCRIPTOR_BRANCH_ALWAYS);
if (packet->interrupt && i == packet_count - 1)
pd->control |= cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS);
context_append(&ctx->context, d, z, header_z);
}
return 0;
}
static int queue_iso_buffer_fill(struct iso_context *ctx,
struct fw_iso_packet *packet,
struct fw_iso_buffer *buffer,
unsigned long payload)
{
struct descriptor *d;
dma_addr_t d_bus, page_bus;
int page, offset, rest, z, i, length;
page = payload >> PAGE_SHIFT;
offset = payload & ~PAGE_MASK;
rest = packet->payload_length;
/* We need one descriptor for each page in the buffer. */
z = DIV_ROUND_UP(offset + rest, PAGE_SIZE);
if (WARN_ON(offset & 3 || rest & 3 || page + z > buffer->page_count))
return -EFAULT;
for (i = 0; i < z; i++) {
d = context_get_descriptors(&ctx->context, 1, &d_bus);
if (d == NULL)
return -ENOMEM;
d->control = cpu_to_le16(DESCRIPTOR_INPUT_MORE |
DESCRIPTOR_BRANCH_ALWAYS);
if (packet->skip && i == 0)
d->control |= cpu_to_le16(DESCRIPTOR_WAIT);
if (packet->interrupt && i == z - 1)
d->control |= cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS);
if (offset + rest < PAGE_SIZE)
length = rest;
else
length = PAGE_SIZE - offset;
d->req_count = cpu_to_le16(length);
d->res_count = d->req_count;
d->transfer_status = 0;
page_bus = page_private(buffer->pages[page]);
d->data_address = cpu_to_le32(page_bus + offset);
dma_sync_single_range_for_device(ctx->context.ohci->card.device,
page_bus, offset, length,
DMA_FROM_DEVICE);
rest -= length;
offset = 0;
page++;
context_append(&ctx->context, d, 1, 0);
}
return 0;
}
static int ohci_queue_iso(struct fw_iso_context *base,
struct fw_iso_packet *packet,
struct fw_iso_buffer *buffer,
unsigned long payload)
{
struct iso_context *ctx = container_of(base, struct iso_context, base);
unsigned long flags;
int ret = -ENOSYS;
spin_lock_irqsave(&ctx->context.ohci->lock, flags);
switch (base->type) {
case FW_ISO_CONTEXT_TRANSMIT:
ret = queue_iso_transmit(ctx, packet, buffer, payload);
break;
case FW_ISO_CONTEXT_RECEIVE:
ret = queue_iso_packet_per_buffer(ctx, packet, buffer, payload);
break;
case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
ret = queue_iso_buffer_fill(ctx, packet, buffer, payload);
break;
}
spin_unlock_irqrestore(&ctx->context.ohci->lock, flags);
return ret;
}
static void ohci_flush_queue_iso(struct fw_iso_context *base)
{
struct context *ctx =
&container_of(base, struct iso_context, base)->context;
reg_write(ctx->ohci, CONTROL_SET(ctx->regs), CONTEXT_WAKE);
}
static int ohci_flush_iso_completions(struct fw_iso_context *base)
{
struct iso_context *ctx = container_of(base, struct iso_context, base);
int ret = 0;
tasklet_disable(&ctx->context.tasklet);
if (!test_and_set_bit_lock(0, &ctx->flushing_completions)) {
context_tasklet((unsigned long)&ctx->context);
switch (base->type) {
case FW_ISO_CONTEXT_TRANSMIT:
case FW_ISO_CONTEXT_RECEIVE:
if (ctx->header_length != 0)
flush_iso_completions(ctx);
break;
case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
if (ctx->mc_completed != 0)
flush_ir_buffer_fill(ctx);
break;
default:
ret = -ENOSYS;
}
clear_bit_unlock(0, &ctx->flushing_completions);
smp_mb__after_atomic();
}
tasklet_enable(&ctx->context.tasklet);
return ret;
}
static const struct fw_card_driver ohci_driver = {
.enable = ohci_enable,
.read_phy_reg = ohci_read_phy_reg,
.update_phy_reg = ohci_update_phy_reg,
.set_config_rom = ohci_set_config_rom,
.send_request = ohci_send_request,
.send_response = ohci_send_response,
.cancel_packet = ohci_cancel_packet,
.enable_phys_dma = ohci_enable_phys_dma,
.read_csr = ohci_read_csr,
.write_csr = ohci_write_csr,
.allocate_iso_context = ohci_allocate_iso_context,
.free_iso_context = ohci_free_iso_context,
.set_iso_channels = ohci_set_iso_channels,
.queue_iso = ohci_queue_iso,
.flush_queue_iso = ohci_flush_queue_iso,
.flush_iso_completions = ohci_flush_iso_completions,
.start_iso = ohci_start_iso,
.stop_iso = ohci_stop_iso,
};
#ifdef CONFIG_PPC_PMAC
static void pmac_ohci_on(struct pci_dev *dev)
{
if (machine_is(powermac)) {
struct device_node *ofn = pci_device_to_OF_node(dev);
if (ofn) {
pmac_call_feature(PMAC_FTR_1394_CABLE_POWER, ofn, 0, 1);
pmac_call_feature(PMAC_FTR_1394_ENABLE, ofn, 0, 1);
}
}
}
static void pmac_ohci_off(struct pci_dev *dev)
{
if (machine_is(powermac)) {
struct device_node *ofn = pci_device_to_OF_node(dev);
if (ofn) {
pmac_call_feature(PMAC_FTR_1394_ENABLE, ofn, 0, 0);
pmac_call_feature(PMAC_FTR_1394_CABLE_POWER, ofn, 0, 0);
}
}
}
#else
static inline void pmac_ohci_on(struct pci_dev *dev) {}
static inline void pmac_ohci_off(struct pci_dev *dev) {}
#endif /* CONFIG_PPC_PMAC */
static int pci_probe(struct pci_dev *dev,
const struct pci_device_id *ent)
{
struct fw_ohci *ohci;
u32 bus_options, max_receive, link_speed, version;
u64 guid;
int i, err;
size_t size;
if (dev->vendor == PCI_VENDOR_ID_PINNACLE_SYSTEMS) {
dev_err(&dev->dev, "Pinnacle MovieBoard is not yet supported\n");
return -ENOSYS;
}
ohci = kzalloc(sizeof(*ohci), GFP_KERNEL);
if (ohci == NULL) {
err = -ENOMEM;
goto fail;
}
fw_card_initialize(&ohci->card, &ohci_driver, &dev->dev);
pmac_ohci_on(dev);
err = pci_enable_device(dev);
if (err) {
dev_err(&dev->dev, "failed to enable OHCI hardware\n");
goto fail_free;
}
pci_set_master(dev);
pci_write_config_dword(dev, OHCI1394_PCI_HCI_Control, 0);
pci_set_drvdata(dev, ohci);
spin_lock_init(&ohci->lock);
mutex_init(&ohci->phy_reg_mutex);
INIT_WORK(&ohci->bus_reset_work, bus_reset_work);
if (!(pci_resource_flags(dev, 0) & IORESOURCE_MEM) ||
pci_resource_len(dev, 0) < OHCI1394_REGISTER_SIZE) {
ohci_err(ohci, "invalid MMIO resource\n");
err = -ENXIO;
goto fail_disable;
}
err = pci_request_region(dev, 0, ohci_driver_name);
if (err) {
ohci_err(ohci, "MMIO resource unavailable\n");
goto fail_disable;
}
ohci->registers = pci_iomap(dev, 0, OHCI1394_REGISTER_SIZE);
if (ohci->registers == NULL) {
ohci_err(ohci, "failed to remap registers\n");
err = -ENXIO;
goto fail_iomem;
}
for (i = 0; i < ARRAY_SIZE(ohci_quirks); i++)
if ((ohci_quirks[i].vendor == dev->vendor) &&
(ohci_quirks[i].device == (unsigned short)PCI_ANY_ID ||
ohci_quirks[i].device == dev->device) &&
(ohci_quirks[i].revision == (unsigned short)PCI_ANY_ID ||
ohci_quirks[i].revision >= dev->revision)) {
ohci->quirks = ohci_quirks[i].flags;
break;
}
if (param_quirks)
ohci->quirks = param_quirks;
/*
* Because dma_alloc_coherent() allocates at least one page,
* we save space by using a common buffer for the AR request/
* response descriptors and the self IDs buffer.
*/
BUILD_BUG_ON(AR_BUFFERS * sizeof(struct descriptor) > PAGE_SIZE/4);
BUILD_BUG_ON(SELF_ID_BUF_SIZE > PAGE_SIZE/2);
ohci->misc_buffer = dma_alloc_coherent(ohci->card.device,
PAGE_SIZE,
&ohci->misc_buffer_bus,
GFP_KERNEL);
if (!ohci->misc_buffer) {
err = -ENOMEM;
goto fail_iounmap;
}
err = ar_context_init(&ohci->ar_request_ctx, ohci, 0,
OHCI1394_AsReqRcvContextControlSet);
if (err < 0)
goto fail_misc_buf;
err = ar_context_init(&ohci->ar_response_ctx, ohci, PAGE_SIZE/4,
OHCI1394_AsRspRcvContextControlSet);
if (err < 0)
goto fail_arreq_ctx;
err = context_init(&ohci->at_request_ctx, ohci,
OHCI1394_AsReqTrContextControlSet, handle_at_packet);
if (err < 0)
goto fail_arrsp_ctx;
err = context_init(&ohci->at_response_ctx, ohci,
OHCI1394_AsRspTrContextControlSet, handle_at_packet);
if (err < 0)
goto fail_atreq_ctx;
reg_write(ohci, OHCI1394_IsoRecvIntMaskSet, ~0);
ohci->ir_context_channels = ~0ULL;
ohci->ir_context_support = reg_read(ohci, OHCI1394_IsoRecvIntMaskSet);
reg_write(ohci, OHCI1394_IsoRecvIntMaskClear, ~0);
ohci->ir_context_mask = ohci->ir_context_support;
ohci->n_ir = hweight32(ohci->ir_context_mask);
size = sizeof(struct iso_context) * ohci->n_ir;
ohci->ir_context_list = kzalloc(size, GFP_KERNEL);
reg_write(ohci, OHCI1394_IsoXmitIntMaskSet, ~0);
ohci->it_context_support = reg_read(ohci, OHCI1394_IsoXmitIntMaskSet);
/* JMicron JMB38x often shows 0 at first read, just ignore it */
if (!ohci->it_context_support) {
ohci_notice(ohci, "overriding IsoXmitIntMask\n");
ohci->it_context_support = 0xf;
}
reg_write(ohci, OHCI1394_IsoXmitIntMaskClear, ~0);
ohci->it_context_mask = ohci->it_context_support;
ohci->n_it = hweight32(ohci->it_context_mask);
size = sizeof(struct iso_context) * ohci->n_it;
ohci->it_context_list = kzalloc(size, GFP_KERNEL);
if (ohci->it_context_list == NULL || ohci->ir_context_list == NULL) {
err = -ENOMEM;
goto fail_contexts;
}
ohci->self_id = ohci->misc_buffer + PAGE_SIZE/2;
ohci->self_id_bus = ohci->misc_buffer_bus + PAGE_SIZE/2;
bus_options = reg_read(ohci, OHCI1394_BusOptions);
max_receive = (bus_options >> 12) & 0xf;
link_speed = bus_options & 0x7;
guid = ((u64) reg_read(ohci, OHCI1394_GUIDHi) << 32) |
reg_read(ohci, OHCI1394_GUIDLo);
if (!(ohci->quirks & QUIRK_NO_MSI))
pci_enable_msi(dev);
if (request_irq(dev->irq, irq_handler,
pci_dev_msi_enabled(dev) ? 0 : IRQF_SHARED,
ohci_driver_name, ohci)) {
ohci_err(ohci, "failed to allocate interrupt %d\n", dev->irq);
err = -EIO;
goto fail_msi;
}
err = fw_card_add(&ohci->card, max_receive, link_speed, guid);
if (err)
goto fail_irq;
version = reg_read(ohci, OHCI1394_Version) & 0x00ff00ff;
ohci_notice(ohci,
"added OHCI v%x.%x device as card %d, "
"%d IR + %d IT contexts, quirks 0x%x%s\n",
version >> 16, version & 0xff, ohci->card.index,
ohci->n_ir, ohci->n_it, ohci->quirks,
reg_read(ohci, OHCI1394_PhyUpperBound) ?
", physUB" : "");
return 0;
fail_irq:
free_irq(dev->irq, ohci);
fail_msi:
pci_disable_msi(dev);
fail_contexts:
kfree(ohci->ir_context_list);
kfree(ohci->it_context_list);
context_release(&ohci->at_response_ctx);
fail_atreq_ctx:
context_release(&ohci->at_request_ctx);
fail_arrsp_ctx:
ar_context_release(&ohci->ar_response_ctx);
fail_arreq_ctx:
ar_context_release(&ohci->ar_request_ctx);
fail_misc_buf:
dma_free_coherent(ohci->card.device, PAGE_SIZE,
ohci->misc_buffer, ohci->misc_buffer_bus);
fail_iounmap:
pci_iounmap(dev, ohci->registers);
fail_iomem:
pci_release_region(dev, 0);
fail_disable:
pci_disable_device(dev);
fail_free:
kfree(ohci);
pmac_ohci_off(dev);
fail:
return err;
}
static void pci_remove(struct pci_dev *dev)
{
struct fw_ohci *ohci = pci_get_drvdata(dev);
/*
* If the removal is happening from the suspend state, LPS won't be
* enabled and host registers (eg., IntMaskClear) won't be accessible.
*/
if (reg_read(ohci, OHCI1394_HCControlSet) & OHCI1394_HCControl_LPS) {
reg_write(ohci, OHCI1394_IntMaskClear, ~0);
flush_writes(ohci);
}
cancel_work_sync(&ohci->bus_reset_work);
fw_core_remove_card(&ohci->card);
/*
* FIXME: Fail all pending packets here, now that the upper
* layers can't queue any more.
*/
software_reset(ohci);
free_irq(dev->irq, ohci);
if (ohci->next_config_rom && ohci->next_config_rom != ohci->config_rom)
dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
ohci->next_config_rom, ohci->next_config_rom_bus);
if (ohci->config_rom)
dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
ohci->config_rom, ohci->config_rom_bus);
ar_context_release(&ohci->ar_request_ctx);
ar_context_release(&ohci->ar_response_ctx);
dma_free_coherent(ohci->card.device, PAGE_SIZE,
ohci->misc_buffer, ohci->misc_buffer_bus);
context_release(&ohci->at_request_ctx);
context_release(&ohci->at_response_ctx);
kfree(ohci->it_context_list);
kfree(ohci->ir_context_list);
pci_disable_msi(dev);
pci_iounmap(dev, ohci->registers);
pci_release_region(dev, 0);
pci_disable_device(dev);
kfree(ohci);
pmac_ohci_off(dev);
dev_notice(&dev->dev, "removed fw-ohci device\n");
}
#ifdef CONFIG_PM
static int pci_suspend(struct pci_dev *dev, pm_message_t state)
{
struct fw_ohci *ohci = pci_get_drvdata(dev);
int err;
software_reset(ohci);
err = pci_save_state(dev);
if (err) {
ohci_err(ohci, "pci_save_state failed\n");
return err;
}
err = pci_set_power_state(dev, pci_choose_state(dev, state));
if (err)
ohci_err(ohci, "pci_set_power_state failed with %d\n", err);
pmac_ohci_off(dev);
return 0;
}
static int pci_resume(struct pci_dev *dev)
{
struct fw_ohci *ohci = pci_get_drvdata(dev);
int err;
pmac_ohci_on(dev);
pci_set_power_state(dev, PCI_D0);
pci_restore_state(dev);
err = pci_enable_device(dev);
if (err) {
ohci_err(ohci, "pci_enable_device failed\n");
return err;
}
/* Some systems don't setup GUID register on resume from ram */
if (!reg_read(ohci, OHCI1394_GUIDLo) &&
!reg_read(ohci, OHCI1394_GUIDHi)) {
reg_write(ohci, OHCI1394_GUIDLo, (u32)ohci->card.guid);
reg_write(ohci, OHCI1394_GUIDHi, (u32)(ohci->card.guid >> 32));
}
err = ohci_enable(&ohci->card, NULL, 0);
if (err)
return err;
ohci_resume_iso_dma(ohci);
return 0;
}
#endif
static const struct pci_device_id pci_table[] = {
{ PCI_DEVICE_CLASS(PCI_CLASS_SERIAL_FIREWIRE_OHCI, ~0) },
{ }
};
MODULE_DEVICE_TABLE(pci, pci_table);
static struct pci_driver fw_ohci_pci_driver = {
.name = ohci_driver_name,
.id_table = pci_table,
.probe = pci_probe,
.remove = pci_remove,
#ifdef CONFIG_PM
.resume = pci_resume,
.suspend = pci_suspend,
#endif
};
static int __init fw_ohci_init(void)
{
selfid_workqueue = alloc_workqueue(KBUILD_MODNAME, WQ_MEM_RECLAIM, 0);
if (!selfid_workqueue)
return -ENOMEM;
return pci_register_driver(&fw_ohci_pci_driver);
}
static void __exit fw_ohci_cleanup(void)
{
pci_unregister_driver(&fw_ohci_pci_driver);
destroy_workqueue(selfid_workqueue);
}
module_init(fw_ohci_init);
module_exit(fw_ohci_cleanup);
MODULE_AUTHOR("Kristian Hoegsberg <krh@bitplanet.net>");
MODULE_DESCRIPTION("Driver for PCI OHCI IEEE1394 controllers");
MODULE_LICENSE("GPL");
/* Provide a module alias so root-on-sbp2 initrds don't break. */
MODULE_ALIAS("ohci1394");
| gpl-2.0 |
locke12456/linux | arch/s390/mm/extmem.c | 616 | 18639 | /*
* Author(s)......: Carsten Otte <cotte@de.ibm.com>
* Rob M van der Heij <rvdheij@nl.ibm.com>
* Steven Shultz <shultzss@us.ibm.com>
* Bugreports.to..: <Linux390@de.ibm.com>
* Copyright IBM Corp. 2002, 2004
*/
#define KMSG_COMPONENT "extmem"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/spinlock.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/bootmem.h>
#include <linux/ctype.h>
#include <linux/ioport.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/ebcdic.h>
#include <asm/errno.h>
#include <asm/extmem.h>
#include <asm/cpcmd.h>
#include <asm/setup.h>
#define DCSS_LOADSHR 0x00
#define DCSS_LOADNSR 0x04
#define DCSS_PURGESEG 0x08
#define DCSS_FINDSEG 0x0c
#define DCSS_LOADNOLY 0x10
#define DCSS_SEGEXT 0x18
#define DCSS_LOADSHRX 0x20
#define DCSS_LOADNSRX 0x24
#define DCSS_FINDSEGX 0x2c
#define DCSS_SEGEXTX 0x38
#define DCSS_FINDSEGA 0x0c
struct qrange {
unsigned long start; /* last byte type */
unsigned long end; /* last byte reserved */
};
struct qout64 {
unsigned long segstart;
unsigned long segend;
int segcnt;
int segrcnt;
struct qrange range[6];
};
struct qrange_old {
unsigned int start; /* last byte type */
unsigned int end; /* last byte reserved */
};
/* output area format for the Diag x'64' old subcode x'18' */
struct qout64_old {
int segstart;
int segend;
int segcnt;
int segrcnt;
struct qrange_old range[6];
};
struct qin64 {
char qopcode;
char rsrv1[3];
char qrcode;
char rsrv2[3];
char qname[8];
unsigned int qoutptr;
short int qoutlen;
};
struct dcss_segment {
struct list_head list;
char dcss_name[8];
char res_name[15];
unsigned long start_addr;
unsigned long end;
atomic_t ref_count;
int do_nonshared;
unsigned int vm_segtype;
struct qrange range[6];
int segcnt;
struct resource *res;
};
static DEFINE_MUTEX(dcss_lock);
static LIST_HEAD(dcss_list);
static char *segtype_string[] = { "SW", "EW", "SR", "ER", "SN", "EN", "SC",
"EW/EN-MIXED" };
static int loadshr_scode, loadnsr_scode, findseg_scode;
static int segext_scode, purgeseg_scode;
static int scode_set;
/* set correct Diag x'64' subcodes. */
static int
dcss_set_subcodes(void)
{
char *name = kmalloc(8 * sizeof(char), GFP_KERNEL | GFP_DMA);
unsigned long rx, ry;
int rc;
if (name == NULL)
return -ENOMEM;
rx = (unsigned long) name;
ry = DCSS_FINDSEGX;
strcpy(name, "dummy");
asm volatile(
" diag %0,%1,0x64\n"
"0: ipm %2\n"
" srl %2,28\n"
" j 2f\n"
"1: la %2,3\n"
"2:\n"
EX_TABLE(0b, 1b)
: "+d" (rx), "+d" (ry), "=d" (rc) : : "cc");
kfree(name);
/* Diag x'64' new subcodes are supported, set to new subcodes */
if (rc != 3) {
loadshr_scode = DCSS_LOADSHRX;
loadnsr_scode = DCSS_LOADNSRX;
purgeseg_scode = DCSS_PURGESEG;
findseg_scode = DCSS_FINDSEGX;
segext_scode = DCSS_SEGEXTX;
return 0;
}
/* Diag x'64' new subcodes are not supported, set to old subcodes */
loadshr_scode = DCSS_LOADNOLY;
loadnsr_scode = DCSS_LOADNSR;
purgeseg_scode = DCSS_PURGESEG;
findseg_scode = DCSS_FINDSEG;
segext_scode = DCSS_SEGEXT;
return 0;
}
/*
* Create the 8 bytes, ebcdic VM segment name from
* an ascii name.
*/
static void
dcss_mkname(char *name, char *dcss_name)
{
int i;
for (i = 0; i < 8; i++) {
if (name[i] == '\0')
break;
dcss_name[i] = toupper(name[i]);
};
for (; i < 8; i++)
dcss_name[i] = ' ';
ASCEBC(dcss_name, 8);
}
/*
* search all segments in dcss_list, and return the one
* namend *name. If not found, return NULL.
*/
static struct dcss_segment *
segment_by_name (char *name)
{
char dcss_name[9];
struct list_head *l;
struct dcss_segment *tmp, *retval = NULL;
BUG_ON(!mutex_is_locked(&dcss_lock));
dcss_mkname (name, dcss_name);
list_for_each (l, &dcss_list) {
tmp = list_entry (l, struct dcss_segment, list);
if (memcmp(tmp->dcss_name, dcss_name, 8) == 0) {
retval = tmp;
break;
}
}
return retval;
}
/*
* Perform a function on a dcss segment.
*/
static inline int
dcss_diag(int *func, void *parameter,
unsigned long *ret1, unsigned long *ret2)
{
unsigned long rx, ry;
int rc;
if (scode_set == 0) {
rc = dcss_set_subcodes();
if (rc < 0)
return rc;
scode_set = 1;
}
rx = (unsigned long) parameter;
ry = (unsigned long) *func;
/* 64-bit Diag x'64' new subcode, keep in 64-bit addressing mode */
if (*func > DCSS_SEGEXT)
asm volatile(
" diag %0,%1,0x64\n"
" ipm %2\n"
" srl %2,28\n"
: "+d" (rx), "+d" (ry), "=d" (rc) : : "cc");
/* 31-bit Diag x'64' old subcode, switch to 31-bit addressing mode */
else
asm volatile(
" sam31\n"
" diag %0,%1,0x64\n"
" sam64\n"
" ipm %2\n"
" srl %2,28\n"
: "+d" (rx), "+d" (ry), "=d" (rc) : : "cc");
*ret1 = rx;
*ret2 = ry;
return rc;
}
static inline int
dcss_diag_translate_rc (int vm_rc) {
if (vm_rc == 44)
return -ENOENT;
return -EIO;
}
/* do a diag to get info about a segment.
* fills start_address, end and vm_segtype fields
*/
static int
query_segment_type (struct dcss_segment *seg)
{
unsigned long dummy, vmrc;
int diag_cc, rc, i;
struct qout64 *qout;
struct qin64 *qin;
qin = kmalloc(sizeof(*qin), GFP_KERNEL | GFP_DMA);
qout = kmalloc(sizeof(*qout), GFP_KERNEL | GFP_DMA);
if ((qin == NULL) || (qout == NULL)) {
rc = -ENOMEM;
goto out_free;
}
/* initialize diag input parameters */
qin->qopcode = DCSS_FINDSEGA;
qin->qoutptr = (unsigned long) qout;
qin->qoutlen = sizeof(struct qout64);
memcpy (qin->qname, seg->dcss_name, 8);
diag_cc = dcss_diag(&segext_scode, qin, &dummy, &vmrc);
if (diag_cc < 0) {
rc = diag_cc;
goto out_free;
}
if (diag_cc > 1) {
pr_warning("Querying a DCSS type failed with rc=%ld\n", vmrc);
rc = dcss_diag_translate_rc (vmrc);
goto out_free;
}
/* Only old format of output area of Diagnose x'64' is supported,
copy data for the new format. */
if (segext_scode == DCSS_SEGEXT) {
struct qout64_old *qout_old;
qout_old = kzalloc(sizeof(*qout_old), GFP_KERNEL | GFP_DMA);
if (qout_old == NULL) {
rc = -ENOMEM;
goto out_free;
}
memcpy(qout_old, qout, sizeof(struct qout64_old));
qout->segstart = (unsigned long) qout_old->segstart;
qout->segend = (unsigned long) qout_old->segend;
qout->segcnt = qout_old->segcnt;
qout->segrcnt = qout_old->segrcnt;
if (qout->segcnt > 6)
qout->segrcnt = 6;
for (i = 0; i < qout->segrcnt; i++) {
qout->range[i].start =
(unsigned long) qout_old->range[i].start;
qout->range[i].end =
(unsigned long) qout_old->range[i].end;
}
kfree(qout_old);
}
if (qout->segcnt > 6) {
rc = -EOPNOTSUPP;
goto out_free;
}
if (qout->segcnt == 1) {
seg->vm_segtype = qout->range[0].start & 0xff;
} else {
/* multi-part segment. only one type supported here:
- all parts are contiguous
- all parts are either EW or EN type
- maximum 6 parts allowed */
unsigned long start = qout->segstart >> PAGE_SHIFT;
for (i=0; i<qout->segcnt; i++) {
if (((qout->range[i].start & 0xff) != SEG_TYPE_EW) &&
((qout->range[i].start & 0xff) != SEG_TYPE_EN)) {
rc = -EOPNOTSUPP;
goto out_free;
}
if (start != qout->range[i].start >> PAGE_SHIFT) {
rc = -EOPNOTSUPP;
goto out_free;
}
start = (qout->range[i].end >> PAGE_SHIFT) + 1;
}
seg->vm_segtype = SEG_TYPE_EWEN;
}
/* analyze diag output and update seg */
seg->start_addr = qout->segstart;
seg->end = qout->segend;
memcpy (seg->range, qout->range, 6*sizeof(struct qrange));
seg->segcnt = qout->segcnt;
rc = 0;
out_free:
kfree(qin);
kfree(qout);
return rc;
}
/*
* get info about a segment
* possible return values:
* -ENOSYS : we are not running on VM
* -EIO : could not perform query diagnose
* -ENOENT : no such segment
* -EOPNOTSUPP: multi-part segment cannot be used with linux
* -ENOMEM : out of memory
* 0 .. 6 : type of segment as defined in include/asm-s390/extmem.h
*/
int
segment_type (char* name)
{
int rc;
struct dcss_segment seg;
if (!MACHINE_IS_VM)
return -ENOSYS;
dcss_mkname(name, seg.dcss_name);
rc = query_segment_type (&seg);
if (rc < 0)
return rc;
return seg.vm_segtype;
}
/*
* check if segment collides with other segments that are currently loaded
* returns 1 if this is the case, 0 if no collision was found
*/
static int
segment_overlaps_others (struct dcss_segment *seg)
{
struct list_head *l;
struct dcss_segment *tmp;
BUG_ON(!mutex_is_locked(&dcss_lock));
list_for_each(l, &dcss_list) {
tmp = list_entry(l, struct dcss_segment, list);
if ((tmp->start_addr >> 20) > (seg->end >> 20))
continue;
if ((tmp->end >> 20) < (seg->start_addr >> 20))
continue;
if (seg == tmp)
continue;
return 1;
}
return 0;
}
/*
* real segment loading function, called from segment_load
*/
static int
__segment_load (char *name, int do_nonshared, unsigned long *addr, unsigned long *end)
{
unsigned long start_addr, end_addr, dummy;
struct dcss_segment *seg;
int rc, diag_cc;
start_addr = end_addr = 0;
seg = kmalloc(sizeof(*seg), GFP_KERNEL | GFP_DMA);
if (seg == NULL) {
rc = -ENOMEM;
goto out;
}
dcss_mkname (name, seg->dcss_name);
rc = query_segment_type (seg);
if (rc < 0)
goto out_free;
if (loadshr_scode == DCSS_LOADSHRX) {
if (segment_overlaps_others(seg)) {
rc = -EBUSY;
goto out_free;
}
}
rc = vmem_add_mapping(seg->start_addr, seg->end - seg->start_addr + 1);
if (rc)
goto out_free;
seg->res = kzalloc(sizeof(struct resource), GFP_KERNEL);
if (seg->res == NULL) {
rc = -ENOMEM;
goto out_shared;
}
seg->res->flags = IORESOURCE_BUSY | IORESOURCE_MEM;
seg->res->start = seg->start_addr;
seg->res->end = seg->end;
memcpy(&seg->res_name, seg->dcss_name, 8);
EBCASC(seg->res_name, 8);
seg->res_name[8] = '\0';
strncat(seg->res_name, " (DCSS)", 7);
seg->res->name = seg->res_name;
rc = seg->vm_segtype;
if (rc == SEG_TYPE_SC ||
((rc == SEG_TYPE_SR || rc == SEG_TYPE_ER) && !do_nonshared))
seg->res->flags |= IORESOURCE_READONLY;
if (request_resource(&iomem_resource, seg->res)) {
rc = -EBUSY;
kfree(seg->res);
goto out_shared;
}
if (do_nonshared)
diag_cc = dcss_diag(&loadnsr_scode, seg->dcss_name,
&start_addr, &end_addr);
else
diag_cc = dcss_diag(&loadshr_scode, seg->dcss_name,
&start_addr, &end_addr);
if (diag_cc < 0) {
dcss_diag(&purgeseg_scode, seg->dcss_name,
&dummy, &dummy);
rc = diag_cc;
goto out_resource;
}
if (diag_cc > 1) {
pr_warning("Loading DCSS %s failed with rc=%ld\n", name,
end_addr);
rc = dcss_diag_translate_rc(end_addr);
dcss_diag(&purgeseg_scode, seg->dcss_name,
&dummy, &dummy);
goto out_resource;
}
seg->start_addr = start_addr;
seg->end = end_addr;
seg->do_nonshared = do_nonshared;
atomic_set(&seg->ref_count, 1);
list_add(&seg->list, &dcss_list);
*addr = seg->start_addr;
*end = seg->end;
if (do_nonshared)
pr_info("DCSS %s of range %p to %p and type %s loaded as "
"exclusive-writable\n", name, (void*) seg->start_addr,
(void*) seg->end, segtype_string[seg->vm_segtype]);
else {
pr_info("DCSS %s of range %p to %p and type %s loaded in "
"shared access mode\n", name, (void*) seg->start_addr,
(void*) seg->end, segtype_string[seg->vm_segtype]);
}
goto out;
out_resource:
release_resource(seg->res);
kfree(seg->res);
out_shared:
vmem_remove_mapping(seg->start_addr, seg->end - seg->start_addr + 1);
out_free:
kfree(seg);
out:
return rc;
}
/*
* this function loads a DCSS segment
* name : name of the DCSS
* do_nonshared : 0 indicates that the dcss should be shared with other linux images
* 1 indicates that the dcss should be exclusive for this linux image
* addr : will be filled with start address of the segment
* end : will be filled with end address of the segment
* return values:
* -ENOSYS : we are not running on VM
* -EIO : could not perform query or load diagnose
* -ENOENT : no such segment
* -EOPNOTSUPP: multi-part segment cannot be used with linux
* -ENOSPC : segment cannot be used (overlaps with storage)
* -EBUSY : segment can temporarily not be used (overlaps with dcss)
* -ERANGE : segment cannot be used (exceeds kernel mapping range)
* -EPERM : segment is currently loaded with incompatible permissions
* -ENOMEM : out of memory
* 0 .. 6 : type of segment as defined in include/asm-s390/extmem.h
*/
int
segment_load (char *name, int do_nonshared, unsigned long *addr,
unsigned long *end)
{
struct dcss_segment *seg;
int rc;
if (!MACHINE_IS_VM)
return -ENOSYS;
mutex_lock(&dcss_lock);
seg = segment_by_name (name);
if (seg == NULL)
rc = __segment_load (name, do_nonshared, addr, end);
else {
if (do_nonshared == seg->do_nonshared) {
atomic_inc(&seg->ref_count);
*addr = seg->start_addr;
*end = seg->end;
rc = seg->vm_segtype;
} else {
*addr = *end = 0;
rc = -EPERM;
}
}
mutex_unlock(&dcss_lock);
return rc;
}
/*
* this function modifies the shared state of a DCSS segment. note that
* name : name of the DCSS
* do_nonshared : 0 indicates that the dcss should be shared with other linux images
* 1 indicates that the dcss should be exclusive for this linux image
* return values:
* -EIO : could not perform load diagnose (segment gone!)
* -ENOENT : no such segment (segment gone!)
* -EAGAIN : segment is in use by other exploiters, try later
* -EINVAL : no segment with the given name is currently loaded - name invalid
* -EBUSY : segment can temporarily not be used (overlaps with dcss)
* 0 : operation succeeded
*/
int
segment_modify_shared (char *name, int do_nonshared)
{
struct dcss_segment *seg;
unsigned long start_addr, end_addr, dummy;
int rc, diag_cc;
start_addr = end_addr = 0;
mutex_lock(&dcss_lock);
seg = segment_by_name (name);
if (seg == NULL) {
rc = -EINVAL;
goto out_unlock;
}
if (do_nonshared == seg->do_nonshared) {
pr_info("DCSS %s is already in the requested access "
"mode\n", name);
rc = 0;
goto out_unlock;
}
if (atomic_read (&seg->ref_count) != 1) {
pr_warning("DCSS %s is in use and cannot be reloaded\n",
name);
rc = -EAGAIN;
goto out_unlock;
}
release_resource(seg->res);
if (do_nonshared)
seg->res->flags &= ~IORESOURCE_READONLY;
else
if (seg->vm_segtype == SEG_TYPE_SR ||
seg->vm_segtype == SEG_TYPE_ER)
seg->res->flags |= IORESOURCE_READONLY;
if (request_resource(&iomem_resource, seg->res)) {
pr_warning("DCSS %s overlaps with used memory resources "
"and cannot be reloaded\n", name);
rc = -EBUSY;
kfree(seg->res);
goto out_del_mem;
}
dcss_diag(&purgeseg_scode, seg->dcss_name, &dummy, &dummy);
if (do_nonshared)
diag_cc = dcss_diag(&loadnsr_scode, seg->dcss_name,
&start_addr, &end_addr);
else
diag_cc = dcss_diag(&loadshr_scode, seg->dcss_name,
&start_addr, &end_addr);
if (diag_cc < 0) {
rc = diag_cc;
goto out_del_res;
}
if (diag_cc > 1) {
pr_warning("Reloading DCSS %s failed with rc=%ld\n", name,
end_addr);
rc = dcss_diag_translate_rc(end_addr);
goto out_del_res;
}
seg->start_addr = start_addr;
seg->end = end_addr;
seg->do_nonshared = do_nonshared;
rc = 0;
goto out_unlock;
out_del_res:
release_resource(seg->res);
kfree(seg->res);
out_del_mem:
vmem_remove_mapping(seg->start_addr, seg->end - seg->start_addr + 1);
list_del(&seg->list);
dcss_diag(&purgeseg_scode, seg->dcss_name, &dummy, &dummy);
kfree(seg);
out_unlock:
mutex_unlock(&dcss_lock);
return rc;
}
/*
* Decrease the use count of a DCSS segment and remove
* it from the address space if nobody is using it
* any longer.
*/
void
segment_unload(char *name)
{
unsigned long dummy;
struct dcss_segment *seg;
if (!MACHINE_IS_VM)
return;
mutex_lock(&dcss_lock);
seg = segment_by_name (name);
if (seg == NULL) {
pr_err("Unloading unknown DCSS %s failed\n", name);
goto out_unlock;
}
if (atomic_dec_return(&seg->ref_count) != 0)
goto out_unlock;
release_resource(seg->res);
kfree(seg->res);
vmem_remove_mapping(seg->start_addr, seg->end - seg->start_addr + 1);
list_del(&seg->list);
dcss_diag(&purgeseg_scode, seg->dcss_name, &dummy, &dummy);
kfree(seg);
out_unlock:
mutex_unlock(&dcss_lock);
}
/*
* save segment content permanently
*/
void
segment_save(char *name)
{
struct dcss_segment *seg;
char cmd1[160];
char cmd2[80];
int i, response;
if (!MACHINE_IS_VM)
return;
mutex_lock(&dcss_lock);
seg = segment_by_name (name);
if (seg == NULL) {
pr_err("Saving unknown DCSS %s failed\n", name);
goto out;
}
sprintf(cmd1, "DEFSEG %s", name);
for (i=0; i<seg->segcnt; i++) {
sprintf(cmd1+strlen(cmd1), " %lX-%lX %s",
seg->range[i].start >> PAGE_SHIFT,
seg->range[i].end >> PAGE_SHIFT,
segtype_string[seg->range[i].start & 0xff]);
}
sprintf(cmd2, "SAVESEG %s", name);
response = 0;
cpcmd(cmd1, NULL, 0, &response);
if (response) {
pr_err("Saving a DCSS failed with DEFSEG response code "
"%i\n", response);
goto out;
}
cpcmd(cmd2, NULL, 0, &response);
if (response) {
pr_err("Saving a DCSS failed with SAVESEG response code "
"%i\n", response);
goto out;
}
out:
mutex_unlock(&dcss_lock);
}
/*
* print appropriate error message for segment_load()/segment_type()
* return code
*/
void segment_warning(int rc, char *seg_name)
{
switch (rc) {
case -ENOENT:
pr_err("DCSS %s cannot be loaded or queried\n", seg_name);
break;
case -ENOSYS:
pr_err("DCSS %s cannot be loaded or queried without "
"z/VM\n", seg_name);
break;
case -EIO:
pr_err("Loading or querying DCSS %s resulted in a "
"hardware error\n", seg_name);
break;
case -EOPNOTSUPP:
pr_err("DCSS %s has multiple page ranges and cannot be "
"loaded or queried\n", seg_name);
break;
case -ENOSPC:
pr_err("DCSS %s overlaps with used storage and cannot "
"be loaded\n", seg_name);
break;
case -EBUSY:
pr_err("%s needs used memory resources and cannot be "
"loaded or queried\n", seg_name);
break;
case -EPERM:
pr_err("DCSS %s is already loaded in a different access "
"mode\n", seg_name);
break;
case -ENOMEM:
pr_err("There is not enough memory to load or query "
"DCSS %s\n", seg_name);
break;
case -ERANGE:
pr_err("DCSS %s exceeds the kernel mapping range (%lu) "
"and cannot be loaded\n", seg_name, VMEM_MAX_PHYS);
break;
default:
break;
}
}
EXPORT_SYMBOL(segment_load);
EXPORT_SYMBOL(segment_unload);
EXPORT_SYMBOL(segment_save);
EXPORT_SYMBOL(segment_type);
EXPORT_SYMBOL(segment_modify_shared);
EXPORT_SYMBOL(segment_warning);
| gpl-2.0 |
uileyar/fastsocket | kernel/drivers/uio/uio_aec.c | 616 | 4325 | /*
* uio_aec.c -- simple driver for Adrienne Electronics Corp time code PCI device
*
* Copyright (C) 2008 Brandon Philips <brandon@ifup.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* 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/pci.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <linux/uio_driver.h>
#define PCI_VENDOR_ID_AEC 0xaecb
#define PCI_DEVICE_ID_AEC_VITCLTC 0x6250
#define INT_ENABLE_ADDR 0xFC
#define INT_ENABLE 0x10
#define INT_DISABLE 0x0
#define INT_MASK_ADDR 0x2E
#define INT_MASK_ALL 0x3F
#define INTA_DRVR_ADDR 0xFE
#define INTA_ENABLED_FLAG 0x08
#define INTA_FLAG 0x01
#define MAILBOX 0x0F
static struct pci_device_id ids[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_AEC, PCI_DEVICE_ID_AEC_VITCLTC), },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, ids);
static irqreturn_t aectc_irq(int irq, struct uio_info *dev_info)
{
void __iomem *int_flag = dev_info->priv + INTA_DRVR_ADDR;
unsigned char status = ioread8(int_flag);
if ((status & INTA_ENABLED_FLAG) && (status & INTA_FLAG)) {
/* application writes 0x00 to 0x2F to get next interrupt */
status = ioread8(dev_info->priv + MAILBOX);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
static void print_board_data(struct pci_dev *pdev, struct uio_info *i)
{
dev_info(&pdev->dev, "PCI-TC board vendor: %x%x number: %x%x"
" revision: %c%c\n",
ioread8(i->priv + 0x01),
ioread8(i->priv + 0x00),
ioread8(i->priv + 0x03),
ioread8(i->priv + 0x02),
ioread8(i->priv + 0x06),
ioread8(i->priv + 0x07));
}
static int __devinit probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
struct uio_info *info;
int ret;
info = kzalloc(sizeof(struct uio_info), GFP_KERNEL);
if (!info)
return -ENOMEM;
if (pci_enable_device(pdev))
goto out_free;
if (pci_request_regions(pdev, "aectc"))
goto out_disable;
info->name = "aectc";
info->port[0].start = pci_resource_start(pdev, 0);
if (!info->port[0].start)
goto out_release;
info->priv = pci_iomap(pdev, 0, 0);
if (!info->priv)
goto out_release;
info->port[0].size = pci_resource_len(pdev, 0);
info->port[0].porttype = UIO_PORT_GPIO;
info->version = "0.0.1";
info->irq = pdev->irq;
info->irq_flags = IRQF_SHARED;
info->handler = aectc_irq;
print_board_data(pdev, info);
ret = uio_register_device(&pdev->dev, info);
if (ret)
goto out_unmap;
iowrite32(INT_ENABLE, info->priv + INT_ENABLE_ADDR);
iowrite8(INT_MASK_ALL, info->priv + INT_MASK_ADDR);
if (!(ioread8(info->priv + INTA_DRVR_ADDR)
& INTA_ENABLED_FLAG))
dev_err(&pdev->dev, "aectc: interrupts not enabled\n");
pci_set_drvdata(pdev, info);
return 0;
out_unmap:
pci_iounmap(pdev, info->priv);
out_release:
pci_release_regions(pdev);
out_disable:
pci_disable_device(pdev);
out_free:
kfree(info);
return -ENODEV;
}
static void remove(struct pci_dev *pdev)
{
struct uio_info *info = pci_get_drvdata(pdev);
/* disable interrupts */
iowrite8(INT_DISABLE, info->priv + INT_MASK_ADDR);
iowrite32(INT_DISABLE, info->priv + INT_ENABLE_ADDR);
/* read mailbox to ensure board drops irq */
ioread8(info->priv + MAILBOX);
uio_unregister_device(info);
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
iounmap(info->priv);
kfree(info);
}
static struct pci_driver pci_driver = {
.name = "aectc",
.id_table = ids,
.probe = probe,
.remove = remove,
};
static int __init aectc_init(void)
{
return pci_register_driver(&pci_driver);
}
static void __exit aectc_exit(void)
{
pci_unregister_driver(&pci_driver);
}
MODULE_LICENSE("GPL");
module_init(aectc_init);
module_exit(aectc_exit);
| gpl-2.0 |
willizambranoback/evolution_CM13 | fs/compat.c | 1384 | 45660 | /*
* linux/fs/compat.c
*
* Kernel compatibililty routines for e.g. 32 bit syscall support
* on 64 bit kernels.
*
* Copyright (C) 2002 Stephen Rothwell, IBM Corporation
* Copyright (C) 1997-2000 Jakub Jelinek (jakub@redhat.com)
* Copyright (C) 1998 Eddie C. Dost (ecd@skynet.be)
* Copyright (C) 2001,2002 Andi Kleen, SuSE Labs
* Copyright (C) 2003 Pavel Machek (pavel@ucw.cz)
*
* 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/stddef.h>
#include <linux/kernel.h>
#include <linux/linkage.h>
#include <linux/compat.h>
#include <linux/errno.h>
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/fcntl.h>
#include <linux/namei.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/vfs.h>
#include <linux/ioctl.h>
#include <linux/init.h>
#include <linux/ncp_mount.h>
#include <linux/nfs4_mount.h>
#include <linux/syscalls.h>
#include <linux/ctype.h>
#include <linux/dirent.h>
#include <linux/fsnotify.h>
#include <linux/highuid.h>
#include <linux/personality.h>
#include <linux/rwsem.h>
#include <linux/tsacct_kern.h>
#include <linux/security.h>
#include <linux/highmem.h>
#include <linux/signal.h>
#include <linux/poll.h>
#include <linux/mm.h>
#include <linux/eventpoll.h>
#include <linux/fs_struct.h>
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <asm/uaccess.h>
#include <asm/mmu_context.h>
#include <asm/ioctls.h>
#include "internal.h"
int compat_log = 1;
int compat_printk(const char *fmt, ...)
{
va_list ap;
int ret;
if (!compat_log)
return 0;
va_start(ap, fmt);
ret = vprintk(fmt, ap);
va_end(ap);
return ret;
}
#include "read_write.h"
/*
* Not all architectures have sys_utime, so implement this in terms
* of sys_utimes.
*/
asmlinkage long compat_sys_utime(const char __user *filename,
struct compat_utimbuf __user *t)
{
struct timespec tv[2];
if (t) {
if (get_user(tv[0].tv_sec, &t->actime) ||
get_user(tv[1].tv_sec, &t->modtime))
return -EFAULT;
tv[0].tv_nsec = 0;
tv[1].tv_nsec = 0;
}
return do_utimes(AT_FDCWD, filename, t ? tv : NULL, 0);
}
asmlinkage long compat_sys_utimensat(unsigned int dfd, const char __user *filename, struct compat_timespec __user *t, int flags)
{
struct timespec tv[2];
if (t) {
if (get_compat_timespec(&tv[0], &t[0]) ||
get_compat_timespec(&tv[1], &t[1]))
return -EFAULT;
if (tv[0].tv_nsec == UTIME_OMIT && tv[1].tv_nsec == UTIME_OMIT)
return 0;
}
return do_utimes(dfd, filename, t ? tv : NULL, flags);
}
asmlinkage long compat_sys_futimesat(unsigned int dfd, const char __user *filename, struct compat_timeval __user *t)
{
struct timespec tv[2];
if (t) {
if (get_user(tv[0].tv_sec, &t[0].tv_sec) ||
get_user(tv[0].tv_nsec, &t[0].tv_usec) ||
get_user(tv[1].tv_sec, &t[1].tv_sec) ||
get_user(tv[1].tv_nsec, &t[1].tv_usec))
return -EFAULT;
if (tv[0].tv_nsec >= 1000000 || tv[0].tv_nsec < 0 ||
tv[1].tv_nsec >= 1000000 || tv[1].tv_nsec < 0)
return -EINVAL;
tv[0].tv_nsec *= 1000;
tv[1].tv_nsec *= 1000;
}
return do_utimes(dfd, filename, t ? tv : NULL, 0);
}
asmlinkage long compat_sys_utimes(const char __user *filename, struct compat_timeval __user *t)
{
return compat_sys_futimesat(AT_FDCWD, filename, t);
}
static int cp_compat_stat(struct kstat *stat, struct compat_stat __user *ubuf)
{
struct compat_stat tmp;
if (!old_valid_dev(stat->dev) || !old_valid_dev(stat->rdev))
return -EOVERFLOW;
memset(&tmp, 0, sizeof(tmp));
tmp.st_dev = old_encode_dev(stat->dev);
tmp.st_ino = stat->ino;
if (sizeof(tmp.st_ino) < sizeof(stat->ino) && tmp.st_ino != stat->ino)
return -EOVERFLOW;
tmp.st_mode = stat->mode;
tmp.st_nlink = stat->nlink;
if (tmp.st_nlink != stat->nlink)
return -EOVERFLOW;
SET_UID(tmp.st_uid, stat->uid);
SET_GID(tmp.st_gid, stat->gid);
tmp.st_rdev = old_encode_dev(stat->rdev);
if ((u64) stat->size > MAX_NON_LFS)
return -EOVERFLOW;
tmp.st_size = stat->size;
tmp.st_atime = stat->atime.tv_sec;
tmp.st_atime_nsec = stat->atime.tv_nsec;
tmp.st_mtime = stat->mtime.tv_sec;
tmp.st_mtime_nsec = stat->mtime.tv_nsec;
tmp.st_ctime = stat->ctime.tv_sec;
tmp.st_ctime_nsec = stat->ctime.tv_nsec;
tmp.st_blocks = stat->blocks;
tmp.st_blksize = stat->blksize;
return copy_to_user(ubuf, &tmp, sizeof(tmp)) ? -EFAULT : 0;
}
asmlinkage long compat_sys_newstat(const char __user * filename,
struct compat_stat __user *statbuf)
{
struct kstat stat;
int error;
error = vfs_stat(filename, &stat);
if (error)
return error;
return cp_compat_stat(&stat, statbuf);
}
asmlinkage long compat_sys_newlstat(const char __user * filename,
struct compat_stat __user *statbuf)
{
struct kstat stat;
int error;
error = vfs_lstat(filename, &stat);
if (error)
return error;
return cp_compat_stat(&stat, statbuf);
}
#ifndef __ARCH_WANT_STAT64
asmlinkage long compat_sys_newfstatat(unsigned int dfd,
const char __user *filename,
struct compat_stat __user *statbuf, int flag)
{
struct kstat stat;
int error;
error = vfs_fstatat(dfd, filename, &stat, flag);
if (error)
return error;
return cp_compat_stat(&stat, statbuf);
}
#endif
asmlinkage long compat_sys_newfstat(unsigned int fd,
struct compat_stat __user * statbuf)
{
struct kstat stat;
int error = vfs_fstat(fd, &stat);
if (!error)
error = cp_compat_stat(&stat, statbuf);
return error;
}
static int put_compat_statfs(struct compat_statfs __user *ubuf, struct kstatfs *kbuf)
{
if (sizeof ubuf->f_blocks == 4) {
if ((kbuf->f_blocks | kbuf->f_bfree | kbuf->f_bavail |
kbuf->f_bsize | kbuf->f_frsize) & 0xffffffff00000000ULL)
return -EOVERFLOW;
/* f_files and f_ffree may be -1; it's okay
* to stuff that into 32 bits */
if (kbuf->f_files != 0xffffffffffffffffULL
&& (kbuf->f_files & 0xffffffff00000000ULL))
return -EOVERFLOW;
if (kbuf->f_ffree != 0xffffffffffffffffULL
&& (kbuf->f_ffree & 0xffffffff00000000ULL))
return -EOVERFLOW;
}
if (!access_ok(VERIFY_WRITE, ubuf, sizeof(*ubuf)) ||
__put_user(kbuf->f_type, &ubuf->f_type) ||
__put_user(kbuf->f_bsize, &ubuf->f_bsize) ||
__put_user(kbuf->f_blocks, &ubuf->f_blocks) ||
__put_user(kbuf->f_bfree, &ubuf->f_bfree) ||
__put_user(kbuf->f_bavail, &ubuf->f_bavail) ||
__put_user(kbuf->f_files, &ubuf->f_files) ||
__put_user(kbuf->f_ffree, &ubuf->f_ffree) ||
__put_user(kbuf->f_namelen, &ubuf->f_namelen) ||
__put_user(kbuf->f_fsid.val[0], &ubuf->f_fsid.val[0]) ||
__put_user(kbuf->f_fsid.val[1], &ubuf->f_fsid.val[1]) ||
__put_user(kbuf->f_frsize, &ubuf->f_frsize) ||
__put_user(kbuf->f_flags, &ubuf->f_flags) ||
__clear_user(ubuf->f_spare, sizeof(ubuf->f_spare)))
return -EFAULT;
return 0;
}
/*
* The following statfs calls are copies of code from fs/statfs.c and
* should be checked against those from time to time
*/
asmlinkage long compat_sys_statfs(const char __user *pathname, struct compat_statfs __user *buf)
{
struct kstatfs tmp;
int error = user_statfs(pathname, &tmp);
if (!error)
error = put_compat_statfs(buf, &tmp);
return error;
}
asmlinkage long compat_sys_fstatfs(unsigned int fd, struct compat_statfs __user *buf)
{
struct kstatfs tmp;
int error = fd_statfs(fd, &tmp);
if (!error)
error = put_compat_statfs(buf, &tmp);
return error;
}
static int put_compat_statfs64(struct compat_statfs64 __user *ubuf, struct kstatfs *kbuf)
{
if (sizeof ubuf->f_blocks == 4) {
if ((kbuf->f_blocks | kbuf->f_bfree | kbuf->f_bavail |
kbuf->f_bsize | kbuf->f_frsize) & 0xffffffff00000000ULL)
return -EOVERFLOW;
/* f_files and f_ffree may be -1; it's okay
* to stuff that into 32 bits */
if (kbuf->f_files != 0xffffffffffffffffULL
&& (kbuf->f_files & 0xffffffff00000000ULL))
return -EOVERFLOW;
if (kbuf->f_ffree != 0xffffffffffffffffULL
&& (kbuf->f_ffree & 0xffffffff00000000ULL))
return -EOVERFLOW;
}
if (!access_ok(VERIFY_WRITE, ubuf, sizeof(*ubuf)) ||
__put_user(kbuf->f_type, &ubuf->f_type) ||
__put_user(kbuf->f_bsize, &ubuf->f_bsize) ||
__put_user(kbuf->f_blocks, &ubuf->f_blocks) ||
__put_user(kbuf->f_bfree, &ubuf->f_bfree) ||
__put_user(kbuf->f_bavail, &ubuf->f_bavail) ||
__put_user(kbuf->f_files, &ubuf->f_files) ||
__put_user(kbuf->f_ffree, &ubuf->f_ffree) ||
__put_user(kbuf->f_namelen, &ubuf->f_namelen) ||
__put_user(kbuf->f_fsid.val[0], &ubuf->f_fsid.val[0]) ||
__put_user(kbuf->f_fsid.val[1], &ubuf->f_fsid.val[1]) ||
__put_user(kbuf->f_frsize, &ubuf->f_frsize) ||
__put_user(kbuf->f_flags, &ubuf->f_flags) ||
__clear_user(ubuf->f_spare, sizeof(ubuf->f_spare)))
return -EFAULT;
return 0;
}
asmlinkage long compat_sys_statfs64(const char __user *pathname, compat_size_t sz, struct compat_statfs64 __user *buf)
{
struct kstatfs tmp;
int error;
if (sz != sizeof(*buf))
return -EINVAL;
error = user_statfs(pathname, &tmp);
if (!error)
error = put_compat_statfs64(buf, &tmp);
return error;
}
asmlinkage long compat_sys_fstatfs64(unsigned int fd, compat_size_t sz, struct compat_statfs64 __user *buf)
{
struct kstatfs tmp;
int error;
if (sz != sizeof(*buf))
return -EINVAL;
error = fd_statfs(fd, &tmp);
if (!error)
error = put_compat_statfs64(buf, &tmp);
return error;
}
/*
* This is a copy of sys_ustat, just dealing with a structure layout.
* Given how simple this syscall is that apporach is more maintainable
* than the various conversion hacks.
*/
asmlinkage long compat_sys_ustat(unsigned dev, struct compat_ustat __user *u)
{
struct compat_ustat tmp;
struct kstatfs sbuf;
int err = vfs_ustat(new_decode_dev(dev), &sbuf);
if (err)
return err;
memset(&tmp, 0, sizeof(struct compat_ustat));
tmp.f_tfree = sbuf.f_bfree;
tmp.f_tinode = sbuf.f_ffree;
if (copy_to_user(u, &tmp, sizeof(struct compat_ustat)))
return -EFAULT;
return 0;
}
static int get_compat_flock(struct flock *kfl, struct compat_flock __user *ufl)
{
if (!access_ok(VERIFY_READ, ufl, sizeof(*ufl)) ||
__get_user(kfl->l_type, &ufl->l_type) ||
__get_user(kfl->l_whence, &ufl->l_whence) ||
__get_user(kfl->l_start, &ufl->l_start) ||
__get_user(kfl->l_len, &ufl->l_len) ||
__get_user(kfl->l_pid, &ufl->l_pid))
return -EFAULT;
return 0;
}
static int put_compat_flock(struct flock *kfl, struct compat_flock __user *ufl)
{
if (!access_ok(VERIFY_WRITE, ufl, sizeof(*ufl)) ||
__put_user(kfl->l_type, &ufl->l_type) ||
__put_user(kfl->l_whence, &ufl->l_whence) ||
__put_user(kfl->l_start, &ufl->l_start) ||
__put_user(kfl->l_len, &ufl->l_len) ||
__put_user(kfl->l_pid, &ufl->l_pid))
return -EFAULT;
return 0;
}
#ifndef HAVE_ARCH_GET_COMPAT_FLOCK64
static int get_compat_flock64(struct flock *kfl, struct compat_flock64 __user *ufl)
{
if (!access_ok(VERIFY_READ, ufl, sizeof(*ufl)) ||
__get_user(kfl->l_type, &ufl->l_type) ||
__get_user(kfl->l_whence, &ufl->l_whence) ||
__get_user(kfl->l_start, &ufl->l_start) ||
__get_user(kfl->l_len, &ufl->l_len) ||
__get_user(kfl->l_pid, &ufl->l_pid))
return -EFAULT;
return 0;
}
#endif
#ifndef HAVE_ARCH_PUT_COMPAT_FLOCK64
static int put_compat_flock64(struct flock *kfl, struct compat_flock64 __user *ufl)
{
if (!access_ok(VERIFY_WRITE, ufl, sizeof(*ufl)) ||
__put_user(kfl->l_type, &ufl->l_type) ||
__put_user(kfl->l_whence, &ufl->l_whence) ||
__put_user(kfl->l_start, &ufl->l_start) ||
__put_user(kfl->l_len, &ufl->l_len) ||
__put_user(kfl->l_pid, &ufl->l_pid))
return -EFAULT;
return 0;
}
#endif
asmlinkage long compat_sys_fcntl64(unsigned int fd, unsigned int cmd,
unsigned long arg)
{
mm_segment_t old_fs;
struct flock f;
long ret;
switch (cmd) {
case F_GETLK:
case F_SETLK:
case F_SETLKW:
ret = get_compat_flock(&f, compat_ptr(arg));
if (ret != 0)
break;
old_fs = get_fs();
set_fs(KERNEL_DS);
ret = sys_fcntl(fd, cmd, (unsigned long)&f);
set_fs(old_fs);
if (cmd == F_GETLK && ret == 0) {
/* GETLK was successful and we need to return the data...
* but it needs to fit in the compat structure.
* l_start shouldn't be too big, unless the original
* start + end is greater than COMPAT_OFF_T_MAX, in which
* case the app was asking for trouble, so we return
* -EOVERFLOW in that case.
* l_len could be too big, in which case we just truncate it,
* and only allow the app to see that part of the conflicting
* lock that might make sense to it anyway
*/
if (f.l_start > COMPAT_OFF_T_MAX)
ret = -EOVERFLOW;
if (f.l_len > COMPAT_OFF_T_MAX)
f.l_len = COMPAT_OFF_T_MAX;
if (ret == 0)
ret = put_compat_flock(&f, compat_ptr(arg));
}
break;
case F_GETLK64:
case F_SETLK64:
case F_SETLKW64:
ret = get_compat_flock64(&f, compat_ptr(arg));
if (ret != 0)
break;
old_fs = get_fs();
set_fs(KERNEL_DS);
ret = sys_fcntl(fd, (cmd == F_GETLK64) ? F_GETLK :
((cmd == F_SETLK64) ? F_SETLK : F_SETLKW),
(unsigned long)&f);
set_fs(old_fs);
if (cmd == F_GETLK64 && ret == 0) {
/* need to return lock information - see above for commentary */
if (f.l_start > COMPAT_LOFF_T_MAX)
ret = -EOVERFLOW;
if (f.l_len > COMPAT_LOFF_T_MAX)
f.l_len = COMPAT_LOFF_T_MAX;
if (ret == 0)
ret = put_compat_flock64(&f, compat_ptr(arg));
}
break;
default:
ret = sys_fcntl(fd, cmd, arg);
break;
}
return ret;
}
asmlinkage long compat_sys_fcntl(unsigned int fd, unsigned int cmd,
unsigned long arg)
{
if ((cmd == F_GETLK64) || (cmd == F_SETLK64) || (cmd == F_SETLKW64))
return -EINVAL;
return compat_sys_fcntl64(fd, cmd, arg);
}
asmlinkage long
compat_sys_io_setup(unsigned nr_reqs, u32 __user *ctx32p)
{
long ret;
aio_context_t ctx64;
mm_segment_t oldfs = get_fs();
if (unlikely(get_user(ctx64, ctx32p)))
return -EFAULT;
set_fs(KERNEL_DS);
/* The __user pointer cast is valid because of the set_fs() */
ret = sys_io_setup(nr_reqs, (aio_context_t __user *) &ctx64);
set_fs(oldfs);
/* truncating is ok because it's a user address */
if (!ret)
ret = put_user((u32) ctx64, ctx32p);
return ret;
}
asmlinkage long
compat_sys_io_getevents(aio_context_t ctx_id,
unsigned long min_nr,
unsigned long nr,
struct io_event __user *events,
struct compat_timespec __user *timeout)
{
long ret;
struct timespec t;
struct timespec __user *ut = NULL;
ret = -EFAULT;
if (unlikely(!access_ok(VERIFY_WRITE, events,
nr * sizeof(struct io_event))))
goto out;
if (timeout) {
if (get_compat_timespec(&t, timeout))
goto out;
ut = compat_alloc_user_space(sizeof(*ut));
if (copy_to_user(ut, &t, sizeof(t)) )
goto out;
}
ret = sys_io_getevents(ctx_id, min_nr, nr, events, ut);
out:
return ret;
}
/* A write operation does a read from user space and vice versa */
#define vrfy_dir(type) ((type) == READ ? VERIFY_WRITE : VERIFY_READ)
ssize_t compat_rw_copy_check_uvector(int type,
const struct compat_iovec __user *uvector, unsigned long nr_segs,
unsigned long fast_segs, struct iovec *fast_pointer,
struct iovec **ret_pointer, int check_access)
{
compat_ssize_t tot_len;
struct iovec *iov = *ret_pointer = fast_pointer;
ssize_t ret = 0;
int seg;
/*
* SuS says "The readv() function *may* fail if the iovcnt argument
* was less than or equal to 0, or greater than {IOV_MAX}. Linux has
* traditionally returned zero for zero segments, so...
*/
if (nr_segs == 0)
goto out;
ret = -EINVAL;
if (nr_segs > UIO_MAXIOV || nr_segs < 0)
goto out;
if (nr_segs > fast_segs) {
ret = -ENOMEM;
iov = kmalloc(nr_segs*sizeof(struct iovec), GFP_KERNEL);
if (iov == NULL)
goto out;
}
*ret_pointer = iov;
ret = -EFAULT;
if (!access_ok(VERIFY_READ, uvector, nr_segs*sizeof(*uvector)))
goto out;
/*
* Single unix specification:
* We should -EINVAL if an element length is not >= 0 and fitting an
* ssize_t.
*
* In Linux, the total length is limited to MAX_RW_COUNT, there is
* no overflow possibility.
*/
tot_len = 0;
ret = -EINVAL;
for (seg = 0; seg < nr_segs; seg++) {
compat_uptr_t buf;
compat_ssize_t len;
if (__get_user(len, &uvector->iov_len) ||
__get_user(buf, &uvector->iov_base)) {
ret = -EFAULT;
goto out;
}
if (len < 0) /* size_t not fitting in compat_ssize_t .. */
goto out;
if (check_access &&
!access_ok(vrfy_dir(type), compat_ptr(buf), len)) {
ret = -EFAULT;
goto out;
}
if (len > MAX_RW_COUNT - tot_len)
len = MAX_RW_COUNT - tot_len;
tot_len += len;
iov->iov_base = compat_ptr(buf);
iov->iov_len = (compat_size_t) len;
uvector++;
iov++;
}
ret = tot_len;
out:
return ret;
}
static inline long
copy_iocb(long nr, u32 __user *ptr32, struct iocb __user * __user *ptr64)
{
compat_uptr_t uptr;
int i;
for (i = 0; i < nr; ++i) {
if (get_user(uptr, ptr32 + i))
return -EFAULT;
if (put_user(compat_ptr(uptr), ptr64 + i))
return -EFAULT;
}
return 0;
}
#define MAX_AIO_SUBMITS (PAGE_SIZE/sizeof(struct iocb *))
asmlinkage long
compat_sys_io_submit(aio_context_t ctx_id, int nr, u32 __user *iocb)
{
struct iocb __user * __user *iocb64;
long ret;
if (unlikely(nr < 0))
return -EINVAL;
if (nr > MAX_AIO_SUBMITS)
nr = MAX_AIO_SUBMITS;
iocb64 = compat_alloc_user_space(nr * sizeof(*iocb64));
ret = copy_iocb(nr, iocb, iocb64);
if (!ret)
ret = do_io_submit(ctx_id, nr, iocb64, 1);
return ret;
}
struct compat_ncp_mount_data {
compat_int_t version;
compat_uint_t ncp_fd;
__compat_uid_t mounted_uid;
compat_pid_t wdog_pid;
unsigned char mounted_vol[NCP_VOLNAME_LEN + 1];
compat_uint_t time_out;
compat_uint_t retry_count;
compat_uint_t flags;
__compat_uid_t uid;
__compat_gid_t gid;
compat_mode_t file_mode;
compat_mode_t dir_mode;
};
struct compat_ncp_mount_data_v4 {
compat_int_t version;
compat_ulong_t flags;
compat_ulong_t mounted_uid;
compat_long_t wdog_pid;
compat_uint_t ncp_fd;
compat_uint_t time_out;
compat_uint_t retry_count;
compat_ulong_t uid;
compat_ulong_t gid;
compat_ulong_t file_mode;
compat_ulong_t dir_mode;
};
static void *do_ncp_super_data_conv(void *raw_data)
{
int version = *(unsigned int *)raw_data;
if (version == 3) {
struct compat_ncp_mount_data *c_n = raw_data;
struct ncp_mount_data *n = raw_data;
n->dir_mode = c_n->dir_mode;
n->file_mode = c_n->file_mode;
n->gid = c_n->gid;
n->uid = c_n->uid;
memmove (n->mounted_vol, c_n->mounted_vol, (sizeof (c_n->mounted_vol) + 3 * sizeof (unsigned int)));
n->wdog_pid = c_n->wdog_pid;
n->mounted_uid = c_n->mounted_uid;
} else if (version == 4) {
struct compat_ncp_mount_data_v4 *c_n = raw_data;
struct ncp_mount_data_v4 *n = raw_data;
n->dir_mode = c_n->dir_mode;
n->file_mode = c_n->file_mode;
n->gid = c_n->gid;
n->uid = c_n->uid;
n->retry_count = c_n->retry_count;
n->time_out = c_n->time_out;
n->ncp_fd = c_n->ncp_fd;
n->wdog_pid = c_n->wdog_pid;
n->mounted_uid = c_n->mounted_uid;
n->flags = c_n->flags;
} else if (version != 5) {
return NULL;
}
return raw_data;
}
struct compat_nfs_string {
compat_uint_t len;
compat_uptr_t data;
};
static inline void compat_nfs_string(struct nfs_string *dst,
struct compat_nfs_string *src)
{
dst->data = compat_ptr(src->data);
dst->len = src->len;
}
struct compat_nfs4_mount_data_v1 {
compat_int_t version;
compat_int_t flags;
compat_int_t rsize;
compat_int_t wsize;
compat_int_t timeo;
compat_int_t retrans;
compat_int_t acregmin;
compat_int_t acregmax;
compat_int_t acdirmin;
compat_int_t acdirmax;
struct compat_nfs_string client_addr;
struct compat_nfs_string mnt_path;
struct compat_nfs_string hostname;
compat_uint_t host_addrlen;
compat_uptr_t host_addr;
compat_int_t proto;
compat_int_t auth_flavourlen;
compat_uptr_t auth_flavours;
};
static int do_nfs4_super_data_conv(void *raw_data)
{
int version = *(compat_uint_t *) raw_data;
if (version == 1) {
struct compat_nfs4_mount_data_v1 *raw = raw_data;
struct nfs4_mount_data *real = raw_data;
/* copy the fields backwards */
real->auth_flavours = compat_ptr(raw->auth_flavours);
real->auth_flavourlen = raw->auth_flavourlen;
real->proto = raw->proto;
real->host_addr = compat_ptr(raw->host_addr);
real->host_addrlen = raw->host_addrlen;
compat_nfs_string(&real->hostname, &raw->hostname);
compat_nfs_string(&real->mnt_path, &raw->mnt_path);
compat_nfs_string(&real->client_addr, &raw->client_addr);
real->acdirmax = raw->acdirmax;
real->acdirmin = raw->acdirmin;
real->acregmax = raw->acregmax;
real->acregmin = raw->acregmin;
real->retrans = raw->retrans;
real->timeo = raw->timeo;
real->wsize = raw->wsize;
real->rsize = raw->rsize;
real->flags = raw->flags;
real->version = raw->version;
}
return 0;
}
#define NCPFS_NAME "ncpfs"
#define NFS4_NAME "nfs4"
asmlinkage long compat_sys_mount(const char __user * dev_name,
const char __user * dir_name,
const char __user * type, unsigned long flags,
const void __user * data)
{
char *kernel_type;
unsigned long data_page;
char *kernel_dev;
char *dir_page;
int retval;
retval = copy_mount_string(type, &kernel_type);
if (retval < 0)
goto out;
dir_page = getname(dir_name);
retval = PTR_ERR(dir_page);
if (IS_ERR(dir_page))
goto out1;
retval = copy_mount_string(dev_name, &kernel_dev);
if (retval < 0)
goto out2;
retval = copy_mount_options(data, &data_page);
if (retval < 0)
goto out3;
retval = -EINVAL;
if (kernel_type && data_page) {
if (!strcmp(kernel_type, NCPFS_NAME)) {
do_ncp_super_data_conv((void *)data_page);
} else if (!strcmp(kernel_type, NFS4_NAME)) {
if (do_nfs4_super_data_conv((void *) data_page))
goto out4;
}
}
retval = do_mount(kernel_dev, dir_page, kernel_type,
flags, (void*)data_page);
out4:
free_page(data_page);
out3:
kfree(kernel_dev);
out2:
putname(dir_page);
out1:
kfree(kernel_type);
out:
return retval;
}
struct compat_old_linux_dirent {
compat_ulong_t d_ino;
compat_ulong_t d_offset;
unsigned short d_namlen;
char d_name[1];
};
struct compat_readdir_callback {
struct compat_old_linux_dirent __user *dirent;
int result;
};
static int compat_fillonedir(void *__buf, const char *name, int namlen,
loff_t offset, u64 ino, unsigned int d_type)
{
struct compat_readdir_callback *buf = __buf;
struct compat_old_linux_dirent __user *dirent;
compat_ulong_t d_ino;
if (buf->result)
return -EINVAL;
d_ino = ino;
if (sizeof(d_ino) < sizeof(ino) && d_ino != ino) {
buf->result = -EOVERFLOW;
return -EOVERFLOW;
}
buf->result++;
dirent = buf->dirent;
if (!access_ok(VERIFY_WRITE, dirent,
(unsigned long)(dirent->d_name + namlen + 1) -
(unsigned long)dirent))
goto efault;
if ( __put_user(d_ino, &dirent->d_ino) ||
__put_user(offset, &dirent->d_offset) ||
__put_user(namlen, &dirent->d_namlen) ||
__copy_to_user(dirent->d_name, name, namlen) ||
__put_user(0, dirent->d_name + namlen))
goto efault;
return 0;
efault:
buf->result = -EFAULT;
return -EFAULT;
}
asmlinkage long compat_sys_old_readdir(unsigned int fd,
struct compat_old_linux_dirent __user *dirent, unsigned int count)
{
int error;
struct file *file;
struct compat_readdir_callback buf;
error = -EBADF;
file = fget(fd);
if (!file)
goto out;
buf.result = 0;
buf.dirent = dirent;
error = vfs_readdir(file, compat_fillonedir, &buf);
if (buf.result)
error = buf.result;
fput(file);
out:
return error;
}
struct compat_linux_dirent {
compat_ulong_t d_ino;
compat_ulong_t d_off;
unsigned short d_reclen;
char d_name[1];
};
struct compat_getdents_callback {
struct compat_linux_dirent __user *current_dir;
struct compat_linux_dirent __user *previous;
int count;
int error;
};
static int compat_filldir(void *__buf, const char *name, int namlen,
loff_t offset, u64 ino, unsigned int d_type)
{
struct compat_linux_dirent __user * dirent;
struct compat_getdents_callback *buf = __buf;
compat_ulong_t d_ino;
int reclen = ALIGN(offsetof(struct compat_linux_dirent, d_name) +
namlen + 2, sizeof(compat_long_t));
buf->error = -EINVAL; /* only used if we fail.. */
if (reclen > buf->count)
return -EINVAL;
d_ino = ino;
if (sizeof(d_ino) < sizeof(ino) && d_ino != ino) {
buf->error = -EOVERFLOW;
return -EOVERFLOW;
}
dirent = buf->previous;
if (dirent) {
if (__put_user(offset, &dirent->d_off))
goto efault;
}
dirent = buf->current_dir;
if (__put_user(d_ino, &dirent->d_ino))
goto efault;
if (__put_user(reclen, &dirent->d_reclen))
goto efault;
if (copy_to_user(dirent->d_name, name, namlen))
goto efault;
if (__put_user(0, dirent->d_name + namlen))
goto efault;
if (__put_user(d_type, (char __user *) dirent + reclen - 1))
goto efault;
buf->previous = dirent;
dirent = (void __user *)dirent + reclen;
buf->current_dir = dirent;
buf->count -= reclen;
return 0;
efault:
buf->error = -EFAULT;
return -EFAULT;
}
asmlinkage long compat_sys_getdents(unsigned int fd,
struct compat_linux_dirent __user *dirent, unsigned int count)
{
struct file * file;
struct compat_linux_dirent __user * lastdirent;
struct compat_getdents_callback buf;
int error;
error = -EFAULT;
if (!access_ok(VERIFY_WRITE, dirent, count))
goto out;
error = -EBADF;
file = fget(fd);
if (!file)
goto out;
buf.current_dir = dirent;
buf.previous = NULL;
buf.count = count;
buf.error = 0;
error = vfs_readdir(file, compat_filldir, &buf);
if (error >= 0)
error = buf.error;
lastdirent = buf.previous;
if (lastdirent) {
if (put_user(file->f_pos, &lastdirent->d_off))
error = -EFAULT;
else
error = count - buf.count;
}
fput(file);
out:
return error;
}
#ifndef __ARCH_OMIT_COMPAT_SYS_GETDENTS64
struct compat_getdents_callback64 {
struct linux_dirent64 __user *current_dir;
struct linux_dirent64 __user *previous;
int count;
int error;
};
static int compat_filldir64(void * __buf, const char * name, int namlen, loff_t offset,
u64 ino, unsigned int d_type)
{
struct linux_dirent64 __user *dirent;
struct compat_getdents_callback64 *buf = __buf;
int reclen = ALIGN(offsetof(struct linux_dirent64, d_name) + namlen + 1,
sizeof(u64));
u64 off;
buf->error = -EINVAL; /* only used if we fail.. */
if (reclen > buf->count)
return -EINVAL;
dirent = buf->previous;
if (dirent) {
if (__put_user_unaligned(offset, &dirent->d_off))
goto efault;
}
dirent = buf->current_dir;
if (__put_user_unaligned(ino, &dirent->d_ino))
goto efault;
off = 0;
if (__put_user_unaligned(off, &dirent->d_off))
goto efault;
if (__put_user(reclen, &dirent->d_reclen))
goto efault;
if (__put_user(d_type, &dirent->d_type))
goto efault;
if (copy_to_user(dirent->d_name, name, namlen))
goto efault;
if (__put_user(0, dirent->d_name + namlen))
goto efault;
buf->previous = dirent;
dirent = (void __user *)dirent + reclen;
buf->current_dir = dirent;
buf->count -= reclen;
return 0;
efault:
buf->error = -EFAULT;
return -EFAULT;
}
asmlinkage long compat_sys_getdents64(unsigned int fd,
struct linux_dirent64 __user * dirent, unsigned int count)
{
struct file * file;
struct linux_dirent64 __user * lastdirent;
struct compat_getdents_callback64 buf;
int error;
error = -EFAULT;
if (!access_ok(VERIFY_WRITE, dirent, count))
goto out;
error = -EBADF;
file = fget(fd);
if (!file)
goto out;
buf.current_dir = dirent;
buf.previous = NULL;
buf.count = count;
buf.error = 0;
error = vfs_readdir(file, compat_filldir64, &buf);
if (error >= 0)
error = buf.error;
lastdirent = buf.previous;
if (lastdirent) {
typeof(lastdirent->d_off) d_off = file->f_pos;
if (__put_user_unaligned(d_off, &lastdirent->d_off))
error = -EFAULT;
else
error = count - buf.count;
}
fput(file);
out:
return error;
}
#endif /* ! __ARCH_OMIT_COMPAT_SYS_GETDENTS64 */
static ssize_t compat_do_readv_writev(int type, struct file *file,
const struct compat_iovec __user *uvector,
unsigned long nr_segs, loff_t *pos)
{
compat_ssize_t tot_len;
struct iovec iovstack[UIO_FASTIOV];
struct iovec *iov = iovstack;
ssize_t ret;
io_fn_t fn;
iov_fn_t fnv;
ret = -EINVAL;
if (!file->f_op)
goto out;
ret = compat_rw_copy_check_uvector(type, uvector, nr_segs,
UIO_FASTIOV, iovstack, &iov, 1);
if (ret <= 0)
goto out;
tot_len = ret;
ret = rw_verify_area(type, file, pos, tot_len);
if (ret < 0)
goto out;
fnv = NULL;
if (type == READ) {
fn = file->f_op->read;
fnv = file->f_op->aio_read;
} else {
fn = (io_fn_t)file->f_op->write;
fnv = file->f_op->aio_write;
}
if (fnv)
ret = do_sync_readv_writev(file, iov, nr_segs, tot_len,
pos, fnv);
else
ret = do_loop_readv_writev(file, iov, nr_segs, pos, fn);
out:
if (iov != iovstack)
kfree(iov);
if ((ret + (type == READ)) > 0) {
if (type == READ)
fsnotify_access(file);
else
fsnotify_modify(file);
}
return ret;
}
static size_t compat_readv(struct file *file,
const struct compat_iovec __user *vec,
unsigned long vlen, loff_t *pos)
{
ssize_t ret = -EBADF;
if (!(file->f_mode & FMODE_READ))
goto out;
ret = -EINVAL;
if (!file->f_op || (!file->f_op->aio_read && !file->f_op->read))
goto out;
ret = compat_do_readv_writev(READ, file, vec, vlen, pos);
out:
if (ret > 0)
add_rchar(current, ret);
inc_syscr(current);
return ret;
}
asmlinkage ssize_t
compat_sys_readv(unsigned long fd, const struct compat_iovec __user *vec,
unsigned long vlen)
{
struct file *file;
int fput_needed;
ssize_t ret;
loff_t pos;
file = fget_light(fd, &fput_needed);
if (!file)
return -EBADF;
pos = file->f_pos;
ret = compat_readv(file, vec, vlen, &pos);
file->f_pos = pos;
fput_light(file, fput_needed);
return ret;
}
asmlinkage ssize_t
compat_sys_preadv64(unsigned long fd, const struct compat_iovec __user *vec,
unsigned long vlen, loff_t pos)
{
struct file *file;
int fput_needed;
ssize_t ret;
if (pos < 0)
return -EINVAL;
file = fget_light(fd, &fput_needed);
if (!file)
return -EBADF;
ret = -ESPIPE;
if (file->f_mode & FMODE_PREAD)
ret = compat_readv(file, vec, vlen, &pos);
fput_light(file, fput_needed);
return ret;
}
asmlinkage ssize_t
compat_sys_preadv(unsigned long fd, const struct compat_iovec __user *vec,
unsigned long vlen, u32 pos_low, u32 pos_high)
{
loff_t pos = ((loff_t)pos_high << 32) | pos_low;
return compat_sys_preadv64(fd, vec, vlen, pos);
}
static size_t compat_writev(struct file *file,
const struct compat_iovec __user *vec,
unsigned long vlen, loff_t *pos)
{
ssize_t ret = -EBADF;
if (!(file->f_mode & FMODE_WRITE))
goto out;
ret = -EINVAL;
if (!file->f_op || (!file->f_op->aio_write && !file->f_op->write))
goto out;
ret = compat_do_readv_writev(WRITE, file, vec, vlen, pos);
out:
if (ret > 0)
add_wchar(current, ret);
inc_syscw(current);
return ret;
}
asmlinkage ssize_t
compat_sys_writev(unsigned long fd, const struct compat_iovec __user *vec,
unsigned long vlen)
{
struct file *file;
int fput_needed;
ssize_t ret;
loff_t pos;
file = fget_light(fd, &fput_needed);
if (!file)
return -EBADF;
pos = file->f_pos;
ret = compat_writev(file, vec, vlen, &pos);
file->f_pos = pos;
fput_light(file, fput_needed);
return ret;
}
asmlinkage ssize_t
compat_sys_pwritev64(unsigned long fd, const struct compat_iovec __user *vec,
unsigned long vlen, loff_t pos)
{
struct file *file;
int fput_needed;
ssize_t ret;
if (pos < 0)
return -EINVAL;
file = fget_light(fd, &fput_needed);
if (!file)
return -EBADF;
ret = -ESPIPE;
if (file->f_mode & FMODE_PWRITE)
ret = compat_writev(file, vec, vlen, &pos);
fput_light(file, fput_needed);
return ret;
}
asmlinkage ssize_t
compat_sys_pwritev(unsigned long fd, const struct compat_iovec __user *vec,
unsigned long vlen, u32 pos_low, u32 pos_high)
{
loff_t pos = ((loff_t)pos_high << 32) | pos_low;
return compat_sys_pwritev64(fd, vec, vlen, pos);
}
asmlinkage long
compat_sys_vmsplice(int fd, const struct compat_iovec __user *iov32,
unsigned int nr_segs, unsigned int flags)
{
unsigned i;
struct iovec __user *iov;
if (nr_segs > UIO_MAXIOV)
return -EINVAL;
iov = compat_alloc_user_space(nr_segs * sizeof(struct iovec));
for (i = 0; i < nr_segs; i++) {
struct compat_iovec v;
if (get_user(v.iov_base, &iov32[i].iov_base) ||
get_user(v.iov_len, &iov32[i].iov_len) ||
put_user(compat_ptr(v.iov_base), &iov[i].iov_base) ||
put_user(v.iov_len, &iov[i].iov_len))
return -EFAULT;
}
return sys_vmsplice(fd, iov, nr_segs, flags);
}
/*
* Exactly like fs/open.c:sys_open(), except that it doesn't set the
* O_LARGEFILE flag.
*/
asmlinkage long
compat_sys_open(const char __user *filename, int flags, umode_t mode)
{
return do_sys_open(AT_FDCWD, filename, flags, mode);
}
/*
* Exactly like fs/open.c:sys_openat(), except that it doesn't set the
* O_LARGEFILE flag.
*/
asmlinkage long
compat_sys_openat(unsigned int dfd, const char __user *filename, int flags, umode_t mode)
{
return do_sys_open(dfd, filename, flags, mode);
}
#define __COMPAT_NFDBITS (8 * sizeof(compat_ulong_t))
static int poll_select_copy_remaining(struct timespec *end_time, void __user *p,
int timeval, int ret)
{
struct timespec ts;
if (!p)
return ret;
if (current->personality & STICKY_TIMEOUTS)
goto sticky;
/* No update for zero timeout */
if (!end_time->tv_sec && !end_time->tv_nsec)
return ret;
ktime_get_ts(&ts);
ts = timespec_sub(*end_time, ts);
if (ts.tv_sec < 0)
ts.tv_sec = ts.tv_nsec = 0;
if (timeval) {
struct compat_timeval rtv;
rtv.tv_sec = ts.tv_sec;
rtv.tv_usec = ts.tv_nsec / NSEC_PER_USEC;
if (!copy_to_user(p, &rtv, sizeof(rtv)))
return ret;
} else {
struct compat_timespec rts;
rts.tv_sec = ts.tv_sec;
rts.tv_nsec = ts.tv_nsec;
if (!copy_to_user(p, &rts, sizeof(rts)))
return ret;
}
/*
* If an application puts its timeval in read-only memory, we
* don't want the Linux-specific update to the timeval to
* cause a fault after the select has completed
* successfully. However, because we're not updating the
* timeval, we can't restart the system call.
*/
sticky:
if (ret == -ERESTARTNOHAND)
ret = -EINTR;
return ret;
}
/*
* Ooo, nasty. We need here to frob 32-bit unsigned longs to
* 64-bit unsigned longs.
*/
static
int compat_get_fd_set(unsigned long nr, compat_ulong_t __user *ufdset,
unsigned long *fdset)
{
nr = DIV_ROUND_UP(nr, __COMPAT_NFDBITS);
if (ufdset) {
unsigned long odd;
if (!access_ok(VERIFY_WRITE, ufdset, nr*sizeof(compat_ulong_t)))
return -EFAULT;
odd = nr & 1UL;
nr &= ~1UL;
while (nr) {
unsigned long h, l;
if (__get_user(l, ufdset) || __get_user(h, ufdset+1))
return -EFAULT;
ufdset += 2;
*fdset++ = h << 32 | l;
nr -= 2;
}
if (odd && __get_user(*fdset, ufdset))
return -EFAULT;
} else {
/* Tricky, must clear full unsigned long in the
* kernel fdset at the end, this makes sure that
* actually happens.
*/
memset(fdset, 0, ((nr + 1) & ~1)*sizeof(compat_ulong_t));
}
return 0;
}
static
int compat_set_fd_set(unsigned long nr, compat_ulong_t __user *ufdset,
unsigned long *fdset)
{
unsigned long odd;
nr = DIV_ROUND_UP(nr, __COMPAT_NFDBITS);
if (!ufdset)
return 0;
odd = nr & 1UL;
nr &= ~1UL;
while (nr) {
unsigned long h, l;
l = *fdset++;
h = l >> 32;
if (__put_user(l, ufdset) || __put_user(h, ufdset+1))
return -EFAULT;
ufdset += 2;
nr -= 2;
}
if (odd && __put_user(*fdset, ufdset))
return -EFAULT;
return 0;
}
/*
* This is a virtual copy of sys_select from fs/select.c and probably
* should be compared to it from time to time
*/
/*
* We can actually return ERESTARTSYS instead of EINTR, but I'd
* like to be certain this leads to no problems. So I return
* EINTR just for safety.
*
* Update: ERESTARTSYS breaks at least the xview clock binary, so
* I'm trying ERESTARTNOHAND which restart only when you want to.
*/
int compat_core_sys_select(int n, compat_ulong_t __user *inp,
compat_ulong_t __user *outp, compat_ulong_t __user *exp,
struct timespec *end_time)
{
fd_set_bits fds;
void *bits;
int size, max_fds, ret = -EINVAL;
struct fdtable *fdt;
long stack_fds[SELECT_STACK_ALLOC/sizeof(long)];
if (n < 0)
goto out_nofds;
/* max_fds can increase, so grab it once to avoid race */
rcu_read_lock();
fdt = files_fdtable(current->files);
max_fds = fdt->max_fds;
rcu_read_unlock();
if (n > max_fds)
n = max_fds;
/*
* We need 6 bitmaps (in/out/ex for both incoming and outgoing),
* since we used fdset we need to allocate memory in units of
* long-words.
*/
size = FDS_BYTES(n);
bits = stack_fds;
if (size > sizeof(stack_fds) / 6) {
bits = kmalloc(6 * size, GFP_KERNEL);
ret = -ENOMEM;
if (!bits)
goto out_nofds;
}
fds.in = (unsigned long *) bits;
fds.out = (unsigned long *) (bits + size);
fds.ex = (unsigned long *) (bits + 2*size);
fds.res_in = (unsigned long *) (bits + 3*size);
fds.res_out = (unsigned long *) (bits + 4*size);
fds.res_ex = (unsigned long *) (bits + 5*size);
if ((ret = compat_get_fd_set(n, inp, fds.in)) ||
(ret = compat_get_fd_set(n, outp, fds.out)) ||
(ret = compat_get_fd_set(n, exp, fds.ex)))
goto out;
zero_fd_set(n, fds.res_in);
zero_fd_set(n, fds.res_out);
zero_fd_set(n, fds.res_ex);
ret = do_select(n, &fds, end_time);
if (ret < 0)
goto out;
if (!ret) {
ret = -ERESTARTNOHAND;
if (signal_pending(current))
goto out;
ret = 0;
}
if (compat_set_fd_set(n, inp, fds.res_in) ||
compat_set_fd_set(n, outp, fds.res_out) ||
compat_set_fd_set(n, exp, fds.res_ex))
ret = -EFAULT;
out:
if (bits != stack_fds)
kfree(bits);
out_nofds:
return ret;
}
asmlinkage long compat_sys_select(int n, compat_ulong_t __user *inp,
compat_ulong_t __user *outp, compat_ulong_t __user *exp,
struct compat_timeval __user *tvp)
{
struct timespec end_time, *to = NULL;
struct compat_timeval tv;
int ret;
if (tvp) {
if (copy_from_user(&tv, tvp, sizeof(tv)))
return -EFAULT;
to = &end_time;
if (poll_select_set_timeout(to,
tv.tv_sec + (tv.tv_usec / USEC_PER_SEC),
(tv.tv_usec % USEC_PER_SEC) * NSEC_PER_USEC))
return -EINVAL;
}
ret = compat_core_sys_select(n, inp, outp, exp, to);
ret = poll_select_copy_remaining(&end_time, tvp, 1, ret);
return ret;
}
struct compat_sel_arg_struct {
compat_ulong_t n;
compat_uptr_t inp;
compat_uptr_t outp;
compat_uptr_t exp;
compat_uptr_t tvp;
};
asmlinkage long compat_sys_old_select(struct compat_sel_arg_struct __user *arg)
{
struct compat_sel_arg_struct a;
if (copy_from_user(&a, arg, sizeof(a)))
return -EFAULT;
return compat_sys_select(a.n, compat_ptr(a.inp), compat_ptr(a.outp),
compat_ptr(a.exp), compat_ptr(a.tvp));
}
#ifdef HAVE_SET_RESTORE_SIGMASK
static long do_compat_pselect(int n, compat_ulong_t __user *inp,
compat_ulong_t __user *outp, compat_ulong_t __user *exp,
struct compat_timespec __user *tsp, compat_sigset_t __user *sigmask,
compat_size_t sigsetsize)
{
compat_sigset_t ss32;
sigset_t ksigmask, sigsaved;
struct compat_timespec ts;
struct timespec end_time, *to = NULL;
int ret;
if (tsp) {
if (copy_from_user(&ts, tsp, sizeof(ts)))
return -EFAULT;
to = &end_time;
if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec))
return -EINVAL;
}
if (sigmask) {
if (sigsetsize != sizeof(compat_sigset_t))
return -EINVAL;
if (copy_from_user(&ss32, sigmask, sizeof(ss32)))
return -EFAULT;
sigset_from_compat(&ksigmask, &ss32);
sigdelsetmask(&ksigmask, sigmask(SIGKILL)|sigmask(SIGSTOP));
sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
}
ret = compat_core_sys_select(n, inp, outp, exp, to);
ret = poll_select_copy_remaining(&end_time, tsp, 0, ret);
if (ret == -ERESTARTNOHAND) {
/*
* Don't restore the signal mask yet. Let do_signal() deliver
* the signal on the way back to userspace, before the signal
* mask is restored.
*/
if (sigmask) {
memcpy(¤t->saved_sigmask, &sigsaved,
sizeof(sigsaved));
set_restore_sigmask();
}
} else if (sigmask)
sigprocmask(SIG_SETMASK, &sigsaved, NULL);
return ret;
}
asmlinkage long compat_sys_pselect6(int n, compat_ulong_t __user *inp,
compat_ulong_t __user *outp, compat_ulong_t __user *exp,
struct compat_timespec __user *tsp, void __user *sig)
{
compat_size_t sigsetsize = 0;
compat_uptr_t up = 0;
if (sig) {
if (!access_ok(VERIFY_READ, sig,
sizeof(compat_uptr_t)+sizeof(compat_size_t)) ||
__get_user(up, (compat_uptr_t __user *)sig) ||
__get_user(sigsetsize,
(compat_size_t __user *)(sig+sizeof(up))))
return -EFAULT;
}
return do_compat_pselect(n, inp, outp, exp, tsp, compat_ptr(up),
sigsetsize);
}
asmlinkage long compat_sys_ppoll(struct pollfd __user *ufds,
unsigned int nfds, struct compat_timespec __user *tsp,
const compat_sigset_t __user *sigmask, compat_size_t sigsetsize)
{
compat_sigset_t ss32;
sigset_t ksigmask, sigsaved;
struct compat_timespec ts;
struct timespec end_time, *to = NULL;
int ret;
if (tsp) {
if (copy_from_user(&ts, tsp, sizeof(ts)))
return -EFAULT;
to = &end_time;
if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec))
return -EINVAL;
}
if (sigmask) {
if (sigsetsize != sizeof(compat_sigset_t))
return -EINVAL;
if (copy_from_user(&ss32, sigmask, sizeof(ss32)))
return -EFAULT;
sigset_from_compat(&ksigmask, &ss32);
sigdelsetmask(&ksigmask, sigmask(SIGKILL)|sigmask(SIGSTOP));
sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
}
ret = do_sys_poll(ufds, nfds, to);
/* We can restart this syscall, usually */
if (ret == -EINTR) {
/*
* Don't restore the signal mask yet. Let do_signal() deliver
* the signal on the way back to userspace, before the signal
* mask is restored.
*/
if (sigmask) {
memcpy(¤t->saved_sigmask, &sigsaved,
sizeof(sigsaved));
set_restore_sigmask();
}
ret = -ERESTARTNOHAND;
} else if (sigmask)
sigprocmask(SIG_SETMASK, &sigsaved, NULL);
ret = poll_select_copy_remaining(&end_time, tsp, 0, ret);
return ret;
}
#endif /* HAVE_SET_RESTORE_SIGMASK */
#ifdef CONFIG_EPOLL
#ifdef HAVE_SET_RESTORE_SIGMASK
asmlinkage long compat_sys_epoll_pwait(int epfd,
struct compat_epoll_event __user *events,
int maxevents, int timeout,
const compat_sigset_t __user *sigmask,
compat_size_t sigsetsize)
{
long err;
compat_sigset_t csigmask;
sigset_t ksigmask, sigsaved;
/*
* If the caller wants a certain signal mask to be set during the wait,
* we apply it here.
*/
if (sigmask) {
if (sigsetsize != sizeof(compat_sigset_t))
return -EINVAL;
if (copy_from_user(&csigmask, sigmask, sizeof(csigmask)))
return -EFAULT;
sigset_from_compat(&ksigmask, &csigmask);
sigdelsetmask(&ksigmask, sigmask(SIGKILL) | sigmask(SIGSTOP));
sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
}
err = sys_epoll_wait(epfd, events, maxevents, timeout);
/*
* If we changed the signal mask, we need to restore the original one.
* In case we've got a signal while waiting, we do not restore the
* signal mask yet, and we allow do_signal() to deliver the signal on
* the way back to userspace, before the signal mask is restored.
*/
if (sigmask) {
if (err == -EINTR) {
memcpy(¤t->saved_sigmask, &sigsaved,
sizeof(sigsaved));
set_restore_sigmask();
} else
sigprocmask(SIG_SETMASK, &sigsaved, NULL);
}
return err;
}
#endif /* HAVE_SET_RESTORE_SIGMASK */
#endif /* CONFIG_EPOLL */
#ifdef CONFIG_SIGNALFD
asmlinkage long compat_sys_signalfd4(int ufd,
const compat_sigset_t __user *sigmask,
compat_size_t sigsetsize, int flags)
{
compat_sigset_t ss32;
sigset_t tmp;
sigset_t __user *ksigmask;
if (sigsetsize != sizeof(compat_sigset_t))
return -EINVAL;
if (copy_from_user(&ss32, sigmask, sizeof(ss32)))
return -EFAULT;
sigset_from_compat(&tmp, &ss32);
ksigmask = compat_alloc_user_space(sizeof(sigset_t));
if (copy_to_user(ksigmask, &tmp, sizeof(sigset_t)))
return -EFAULT;
return sys_signalfd4(ufd, ksigmask, sizeof(sigset_t), flags);
}
asmlinkage long compat_sys_signalfd(int ufd,
const compat_sigset_t __user *sigmask,
compat_size_t sigsetsize)
{
return compat_sys_signalfd4(ufd, sigmask, sigsetsize, 0);
}
#endif /* CONFIG_SIGNALFD */
#ifdef CONFIG_TIMERFD
asmlinkage long compat_sys_timerfd_settime(int ufd, int flags,
const struct compat_itimerspec __user *utmr,
struct compat_itimerspec __user *otmr)
{
int error;
struct itimerspec t;
struct itimerspec __user *ut;
if (get_compat_itimerspec(&t, utmr))
return -EFAULT;
ut = compat_alloc_user_space(2 * sizeof(struct itimerspec));
if (copy_to_user(&ut[0], &t, sizeof(t)))
return -EFAULT;
error = sys_timerfd_settime(ufd, flags, &ut[0], &ut[1]);
if (!error && otmr)
error = (copy_from_user(&t, &ut[1], sizeof(struct itimerspec)) ||
put_compat_itimerspec(otmr, &t)) ? -EFAULT: 0;
return error;
}
asmlinkage long compat_sys_timerfd_gettime(int ufd,
struct compat_itimerspec __user *otmr)
{
int error;
struct itimerspec t;
struct itimerspec __user *ut;
ut = compat_alloc_user_space(sizeof(struct itimerspec));
error = sys_timerfd_gettime(ufd, ut);
if (!error)
error = (copy_from_user(&t, ut, sizeof(struct itimerspec)) ||
put_compat_itimerspec(otmr, &t)) ? -EFAULT: 0;
return error;
}
#endif /* CONFIG_TIMERFD */
#ifdef CONFIG_FHANDLE
/*
* Exactly like fs/open.c:sys_open_by_handle_at(), except that it
* doesn't set the O_LARGEFILE flag.
*/
asmlinkage long
compat_sys_open_by_handle_at(int mountdirfd,
struct file_handle __user *handle, int flags)
{
return do_handle_open(mountdirfd, handle, flags);
}
#endif
| gpl-2.0 |
azureplus/linux | drivers/char/mwave/tp3780i.c | 2152 | 18123 | /*
*
* tp3780i.c -- board driver for 3780i on ThinkPads
*
*
* Written By: Mike Sullivan IBM Corporation
*
* Copyright (C) 1999 IBM Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* NO WARRANTY
* THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
* LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
* solely responsible for determining the appropriateness of using and
* distributing the Program and assumes all risks associated with its
* exercise of rights under this Agreement, including but not limited to
* the risks and costs of program errors, damage to or loss of data,
* programs or equipment, and unavailability or interruption of operations.
*
* DISCLAIMER OF LIABILITY
* NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), 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 OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
* HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
*
* 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
*
*
* 10/23/2000 - Alpha Release
* First release to the public
*/
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/ptrace.h>
#include <linux/ioport.h>
#include <asm/io.h>
#include "smapi.h"
#include "mwavedd.h"
#include "tp3780i.h"
#include "3780i.h"
#include "mwavepub.h"
static unsigned short s_ausThinkpadIrqToField[16] =
{ 0xFFFF, 0xFFFF, 0xFFFF, 0x0001, 0x0002, 0x0003, 0xFFFF, 0x0004,
0xFFFF, 0xFFFF, 0x0005, 0x0006, 0xFFFF, 0xFFFF, 0xFFFF, 0x0007 };
static unsigned short s_ausThinkpadDmaToField[8] =
{ 0x0001, 0x0002, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0x0003, 0x0004 };
static unsigned short s_numIrqs = 16, s_numDmas = 8;
static void EnableSRAM(THINKPAD_BD_DATA * pBDData)
{
DSP_3780I_CONFIG_SETTINGS *pSettings = &pBDData->rDspSettings;
unsigned short usDspBaseIO = pSettings->usDspBaseIO;
DSP_GPIO_OUTPUT_DATA_15_8 rGpioOutputData;
DSP_GPIO_DRIVER_ENABLE_15_8 rGpioDriverEnable;
DSP_GPIO_MODE_15_8 rGpioMode;
PRINTK_1(TRACE_TP3780I, "tp3780i::EnableSRAM, entry\n");
MKWORD(rGpioMode) = ReadMsaCfg(DSP_GpioModeControl_15_8);
rGpioMode.GpioMode10 = 0;
WriteMsaCfg(DSP_GpioModeControl_15_8, MKWORD(rGpioMode));
MKWORD(rGpioDriverEnable) = 0;
rGpioDriverEnable.Enable10 = TRUE;
rGpioDriverEnable.Mask10 = TRUE;
WriteMsaCfg(DSP_GpioDriverEnable_15_8, MKWORD(rGpioDriverEnable));
MKWORD(rGpioOutputData) = 0;
rGpioOutputData.Latch10 = 0;
rGpioOutputData.Mask10 = TRUE;
WriteMsaCfg(DSP_GpioOutputData_15_8, MKWORD(rGpioOutputData));
PRINTK_1(TRACE_TP3780I, "tp3780i::EnableSRAM exit\n");
}
static irqreturn_t UartInterrupt(int irq, void *dev_id)
{
PRINTK_3(TRACE_TP3780I,
"tp3780i::UartInterrupt entry irq %x dev_id %p\n", irq, dev_id);
return IRQ_HANDLED;
}
static irqreturn_t DspInterrupt(int irq, void *dev_id)
{
pMWAVE_DEVICE_DATA pDrvData = &mwave_s_mdd;
DSP_3780I_CONFIG_SETTINGS *pSettings = &pDrvData->rBDData.rDspSettings;
unsigned short usDspBaseIO = pSettings->usDspBaseIO;
unsigned short usIPCSource = 0, usIsolationMask, usPCNum;
PRINTK_3(TRACE_TP3780I,
"tp3780i::DspInterrupt entry irq %x dev_id %p\n", irq, dev_id);
if (dsp3780I_GetIPCSource(usDspBaseIO, &usIPCSource) == 0) {
PRINTK_2(TRACE_TP3780I,
"tp3780i::DspInterrupt, return from dsp3780i_GetIPCSource, usIPCSource %x\n",
usIPCSource);
usIsolationMask = 1;
for (usPCNum = 1; usPCNum <= 16; usPCNum++) {
if (usIPCSource & usIsolationMask) {
usIPCSource &= ~usIsolationMask;
PRINTK_3(TRACE_TP3780I,
"tp3780i::DspInterrupt usPCNum %x usIPCSource %x\n",
usPCNum, usIPCSource);
if (pDrvData->IPCs[usPCNum - 1].usIntCount == 0) {
pDrvData->IPCs[usPCNum - 1].usIntCount = 1;
}
PRINTK_2(TRACE_TP3780I,
"tp3780i::DspInterrupt usIntCount %x\n",
pDrvData->IPCs[usPCNum - 1].usIntCount);
if (pDrvData->IPCs[usPCNum - 1].bIsEnabled == TRUE) {
PRINTK_2(TRACE_TP3780I,
"tp3780i::DspInterrupt, waking up usPCNum %x\n",
usPCNum - 1);
wake_up_interruptible(&pDrvData->IPCs[usPCNum - 1].ipc_wait_queue);
} else {
PRINTK_2(TRACE_TP3780I,
"tp3780i::DspInterrupt, no one waiting for IPC %x\n",
usPCNum - 1);
}
}
if (usIPCSource == 0)
break;
/* try next IPC */
usIsolationMask = usIsolationMask << 1;
}
} else {
PRINTK_1(TRACE_TP3780I,
"tp3780i::DspInterrupt, return false from dsp3780i_GetIPCSource\n");
}
PRINTK_1(TRACE_TP3780I, "tp3780i::DspInterrupt exit\n");
return IRQ_HANDLED;
}
int tp3780I_InitializeBoardData(THINKPAD_BD_DATA * pBDData)
{
int retval = 0;
DSP_3780I_CONFIG_SETTINGS *pSettings = &pBDData->rDspSettings;
PRINTK_2(TRACE_TP3780I, "tp3780i::tp3780I_InitializeBoardData entry pBDData %p\n", pBDData);
pBDData->bDSPEnabled = FALSE;
pSettings->bInterruptClaimed = FALSE;
retval = smapi_init();
if (retval) {
PRINTK_ERROR(KERN_ERR_MWAVE "tp3780i::tp3780I_InitializeBoardData: Error: SMAPI is not available on this machine\n");
} else {
if (mwave_3780i_irq || mwave_3780i_io || mwave_uart_irq || mwave_uart_io) {
retval = smapi_set_DSP_cfg();
}
}
PRINTK_2(TRACE_TP3780I, "tp3780i::tp3780I_InitializeBoardData exit retval %x\n", retval);
return retval;
}
int tp3780I_Cleanup(THINKPAD_BD_DATA * pBDData)
{
int retval = 0;
PRINTK_2(TRACE_TP3780I,
"tp3780i::tp3780I_Cleanup entry and exit pBDData %p\n", pBDData);
return retval;
}
int tp3780I_CalcResources(THINKPAD_BD_DATA * pBDData)
{
SMAPI_DSP_SETTINGS rSmapiInfo;
DSP_3780I_CONFIG_SETTINGS *pSettings = &pBDData->rDspSettings;
PRINTK_2(TRACE_TP3780I,
"tp3780i::tp3780I_CalcResources entry pBDData %p\n", pBDData);
if (smapi_query_DSP_cfg(&rSmapiInfo)) {
PRINTK_ERROR(KERN_ERR_MWAVE "tp3780i::tp3780I_CalcResources: Error: Could not query DSP config. Aborting.\n");
return -EIO;
}
/* Sanity check */
if (
( rSmapiInfo.usDspIRQ == 0 )
|| ( rSmapiInfo.usDspBaseIO == 0 )
|| ( rSmapiInfo.usUartIRQ == 0 )
|| ( rSmapiInfo.usUartBaseIO == 0 )
) {
PRINTK_ERROR(KERN_ERR_MWAVE "tp3780i::tp3780I_CalcResources: Error: Illegal resource setting. Aborting.\n");
return -EIO;
}
pSettings->bDSPEnabled = (rSmapiInfo.bDSPEnabled && rSmapiInfo.bDSPPresent);
pSettings->bModemEnabled = rSmapiInfo.bModemEnabled;
pSettings->usDspIrq = rSmapiInfo.usDspIRQ;
pSettings->usDspDma = rSmapiInfo.usDspDMA;
pSettings->usDspBaseIO = rSmapiInfo.usDspBaseIO;
pSettings->usUartIrq = rSmapiInfo.usUartIRQ;
pSettings->usUartBaseIO = rSmapiInfo.usUartBaseIO;
pSettings->uDStoreSize = TP_ABILITIES_DATA_SIZE;
pSettings->uIStoreSize = TP_ABILITIES_INST_SIZE;
pSettings->uIps = TP_ABILITIES_INTS_PER_SEC;
if (pSettings->bDSPEnabled && pSettings->bModemEnabled && pSettings->usDspIrq == pSettings->usUartIrq) {
pBDData->bShareDspIrq = pBDData->bShareUartIrq = 1;
} else {
pBDData->bShareDspIrq = pBDData->bShareUartIrq = 0;
}
PRINTK_1(TRACE_TP3780I, "tp3780i::tp3780I_CalcResources exit\n");
return 0;
}
int tp3780I_ClaimResources(THINKPAD_BD_DATA * pBDData)
{
int retval = 0;
DSP_3780I_CONFIG_SETTINGS *pSettings = &pBDData->rDspSettings;
struct resource *pres;
PRINTK_2(TRACE_TP3780I,
"tp3780i::tp3780I_ClaimResources entry pBDData %p\n", pBDData);
pres = request_region(pSettings->usDspBaseIO, 16, "mwave_3780i");
if ( pres == NULL ) retval = -EIO;
if (retval) {
PRINTK_ERROR(KERN_ERR_MWAVE "tp3780i::tp3780I_ClaimResources: Error: Could not claim I/O region starting at %x\n", pSettings->usDspBaseIO);
retval = -EIO;
}
PRINTK_2(TRACE_TP3780I, "tp3780i::tp3780I_ClaimResources exit retval %x\n", retval);
return retval;
}
int tp3780I_ReleaseResources(THINKPAD_BD_DATA * pBDData)
{
int retval = 0;
DSP_3780I_CONFIG_SETTINGS *pSettings = &pBDData->rDspSettings;
PRINTK_2(TRACE_TP3780I,
"tp3780i::tp3780I_ReleaseResources entry pBDData %p\n", pBDData);
release_region(pSettings->usDspBaseIO & (~3), 16);
if (pSettings->bInterruptClaimed) {
free_irq(pSettings->usDspIrq, NULL);
pSettings->bInterruptClaimed = FALSE;
}
PRINTK_2(TRACE_TP3780I,
"tp3780i::tp3780I_ReleaseResources exit retval %x\n", retval);
return retval;
}
int tp3780I_EnableDSP(THINKPAD_BD_DATA * pBDData)
{
DSP_3780I_CONFIG_SETTINGS *pSettings = &pBDData->rDspSettings;
BOOLEAN bDSPPoweredUp = FALSE, bInterruptAllocated = FALSE;
PRINTK_2(TRACE_TP3780I, "tp3780i::tp3780I_EnableDSP entry pBDData %p\n", pBDData);
if (pBDData->bDSPEnabled) {
PRINTK_ERROR(KERN_ERR_MWAVE "tp3780i::tp3780I_EnableDSP: Error: DSP already enabled!\n");
goto exit_cleanup;
}
if (!pSettings->bDSPEnabled) {
PRINTK_ERROR(KERN_ERR_MWAVE "tp3780::tp3780I_EnableDSP: Error: pSettings->bDSPEnabled not set\n");
goto exit_cleanup;
}
if (
(pSettings->usDspIrq >= s_numIrqs)
|| (pSettings->usDspDma >= s_numDmas)
|| (s_ausThinkpadIrqToField[pSettings->usDspIrq] == 0xFFFF)
|| (s_ausThinkpadDmaToField[pSettings->usDspDma] == 0xFFFF)
) {
PRINTK_ERROR(KERN_ERR_MWAVE "tp3780i::tp3780I_EnableDSP: Error: invalid irq %x\n", pSettings->usDspIrq);
goto exit_cleanup;
}
if (
((pSettings->usDspBaseIO & 0xF00F) != 0)
|| (pSettings->usDspBaseIO & 0x0FF0) == 0
) {
PRINTK_ERROR(KERN_ERR_MWAVE "tp3780i::tp3780I_EnableDSP: Error: Invalid DSP base I/O address %x\n", pSettings->usDspBaseIO);
goto exit_cleanup;
}
if (pSettings->bModemEnabled) {
if (
pSettings->usUartIrq >= s_numIrqs
|| s_ausThinkpadIrqToField[pSettings->usUartIrq] == 0xFFFF
) {
PRINTK_ERROR(KERN_ERR_MWAVE "tp3780i::tp3780I_EnableDSP: Error: Invalid UART IRQ %x\n", pSettings->usUartIrq);
goto exit_cleanup;
}
switch (pSettings->usUartBaseIO) {
case 0x03F8:
case 0x02F8:
case 0x03E8:
case 0x02E8:
break;
default:
PRINTK_ERROR("tp3780i::tp3780I_EnableDSP: Error: Invalid UART base I/O address %x\n", pSettings->usUartBaseIO);
goto exit_cleanup;
}
}
pSettings->bDspIrqActiveLow = pSettings->bDspIrqPulse = TRUE;
pSettings->bUartIrqActiveLow = pSettings->bUartIrqPulse = TRUE;
if (pBDData->bShareDspIrq) {
pSettings->bDspIrqActiveLow = FALSE;
}
if (pBDData->bShareUartIrq) {
pSettings->bUartIrqActiveLow = FALSE;
}
pSettings->usNumTransfers = TP_CFG_NumTransfers;
pSettings->usReRequest = TP_CFG_RerequestTimer;
pSettings->bEnableMEMCS16 = TP_CFG_MEMCS16;
pSettings->usIsaMemCmdWidth = TP_CFG_IsaMemCmdWidth;
pSettings->bGateIOCHRDY = TP_CFG_GateIOCHRDY;
pSettings->bEnablePwrMgmt = TP_CFG_EnablePwrMgmt;
pSettings->usHBusTimerLoadValue = TP_CFG_HBusTimerValue;
pSettings->bDisableLBusTimeout = TP_CFG_DisableLBusTimeout;
pSettings->usN_Divisor = TP_CFG_N_Divisor;
pSettings->usM_Multiplier = TP_CFG_M_Multiplier;
pSettings->bPllBypass = TP_CFG_PllBypass;
pSettings->usChipletEnable = TP_CFG_ChipletEnable;
if (request_irq(pSettings->usUartIrq, &UartInterrupt, 0, "mwave_uart", NULL)) {
PRINTK_ERROR(KERN_ERR_MWAVE "tp3780i::tp3780I_EnableDSP: Error: Could not get UART IRQ %x\n", pSettings->usUartIrq);
goto exit_cleanup;
} else { /* no conflict just release */
free_irq(pSettings->usUartIrq, NULL);
}
if (request_irq(pSettings->usDspIrq, &DspInterrupt, 0, "mwave_3780i", NULL)) {
PRINTK_ERROR("tp3780i::tp3780I_EnableDSP: Error: Could not get 3780i IRQ %x\n", pSettings->usDspIrq);
goto exit_cleanup;
} else {
PRINTK_3(TRACE_TP3780I,
"tp3780i::tp3780I_EnableDSP, got interrupt %x bShareDspIrq %x\n",
pSettings->usDspIrq, pBDData->bShareDspIrq);
bInterruptAllocated = TRUE;
pSettings->bInterruptClaimed = TRUE;
}
smapi_set_DSP_power_state(FALSE);
if (smapi_set_DSP_power_state(TRUE)) {
PRINTK_ERROR(KERN_ERR_MWAVE "tp3780i::tp3780I_EnableDSP: Error: smapi_set_DSP_power_state(TRUE) failed\n");
goto exit_cleanup;
} else {
bDSPPoweredUp = TRUE;
}
if (dsp3780I_EnableDSP(pSettings, s_ausThinkpadIrqToField, s_ausThinkpadDmaToField)) {
PRINTK_ERROR("tp3780i::tp3780I_EnableDSP: Error: dsp7880I_EnableDSP() failed\n");
goto exit_cleanup;
}
EnableSRAM(pBDData);
pBDData->bDSPEnabled = TRUE;
PRINTK_1(TRACE_TP3780I, "tp3780i::tp3780I_EnableDSP exit\n");
return 0;
exit_cleanup:
PRINTK_ERROR("tp3780i::tp3780I_EnableDSP: Cleaning up\n");
if (bDSPPoweredUp)
smapi_set_DSP_power_state(FALSE);
if (bInterruptAllocated) {
free_irq(pSettings->usDspIrq, NULL);
pSettings->bInterruptClaimed = FALSE;
}
return -EIO;
}
int tp3780I_DisableDSP(THINKPAD_BD_DATA * pBDData)
{
int retval = 0;
DSP_3780I_CONFIG_SETTINGS *pSettings = &pBDData->rDspSettings;
PRINTK_2(TRACE_TP3780I, "tp3780i::tp3780I_DisableDSP entry pBDData %p\n", pBDData);
if (pBDData->bDSPEnabled) {
dsp3780I_DisableDSP(&pBDData->rDspSettings);
if (pSettings->bInterruptClaimed) {
free_irq(pSettings->usDspIrq, NULL);
pSettings->bInterruptClaimed = FALSE;
}
smapi_set_DSP_power_state(FALSE);
pBDData->bDSPEnabled = FALSE;
}
PRINTK_2(TRACE_TP3780I, "tp3780i::tp3780I_DisableDSP exit retval %x\n", retval);
return retval;
}
int tp3780I_ResetDSP(THINKPAD_BD_DATA * pBDData)
{
int retval = 0;
DSP_3780I_CONFIG_SETTINGS *pSettings = &pBDData->rDspSettings;
PRINTK_2(TRACE_TP3780I, "tp3780i::tp3780I_ResetDSP entry pBDData %p\n",
pBDData);
if (dsp3780I_Reset(pSettings) == 0) {
EnableSRAM(pBDData);
} else {
retval = -EIO;
}
PRINTK_2(TRACE_TP3780I, "tp3780i::tp3780I_ResetDSP exit retval %x\n", retval);
return retval;
}
int tp3780I_StartDSP(THINKPAD_BD_DATA * pBDData)
{
int retval = 0;
DSP_3780I_CONFIG_SETTINGS *pSettings = &pBDData->rDspSettings;
PRINTK_2(TRACE_TP3780I, "tp3780i::tp3780I_StartDSP entry pBDData %p\n", pBDData);
if (dsp3780I_Run(pSettings) == 0) {
// @BUG @TBD EnableSRAM(pBDData);
} else {
retval = -EIO;
}
PRINTK_2(TRACE_TP3780I, "tp3780i::tp3780I_StartDSP exit retval %x\n", retval);
return retval;
}
int tp3780I_QueryAbilities(THINKPAD_BD_DATA * pBDData, MW_ABILITIES * pAbilities)
{
int retval = 0;
PRINTK_2(TRACE_TP3780I,
"tp3780i::tp3780I_QueryAbilities entry pBDData %p\n", pBDData);
memset(pAbilities, 0, sizeof(*pAbilities));
/* fill out standard constant fields */
pAbilities->instr_per_sec = pBDData->rDspSettings.uIps;
pAbilities->data_size = pBDData->rDspSettings.uDStoreSize;
pAbilities->inst_size = pBDData->rDspSettings.uIStoreSize;
pAbilities->bus_dma_bw = pBDData->rDspSettings.uDmaBandwidth;
/* fill out dynamically determined fields */
pAbilities->component_list[0] = 0x00010000 | MW_ADC_MASK;
pAbilities->component_list[1] = 0x00010000 | MW_ACI_MASK;
pAbilities->component_list[2] = 0x00010000 | MW_AIC1_MASK;
pAbilities->component_list[3] = 0x00010000 | MW_AIC2_MASK;
pAbilities->component_list[4] = 0x00010000 | MW_CDDAC_MASK;
pAbilities->component_list[5] = 0x00010000 | MW_MIDI_MASK;
pAbilities->component_list[6] = 0x00010000 | MW_UART_MASK;
pAbilities->component_count = 7;
/* Fill out Mwave OS and BIOS task names */
memcpy(pAbilities->mwave_os_name, TP_ABILITIES_MWAVEOS_NAME,
sizeof(TP_ABILITIES_MWAVEOS_NAME));
memcpy(pAbilities->bios_task_name, TP_ABILITIES_BIOSTASK_NAME,
sizeof(TP_ABILITIES_BIOSTASK_NAME));
PRINTK_1(TRACE_TP3780I,
"tp3780i::tp3780I_QueryAbilities exit retval=SUCCESSFUL\n");
return retval;
}
int tp3780I_ReadWriteDspDStore(THINKPAD_BD_DATA * pBDData, unsigned int uOpcode,
void __user *pvBuffer, unsigned int uCount,
unsigned long ulDSPAddr)
{
int retval = 0;
DSP_3780I_CONFIG_SETTINGS *pSettings = &pBDData->rDspSettings;
unsigned short usDspBaseIO = pSettings->usDspBaseIO;
BOOLEAN bRC = 0;
PRINTK_6(TRACE_TP3780I,
"tp3780i::tp3780I_ReadWriteDspDStore entry pBDData %p, uOpcode %x, pvBuffer %p, uCount %x, ulDSPAddr %lx\n",
pBDData, uOpcode, pvBuffer, uCount, ulDSPAddr);
if (pBDData->bDSPEnabled) {
switch (uOpcode) {
case IOCTL_MW_READ_DATA:
bRC = dsp3780I_ReadDStore(usDspBaseIO, pvBuffer, uCount, ulDSPAddr);
break;
case IOCTL_MW_READCLEAR_DATA:
bRC = dsp3780I_ReadAndClearDStore(usDspBaseIO, pvBuffer, uCount, ulDSPAddr);
break;
case IOCTL_MW_WRITE_DATA:
bRC = dsp3780I_WriteDStore(usDspBaseIO, pvBuffer, uCount, ulDSPAddr);
break;
}
}
retval = (bRC) ? -EIO : 0;
PRINTK_2(TRACE_TP3780I, "tp3780i::tp3780I_ReadWriteDspDStore exit retval %x\n", retval);
return retval;
}
int tp3780I_ReadWriteDspIStore(THINKPAD_BD_DATA * pBDData, unsigned int uOpcode,
void __user *pvBuffer, unsigned int uCount,
unsigned long ulDSPAddr)
{
int retval = 0;
DSP_3780I_CONFIG_SETTINGS *pSettings = &pBDData->rDspSettings;
unsigned short usDspBaseIO = pSettings->usDspBaseIO;
BOOLEAN bRC = 0;
PRINTK_6(TRACE_TP3780I,
"tp3780i::tp3780I_ReadWriteDspIStore entry pBDData %p, uOpcode %x, pvBuffer %p, uCount %x, ulDSPAddr %lx\n",
pBDData, uOpcode, pvBuffer, uCount, ulDSPAddr);
if (pBDData->bDSPEnabled) {
switch (uOpcode) {
case IOCTL_MW_READ_INST:
bRC = dsp3780I_ReadIStore(usDspBaseIO, pvBuffer, uCount, ulDSPAddr);
break;
case IOCTL_MW_WRITE_INST:
bRC = dsp3780I_WriteIStore(usDspBaseIO, pvBuffer, uCount, ulDSPAddr);
break;
}
}
retval = (bRC) ? -EIO : 0;
PRINTK_2(TRACE_TP3780I,
"tp3780i::tp3780I_ReadWriteDspIStore exit retval %x\n", retval);
return retval;
}
| gpl-2.0 |
mdeejay/android_kernel_ville | drivers/gpu/drm/radeon/radeon_gem.c | 2664 | 10044 | /*
* Copyright 2008 Advanced Micro Devices, Inc.
* Copyright 2008 Red Hat Inc.
* Copyright 2009 Jerome Glisse.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Dave Airlie
* Alex Deucher
* Jerome Glisse
*/
#include "drmP.h"
#include "drm.h"
#include "radeon_drm.h"
#include "radeon.h"
int radeon_gem_object_init(struct drm_gem_object *obj)
{
BUG();
return 0;
}
void radeon_gem_object_free(struct drm_gem_object *gobj)
{
struct radeon_bo *robj = gem_to_radeon_bo(gobj);
if (robj) {
radeon_bo_unref(&robj);
}
}
int radeon_gem_object_create(struct radeon_device *rdev, int size,
int alignment, int initial_domain,
bool discardable, bool kernel,
struct drm_gem_object **obj)
{
struct radeon_bo *robj;
int r;
*obj = NULL;
/* At least align on page size */
if (alignment < PAGE_SIZE) {
alignment = PAGE_SIZE;
}
r = radeon_bo_create(rdev, size, alignment, kernel, initial_domain, &robj);
if (r) {
if (r != -ERESTARTSYS)
DRM_ERROR("Failed to allocate GEM object (%d, %d, %u, %d)\n",
size, initial_domain, alignment, r);
return r;
}
*obj = &robj->gem_base;
mutex_lock(&rdev->gem.mutex);
list_add_tail(&robj->list, &rdev->gem.objects);
mutex_unlock(&rdev->gem.mutex);
return 0;
}
int radeon_gem_object_pin(struct drm_gem_object *obj, uint32_t pin_domain,
uint64_t *gpu_addr)
{
struct radeon_bo *robj = gem_to_radeon_bo(obj);
int r;
r = radeon_bo_reserve(robj, false);
if (unlikely(r != 0))
return r;
r = radeon_bo_pin(robj, pin_domain, gpu_addr);
radeon_bo_unreserve(robj);
return r;
}
void radeon_gem_object_unpin(struct drm_gem_object *obj)
{
struct radeon_bo *robj = gem_to_radeon_bo(obj);
int r;
r = radeon_bo_reserve(robj, false);
if (likely(r == 0)) {
radeon_bo_unpin(robj);
radeon_bo_unreserve(robj);
}
}
int radeon_gem_set_domain(struct drm_gem_object *gobj,
uint32_t rdomain, uint32_t wdomain)
{
struct radeon_bo *robj;
uint32_t domain;
int r;
/* FIXME: reeimplement */
robj = gem_to_radeon_bo(gobj);
/* work out where to validate the buffer to */
domain = wdomain;
if (!domain) {
domain = rdomain;
}
if (!domain) {
/* Do nothings */
printk(KERN_WARNING "Set domain withou domain !\n");
return 0;
}
if (domain == RADEON_GEM_DOMAIN_CPU) {
/* Asking for cpu access wait for object idle */
r = radeon_bo_wait(robj, NULL, false);
if (r) {
printk(KERN_ERR "Failed to wait for object !\n");
return r;
}
}
return 0;
}
int radeon_gem_init(struct radeon_device *rdev)
{
INIT_LIST_HEAD(&rdev->gem.objects);
return 0;
}
void radeon_gem_fini(struct radeon_device *rdev)
{
radeon_bo_force_delete(rdev);
}
/*
* GEM ioctls.
*/
int radeon_gem_info_ioctl(struct drm_device *dev, void *data,
struct drm_file *filp)
{
struct radeon_device *rdev = dev->dev_private;
struct drm_radeon_gem_info *args = data;
struct ttm_mem_type_manager *man;
man = &rdev->mman.bdev.man[TTM_PL_VRAM];
args->vram_size = rdev->mc.real_vram_size;
args->vram_visible = (u64)man->size << PAGE_SHIFT;
if (rdev->stollen_vga_memory)
args->vram_visible -= radeon_bo_size(rdev->stollen_vga_memory);
args->vram_visible -= radeon_fbdev_total_size(rdev);
args->gart_size = rdev->mc.gtt_size - rdev->cp.ring_size - 4096 -
RADEON_IB_POOL_SIZE*64*1024;
return 0;
}
int radeon_gem_pread_ioctl(struct drm_device *dev, void *data,
struct drm_file *filp)
{
/* TODO: implement */
DRM_ERROR("unimplemented %s\n", __func__);
return -ENOSYS;
}
int radeon_gem_pwrite_ioctl(struct drm_device *dev, void *data,
struct drm_file *filp)
{
/* TODO: implement */
DRM_ERROR("unimplemented %s\n", __func__);
return -ENOSYS;
}
int radeon_gem_create_ioctl(struct drm_device *dev, void *data,
struct drm_file *filp)
{
struct radeon_device *rdev = dev->dev_private;
struct drm_radeon_gem_create *args = data;
struct drm_gem_object *gobj;
uint32_t handle;
int r;
/* create a gem object to contain this object in */
args->size = roundup(args->size, PAGE_SIZE);
r = radeon_gem_object_create(rdev, args->size, args->alignment,
args->initial_domain, false,
false, &gobj);
if (r) {
return r;
}
r = drm_gem_handle_create(filp, gobj, &handle);
/* drop reference from allocate - handle holds it now */
drm_gem_object_unreference_unlocked(gobj);
if (r) {
return r;
}
args->handle = handle;
return 0;
}
int radeon_gem_set_domain_ioctl(struct drm_device *dev, void *data,
struct drm_file *filp)
{
/* transition the BO to a domain -
* just validate the BO into a certain domain */
struct drm_radeon_gem_set_domain *args = data;
struct drm_gem_object *gobj;
struct radeon_bo *robj;
int r;
/* for now if someone requests domain CPU -
* just make sure the buffer is finished with */
/* just do a BO wait for now */
gobj = drm_gem_object_lookup(dev, filp, args->handle);
if (gobj == NULL) {
return -ENOENT;
}
robj = gem_to_radeon_bo(gobj);
r = radeon_gem_set_domain(gobj, args->read_domains, args->write_domain);
drm_gem_object_unreference_unlocked(gobj);
return r;
}
int radeon_mode_dumb_mmap(struct drm_file *filp,
struct drm_device *dev,
uint32_t handle, uint64_t *offset_p)
{
struct drm_gem_object *gobj;
struct radeon_bo *robj;
gobj = drm_gem_object_lookup(dev, filp, handle);
if (gobj == NULL) {
return -ENOENT;
}
robj = gem_to_radeon_bo(gobj);
*offset_p = radeon_bo_mmap_offset(robj);
drm_gem_object_unreference_unlocked(gobj);
return 0;
}
int radeon_gem_mmap_ioctl(struct drm_device *dev, void *data,
struct drm_file *filp)
{
struct drm_radeon_gem_mmap *args = data;
return radeon_mode_dumb_mmap(filp, dev, args->handle, &args->addr_ptr);
}
int radeon_gem_busy_ioctl(struct drm_device *dev, void *data,
struct drm_file *filp)
{
struct drm_radeon_gem_busy *args = data;
struct drm_gem_object *gobj;
struct radeon_bo *robj;
int r;
uint32_t cur_placement = 0;
gobj = drm_gem_object_lookup(dev, filp, args->handle);
if (gobj == NULL) {
return -ENOENT;
}
robj = gem_to_radeon_bo(gobj);
r = radeon_bo_wait(robj, &cur_placement, true);
switch (cur_placement) {
case TTM_PL_VRAM:
args->domain = RADEON_GEM_DOMAIN_VRAM;
break;
case TTM_PL_TT:
args->domain = RADEON_GEM_DOMAIN_GTT;
break;
case TTM_PL_SYSTEM:
args->domain = RADEON_GEM_DOMAIN_CPU;
default:
break;
}
drm_gem_object_unreference_unlocked(gobj);
return r;
}
int radeon_gem_wait_idle_ioctl(struct drm_device *dev, void *data,
struct drm_file *filp)
{
struct drm_radeon_gem_wait_idle *args = data;
struct drm_gem_object *gobj;
struct radeon_bo *robj;
int r;
gobj = drm_gem_object_lookup(dev, filp, args->handle);
if (gobj == NULL) {
return -ENOENT;
}
robj = gem_to_radeon_bo(gobj);
r = radeon_bo_wait(robj, NULL, false);
/* callback hw specific functions if any */
if (robj->rdev->asic->ioctl_wait_idle)
robj->rdev->asic->ioctl_wait_idle(robj->rdev, robj);
drm_gem_object_unreference_unlocked(gobj);
return r;
}
int radeon_gem_set_tiling_ioctl(struct drm_device *dev, void *data,
struct drm_file *filp)
{
struct drm_radeon_gem_set_tiling *args = data;
struct drm_gem_object *gobj;
struct radeon_bo *robj;
int r = 0;
DRM_DEBUG("%d \n", args->handle);
gobj = drm_gem_object_lookup(dev, filp, args->handle);
if (gobj == NULL)
return -ENOENT;
robj = gem_to_radeon_bo(gobj);
r = radeon_bo_set_tiling_flags(robj, args->tiling_flags, args->pitch);
drm_gem_object_unreference_unlocked(gobj);
return r;
}
int radeon_gem_get_tiling_ioctl(struct drm_device *dev, void *data,
struct drm_file *filp)
{
struct drm_radeon_gem_get_tiling *args = data;
struct drm_gem_object *gobj;
struct radeon_bo *rbo;
int r = 0;
DRM_DEBUG("\n");
gobj = drm_gem_object_lookup(dev, filp, args->handle);
if (gobj == NULL)
return -ENOENT;
rbo = gem_to_radeon_bo(gobj);
r = radeon_bo_reserve(rbo, false);
if (unlikely(r != 0))
goto out;
radeon_bo_get_tiling_flags(rbo, &args->tiling_flags, &args->pitch);
radeon_bo_unreserve(rbo);
out:
drm_gem_object_unreference_unlocked(gobj);
return r;
}
int radeon_mode_dumb_create(struct drm_file *file_priv,
struct drm_device *dev,
struct drm_mode_create_dumb *args)
{
struct radeon_device *rdev = dev->dev_private;
struct drm_gem_object *gobj;
uint32_t handle;
int r;
args->pitch = radeon_align_pitch(rdev, args->width, args->bpp, 0) * ((args->bpp + 1) / 8);
args->size = args->pitch * args->height;
args->size = ALIGN(args->size, PAGE_SIZE);
r = radeon_gem_object_create(rdev, args->size, 0,
RADEON_GEM_DOMAIN_VRAM,
false, ttm_bo_type_device,
&gobj);
if (r)
return -ENOMEM;
r = drm_gem_handle_create(file_priv, gobj, &handle);
/* drop reference from allocate - handle holds it now */
drm_gem_object_unreference_unlocked(gobj);
if (r) {
return r;
}
args->handle = handle;
return 0;
}
int radeon_mode_dumb_destroy(struct drm_file *file_priv,
struct drm_device *dev,
uint32_t handle)
{
return drm_gem_handle_delete(file_priv, handle);
}
| gpl-2.0 |
CyanogenMod-S6310/kernel | arch/mips/netlogic/common/irq.c | 4456 | 6087 | /*
* Copyright 2003-2011 NetLogic Microsystems, Inc. (NetLogic). All rights
* reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the NetLogic
* license below:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETLOGIC ``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 NETLOGIC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/linkage.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <asm/errno.h>
#include <asm/signal.h>
#include <asm/ptrace.h>
#include <asm/mipsregs.h>
#include <asm/thread_info.h>
#include <asm/netlogic/mips-extns.h>
#include <asm/netlogic/interrupt.h>
#include <asm/netlogic/haldefs.h>
#include <asm/netlogic/common.h>
#if defined(CONFIG_CPU_XLP)
#include <asm/netlogic/xlp-hal/iomap.h>
#include <asm/netlogic/xlp-hal/xlp.h>
#include <asm/netlogic/xlp-hal/pic.h>
#elif defined(CONFIG_CPU_XLR)
#include <asm/netlogic/xlr/iomap.h>
#include <asm/netlogic/xlr/pic.h>
#else
#error "Unknown CPU"
#endif
/*
* These are the routines that handle all the low level interrupt stuff.
* Actions handled here are: initialization of the interrupt map, requesting of
* interrupt lines by handlers, dispatching if interrupts to handlers, probing
* for interrupt lines
*/
/* Globals */
static uint64_t nlm_irq_mask;
static DEFINE_SPINLOCK(nlm_pic_lock);
static void xlp_pic_enable(struct irq_data *d)
{
unsigned long flags;
int irt;
irt = nlm_irq_to_irt(d->irq);
if (irt == -1)
return;
spin_lock_irqsave(&nlm_pic_lock, flags);
nlm_pic_enable_irt(nlm_pic_base, irt);
spin_unlock_irqrestore(&nlm_pic_lock, flags);
}
static void xlp_pic_disable(struct irq_data *d)
{
unsigned long flags;
int irt;
irt = nlm_irq_to_irt(d->irq);
if (irt == -1)
return;
spin_lock_irqsave(&nlm_pic_lock, flags);
nlm_pic_disable_irt(nlm_pic_base, irt);
spin_unlock_irqrestore(&nlm_pic_lock, flags);
}
static void xlp_pic_mask_ack(struct irq_data *d)
{
uint64_t mask = 1ull << d->irq;
write_c0_eirr(mask); /* ack by writing EIRR */
}
static void xlp_pic_unmask(struct irq_data *d)
{
void *hd = irq_data_get_irq_handler_data(d);
int irt;
irt = nlm_irq_to_irt(d->irq);
if (irt == -1)
return;
if (hd) {
void (*extra_ack)(void *) = hd;
extra_ack(d);
}
/* Ack is a single write, no need to lock */
nlm_pic_ack(nlm_pic_base, irt);
}
static struct irq_chip xlp_pic = {
.name = "XLP-PIC",
.irq_enable = xlp_pic_enable,
.irq_disable = xlp_pic_disable,
.irq_mask_ack = xlp_pic_mask_ack,
.irq_unmask = xlp_pic_unmask,
};
static void cpuintr_disable(struct irq_data *d)
{
uint64_t eimr;
uint64_t mask = 1ull << d->irq;
eimr = read_c0_eimr();
write_c0_eimr(eimr & ~mask);
}
static void cpuintr_enable(struct irq_data *d)
{
uint64_t eimr;
uint64_t mask = 1ull << d->irq;
eimr = read_c0_eimr();
write_c0_eimr(eimr | mask);
}
static void cpuintr_ack(struct irq_data *d)
{
uint64_t mask = 1ull << d->irq;
write_c0_eirr(mask);
}
static void cpuintr_nop(struct irq_data *d)
{
WARN(d->irq >= PIC_IRQ_BASE, "Bad irq %d", d->irq);
}
/*
* Chip definition for CPU originated interrupts(timer, msg) and
* IPIs
*/
struct irq_chip nlm_cpu_intr = {
.name = "XLP-CPU-INTR",
.irq_enable = cpuintr_enable,
.irq_disable = cpuintr_disable,
.irq_mask = cpuintr_nop,
.irq_ack = cpuintr_nop,
.irq_eoi = cpuintr_ack,
};
void __init init_nlm_common_irqs(void)
{
int i, irq, irt;
for (i = 0; i < PIC_IRT_FIRST_IRQ; i++)
irq_set_chip_and_handler(i, &nlm_cpu_intr, handle_percpu_irq);
for (i = PIC_IRT_FIRST_IRQ; i <= PIC_IRT_LAST_IRQ ; i++)
irq_set_chip_and_handler(i, &xlp_pic, handle_level_irq);
#ifdef CONFIG_SMP
irq_set_chip_and_handler(IRQ_IPI_SMP_FUNCTION, &nlm_cpu_intr,
nlm_smp_function_ipi_handler);
irq_set_chip_and_handler(IRQ_IPI_SMP_RESCHEDULE, &nlm_cpu_intr,
nlm_smp_resched_ipi_handler);
nlm_irq_mask |=
((1ULL << IRQ_IPI_SMP_FUNCTION) | (1ULL << IRQ_IPI_SMP_RESCHEDULE));
#endif
for (irq = PIC_IRT_FIRST_IRQ; irq <= PIC_IRT_LAST_IRQ; irq++) {
irt = nlm_irq_to_irt(irq);
if (irt == -1)
continue;
nlm_irq_mask |= (1ULL << irq);
nlm_pic_init_irt(nlm_pic_base, irt, irq, 0);
}
nlm_irq_mask |= (1ULL << IRQ_TIMER);
}
void __init arch_init_irq(void)
{
/* Initialize the irq descriptors */
init_nlm_common_irqs();
write_c0_eimr(nlm_irq_mask);
}
void __cpuinit nlm_smp_irq_init(void)
{
/* set interrupt mask for non-zero cpus */
write_c0_eimr(nlm_irq_mask);
}
asmlinkage void plat_irq_dispatch(void)
{
uint64_t eirr;
int i;
eirr = read_c0_eirr() & read_c0_eimr();
if (eirr & (1 << IRQ_TIMER)) {
do_IRQ(IRQ_TIMER);
return;
}
i = __ilog2_u64(eirr);
if (i == -1)
return;
do_IRQ(i);
}
| gpl-2.0 |
xiaognol/android_kernel_lg_f320s | arch/sparc/kernel/leon_pci.c | 4456 | 4906 | /*
* leon_pci.c: LEON Host PCI support
*
* Copyright (C) 2011 Aeroflex Gaisler AB, Daniel Hellstrom
*
* Code is partially derived from pcic.c
*/
#include <linux/of_device.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/export.h>
#include <asm/leon.h>
#include <asm/leon_pci.h>
/* The LEON architecture does not rely on a BIOS or bootloader to setup
* PCI for us. The Linux generic routines are used to setup resources,
* reset values of configuration-space register settings are preserved.
*
* PCI Memory and Prefetchable Memory is direct-mapped. However I/O Space is
* accessed through a Window which is translated to low 64KB in PCI space, the
* first 4KB is not used so 60KB is available.
*/
void leon_pci_init(struct platform_device *ofdev, struct leon_pci_info *info)
{
LIST_HEAD(resources);
struct pci_bus *root_bus;
pci_add_resource_offset(&resources, &info->io_space,
info->io_space.start - 0x1000);
pci_add_resource(&resources, &info->mem_space);
root_bus = pci_scan_root_bus(&ofdev->dev, 0, info->ops, info,
&resources);
if (root_bus) {
/* Setup IRQs of all devices using custom routines */
pci_fixup_irqs(pci_common_swizzle, info->map_irq);
/* Assign devices with resources */
pci_assign_unassigned_resources();
} else {
pci_free_resource_list(&resources);
}
}
void __devinit pcibios_fixup_bus(struct pci_bus *pbus)
{
struct pci_dev *dev;
int i, has_io, has_mem;
u16 cmd;
list_for_each_entry(dev, &pbus->devices, bus_list) {
/*
* We can not rely on that the bootloader has enabled I/O
* or memory access to PCI devices. Instead we enable it here
* if the device has BARs of respective type.
*/
has_io = has_mem = 0;
for (i = 0; i < PCI_ROM_RESOURCE; i++) {
unsigned long f = dev->resource[i].flags;
if (f & IORESOURCE_IO)
has_io = 1;
else if (f & IORESOURCE_MEM)
has_mem = 1;
}
/* ROM BARs are mapped into 32-bit memory space */
if (dev->resource[PCI_ROM_RESOURCE].end != 0) {
dev->resource[PCI_ROM_RESOURCE].flags |=
IORESOURCE_ROM_ENABLE;
has_mem = 1;
}
pci_bus_read_config_word(pbus, dev->devfn, PCI_COMMAND, &cmd);
if (has_io && !(cmd & PCI_COMMAND_IO)) {
#ifdef CONFIG_PCI_DEBUG
printk(KERN_INFO "LEONPCI: Enabling I/O for dev %s\n",
pci_name(dev));
#endif
cmd |= PCI_COMMAND_IO;
pci_bus_write_config_word(pbus, dev->devfn, PCI_COMMAND,
cmd);
}
if (has_mem && !(cmd & PCI_COMMAND_MEMORY)) {
#ifdef CONFIG_PCI_DEBUG
printk(KERN_INFO "LEONPCI: Enabling MEMORY for dev"
"%s\n", pci_name(dev));
#endif
cmd |= PCI_COMMAND_MEMORY;
pci_bus_write_config_word(pbus, dev->devfn, PCI_COMMAND,
cmd);
}
}
}
/*
* Other archs parse arguments here.
*/
char * __devinit pcibios_setup(char *str)
{
return str;
}
resource_size_t pcibios_align_resource(void *data, const struct resource *res,
resource_size_t size, resource_size_t align)
{
return res->start;
}
int pcibios_enable_device(struct pci_dev *dev, int mask)
{
return pci_enable_resources(dev, mask);
}
void __devinit pcibios_update_irq(struct pci_dev *dev, int irq)
{
#ifdef CONFIG_PCI_DEBUG
printk(KERN_DEBUG "LEONPCI: Assigning IRQ %02d to %s\n", irq,
pci_name(dev));
#endif
pci_write_config_byte(dev, PCI_INTERRUPT_LINE, irq);
}
/* in/out routines taken from pcic.c
*
* This probably belongs here rather than ioport.c because
* we do not want this crud linked into SBus kernels.
* Also, think for a moment about likes of floppy.c that
* include architecture specific parts. They may want to redefine ins/outs.
*
* We do not use horrible macros here because we want to
* advance pointer by sizeof(size).
*/
void outsb(unsigned long addr, const void *src, unsigned long count)
{
while (count) {
count -= 1;
outb(*(const char *)src, addr);
src += 1;
/* addr += 1; */
}
}
EXPORT_SYMBOL(outsb);
void outsw(unsigned long addr, const void *src, unsigned long count)
{
while (count) {
count -= 2;
outw(*(const short *)src, addr);
src += 2;
/* addr += 2; */
}
}
EXPORT_SYMBOL(outsw);
void outsl(unsigned long addr, const void *src, unsigned long count)
{
while (count) {
count -= 4;
outl(*(const long *)src, addr);
src += 4;
/* addr += 4; */
}
}
EXPORT_SYMBOL(outsl);
void insb(unsigned long addr, void *dst, unsigned long count)
{
while (count) {
count -= 1;
*(unsigned char *)dst = inb(addr);
dst += 1;
/* addr += 1; */
}
}
EXPORT_SYMBOL(insb);
void insw(unsigned long addr, void *dst, unsigned long count)
{
while (count) {
count -= 2;
*(unsigned short *)dst = inw(addr);
dst += 2;
/* addr += 2; */
}
}
EXPORT_SYMBOL(insw);
void insl(unsigned long addr, void *dst, unsigned long count)
{
while (count) {
count -= 4;
/*
* XXX I am sure we are in for an unaligned trap here.
*/
*(unsigned long *)dst = inl(addr);
dst += 4;
/* addr += 4; */
}
}
EXPORT_SYMBOL(insl);
| gpl-2.0 |
sudosurootdev/kernel_lge_g3-wip | arch/arm/mach-omap2/hwspinlock.c | 4968 | 1706 | /*
* OMAP hardware spinlock device initialization
*
* Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com
*
* Contact: Simon Que <sque@ti.com>
* Hari Kanigeri <h-kanigeri2@ti.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/hwspinlock.h>
#include <plat/omap_hwmod.h>
#include <plat/omap_device.h>
static struct hwspinlock_pdata omap_hwspinlock_pdata __initdata = {
.base_id = 0,
};
int __init hwspinlocks_init(void)
{
int retval = 0;
struct omap_hwmod *oh;
struct platform_device *pdev;
const char *oh_name = "spinlock";
const char *dev_name = "omap_hwspinlock";
/*
* Hwmod lookup will fail in case our platform doesn't support the
* hardware spinlock module, so it is safe to run this initcall
* on all omaps
*/
oh = omap_hwmod_lookup(oh_name);
if (oh == NULL)
return -EINVAL;
pdev = omap_device_build(dev_name, 0, oh, &omap_hwspinlock_pdata,
sizeof(struct hwspinlock_pdata),
NULL, 0, false);
if (IS_ERR(pdev)) {
pr_err("Can't build omap_device for %s:%s\n", dev_name,
oh_name);
retval = PTR_ERR(pdev);
}
return retval;
}
/* early board code might need to reserve specific hwspinlock instances */
postcore_initcall(hwspinlocks_init);
| gpl-2.0 |
chenzhiwo/linux-sunxi | arch/arm/mach-omap2/hwspinlock.c | 4968 | 1706 | /*
* OMAP hardware spinlock device initialization
*
* Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com
*
* Contact: Simon Que <sque@ti.com>
* Hari Kanigeri <h-kanigeri2@ti.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/hwspinlock.h>
#include <plat/omap_hwmod.h>
#include <plat/omap_device.h>
static struct hwspinlock_pdata omap_hwspinlock_pdata __initdata = {
.base_id = 0,
};
int __init hwspinlocks_init(void)
{
int retval = 0;
struct omap_hwmod *oh;
struct platform_device *pdev;
const char *oh_name = "spinlock";
const char *dev_name = "omap_hwspinlock";
/*
* Hwmod lookup will fail in case our platform doesn't support the
* hardware spinlock module, so it is safe to run this initcall
* on all omaps
*/
oh = omap_hwmod_lookup(oh_name);
if (oh == NULL)
return -EINVAL;
pdev = omap_device_build(dev_name, 0, oh, &omap_hwspinlock_pdata,
sizeof(struct hwspinlock_pdata),
NULL, 0, false);
if (IS_ERR(pdev)) {
pr_err("Can't build omap_device for %s:%s\n", dev_name,
oh_name);
retval = PTR_ERR(pdev);
}
return retval;
}
/* early board code might need to reserve specific hwspinlock instances */
postcore_initcall(hwspinlocks_init);
| gpl-2.0 |
ubuntustudio-kernel/ubuntu-raring-lowlatency | drivers/net/wireless/b43/lo.c | 9064 | 27470 | /*
Broadcom B43 wireless driver
G PHY LO (LocalOscillator) Measuring and Control routines
Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>,
Copyright (c) 2005, 2006 Stefano Brivio <stefano.brivio@polimi.it>
Copyright (c) 2005-2007 Michael Buesch <m@bues.ch>
Copyright (c) 2005, 2006 Danny van Dyk <kugelfang@gentoo.org>
Copyright (c) 2005, 2006 Andreas Jaggi <andreas.jaggi@waterwave.ch>
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; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "b43.h"
#include "lo.h"
#include "phy_g.h"
#include "main.h"
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/slab.h>
static struct b43_lo_calib *b43_find_lo_calib(struct b43_txpower_lo_control *lo,
const struct b43_bbatt *bbatt,
const struct b43_rfatt *rfatt)
{
struct b43_lo_calib *c;
list_for_each_entry(c, &lo->calib_list, list) {
if (!b43_compare_bbatt(&c->bbatt, bbatt))
continue;
if (!b43_compare_rfatt(&c->rfatt, rfatt))
continue;
return c;
}
return NULL;
}
/* Write the LocalOscillator Control (adjust) value-pair. */
static void b43_lo_write(struct b43_wldev *dev, struct b43_loctl *control)
{
struct b43_phy *phy = &dev->phy;
u16 value;
if (B43_DEBUG) {
if (unlikely(abs(control->i) > 16 || abs(control->q) > 16)) {
b43dbg(dev->wl, "Invalid LO control pair "
"(I: %d, Q: %d)\n", control->i, control->q);
dump_stack();
return;
}
}
B43_WARN_ON(phy->type != B43_PHYTYPE_G);
value = (u8) (control->q);
value |= ((u8) (control->i)) << 8;
b43_phy_write(dev, B43_PHY_LO_CTL, value);
}
static u16 lo_measure_feedthrough(struct b43_wldev *dev,
u16 lna, u16 pga, u16 trsw_rx)
{
struct b43_phy *phy = &dev->phy;
u16 rfover;
u16 feedthrough;
if (phy->gmode) {
lna <<= B43_PHY_RFOVERVAL_LNA_SHIFT;
pga <<= B43_PHY_RFOVERVAL_PGA_SHIFT;
B43_WARN_ON(lna & ~B43_PHY_RFOVERVAL_LNA);
B43_WARN_ON(pga & ~B43_PHY_RFOVERVAL_PGA);
/*FIXME This assertion fails B43_WARN_ON(trsw_rx & ~(B43_PHY_RFOVERVAL_TRSWRX |
B43_PHY_RFOVERVAL_BW));
*/
trsw_rx &= (B43_PHY_RFOVERVAL_TRSWRX | B43_PHY_RFOVERVAL_BW);
/* Construct the RF Override Value */
rfover = B43_PHY_RFOVERVAL_UNK;
rfover |= pga;
rfover |= lna;
rfover |= trsw_rx;
if ((dev->dev->bus_sprom->boardflags_lo & B43_BFL_EXTLNA)
&& phy->rev > 6)
rfover |= B43_PHY_RFOVERVAL_EXTLNA;
b43_phy_write(dev, B43_PHY_PGACTL, 0xE300);
b43_phy_write(dev, B43_PHY_RFOVERVAL, rfover);
udelay(10);
rfover |= B43_PHY_RFOVERVAL_BW_LBW;
b43_phy_write(dev, B43_PHY_RFOVERVAL, rfover);
udelay(10);
rfover |= B43_PHY_RFOVERVAL_BW_LPF;
b43_phy_write(dev, B43_PHY_RFOVERVAL, rfover);
udelay(10);
b43_phy_write(dev, B43_PHY_PGACTL, 0xF300);
} else {
pga |= B43_PHY_PGACTL_UNKNOWN;
b43_phy_write(dev, B43_PHY_PGACTL, pga);
udelay(10);
pga |= B43_PHY_PGACTL_LOWBANDW;
b43_phy_write(dev, B43_PHY_PGACTL, pga);
udelay(10);
pga |= B43_PHY_PGACTL_LPF;
b43_phy_write(dev, B43_PHY_PGACTL, pga);
}
udelay(21);
feedthrough = b43_phy_read(dev, B43_PHY_LO_LEAKAGE);
/* This is a good place to check if we need to relax a bit,
* as this is the main function called regularly
* in the LO calibration. */
cond_resched();
return feedthrough;
}
/* TXCTL Register and Value Table.
* Returns the "TXCTL Register".
* "value" is the "TXCTL Value".
* "pad_mix_gain" is the PAD Mixer Gain.
*/
static u16 lo_txctl_register_table(struct b43_wldev *dev,
u16 *value, u16 *pad_mix_gain)
{
struct b43_phy *phy = &dev->phy;
u16 reg, v, padmix;
if (phy->type == B43_PHYTYPE_B) {
v = 0x30;
if (phy->radio_rev <= 5) {
reg = 0x43;
padmix = 0;
} else {
reg = 0x52;
padmix = 5;
}
} else {
if (phy->rev >= 2 && phy->radio_rev == 8) {
reg = 0x43;
v = 0x10;
padmix = 2;
} else {
reg = 0x52;
v = 0x30;
padmix = 5;
}
}
if (value)
*value = v;
if (pad_mix_gain)
*pad_mix_gain = padmix;
return reg;
}
static void lo_measure_txctl_values(struct b43_wldev *dev)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_g *gphy = phy->g;
struct b43_txpower_lo_control *lo = gphy->lo_control;
u16 reg, mask;
u16 trsw_rx, pga;
u16 radio_pctl_reg;
static const u8 tx_bias_values[] = {
0x09, 0x08, 0x0A, 0x01, 0x00,
0x02, 0x05, 0x04, 0x06,
};
static const u8 tx_magn_values[] = {
0x70, 0x40,
};
if (!has_loopback_gain(phy)) {
radio_pctl_reg = 6;
trsw_rx = 2;
pga = 0;
} else {
int lb_gain; /* Loopback gain (in dB) */
trsw_rx = 0;
lb_gain = gphy->max_lb_gain / 2;
if (lb_gain > 10) {
radio_pctl_reg = 0;
pga = abs(10 - lb_gain) / 6;
pga = clamp_val(pga, 0, 15);
} else {
int cmp_val;
int tmp;
pga = 0;
cmp_val = 0x24;
if ((phy->rev >= 2) &&
(phy->radio_ver == 0x2050) && (phy->radio_rev == 8))
cmp_val = 0x3C;
tmp = lb_gain;
if ((10 - lb_gain) < cmp_val)
tmp = (10 - lb_gain);
if (tmp < 0)
tmp += 6;
else
tmp += 3;
cmp_val /= 4;
tmp /= 4;
if (tmp >= cmp_val)
radio_pctl_reg = cmp_val;
else
radio_pctl_reg = tmp;
}
}
b43_radio_maskset(dev, 0x43, 0xFFF0, radio_pctl_reg);
b43_gphy_set_baseband_attenuation(dev, 2);
reg = lo_txctl_register_table(dev, &mask, NULL);
mask = ~mask;
b43_radio_mask(dev, reg, mask);
if (has_tx_magnification(phy)) {
int i, j;
int feedthrough;
int min_feedth = 0xFFFF;
u8 tx_magn, tx_bias;
for (i = 0; i < ARRAY_SIZE(tx_magn_values); i++) {
tx_magn = tx_magn_values[i];
b43_radio_maskset(dev, 0x52, 0xFF0F, tx_magn);
for (j = 0; j < ARRAY_SIZE(tx_bias_values); j++) {
tx_bias = tx_bias_values[j];
b43_radio_maskset(dev, 0x52, 0xFFF0, tx_bias);
feedthrough =
lo_measure_feedthrough(dev, 0, pga,
trsw_rx);
if (feedthrough < min_feedth) {
lo->tx_bias = tx_bias;
lo->tx_magn = tx_magn;
min_feedth = feedthrough;
}
if (lo->tx_bias == 0)
break;
}
b43_radio_write16(dev, 0x52,
(b43_radio_read16(dev, 0x52)
& 0xFF00) | lo->tx_bias | lo->
tx_magn);
}
} else {
lo->tx_magn = 0;
lo->tx_bias = 0;
b43_radio_mask(dev, 0x52, 0xFFF0); /* TX bias == 0 */
}
lo->txctl_measured_time = jiffies;
}
static void lo_read_power_vector(struct b43_wldev *dev)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_g *gphy = phy->g;
struct b43_txpower_lo_control *lo = gphy->lo_control;
int i;
u64 tmp;
u64 power_vector = 0;
for (i = 0; i < 8; i += 2) {
tmp = b43_shm_read16(dev, B43_SHM_SHARED, 0x310 + i);
power_vector |= (tmp << (i * 8));
/* Clear the vector on the device. */
b43_shm_write16(dev, B43_SHM_SHARED, 0x310 + i, 0);
}
if (power_vector)
lo->power_vector = power_vector;
lo->pwr_vec_read_time = jiffies;
}
/* 802.11/LO/GPHY/MeasuringGains */
static void lo_measure_gain_values(struct b43_wldev *dev,
s16 max_rx_gain, int use_trsw_rx)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_g *gphy = phy->g;
u16 tmp;
if (max_rx_gain < 0)
max_rx_gain = 0;
if (has_loopback_gain(phy)) {
int trsw_rx_gain;
if (use_trsw_rx) {
trsw_rx_gain = gphy->trsw_rx_gain / 2;
if (max_rx_gain >= trsw_rx_gain) {
trsw_rx_gain = max_rx_gain - trsw_rx_gain;
}
} else
trsw_rx_gain = max_rx_gain;
if (trsw_rx_gain < 9) {
gphy->lna_lod_gain = 0;
} else {
gphy->lna_lod_gain = 1;
trsw_rx_gain -= 8;
}
trsw_rx_gain = clamp_val(trsw_rx_gain, 0, 0x2D);
gphy->pga_gain = trsw_rx_gain / 3;
if (gphy->pga_gain >= 5) {
gphy->pga_gain -= 5;
gphy->lna_gain = 2;
} else
gphy->lna_gain = 0;
} else {
gphy->lna_gain = 0;
gphy->trsw_rx_gain = 0x20;
if (max_rx_gain >= 0x14) {
gphy->lna_lod_gain = 1;
gphy->pga_gain = 2;
} else if (max_rx_gain >= 0x12) {
gphy->lna_lod_gain = 1;
gphy->pga_gain = 1;
} else if (max_rx_gain >= 0xF) {
gphy->lna_lod_gain = 1;
gphy->pga_gain = 0;
} else {
gphy->lna_lod_gain = 0;
gphy->pga_gain = 0;
}
}
tmp = b43_radio_read16(dev, 0x7A);
if (gphy->lna_lod_gain == 0)
tmp &= ~0x0008;
else
tmp |= 0x0008;
b43_radio_write16(dev, 0x7A, tmp);
}
struct lo_g_saved_values {
u8 old_channel;
/* Core registers */
u16 reg_3F4;
u16 reg_3E2;
/* PHY registers */
u16 phy_lo_mask;
u16 phy_extg_01;
u16 phy_dacctl_hwpctl;
u16 phy_dacctl;
u16 phy_cck_14;
u16 phy_hpwr_tssictl;
u16 phy_analogover;
u16 phy_analogoverval;
u16 phy_rfover;
u16 phy_rfoverval;
u16 phy_classctl;
u16 phy_cck_3E;
u16 phy_crs0;
u16 phy_pgactl;
u16 phy_cck_2A;
u16 phy_syncctl;
u16 phy_cck_30;
u16 phy_cck_06;
/* Radio registers */
u16 radio_43;
u16 radio_7A;
u16 radio_52;
};
static void lo_measure_setup(struct b43_wldev *dev,
struct lo_g_saved_values *sav)
{
struct ssb_sprom *sprom = dev->dev->bus_sprom;
struct b43_phy *phy = &dev->phy;
struct b43_phy_g *gphy = phy->g;
struct b43_txpower_lo_control *lo = gphy->lo_control;
u16 tmp;
if (b43_has_hardware_pctl(dev)) {
sav->phy_lo_mask = b43_phy_read(dev, B43_PHY_LO_MASK);
sav->phy_extg_01 = b43_phy_read(dev, B43_PHY_EXTG(0x01));
sav->phy_dacctl_hwpctl = b43_phy_read(dev, B43_PHY_DACCTL);
sav->phy_cck_14 = b43_phy_read(dev, B43_PHY_CCK(0x14));
sav->phy_hpwr_tssictl = b43_phy_read(dev, B43_PHY_HPWR_TSSICTL);
b43_phy_set(dev, B43_PHY_HPWR_TSSICTL, 0x100);
b43_phy_set(dev, B43_PHY_EXTG(0x01), 0x40);
b43_phy_set(dev, B43_PHY_DACCTL, 0x40);
b43_phy_set(dev, B43_PHY_CCK(0x14), 0x200);
}
if (phy->type == B43_PHYTYPE_B &&
phy->radio_ver == 0x2050 && phy->radio_rev < 6) {
b43_phy_write(dev, B43_PHY_CCK(0x16), 0x410);
b43_phy_write(dev, B43_PHY_CCK(0x17), 0x820);
}
if (phy->rev >= 2) {
sav->phy_analogover = b43_phy_read(dev, B43_PHY_ANALOGOVER);
sav->phy_analogoverval =
b43_phy_read(dev, B43_PHY_ANALOGOVERVAL);
sav->phy_rfover = b43_phy_read(dev, B43_PHY_RFOVER);
sav->phy_rfoverval = b43_phy_read(dev, B43_PHY_RFOVERVAL);
sav->phy_classctl = b43_phy_read(dev, B43_PHY_CLASSCTL);
sav->phy_cck_3E = b43_phy_read(dev, B43_PHY_CCK(0x3E));
sav->phy_crs0 = b43_phy_read(dev, B43_PHY_CRS0);
b43_phy_mask(dev, B43_PHY_CLASSCTL, 0xFFFC);
b43_phy_mask(dev, B43_PHY_CRS0, 0x7FFF);
b43_phy_set(dev, B43_PHY_ANALOGOVER, 0x0003);
b43_phy_mask(dev, B43_PHY_ANALOGOVERVAL, 0xFFFC);
if (phy->type == B43_PHYTYPE_G) {
if ((phy->rev >= 7) &&
(sprom->boardflags_lo & B43_BFL_EXTLNA)) {
b43_phy_write(dev, B43_PHY_RFOVER, 0x933);
} else {
b43_phy_write(dev, B43_PHY_RFOVER, 0x133);
}
} else {
b43_phy_write(dev, B43_PHY_RFOVER, 0);
}
b43_phy_write(dev, B43_PHY_CCK(0x3E), 0);
}
sav->reg_3F4 = b43_read16(dev, 0x3F4);
sav->reg_3E2 = b43_read16(dev, 0x3E2);
sav->radio_43 = b43_radio_read16(dev, 0x43);
sav->radio_7A = b43_radio_read16(dev, 0x7A);
sav->phy_pgactl = b43_phy_read(dev, B43_PHY_PGACTL);
sav->phy_cck_2A = b43_phy_read(dev, B43_PHY_CCK(0x2A));
sav->phy_syncctl = b43_phy_read(dev, B43_PHY_SYNCCTL);
sav->phy_dacctl = b43_phy_read(dev, B43_PHY_DACCTL);
if (!has_tx_magnification(phy)) {
sav->radio_52 = b43_radio_read16(dev, 0x52);
sav->radio_52 &= 0x00F0;
}
if (phy->type == B43_PHYTYPE_B) {
sav->phy_cck_30 = b43_phy_read(dev, B43_PHY_CCK(0x30));
sav->phy_cck_06 = b43_phy_read(dev, B43_PHY_CCK(0x06));
b43_phy_write(dev, B43_PHY_CCK(0x30), 0x00FF);
b43_phy_write(dev, B43_PHY_CCK(0x06), 0x3F3F);
} else {
b43_write16(dev, 0x3E2, b43_read16(dev, 0x3E2)
| 0x8000);
}
b43_write16(dev, 0x3F4, b43_read16(dev, 0x3F4)
& 0xF000);
tmp =
(phy->type == B43_PHYTYPE_G) ? B43_PHY_LO_MASK : B43_PHY_CCK(0x2E);
b43_phy_write(dev, tmp, 0x007F);
tmp = sav->phy_syncctl;
b43_phy_write(dev, B43_PHY_SYNCCTL, tmp & 0xFF7F);
tmp = sav->radio_7A;
b43_radio_write16(dev, 0x007A, tmp & 0xFFF0);
b43_phy_write(dev, B43_PHY_CCK(0x2A), 0x8A3);
if (phy->type == B43_PHYTYPE_G ||
(phy->type == B43_PHYTYPE_B &&
phy->radio_ver == 0x2050 && phy->radio_rev >= 6)) {
b43_phy_write(dev, B43_PHY_CCK(0x2B), 0x1003);
} else
b43_phy_write(dev, B43_PHY_CCK(0x2B), 0x0802);
if (phy->rev >= 2)
b43_dummy_transmission(dev, false, true);
b43_gphy_channel_switch(dev, 6, 0);
b43_radio_read16(dev, 0x51); /* dummy read */
if (phy->type == B43_PHYTYPE_G)
b43_phy_write(dev, B43_PHY_CCK(0x2F), 0);
/* Re-measure the txctl values, if needed. */
if (time_before(lo->txctl_measured_time,
jiffies - B43_LO_TXCTL_EXPIRE))
lo_measure_txctl_values(dev);
if (phy->type == B43_PHYTYPE_G && phy->rev >= 3) {
b43_phy_write(dev, B43_PHY_LO_MASK, 0xC078);
} else {
if (phy->type == B43_PHYTYPE_B)
b43_phy_write(dev, B43_PHY_CCK(0x2E), 0x8078);
else
b43_phy_write(dev, B43_PHY_LO_MASK, 0x8078);
}
}
static void lo_measure_restore(struct b43_wldev *dev,
struct lo_g_saved_values *sav)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_g *gphy = phy->g;
u16 tmp;
if (phy->rev >= 2) {
b43_phy_write(dev, B43_PHY_PGACTL, 0xE300);
tmp = (gphy->pga_gain << 8);
b43_phy_write(dev, B43_PHY_RFOVERVAL, tmp | 0xA0);
udelay(5);
b43_phy_write(dev, B43_PHY_RFOVERVAL, tmp | 0xA2);
udelay(2);
b43_phy_write(dev, B43_PHY_RFOVERVAL, tmp | 0xA3);
} else {
tmp = (gphy->pga_gain | 0xEFA0);
b43_phy_write(dev, B43_PHY_PGACTL, tmp);
}
if (phy->type == B43_PHYTYPE_G) {
if (phy->rev >= 3)
b43_phy_write(dev, B43_PHY_CCK(0x2E), 0xC078);
else
b43_phy_write(dev, B43_PHY_CCK(0x2E), 0x8078);
if (phy->rev >= 2)
b43_phy_write(dev, B43_PHY_CCK(0x2F), 0x0202);
else
b43_phy_write(dev, B43_PHY_CCK(0x2F), 0x0101);
}
b43_write16(dev, 0x3F4, sav->reg_3F4);
b43_phy_write(dev, B43_PHY_PGACTL, sav->phy_pgactl);
b43_phy_write(dev, B43_PHY_CCK(0x2A), sav->phy_cck_2A);
b43_phy_write(dev, B43_PHY_SYNCCTL, sav->phy_syncctl);
b43_phy_write(dev, B43_PHY_DACCTL, sav->phy_dacctl);
b43_radio_write16(dev, 0x43, sav->radio_43);
b43_radio_write16(dev, 0x7A, sav->radio_7A);
if (!has_tx_magnification(phy)) {
tmp = sav->radio_52;
b43_radio_maskset(dev, 0x52, 0xFF0F, tmp);
}
b43_write16(dev, 0x3E2, sav->reg_3E2);
if (phy->type == B43_PHYTYPE_B &&
phy->radio_ver == 0x2050 && phy->radio_rev <= 5) {
b43_phy_write(dev, B43_PHY_CCK(0x30), sav->phy_cck_30);
b43_phy_write(dev, B43_PHY_CCK(0x06), sav->phy_cck_06);
}
if (phy->rev >= 2) {
b43_phy_write(dev, B43_PHY_ANALOGOVER, sav->phy_analogover);
b43_phy_write(dev, B43_PHY_ANALOGOVERVAL,
sav->phy_analogoverval);
b43_phy_write(dev, B43_PHY_CLASSCTL, sav->phy_classctl);
b43_phy_write(dev, B43_PHY_RFOVER, sav->phy_rfover);
b43_phy_write(dev, B43_PHY_RFOVERVAL, sav->phy_rfoverval);
b43_phy_write(dev, B43_PHY_CCK(0x3E), sav->phy_cck_3E);
b43_phy_write(dev, B43_PHY_CRS0, sav->phy_crs0);
}
if (b43_has_hardware_pctl(dev)) {
tmp = (sav->phy_lo_mask & 0xBFFF);
b43_phy_write(dev, B43_PHY_LO_MASK, tmp);
b43_phy_write(dev, B43_PHY_EXTG(0x01), sav->phy_extg_01);
b43_phy_write(dev, B43_PHY_DACCTL, sav->phy_dacctl_hwpctl);
b43_phy_write(dev, B43_PHY_CCK(0x14), sav->phy_cck_14);
b43_phy_write(dev, B43_PHY_HPWR_TSSICTL, sav->phy_hpwr_tssictl);
}
b43_gphy_channel_switch(dev, sav->old_channel, 1);
}
struct b43_lo_g_statemachine {
int current_state;
int nr_measured;
int state_val_multiplier;
u16 lowest_feedth;
struct b43_loctl min_loctl;
};
/* Loop over each possible value in this state. */
static int lo_probe_possible_loctls(struct b43_wldev *dev,
struct b43_loctl *probe_loctl,
struct b43_lo_g_statemachine *d)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_g *gphy = phy->g;
struct b43_loctl test_loctl;
struct b43_loctl orig_loctl;
struct b43_loctl prev_loctl = {
.i = -100,
.q = -100,
};
int i;
int begin, end;
int found_lower = 0;
u16 feedth;
static const struct b43_loctl modifiers[] = {
{.i = 1,.q = 1,},
{.i = 1,.q = 0,},
{.i = 1,.q = -1,},
{.i = 0,.q = -1,},
{.i = -1,.q = -1,},
{.i = -1,.q = 0,},
{.i = -1,.q = 1,},
{.i = 0,.q = 1,},
};
if (d->current_state == 0) {
begin = 1;
end = 8;
} else if (d->current_state % 2 == 0) {
begin = d->current_state - 1;
end = d->current_state + 1;
} else {
begin = d->current_state - 2;
end = d->current_state + 2;
}
if (begin < 1)
begin += 8;
if (end > 8)
end -= 8;
memcpy(&orig_loctl, probe_loctl, sizeof(struct b43_loctl));
i = begin;
d->current_state = i;
while (1) {
B43_WARN_ON(!(i >= 1 && i <= 8));
memcpy(&test_loctl, &orig_loctl, sizeof(struct b43_loctl));
test_loctl.i += modifiers[i - 1].i * d->state_val_multiplier;
test_loctl.q += modifiers[i - 1].q * d->state_val_multiplier;
if ((test_loctl.i != prev_loctl.i ||
test_loctl.q != prev_loctl.q) &&
(abs(test_loctl.i) <= 16 && abs(test_loctl.q) <= 16)) {
b43_lo_write(dev, &test_loctl);
feedth = lo_measure_feedthrough(dev, gphy->lna_gain,
gphy->pga_gain,
gphy->trsw_rx_gain);
if (feedth < d->lowest_feedth) {
memcpy(probe_loctl, &test_loctl,
sizeof(struct b43_loctl));
found_lower = 1;
d->lowest_feedth = feedth;
if ((d->nr_measured < 2) &&
!has_loopback_gain(phy))
break;
}
}
memcpy(&prev_loctl, &test_loctl, sizeof(prev_loctl));
if (i == end)
break;
if (i == 8)
i = 1;
else
i++;
d->current_state = i;
}
return found_lower;
}
static void lo_probe_loctls_statemachine(struct b43_wldev *dev,
struct b43_loctl *loctl,
int *max_rx_gain)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_g *gphy = phy->g;
struct b43_lo_g_statemachine d;
u16 feedth;
int found_lower;
struct b43_loctl probe_loctl;
int max_repeat = 1, repeat_cnt = 0;
d.nr_measured = 0;
d.state_val_multiplier = 1;
if (has_loopback_gain(phy))
d.state_val_multiplier = 3;
memcpy(&d.min_loctl, loctl, sizeof(struct b43_loctl));
if (has_loopback_gain(phy))
max_repeat = 4;
do {
b43_lo_write(dev, &d.min_loctl);
feedth = lo_measure_feedthrough(dev, gphy->lna_gain,
gphy->pga_gain,
gphy->trsw_rx_gain);
if (feedth < 0x258) {
if (feedth >= 0x12C)
*max_rx_gain += 6;
else
*max_rx_gain += 3;
feedth = lo_measure_feedthrough(dev, gphy->lna_gain,
gphy->pga_gain,
gphy->trsw_rx_gain);
}
d.lowest_feedth = feedth;
d.current_state = 0;
do {
B43_WARN_ON(!
(d.current_state >= 0
&& d.current_state <= 8));
memcpy(&probe_loctl, &d.min_loctl,
sizeof(struct b43_loctl));
found_lower =
lo_probe_possible_loctls(dev, &probe_loctl, &d);
if (!found_lower)
break;
if ((probe_loctl.i == d.min_loctl.i) &&
(probe_loctl.q == d.min_loctl.q))
break;
memcpy(&d.min_loctl, &probe_loctl,
sizeof(struct b43_loctl));
d.nr_measured++;
} while (d.nr_measured < 24);
memcpy(loctl, &d.min_loctl, sizeof(struct b43_loctl));
if (has_loopback_gain(phy)) {
if (d.lowest_feedth > 0x1194)
*max_rx_gain -= 6;
else if (d.lowest_feedth < 0x5DC)
*max_rx_gain += 3;
if (repeat_cnt == 0) {
if (d.lowest_feedth <= 0x5DC) {
d.state_val_multiplier = 1;
repeat_cnt++;
} else
d.state_val_multiplier = 2;
} else if (repeat_cnt == 2)
d.state_val_multiplier = 1;
}
lo_measure_gain_values(dev, *max_rx_gain,
has_loopback_gain(phy));
} while (++repeat_cnt < max_repeat);
}
static
struct b43_lo_calib *b43_calibrate_lo_setting(struct b43_wldev *dev,
const struct b43_bbatt *bbatt,
const struct b43_rfatt *rfatt)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_g *gphy = phy->g;
struct b43_loctl loctl = {
.i = 0,
.q = 0,
};
int max_rx_gain;
struct b43_lo_calib *cal;
struct lo_g_saved_values uninitialized_var(saved_regs);
/* Values from the "TXCTL Register and Value Table" */
u16 txctl_reg;
u16 txctl_value;
u16 pad_mix_gain;
saved_regs.old_channel = phy->channel;
b43_mac_suspend(dev);
lo_measure_setup(dev, &saved_regs);
txctl_reg = lo_txctl_register_table(dev, &txctl_value, &pad_mix_gain);
b43_radio_maskset(dev, 0x43, 0xFFF0, rfatt->att);
b43_radio_maskset(dev, txctl_reg, ~txctl_value, (rfatt->with_padmix ? txctl_value :0));
max_rx_gain = rfatt->att * 2;
max_rx_gain += bbatt->att / 2;
if (rfatt->with_padmix)
max_rx_gain -= pad_mix_gain;
if (has_loopback_gain(phy))
max_rx_gain += gphy->max_lb_gain;
lo_measure_gain_values(dev, max_rx_gain,
has_loopback_gain(phy));
b43_gphy_set_baseband_attenuation(dev, bbatt->att);
lo_probe_loctls_statemachine(dev, &loctl, &max_rx_gain);
lo_measure_restore(dev, &saved_regs);
b43_mac_enable(dev);
if (b43_debug(dev, B43_DBG_LO)) {
b43dbg(dev->wl, "LO: Calibrated for BB(%u), RF(%u,%u) "
"=> I=%d Q=%d\n",
bbatt->att, rfatt->att, rfatt->with_padmix,
loctl.i, loctl.q);
}
cal = kmalloc(sizeof(*cal), GFP_KERNEL);
if (!cal) {
b43warn(dev->wl, "LO calib: out of memory\n");
return NULL;
}
memcpy(&cal->bbatt, bbatt, sizeof(*bbatt));
memcpy(&cal->rfatt, rfatt, sizeof(*rfatt));
memcpy(&cal->ctl, &loctl, sizeof(loctl));
cal->calib_time = jiffies;
INIT_LIST_HEAD(&cal->list);
return cal;
}
/* Get a calibrated LO setting for the given attenuation values.
* Might return a NULL pointer under OOM! */
static
struct b43_lo_calib *b43_get_calib_lo_settings(struct b43_wldev *dev,
const struct b43_bbatt *bbatt,
const struct b43_rfatt *rfatt)
{
struct b43_txpower_lo_control *lo = dev->phy.g->lo_control;
struct b43_lo_calib *c;
c = b43_find_lo_calib(lo, bbatt, rfatt);
if (c)
return c;
/* Not in the list of calibrated LO settings.
* Calibrate it now. */
c = b43_calibrate_lo_setting(dev, bbatt, rfatt);
if (!c)
return NULL;
list_add(&c->list, &lo->calib_list);
return c;
}
void b43_gphy_dc_lt_init(struct b43_wldev *dev, bool update_all)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_g *gphy = phy->g;
struct b43_txpower_lo_control *lo = gphy->lo_control;
int i;
int rf_offset, bb_offset;
const struct b43_rfatt *rfatt;
const struct b43_bbatt *bbatt;
u64 power_vector;
bool table_changed = false;
BUILD_BUG_ON(B43_DC_LT_SIZE != 32);
B43_WARN_ON(lo->rfatt_list.len * lo->bbatt_list.len > 64);
power_vector = lo->power_vector;
if (!update_all && !power_vector)
return; /* Nothing to do. */
/* Suspend the MAC now to avoid continuous suspend/enable
* cycles in the loop. */
b43_mac_suspend(dev);
for (i = 0; i < B43_DC_LT_SIZE * 2; i++) {
struct b43_lo_calib *cal;
int idx;
u16 val;
if (!update_all && !(power_vector & (((u64)1ULL) << i)))
continue;
/* Update the table entry for this power_vector bit.
* The table rows are RFatt entries and columns are BBatt. */
bb_offset = i / lo->rfatt_list.len;
rf_offset = i % lo->rfatt_list.len;
bbatt = &(lo->bbatt_list.list[bb_offset]);
rfatt = &(lo->rfatt_list.list[rf_offset]);
cal = b43_calibrate_lo_setting(dev, bbatt, rfatt);
if (!cal) {
b43warn(dev->wl, "LO: Could not "
"calibrate DC table entry\n");
continue;
}
/*FIXME: Is Q really in the low nibble? */
val = (u8)(cal->ctl.q);
val |= ((u8)(cal->ctl.i)) << 4;
kfree(cal);
/* Get the index into the hardware DC LT. */
idx = i / 2;
/* Change the table in memory. */
if (i % 2) {
/* Change the high byte. */
lo->dc_lt[idx] = (lo->dc_lt[idx] & 0x00FF)
| ((val & 0x00FF) << 8);
} else {
/* Change the low byte. */
lo->dc_lt[idx] = (lo->dc_lt[idx] & 0xFF00)
| (val & 0x00FF);
}
table_changed = true;
}
if (table_changed) {
/* The table changed in memory. Update the hardware table. */
for (i = 0; i < B43_DC_LT_SIZE; i++)
b43_phy_write(dev, 0x3A0 + i, lo->dc_lt[i]);
}
b43_mac_enable(dev);
}
/* Fixup the RF attenuation value for the case where we are
* using the PAD mixer. */
static inline void b43_lo_fixup_rfatt(struct b43_rfatt *rf)
{
if (!rf->with_padmix)
return;
if ((rf->att != 1) && (rf->att != 2) && (rf->att != 3))
rf->att = 4;
}
void b43_lo_g_adjust(struct b43_wldev *dev)
{
struct b43_phy_g *gphy = dev->phy.g;
struct b43_lo_calib *cal;
struct b43_rfatt rf;
memcpy(&rf, &gphy->rfatt, sizeof(rf));
b43_lo_fixup_rfatt(&rf);
cal = b43_get_calib_lo_settings(dev, &gphy->bbatt, &rf);
if (!cal)
return;
b43_lo_write(dev, &cal->ctl);
}
void b43_lo_g_adjust_to(struct b43_wldev *dev,
u16 rfatt, u16 bbatt, u16 tx_control)
{
struct b43_rfatt rf;
struct b43_bbatt bb;
struct b43_lo_calib *cal;
memset(&rf, 0, sizeof(rf));
memset(&bb, 0, sizeof(bb));
rf.att = rfatt;
bb.att = bbatt;
b43_lo_fixup_rfatt(&rf);
cal = b43_get_calib_lo_settings(dev, &bb, &rf);
if (!cal)
return;
b43_lo_write(dev, &cal->ctl);
}
/* Periodic LO maintanance work */
void b43_lo_g_maintanance_work(struct b43_wldev *dev)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_g *gphy = phy->g;
struct b43_txpower_lo_control *lo = gphy->lo_control;
unsigned long now;
unsigned long expire;
struct b43_lo_calib *cal, *tmp;
bool current_item_expired = false;
bool hwpctl;
if (!lo)
return;
now = jiffies;
hwpctl = b43_has_hardware_pctl(dev);
if (hwpctl) {
/* Read the power vector and update it, if needed. */
expire = now - B43_LO_PWRVEC_EXPIRE;
if (time_before(lo->pwr_vec_read_time, expire)) {
lo_read_power_vector(dev);
b43_gphy_dc_lt_init(dev, 0);
}
//FIXME Recalc the whole DC table from time to time?
}
if (hwpctl)
return;
/* Search for expired LO settings. Remove them.
* Recalibrate the current setting, if expired. */
expire = now - B43_LO_CALIB_EXPIRE;
list_for_each_entry_safe(cal, tmp, &lo->calib_list, list) {
if (!time_before(cal->calib_time, expire))
continue;
/* This item expired. */
if (b43_compare_bbatt(&cal->bbatt, &gphy->bbatt) &&
b43_compare_rfatt(&cal->rfatt, &gphy->rfatt)) {
B43_WARN_ON(current_item_expired);
current_item_expired = true;
}
if (b43_debug(dev, B43_DBG_LO)) {
b43dbg(dev->wl, "LO: Item BB(%u), RF(%u,%u), "
"I=%d, Q=%d expired\n",
cal->bbatt.att, cal->rfatt.att,
cal->rfatt.with_padmix,
cal->ctl.i, cal->ctl.q);
}
list_del(&cal->list);
kfree(cal);
}
if (current_item_expired || unlikely(list_empty(&lo->calib_list))) {
/* Recalibrate currently used LO setting. */
if (b43_debug(dev, B43_DBG_LO))
b43dbg(dev->wl, "LO: Recalibrating current LO setting\n");
cal = b43_calibrate_lo_setting(dev, &gphy->bbatt, &gphy->rfatt);
if (cal) {
list_add(&cal->list, &lo->calib_list);
b43_lo_write(dev, &cal->ctl);
} else
b43warn(dev->wl, "Failed to recalibrate current LO setting\n");
}
}
void b43_lo_g_cleanup(struct b43_wldev *dev)
{
struct b43_txpower_lo_control *lo = dev->phy.g->lo_control;
struct b43_lo_calib *cal, *tmp;
if (!lo)
return;
list_for_each_entry_safe(cal, tmp, &lo->calib_list, list) {
list_del(&cal->list);
kfree(cal);
}
}
/* LO Initialization */
void b43_lo_g_init(struct b43_wldev *dev)
{
if (b43_has_hardware_pctl(dev)) {
lo_read_power_vector(dev);
b43_gphy_dc_lt_init(dev, 1);
}
}
| gpl-2.0 |
Arakmar/android_kernel_sony_msm8660 | arch/score/mm/fault.c | 9320 | 5990 | /*
* arch/score/mm/fault.c
*
* Score Processor version.
*
* Copyright (C) 2009 Sunplus Core Technology Co., Ltd.
* Lennox Wu <lennox.wu@sunplusct.com>
* Chen Liqin <liqin.chen@sunplusct.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see the file COPYING, or write
* to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/module.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/ptrace.h>
/*
* This routine handles page faults. It determines the address,
* and the problem, and then passes it off to one of the appropriate
* routines.
*/
asmlinkage void do_page_fault(struct pt_regs *regs, unsigned long write,
unsigned long address)
{
struct vm_area_struct *vma = NULL;
struct task_struct *tsk = current;
struct mm_struct *mm = tsk->mm;
const int field = sizeof(unsigned long) * 2;
siginfo_t info;
int fault;
info.si_code = SEGV_MAPERR;
/*
* 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.
*/
if (unlikely(address >= VMALLOC_START && address <= VMALLOC_END))
goto vmalloc_fault;
#ifdef MODULE_START
if (unlikely(address >= MODULE_START && address < MODULE_END))
goto vmalloc_fault;
#endif
/*
* If we're in an interrupt or have no user
* context, we must not take the fault..
*/
if (in_atomic() || !mm)
goto bad_area_nosemaphore;
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;
/*
* Ok, we have a good vm_area for this memory access, so
* we can handle it..
*/
good_area:
info.si_code = SEGV_ACCERR;
if (write) {
if (!(vma->vm_flags & VM_WRITE))
goto bad_area;
} else {
if (!(vma->vm_flags & (VM_READ | VM_WRITE | VM_EXEC)))
goto bad_area;
}
survive:
/*
* 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);
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)
tsk->maj_flt++;
else
tsk->min_flt++;
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 (user_mode(regs)) {
tsk->thread.cp0_badvaddr = address;
tsk->thread.error_code = write;
info.si_signo = SIGSEGV;
info.si_errno = 0;
/* info.si_code has been set above */
info.si_addr = (void __user *) address;
force_sig_info(SIGSEGV, &info, tsk);
return;
}
no_context:
/* Are we prepared to handle this kernel fault? */
if (fixup_exception(regs)) {
current->thread.cp0_baduaddr = address;
return;
}
/*
* Oops. The kernel tried to access some bad page. We'll have to
* terminate things with extreme prejudice.
*/
bust_spinlocks(1);
printk(KERN_ALERT "CPU %d Unable to handle kernel paging request at "
"virtual address %0*lx, epc == %0*lx, ra == %0*lx\n",
0, field, address, field, regs->cp0_epc,
field, regs->regs[3]);
die("Oops", regs);
/*
* 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 (is_global_init(tsk)) {
yield();
down_read(&mm->mmap_sem);
goto survive;
}
printk("VM: killing process %s\n", tsk->comm);
if (user_mode(regs))
do_group_exit(SIGKILL);
goto no_context;
do_sigbus:
up_read(&mm->mmap_sem);
/* Kernel mode? Handle exceptions or die */
if (!user_mode(regs))
goto no_context;
else
/*
* Send a sigbus, regardless of whether we were in kernel
* or user mode.
*/
tsk->thread.cp0_badvaddr = address;
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRERR;
info.si_addr = (void __user *) address;
force_sig_info(SIGBUS, &info, tsk);
return;
vmalloc_fault:
{
/*
* Synchronize this task's top level page-table
* with the 'reference' page table.
*
* Do _not_ use "tsk" here. We might be inside
* an interrupt in the middle of a task switch..
*/
int offset = __pgd_offset(address);
pgd_t *pgd, *pgd_k;
pud_t *pud, *pud_k;
pmd_t *pmd, *pmd_k;
pte_t *pte_k;
pgd = (pgd_t *) pgd_current + offset;
pgd_k = init_mm.pgd + offset;
if (!pgd_present(*pgd_k))
goto no_context;
set_pgd(pgd, *pgd_k);
pud = pud_offset(pgd, address);
pud_k = pud_offset(pgd_k, address);
if (!pud_present(*pud_k))
goto no_context;
pmd = pmd_offset(pud, address);
pmd_k = pmd_offset(pud_k, address);
if (!pmd_present(*pmd_k))
goto no_context;
set_pmd(pmd, *pmd_k);
pte_k = pte_offset_kernel(pmd_k, address);
if (!pte_present(*pte_k))
goto no_context;
return;
}
}
| gpl-2.0 |
Jovy23/N900TUVUDNF9_Kernel | arch/mips/pci/ops-gt64xxx_pci0.c | 9576 | 4350 | /*
* Copyright (C) 1999, 2000, 2004 MIPS Technologies, Inc.
* All rights reserved.
* Authors: Carsten Langgaard <carstenl@mips.com>
* Maciej W. Rozycki <macro@mips.com>
*
* This program is free software; you can distribute 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 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/pci.h>
#include <linux/kernel.h>
#include <asm/gt64120.h>
#define PCI_ACCESS_READ 0
#define PCI_ACCESS_WRITE 1
/*
* PCI configuration cycle AD bus definition
*/
/* Type 0 */
#define PCI_CFG_TYPE0_REG_SHF 0
#define PCI_CFG_TYPE0_FUNC_SHF 8
/* Type 1 */
#define PCI_CFG_TYPE1_REG_SHF 0
#define PCI_CFG_TYPE1_FUNC_SHF 8
#define PCI_CFG_TYPE1_DEV_SHF 11
#define PCI_CFG_TYPE1_BUS_SHF 16
static int gt64xxx_pci0_pcibios_config_access(unsigned char access_type,
struct pci_bus *bus, unsigned int devfn, int where, u32 * data)
{
unsigned char busnum = bus->number;
u32 intr;
if ((busnum == 0) && (devfn >= PCI_DEVFN(31, 0)))
return -1; /* Because of a bug in the galileo (for slot 31). */
/* Clear cause register bits */
GT_WRITE(GT_INTRCAUSE_OFS, ~(GT_INTRCAUSE_MASABORT0_BIT |
GT_INTRCAUSE_TARABORT0_BIT));
/* Setup address */
GT_WRITE(GT_PCI0_CFGADDR_OFS,
(busnum << GT_PCI0_CFGADDR_BUSNUM_SHF) |
(devfn << GT_PCI0_CFGADDR_FUNCTNUM_SHF) |
((where / 4) << GT_PCI0_CFGADDR_REGNUM_SHF) |
GT_PCI0_CFGADDR_CONFIGEN_BIT);
if (access_type == PCI_ACCESS_WRITE) {
if (busnum == 0 && PCI_SLOT(devfn) == 0) {
/*
* The Galileo system controller is acting
* differently than other devices.
*/
GT_WRITE(GT_PCI0_CFGDATA_OFS, *data);
} else
__GT_WRITE(GT_PCI0_CFGDATA_OFS, *data);
} else {
if (busnum == 0 && PCI_SLOT(devfn) == 0) {
/*
* The Galileo system controller is acting
* differently than other devices.
*/
*data = GT_READ(GT_PCI0_CFGDATA_OFS);
} else
*data = __GT_READ(GT_PCI0_CFGDATA_OFS);
}
/* Check for master or target abort */
intr = GT_READ(GT_INTRCAUSE_OFS);
if (intr & (GT_INTRCAUSE_MASABORT0_BIT | GT_INTRCAUSE_TARABORT0_BIT)) {
/* Error occurred */
/* Clear bits */
GT_WRITE(GT_INTRCAUSE_OFS, ~(GT_INTRCAUSE_MASABORT0_BIT |
GT_INTRCAUSE_TARABORT0_BIT));
return -1;
}
return 0;
}
/*
* We can't address 8 and 16 bit words directly. Instead we have to
* read/write a 32bit word and mask/modify the data we actually want.
*/
static int gt64xxx_pci0_pcibios_read(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 * val)
{
u32 data = 0;
if (gt64xxx_pci0_pcibios_config_access(PCI_ACCESS_READ, bus, devfn,
where, &data))
return PCIBIOS_DEVICE_NOT_FOUND;
if (size == 1)
*val = (data >> ((where & 3) << 3)) & 0xff;
else if (size == 2)
*val = (data >> ((where & 3) << 3)) & 0xffff;
else
*val = data;
return PCIBIOS_SUCCESSFUL;
}
static int gt64xxx_pci0_pcibios_write(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 val)
{
u32 data = 0;
if (size == 4)
data = val;
else {
if (gt64xxx_pci0_pcibios_config_access(PCI_ACCESS_READ, bus,
devfn, where, &data))
return PCIBIOS_DEVICE_NOT_FOUND;
if (size == 1)
data = (data & ~(0xff << ((where & 3) << 3))) |
(val << ((where & 3) << 3));
else if (size == 2)
data = (data & ~(0xffff << ((where & 3) << 3))) |
(val << ((where & 3) << 3));
}
if (gt64xxx_pci0_pcibios_config_access(PCI_ACCESS_WRITE, bus, devfn,
where, &data))
return PCIBIOS_DEVICE_NOT_FOUND;
return PCIBIOS_SUCCESSFUL;
}
struct pci_ops gt64xxx_pci0_ops = {
.read = gt64xxx_pci0_pcibios_read,
.write = gt64xxx_pci0_pcibios_write
};
| gpl-2.0 |
CyanogenMod/android_kernel_cyanogen_msm8974 | sound/synth/emux/emux_proc.c | 12904 | 4566 | /*
* Copyright (C) 2000 Takashi Iwai <tiwai@suse.de>
*
* Proc interface for Emu8k/Emu10k1 WaveTable synth
*
* 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/wait.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/info.h>
#include "emux_voice.h"
#ifdef CONFIG_PROC_FS
static void
snd_emux_proc_info_read(struct snd_info_entry *entry,
struct snd_info_buffer *buf)
{
struct snd_emux *emu;
int i;
emu = entry->private_data;
mutex_lock(&emu->register_mutex);
if (emu->name)
snd_iprintf(buf, "Device: %s\n", emu->name);
snd_iprintf(buf, "Ports: %d\n", emu->num_ports);
snd_iprintf(buf, "Addresses:");
for (i = 0; i < emu->num_ports; i++)
snd_iprintf(buf, " %d:%d", emu->client, emu->ports[i]);
snd_iprintf(buf, "\n");
snd_iprintf(buf, "Use Counter: %d\n", emu->used);
snd_iprintf(buf, "Max Voices: %d\n", emu->max_voices);
snd_iprintf(buf, "Allocated Voices: %d\n", emu->num_voices);
if (emu->memhdr) {
snd_iprintf(buf, "Memory Size: %d\n", emu->memhdr->size);
snd_iprintf(buf, "Memory Available: %d\n", snd_util_mem_avail(emu->memhdr));
snd_iprintf(buf, "Allocated Blocks: %d\n", emu->memhdr->nblocks);
} else {
snd_iprintf(buf, "Memory Size: 0\n");
}
if (emu->sflist) {
mutex_lock(&emu->sflist->presets_mutex);
snd_iprintf(buf, "SoundFonts: %d\n", emu->sflist->fonts_size);
snd_iprintf(buf, "Instruments: %d\n", emu->sflist->zone_counter);
snd_iprintf(buf, "Samples: %d\n", emu->sflist->sample_counter);
snd_iprintf(buf, "Locked Instruments: %d\n", emu->sflist->zone_locked);
snd_iprintf(buf, "Locked Samples: %d\n", emu->sflist->sample_locked);
mutex_unlock(&emu->sflist->presets_mutex);
}
#if 0 /* debug */
if (emu->voices[0].state != SNDRV_EMUX_ST_OFF && emu->voices[0].ch >= 0) {
struct snd_emux_voice *vp = &emu->voices[0];
snd_iprintf(buf, "voice 0: on\n");
snd_iprintf(buf, "mod delay=%x, atkhld=%x, dcysus=%x, rel=%x\n",
vp->reg.parm.moddelay,
vp->reg.parm.modatkhld,
vp->reg.parm.moddcysus,
vp->reg.parm.modrelease);
snd_iprintf(buf, "vol delay=%x, atkhld=%x, dcysus=%x, rel=%x\n",
vp->reg.parm.voldelay,
vp->reg.parm.volatkhld,
vp->reg.parm.voldcysus,
vp->reg.parm.volrelease);
snd_iprintf(buf, "lfo1 delay=%x, lfo2 delay=%x, pefe=%x\n",
vp->reg.parm.lfo1delay,
vp->reg.parm.lfo2delay,
vp->reg.parm.pefe);
snd_iprintf(buf, "fmmod=%x, tremfrq=%x, fm2frq2=%x\n",
vp->reg.parm.fmmod,
vp->reg.parm.tremfrq,
vp->reg.parm.fm2frq2);
snd_iprintf(buf, "cutoff=%x, filterQ=%x, chorus=%x, reverb=%x\n",
vp->reg.parm.cutoff,
vp->reg.parm.filterQ,
vp->reg.parm.chorus,
vp->reg.parm.reverb);
snd_iprintf(buf, "avol=%x, acutoff=%x, apitch=%x\n",
vp->avol, vp->acutoff, vp->apitch);
snd_iprintf(buf, "apan=%x, aaux=%x, ptarget=%x, vtarget=%x, ftarget=%x\n",
vp->apan, vp->aaux,
vp->ptarget,
vp->vtarget,
vp->ftarget);
snd_iprintf(buf, "start=%x, end=%x, loopstart=%x, loopend=%x\n",
vp->reg.start, vp->reg.end, vp->reg.loopstart, vp->reg.loopend);
snd_iprintf(buf, "sample_mode=%x, rate=%x\n", vp->reg.sample_mode, vp->reg.rate_offset);
}
#endif
mutex_unlock(&emu->register_mutex);
}
void snd_emux_proc_init(struct snd_emux *emu, struct snd_card *card, int device)
{
struct snd_info_entry *entry;
char name[64];
sprintf(name, "wavetableD%d", device);
entry = snd_info_create_card_entry(card, name, card->proc_root);
if (entry == NULL)
return;
entry->content = SNDRV_INFO_CONTENT_TEXT;
entry->private_data = emu;
entry->c.text.read = snd_emux_proc_info_read;
if (snd_info_register(entry) < 0)
snd_info_free_entry(entry);
else
emu->proc = entry;
}
void snd_emux_proc_free(struct snd_emux *emu)
{
snd_info_free_entry(emu->proc);
emu->proc = NULL;
}
#endif /* CONFIG_PROC_FS */
| gpl-2.0 |
MassStash/htc_pme_kernel_sense_6.0 | drivers/usb/gadget/function/f_uac1.c | 105 | 47430 | /*
* f_audio.c -- USB Audio class function driver
*
* Copyright (c) 2012-2015, The Linux Foundation. All rights reserved.
* Copyright (C) 2008 Bryan Wu <cooloney@kernel.org>
* Copyright (C) 2008 Analog Devices, Inc
*
* Enter bugs at http://blackfin.uclinux.org/
*
* Licensed under the GPL-2 or later.
*/
#ifdef pr_fmt
#undef pr_fmt
#endif
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/atomic.h>
#include "u_uac1.h"
static int generic_set_cmd(struct usb_audio_control *con, u8 cmd, int value);
static int generic_get_cmd(struct usb_audio_control *con, u8 cmd);
#define SPEAKER_INPUT_TERMINAL_ID 3
#define SPEAKER_OUTPUT_TERMINAL_ID 4
#define MICROPHONE_INPUT_TERMINAL_ID 1
#define MICROPHONE_OUTPUT_TERMINAL_ID 2
/*
* DESCRIPTORS ... most are static, but strings and full
* configuration descriptors are built on demand.
*/
/*
* We have two interfaces- AudioControl and AudioStreaming
*/
#define F_AUDIO_AC_INTERFACE 0
#define F_AUDIO_AS_INTERFACE 1
#define F_AUDIO_NUM_INTERFACES 2
/* B.3.1 Standard AC Interface Descriptor */
static struct usb_interface_descriptor uac1_interface_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bNumEndpoints = 0,
.bInterfaceClass = USB_CLASS_AUDIO,
.bInterfaceSubClass = USB_SUBCLASS_AUDIOCONTROL,
};
DECLARE_UAC_AC_HEADER_DESCRIPTOR(2);
#define UAC_DT_AC_HEADER_LENGTH UAC_DT_AC_HEADER_SIZE(F_AUDIO_NUM_INTERFACES)
#define UAC_DT_TOTAL_LENGTH ( \
UAC_DT_AC_HEADER_LENGTH + \
UAC_DT_INPUT_TERMINAL_SIZE + \
UAC_DT_OUTPUT_TERMINAL_SIZE + \
UAC_DT_INPUT_TERMINAL_SIZE + \
UAC_DT_OUTPUT_TERMINAL_SIZE \
)
/* B.3.2 Class-Specific AC Interface Descriptor */
static struct uac1_ac_header_descriptor_2 uac1_header_desc = {
.bLength = UAC_DT_AC_HEADER_LENGTH,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_HEADER,
.bcdADC = cpu_to_le16(0x0100),
.wTotalLength = cpu_to_le16(UAC_DT_TOTAL_LENGTH),
.bInCollection = F_AUDIO_NUM_INTERFACES,
/*.baInterfaceNr = {
[0] = F_AUDIO_AC_INTERFACE,
[1] = F_AUDIO_AS_INTERFACE,
}
*/
};
static struct uac_input_terminal_descriptor speaker_input_terminal_desc = {
.bLength = UAC_DT_INPUT_TERMINAL_SIZE,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_INPUT_TERMINAL,
.bTerminalID = SPEAKER_INPUT_TERMINAL_ID,
.wTerminalType = UAC_TERMINAL_STREAMING,
.bAssocTerminal = SPEAKER_OUTPUT_TERMINAL_ID,
.wChannelConfig = 0x3,
};
static struct uac1_output_terminal_descriptor speaker_output_terminal_desc = {
.bLength = UAC_DT_OUTPUT_TERMINAL_SIZE,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_OUTPUT_TERMINAL,
.bTerminalID = SPEAKER_OUTPUT_TERMINAL_ID,
.wTerminalType = UAC_OUTPUT_TERMINAL_SPEAKER,
.bAssocTerminal = SPEAKER_INPUT_TERMINAL_ID,
.bSourceID = SPEAKER_INPUT_TERMINAL_ID,
};
static struct usb_audio_control speaker_mute_control = {
.list = LIST_HEAD_INIT(speaker_mute_control.list),
.name = "Speaker Mute Control",
.type = UAC_FU_MUTE,
/* Todo: add real Mute control code */
.set = generic_set_cmd,
.get = generic_get_cmd,
};
static struct usb_audio_control speaker_volume_control = {
.list = LIST_HEAD_INIT(speaker_volume_control.list),
.name = "Speaker Volume Control",
.type = UAC_FU_VOLUME,
/* Todo: add real Volume control code */
.set = generic_set_cmd,
.get = generic_get_cmd,
};
static struct usb_audio_control_selector speaker_fu_controls = {
.list = LIST_HEAD_INIT(speaker_fu_controls.list),
.name = "Speaker Function Unit Controls",
};
static struct uac_input_terminal_descriptor microphone_input_terminal_desc = {
.bLength = UAC_DT_INPUT_TERMINAL_SIZE,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_INPUT_TERMINAL,
.bTerminalID = MICROPHONE_INPUT_TERMINAL_ID,
.wTerminalType = UAC_INPUT_TERMINAL_MICROPHONE,
.bAssocTerminal = MICROPHONE_OUTPUT_TERMINAL_ID,
.bNrChannels = 1,
.wChannelConfig = 0x3,
};
static struct
uac1_output_terminal_descriptor microphone_output_terminal_desc = {
.bLength = UAC_DT_OUTPUT_TERMINAL_SIZE,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_OUTPUT_TERMINAL,
.bTerminalID = MICROPHONE_OUTPUT_TERMINAL_ID,
.wTerminalType = UAC_TERMINAL_STREAMING,
.bAssocTerminal = MICROPHONE_INPUT_TERMINAL_ID,
.bSourceID = MICROPHONE_INPUT_TERMINAL_ID,
};
static struct usb_audio_control microphone_mute_control = {
.list = LIST_HEAD_INIT(microphone_mute_control.list),
.name = "Microphone Mute Control",
.type = UAC_FU_MUTE,
/* Todo: add real Mute control code */
.set = generic_set_cmd,
.get = generic_get_cmd,
};
static struct usb_audio_control microphone_volume_control = {
.list = LIST_HEAD_INIT(microphone_volume_control.list),
.name = "Microphone Volume Control",
.type = UAC_FU_VOLUME,
/* Todo: add real Volume control code */
.set = generic_set_cmd,
.get = generic_get_cmd,
};
static struct usb_audio_control_selector microphone_fu_controls = {
.list = LIST_HEAD_INIT(microphone_fu_controls.list),
.name = "Microphone Feature Unit Controls",
};
/* B.4.1 Standard AS Interface Descriptor */
static struct usb_interface_descriptor speaker_as_interface_alt_0_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bAlternateSetting = 0,
.bNumEndpoints = 0,
.bInterfaceClass = USB_CLASS_AUDIO,
.bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
};
static struct usb_interface_descriptor speaker_as_interface_alt_1_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bAlternateSetting = 1,
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_AUDIO,
.bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
};
/* B.4.2 Class-Specific AS Interface Descriptor */
static struct uac1_as_header_descriptor speaker_as_header_desc = {
.bLength = UAC_DT_AS_HEADER_SIZE,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_AS_GENERAL,
.bTerminalLink = SPEAKER_INPUT_TERMINAL_ID,
.bDelay = 1,
.wFormatTag = UAC_FORMAT_TYPE_I_PCM,
};
DECLARE_UAC_FORMAT_TYPE_I_DISCRETE_DESC(1);
static struct uac_format_type_i_discrete_descriptor_1 speaker_as_type_i_desc = {
.bLength = UAC_FORMAT_TYPE_I_DISCRETE_DESC_SIZE(1),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_FORMAT_TYPE,
.bFormatType = UAC_FORMAT_TYPE_I,
.bSubframeSize = 2,
.bBitResolution = 16,
.bSamFreqType = 1,
};
/* Standard ISO OUT Endpoint Descriptor */
static struct usb_endpoint_descriptor speaker_as_ep_out_desc = {
.bLength = USB_DT_ENDPOINT_AUDIO_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_SYNC_ADAPTIVE
| USB_ENDPOINT_XFER_ISOC,
.wMaxPacketSize = cpu_to_le16(UAC1_OUT_EP_MAX_PACKET_SIZE),
.bInterval = 4,
};
static struct usb_ss_ep_comp_descriptor speaker_as_ep_out_comp_desc = {
.bLength = sizeof(speaker_as_ep_out_comp_desc),
.bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
.wBytesPerInterval = cpu_to_le16(1024),
};
/* Class-specific AS ISO OUT Endpoint Descriptor */
static struct uac_iso_endpoint_descriptor speaker_as_iso_out_desc = {
.bLength = UAC_ISO_ENDPOINT_DESC_SIZE,
.bDescriptorType = USB_DT_CS_ENDPOINT,
.bDescriptorSubtype = UAC_EP_GENERAL,
.bmAttributes = 1,
.bLockDelayUnits = 1,
.wLockDelay = cpu_to_le16(1),
};
static struct usb_audio_control speaker_sample_freq_control = {
.list = LIST_HEAD_INIT(speaker_sample_freq_control.list),
.name = "Speaker Sampling Frequency Control",
.type = UAC_EP_CS_ATTR_SAMPLE_RATE,
.set = generic_set_cmd,
.get = generic_get_cmd,
};
static struct usb_audio_control_selector speaker_as_iso_out = {
.list = LIST_HEAD_INIT(speaker_as_iso_out.list),
.name = "Speaker Iso-out Endpoint Control",
.type = UAC_EP_GENERAL,
.desc = (struct usb_descriptor_header *)&speaker_as_iso_out_desc,
};
/*---------------------------------*/
/* B.4.1 Standard AS Interface Descriptor */
static struct usb_interface_descriptor microphone_as_interface_alt_0_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bAlternateSetting = 0,
.bNumEndpoints = 0,
.bInterfaceClass = USB_CLASS_AUDIO,
.bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
};
static struct usb_interface_descriptor microphone_as_interface_alt_1_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bAlternateSetting = 1,
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_AUDIO,
.bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
};
/* B.4.2 Class-Specific AS Interface Descriptor */
static struct uac1_as_header_descriptor microphone_as_header_desc = {
.bLength = UAC_DT_AS_HEADER_SIZE,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_AS_GENERAL,
.bTerminalLink = MICROPHONE_OUTPUT_TERMINAL_ID,
.bDelay = 1,
.wFormatTag = UAC_FORMAT_TYPE_I_PCM,
};
static struct
uac_format_type_i_discrete_descriptor_1 microphone_as_type_i_desc = {
.bLength = UAC_FORMAT_TYPE_I_DISCRETE_DESC_SIZE(1),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_FORMAT_TYPE,
.bFormatType = UAC_FORMAT_TYPE_I,
.bNrChannels = 1,
.bSubframeSize = 2,
.bBitResolution = 16,
.bSamFreqType = 1,
};
/* Standard ISO IN Endpoint Descriptor */
static struct usb_endpoint_descriptor microphone_as_ep_in_desc = {
.bLength = USB_DT_ENDPOINT_AUDIO_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes =
USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ASYNC,
.wMaxPacketSize = cpu_to_le16(UAC1_IN_EP_MAX_PACKET_SIZE),
.bInterval = 4,
};
static struct usb_ss_ep_comp_descriptor microphone_as_ep_in_comp_desc = {
.bLength = sizeof(microphone_as_ep_in_comp_desc),
.bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
.wBytesPerInterval = cpu_to_le16(1024),
};
/* Class-specific AS ISO IN Endpoint Descriptor */
static struct uac_iso_endpoint_descriptor microphone_as_iso_in_desc = {
.bLength = UAC_ISO_ENDPOINT_DESC_SIZE,
.bDescriptorType = USB_DT_CS_ENDPOINT,
.bDescriptorSubtype = UAC_EP_GENERAL,
.bmAttributes = 1,
.bLockDelayUnits = 1,
.wLockDelay = cpu_to_le16(1),
};
static struct usb_audio_control microphone_sample_freq_control = {
.list = LIST_HEAD_INIT(microphone_sample_freq_control.list),
.name = "Microphone Sampling Frequency Control",
.type = UAC_EP_CS_ATTR_SAMPLE_RATE,
.set = generic_set_cmd,
.get = generic_get_cmd,
};
static struct usb_audio_control_selector microphone_as_iso_in = {
.list = LIST_HEAD_INIT(microphone_as_iso_in.list),
.name = "Microphone Iso-IN Endpoint Control",
.type = UAC_EP_GENERAL,
.desc = (struct usb_descriptor_header *)µphone_as_iso_in_desc,
};
static struct usb_interface_assoc_descriptor
audio_iad_descriptor = {
.bLength = sizeof(audio_iad_descriptor),
.bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
.bFirstInterface = 0, /* updated at bind */
.bInterfaceCount = 3,
.bFunctionClass = USB_CLASS_AUDIO,
.bFunctionSubClass = 0,
.bFunctionProtocol = UAC_VERSION_1,
};
static struct usb_descriptor_header *f_audio_desc[] = {
(struct usb_descriptor_header *)&audio_iad_descriptor,
(struct usb_descriptor_header *)&uac1_interface_desc,
(struct usb_descriptor_header *)&uac1_header_desc,
(struct usb_descriptor_header *)µphone_input_terminal_desc,
(struct usb_descriptor_header *)µphone_output_terminal_desc,
(struct usb_descriptor_header *)&speaker_input_terminal_desc,
(struct usb_descriptor_header *)&speaker_output_terminal_desc,
(struct usb_descriptor_header *)µphone_as_interface_alt_0_desc,
(struct usb_descriptor_header *)µphone_as_interface_alt_1_desc,
(struct usb_descriptor_header *)µphone_as_header_desc,
(struct usb_descriptor_header *)µphone_as_type_i_desc,
(struct usb_descriptor_header *)µphone_as_ep_in_desc,
(struct usb_descriptor_header *)µphone_as_iso_in_desc,
(struct usb_descriptor_header *)&speaker_as_interface_alt_0_desc,
(struct usb_descriptor_header *)&speaker_as_interface_alt_1_desc,
(struct usb_descriptor_header *)&speaker_as_header_desc,
(struct usb_descriptor_header *)&speaker_as_type_i_desc,
(struct usb_descriptor_header *)&speaker_as_ep_out_desc,
(struct usb_descriptor_header *)&speaker_as_iso_out_desc,
NULL,
};
static struct usb_descriptor_header *f_audio_ss_desc[] = {
(struct usb_descriptor_header *)&audio_iad_descriptor,
(struct usb_descriptor_header *)&uac1_interface_desc,
(struct usb_descriptor_header *)&uac1_header_desc,
(struct usb_descriptor_header *)µphone_input_terminal_desc,
(struct usb_descriptor_header *)µphone_output_terminal_desc,
(struct usb_descriptor_header *)&speaker_input_terminal_desc,
(struct usb_descriptor_header *)&speaker_output_terminal_desc,
(struct usb_descriptor_header *)µphone_as_interface_alt_0_desc,
(struct usb_descriptor_header *)µphone_as_interface_alt_1_desc,
(struct usb_descriptor_header *)µphone_as_header_desc,
(struct usb_descriptor_header *)µphone_as_type_i_desc,
(struct usb_descriptor_header *)µphone_as_ep_in_desc,
(struct usb_descriptor_header *)µphone_as_ep_in_comp_desc,
(struct usb_descriptor_header *)µphone_as_iso_in_desc,
(struct usb_descriptor_header *)&speaker_as_interface_alt_0_desc,
(struct usb_descriptor_header *)&speaker_as_interface_alt_1_desc,
(struct usb_descriptor_header *)&speaker_as_header_desc,
(struct usb_descriptor_header *)&speaker_as_type_i_desc,
(struct usb_descriptor_header *)&speaker_as_ep_out_desc,
(struct usb_descriptor_header *)&speaker_as_ep_out_comp_desc,
(struct usb_descriptor_header *)&speaker_as_iso_out_desc,
NULL,
};
enum {
STR_AC_IF,
STR_INPUT_TERMINAL,
STR_INPUT_TERMINAL_CH_NAMES,
STR_FEAT_DESC_0,
STR_OUTPUT_TERMINAL,
STR_AS_IF_ALT0,
STR_AS_IF_ALT1,
};
static struct usb_string strings_uac1[] = {
[STR_AC_IF].s = "AC Interface",
[STR_INPUT_TERMINAL].s = "Input terminal",
[STR_INPUT_TERMINAL_CH_NAMES].s = "Channels",
[STR_FEAT_DESC_0].s = "Volume control & mute",
[STR_OUTPUT_TERMINAL].s = "Output terminal",
[STR_AS_IF_ALT0].s = "AS Interface",
[STR_AS_IF_ALT1].s = "AS Interface",
{ },
};
static struct usb_gadget_strings str_uac1 = {
.language = 0x0409, /* en-us */
.strings = strings_uac1,
};
static struct usb_gadget_strings *uac1_strings[] = {
&str_uac1,
NULL,
};
/*
* This function is an ALSA sound card following USB Audio Class Spec 1.0.
*/
/*-------------------------------------------------------------------------*/
struct f_audio_buf {
u8 *buf;
int actual;
struct list_head list;
};
static struct f_audio_buf *f_audio_buffer_alloc(int buf_size)
{
struct f_audio_buf *copy_buf;
copy_buf = kzalloc(sizeof *copy_buf, GFP_ATOMIC);
if (!copy_buf)
return ERR_PTR(-ENOMEM);
copy_buf->buf = kzalloc(buf_size, GFP_ATOMIC);
if (!copy_buf->buf) {
kfree(copy_buf);
return ERR_PTR(-ENOMEM);
}
return copy_buf;
}
static void f_audio_buffer_free(struct f_audio_buf *audio_buf)
{
if (audio_buf) {
kfree(audio_buf->buf);
kfree(audio_buf);
}
}
/*-------------------------------------------------------------------------*/
struct f_audio {
struct gaudio card;
atomic_t online;
struct mutex mutex;
struct work_struct close_work;
/* endpoints handle full and/or high speeds */
struct usb_ep *out_ep;
struct usb_ep *in_ep;
spinlock_t playback_lock;
struct f_audio_buf *playback_copy_buf;
struct work_struct playback_work;
struct list_head play_queue;
spinlock_t capture_lock;
struct f_audio_buf *capture_copy_buf;
struct work_struct capture_work;
struct list_head capture_queue;
u8 alt_intf[F_AUDIO_NUM_INTERFACES];
/* Control Set command */
struct list_head fu_cs;
struct list_head ep_cs;
u8 set_cmd;
struct usb_audio_control *set_con;
};
static inline struct f_audio *func_to_audio(struct usb_function *f)
{
return container_of(f, struct f_audio, card.func);
}
/*-------------------------------------------------------------------------*/
static void f_audio_playback_work(struct work_struct *data)
{
struct f_audio *audio = container_of(data, struct f_audio,
playback_work);
struct f_audio_buf *play_buf;
struct f_uac1_opts *opts = container_of(audio->card.func.fi,
struct f_uac1_opts, func_inst);
int audio_playback_buf_size = opts->audio_playback_buf_size;
unsigned long flags;
int res = 0;
pr_debug("%s: started\n", __func__);
if (!atomic_read(&audio->online)) {
pr_debug("%s offline\n", __func__);
return;
}
/* set up ASLA audio devices if not already done */
mutex_lock(&audio->mutex);
res = gaudio_setup(&audio->card);
if (res < 0) {
mutex_unlock(&audio->mutex);
return;
}
mutex_unlock(&audio->mutex);
spin_lock_irqsave(&audio->playback_lock, flags);
if (list_empty(&audio->play_queue)) {
pr_err("playback_buf is empty");
spin_unlock_irqrestore(&audio->playback_lock, flags);
return;
}
play_buf = list_first_entry(&audio->play_queue,
struct f_audio_buf, list);
list_del(&play_buf->list);
spin_unlock_irqrestore(&audio->playback_lock, flags);
pr_debug("play_buf->actual = %d", play_buf->actual);
res = u_audio_playback(&audio->card, play_buf->buf,
audio_playback_buf_size);
if (res)
pr_err("copying failed");
f_audio_buffer_free(play_buf);
pr_debug("%s: Done\n", __func__);
}
static int
f_audio_playback_ep_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_audio *audio = req->context;
struct usb_composite_dev *cdev = audio->card.func.config->cdev;
struct f_audio_buf *copy_buf = audio->playback_copy_buf;
struct f_uac1_opts *opts;
int audio_playback_buf_size;
unsigned long flags;
int err;
opts = container_of(audio->card.func.fi, struct f_uac1_opts,
func_inst);
audio_playback_buf_size = opts->audio_playback_buf_size;
if (!copy_buf)
return -EINVAL;
/* Copy buffer is full, add it to the play_queue */
if (audio_playback_buf_size - copy_buf->actual < req->actual) {
pr_debug("audio_playback_buf_size %d - copy_buf->actual %d, req->actual %d",
audio_playback_buf_size, copy_buf->actual, req->actual);
spin_lock_irqsave(&audio->playback_lock, flags);
if (!list_empty(&audio->play_queue) &&
opts->audio_playback_realtime) {
pr_debug("over-runs, audio write slow.. drop the packet\n");
f_audio_buffer_free(copy_buf);
} else {
list_add_tail(©_buf->list, &audio->play_queue);
}
spin_unlock_irqrestore(&audio->playback_lock, flags);
schedule_work(&audio->playback_work);
copy_buf = f_audio_buffer_alloc(audio_playback_buf_size);
if (IS_ERR(copy_buf)) {
pr_err("Failed to allocate playback_copy_buf");
return -ENOMEM;
}
}
pr_debug("Playback %d bytes", req->actual);
memcpy(copy_buf->buf + copy_buf->actual, req->buf, req->actual);
copy_buf->actual += req->actual;
audio->playback_copy_buf = copy_buf;
err = usb_ep_queue(ep, req, GFP_ATOMIC);
if (err)
ERROR(cdev, "%s queue req: %d\n", ep->name, err);
return err;
}
static void f_audio_capture_work(struct work_struct *data)
{
struct f_audio *audio =
container_of(data, struct f_audio, capture_work);
struct f_audio_buf *capture_buf;
struct f_uac1_opts *opts = container_of(audio->card.func.fi,
struct f_uac1_opts, func_inst);
int audio_capture_buf_size = opts->audio_capture_buf_size;
unsigned long flags;
int res = 0;
pr_debug("%s Started\n", __func__);
if (!atomic_read(&audio->online)) {
pr_debug("%s offline\n", __func__);
return;
}
/* set up ASLA audio devices if not already done */
mutex_lock(&audio->mutex);
res = gaudio_setup(&audio->card);
if (res < 0) {
mutex_unlock(&audio->mutex);
return;
}
mutex_unlock(&audio->mutex);
spin_lock_irqsave(&audio->capture_lock, flags);
if (!list_empty(&audio->capture_queue)) {
spin_unlock_irqrestore(&audio->capture_lock, flags);
pr_debug("%s !! buffer already filled\n", __func__);
return;
}
spin_unlock_irqrestore(&audio->capture_lock, flags);
capture_buf = f_audio_buffer_alloc(audio_capture_buf_size);
if (capture_buf <= 0) {
pr_err("%s: buffer alloc failed\n", __func__);
return;
}
res = u_audio_capture(&audio->card, capture_buf->buf,
audio_capture_buf_size);
if (res)
pr_err("copying failed");
pr_debug("Queue capture packet: size %d", audio_capture_buf_size);
spin_lock_irqsave(&audio->capture_lock, flags);
list_add_tail(&capture_buf->list, &audio->capture_queue);
spin_unlock_irqrestore(&audio->capture_lock, flags);
}
static int
f_audio_capture_ep_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_audio *audio = req->context;
struct f_audio_buf *copy_buf = audio->capture_copy_buf;
struct f_uac1_opts *opts = container_of(audio->card.func.fi,
struct f_uac1_opts, func_inst);
int audio_capture_buf_size = opts->audio_capture_buf_size;
unsigned long flags;
int err = 0;
if (copy_buf == 0) {
pr_debug("copy_buf == 0");
spin_lock_irqsave(&audio->capture_lock, flags);
if (list_empty(&audio->capture_queue)) {
spin_unlock_irqrestore(&audio->capture_lock, flags);
pr_debug("%s no data from Audio to send\n", __func__);
schedule_work(&audio->capture_work);
memset(req->buf, 0, opts->req_capture_buf_size);
goto done;
}
copy_buf = list_first_entry(&audio->capture_queue,
struct f_audio_buf, list);
list_del(©_buf->list);
if (list_empty(&audio->capture_queue))
schedule_work(&audio->capture_work);
audio->capture_copy_buf = copy_buf;
spin_unlock_irqrestore(&audio->capture_lock, flags);
}
pr_debug("Copy %d bytes", req->actual);
memcpy(req->buf, copy_buf->buf + copy_buf->actual, req->actual);
copy_buf->actual += req->actual;
if (audio_capture_buf_size - copy_buf->actual < req->actual) {
f_audio_buffer_free(copy_buf);
audio->capture_copy_buf = 0;
schedule_work(&audio->capture_work);
}
done:
err = usb_ep_queue(ep, req, GFP_ATOMIC);
if (err)
pr_err("Failed to queue %s req: err - %d\n", ep->name, err);
return err;
}
static void f_audio_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_audio *audio = req->context;
int status = req->status;
u32 data = 0;
switch (status) {
case 0: /* normal completion? */
if (ep == audio->out_ep) {
f_audio_playback_ep_complete(ep, req);
} else if (ep == audio->in_ep) {
f_audio_capture_ep_complete(ep, req);
} else if (audio->set_con) {
memcpy(&data, req->buf, req->length);
audio->set_con->set(audio->set_con, audio->set_cmd,
le16_to_cpu(data));
audio->set_con = NULL;
}
break;
default:
pr_err("Failed completion: status %d", status);
/* fall through to to free buffer and req */
case -ECONNRESET:
case -ESHUTDOWN:
kfree(req->buf);
usb_ep_free_request(ep, req);
break;
}
}
static int audio_set_intf_req(struct usb_function *f,
const struct usb_ctrlrequest *ctrl)
{
struct f_audio *audio = func_to_audio(f);
struct usb_composite_dev *cdev = f->config->cdev;
struct usb_request *req = cdev->req;
u8 id = ((le16_to_cpu(ctrl->wIndex) >> 8) & 0xFF);
u16 len = le16_to_cpu(ctrl->wLength);
u16 w_value = le16_to_cpu(ctrl->wValue);
u8 con_sel = (w_value >> 8) & 0xFF;
u8 cmd = (ctrl->bRequest & 0x0F);
struct usb_audio_control_selector *cs;
struct usb_audio_control *con;
DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, entity %d\n",
ctrl->bRequest, w_value, len, id);
list_for_each_entry(cs, &audio->fu_cs, list) {
if (cs->id == id) {
list_for_each_entry(con, &cs->control, list) {
if (con->type == con_sel) {
audio->set_con = con;
break;
}
}
break;
}
}
audio->set_cmd = cmd;
req->context = audio;
req->complete = f_audio_complete;
return len;
}
static int audio_get_intf_req(struct usb_function *f,
const struct usb_ctrlrequest *ctrl)
{
struct f_audio *audio = func_to_audio(f);
struct usb_composite_dev *cdev = f->config->cdev;
struct usb_request *req = cdev->req;
int value = -EOPNOTSUPP;
u8 id = ((le16_to_cpu(ctrl->wIndex) >> 8) & 0xFF);
u16 len = le16_to_cpu(ctrl->wLength);
u16 w_value = le16_to_cpu(ctrl->wValue);
u8 con_sel = (w_value >> 8) & 0xFF;
u8 cmd = (ctrl->bRequest & 0x0F);
struct usb_audio_control_selector *cs;
struct usb_audio_control *con;
DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, entity %d\n",
ctrl->bRequest, w_value, len, id);
list_for_each_entry(cs, &audio->fu_cs, list) {
if (cs->id == id) {
list_for_each_entry(con, &cs->control, list) {
if (con->type == con_sel && con->get) {
value = con->get(con, cmd);
break;
}
}
break;
}
}
req->context = audio;
req->complete = f_audio_complete;
len = min_t(size_t, sizeof(value), len);
memcpy(req->buf, &value, len);
return len;
}
static void audio_set_endpoint_complete(struct usb_ep *ep,
struct usb_request *req)
{
struct f_audio *audio = req->context;
u32 data = 0;
if (req->status == 0 && audio->set_con) {
memcpy(&data, req->buf, req->length);
audio->set_con->set(audio->set_con, audio->set_cmd,
le32_to_cpu(data));
audio->set_con = NULL;
}
}
static int audio_set_endpoint_req(struct usb_function *f,
const struct usb_ctrlrequest *ctrl)
{
struct usb_composite_dev *cdev = f->config->cdev;
int value = -EOPNOTSUPP;
u16 ep = le16_to_cpu(ctrl->wIndex);
u16 len = le16_to_cpu(ctrl->wLength);
u16 w_value = le16_to_cpu(ctrl->wValue);
struct f_audio *audio = func_to_audio(f);
struct usb_request *req = cdev->req;
struct usb_audio_control_selector *cs;
struct usb_audio_control *con;
u8 epnum = ep & ~0x80;
u8 con_sel = (w_value >> 8) & 0xFF;
u8 cmd = (ctrl->bRequest & 0x0F);
DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, endp %d, epnum %d\n",
ctrl->bRequest, w_value, len, ep, epnum);
list_for_each_entry(cs, &audio->ep_cs, list) {
if (cs->id != epnum)
continue;
list_for_each_entry(con, &cs->control, list) {
if (con->type != con_sel)
continue;
switch (cmd) {
case UAC__CUR:
case UAC__MIN:
case UAC__MAX:
case UAC__RES:
audio->set_con = con;
audio->set_cmd = cmd;
req->context = audio;
req->complete = audio_set_endpoint_complete;
value = len;
break;
case UAC__MEM:
break;
default:
pr_err("Unknown command");
break;
}
break;
}
break;
}
return value;
}
static int audio_get_endpoint_req(struct usb_function *f,
const struct usb_ctrlrequest *ctrl)
{
struct f_audio *audio = func_to_audio(f);
struct usb_composite_dev *cdev = f->config->cdev;
struct usb_request *req = cdev->req;
struct usb_audio_control_selector *cs;
struct usb_audio_control *con;
int data;
int value = -EOPNOTSUPP;
u8 ep = (le16_to_cpu(ctrl->wIndex) & 0x7F);
u8 epnum = ep & ~0x80;
u16 len = le16_to_cpu(ctrl->wLength);
u16 w_value = le16_to_cpu(ctrl->wValue);
u8 con_sel = (w_value >> 8) & 0xFF;
u8 cmd = (ctrl->bRequest & 0x0F);
DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, endpoint %d\n",
ctrl->bRequest, w_value, len, ep);
list_for_each_entry(cs, &audio->ep_cs, list) {
if (cs->id != epnum)
continue;
list_for_each_entry(con, &cs->control, list) {
if (con->type != con_sel)
continue;
switch (cmd) {
case UAC__CUR:
case UAC__MIN:
case UAC__MAX:
case UAC__RES:
data = cpu_to_le32(generic_get_cmd(con, cmd));
memcpy(req->buf, &data, len);
value = len;
break;
case UAC__MEM:
break;
default:
break;
}
break;
}
break;
}
return value;
}
static int
f_audio_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
{
struct usb_composite_dev *cdev = f->config->cdev;
struct usb_request *req = cdev->req;
int value = -EOPNOTSUPP;
u16 w_index = le16_to_cpu(ctrl->wIndex);
u16 w_value = le16_to_cpu(ctrl->wValue);
u16 w_length = le16_to_cpu(ctrl->wLength);
/* composite driver infrastructure handles everything; interface
* activation uses set_alt().
*/
switch (ctrl->bRequestType) {
case USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE:
pr_debug("USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE");
value = audio_set_intf_req(f, ctrl);
break;
case USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE:
pr_debug("USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE");
value = audio_get_intf_req(f, ctrl);
break;
case USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
pr_debug("USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT");
value = audio_set_endpoint_req(f, ctrl);
break;
case USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
pr_debug("USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT");
value = audio_get_endpoint_req(f, ctrl);
break;
default:
ERROR(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
}
/* respond with data transfer or status phase? */
if (value >= 0) {
DBG(cdev, "audio req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
req->zero = 1;
req->length = value;
value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
if (value < 0)
ERROR(cdev, "audio response on err %d\n", value);
}
/* device either stalls (value < 0) or reports success */
return value;
}
static int f_audio_get_alt(struct usb_function *f, unsigned intf)
{
struct f_audio *audio = func_to_audio(f);
if (intf == uac1_header_desc.baInterfaceNr[0])
return audio->alt_intf[0];
if (intf == uac1_header_desc.baInterfaceNr[1])
return audio->alt_intf[1];
return 0;
}
static int f_audio_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct f_audio *audio = func_to_audio(f);
struct usb_composite_dev *cdev = f->config->cdev;
struct usb_ep *out_ep = audio->out_ep;
struct usb_ep *in_ep = audio->in_ep;
struct usb_request *req;
unsigned long flags;
struct f_uac1_opts *opts;
int req_playback_buf_size, req_playback_count, audio_playback_buf_size;
int req_capture_buf_size, req_capture_count;
int i = 0, err = 0;
DBG(cdev, "intf %d, alt %d\n", intf, alt);
opts = container_of(f->fi, struct f_uac1_opts, func_inst);
req_playback_buf_size = opts->req_playback_buf_size;
req_capture_buf_size = opts->req_capture_buf_size;
req_playback_count = opts->req_playback_count;
req_capture_count = opts->req_capture_count;
audio_playback_buf_size = opts->audio_playback_buf_size;
atomic_set(&audio->online, 1);
if (intf == uac1_header_desc.baInterfaceNr[0]) {
if (audio->alt_intf[0] == alt) {
pr_debug("Alt interface is already set to %d. Do nothing.\n",
alt);
return 0;
}
if (alt == 1) {
err = config_ep_by_speed(cdev->gadget, f, in_ep);
if (err)
return err;
err = usb_ep_enable(in_ep);
if (err) {
pr_err("Failed to enable capture ep");
return err;
}
in_ep->driver_data = audio;
audio->capture_copy_buf = 0;
schedule_work(&audio->capture_work);
for (i = 0; i < req_capture_count && err == 0; i++) {
/* Allocate a write buffer */
req = usb_ep_alloc_request(in_ep, GFP_ATOMIC);
if (!req) {
pr_err("request allocation failed\n");
return -ENOMEM;
}
req->buf = kzalloc(req_capture_buf_size +
cdev->gadget->extra_buf_alloc,
GFP_ATOMIC);
if (!req->buf)
return -ENOMEM;
req->length = req_capture_buf_size;
req->context = audio;
req->complete = f_audio_complete;
err = usb_ep_queue(in_ep, req, GFP_ATOMIC);
if (err)
pr_err("Failed to queue %s req,err%d\n",
in_ep->name, err);
}
} else {
struct f_audio_buf *capture_buf;
usb_ep_disable(in_ep);
spin_lock_irqsave(&audio->capture_lock, flags);
while (!list_empty(&audio->capture_queue)) {
capture_buf =
list_first_entry(
&audio->capture_queue,
struct f_audio_buf,
list);
list_del(&capture_buf->list);
f_audio_buffer_free(capture_buf);
}
spin_unlock_irqrestore(&audio->capture_lock, flags);
}
audio->alt_intf[0] = alt;
} else if (intf == uac1_header_desc.baInterfaceNr[1]) {
if (audio->alt_intf[1] == alt) {
pr_debug("Alt interface is already set to %d. Do nothing.\n",
alt);
return 0;
}
if (alt == 1) {
err = config_ep_by_speed(cdev->gadget, f, out_ep);
if (err)
return err;
err = usb_ep_enable(out_ep);
if (err) {
pr_err("Failed to enable playback ep");
return err;
}
out_ep->driver_data = audio;
audio->playback_copy_buf =
f_audio_buffer_alloc(audio_playback_buf_size);
if (IS_ERR(audio->playback_copy_buf)) {
pr_err("Failed to allocate playback_copy_buf");
return -ENOMEM;
}
/*
* allocate a bunch of read buffers
* and queue them all at once.
*/
for (i = 0; i < req_playback_count && err == 0; i++) {
req = usb_ep_alloc_request(out_ep, GFP_ATOMIC);
if (!req) {
pr_err("request allocation failed\n");
return -ENOMEM;
}
req->buf = kzalloc(req_playback_buf_size,
GFP_ATOMIC);
if (!req->buf) {
pr_err("request buffer allocation failed\n");
return -ENOMEM;
}
req->length = req_playback_buf_size;
req->context = audio;
req->complete = f_audio_complete;
err = usb_ep_queue(out_ep, req, GFP_ATOMIC);
if (err)
pr_err("Failed to queue %s queue req: err %d\n",
out_ep->name, err);
}
pr_debug("Allocated %d requests\n", req_playback_count);
} else {
struct f_audio_buf *playback_copy_buf =
audio->playback_copy_buf;
usb_ep_disable(out_ep);
if (playback_copy_buf) {
pr_err("Schedule playback_work");
list_add_tail(&playback_copy_buf->list,
&audio->play_queue);
schedule_work(&audio->playback_work);
audio->playback_copy_buf = NULL;
} else {
pr_err("playback_buf is empty. Stop.");
}
}
audio->alt_intf[1] = alt;
} else {
pr_err("Interface %d. Do nothing. Return %d\n", intf, err);
}
return err;
}
static void f_audio_close_work(struct work_struct *data)
{
struct f_audio *audio =
container_of(data, struct f_audio, close_work);
pr_debug("close audio files\n");
mutex_lock(&audio->mutex);
gaudio_cleanup(&audio->card);
mutex_unlock(&audio->mutex);
}
static void f_audio_disable(struct usb_function *f)
{
struct f_audio *audio = func_to_audio(f);
struct usb_ep *out_ep = audio->out_ep;
struct usb_ep *in_ep = audio->in_ep;
pr_debug("Disable audio");
atomic_set(&audio->online, 0);
usb_ep_disable(in_ep);
usb_ep_disable(out_ep);
u_audio_clear(&audio->card);
schedule_work(&audio->close_work);
return;
}
/*-------------------------------------------------------------------------*/
static void f_audio_build_desc(struct f_audio *audio)
{
struct gaudio *card = &audio->card;
u8 *sam_freq;
int rate;
/* Set channel numbers */
speaker_input_terminal_desc.bNrChannels =
u_audio_get_playback_channels(card);
speaker_as_type_i_desc.bNrChannels =
u_audio_get_playback_channels(card);
microphone_input_terminal_desc.bNrChannels =
u_audio_get_capture_channels(card);
microphone_as_type_i_desc.bNrChannels =
u_audio_get_capture_channels(card);
/* Set sample rates */
rate = u_audio_get_playback_rate(card);
sam_freq = speaker_as_type_i_desc.tSamFreq[0];
memcpy(sam_freq, &rate, 3);
/* Update maxP as per sample rate, bInterval assumed as 1msec */
speaker_as_ep_out_desc.wMaxPacketSize = (rate / 1000) * 2;
rate = u_audio_get_capture_rate(card);
sam_freq = microphone_as_type_i_desc.tSamFreq[0];
memcpy(sam_freq, &rate, 3);
/* Update maxP as per sample rate, bInterval assumed as 1msec */
microphone_as_ep_in_desc.wMaxPacketSize = (rate / 1000) * 2;
/* Todo: Set Sample bits and other parameters */
return;
}
/* audio function driver setup/binding */
static int
f_audio_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct f_audio *audio = func_to_audio(f);
struct usb_string *us;
int status;
struct usb_ep *ep = NULL;
u8 epaddr;
struct f_uac1_opts *audio_opts;
audio_opts = container_of(f->fi, struct f_uac1_opts, func_inst);
audio->card.gadget = c->cdev->gadget;
audio_opts->card = &audio->card;
/* set up ASLA audio devices */
if (!audio_opts->bound) {
status = gaudio_setup(&audio->card);
if (status < 0)
goto fail;
audio_opts->bound = true;
}
us = usb_gstrings_attach(cdev, uac1_strings, ARRAY_SIZE(strings_uac1));
if (IS_ERR(us)) {
status = PTR_ERR(us);
goto fail;
}
uac1_interface_desc.iInterface = us[STR_AC_IF].id;
speaker_input_terminal_desc.iTerminal = us[STR_INPUT_TERMINAL].id;
speaker_input_terminal_desc.iChannelNames =
us[STR_INPUT_TERMINAL_CH_NAMES].id;
speaker_output_terminal_desc.iTerminal = us[STR_OUTPUT_TERMINAL].id;
speaker_as_interface_alt_0_desc.iInterface = us[STR_AS_IF_ALT0].id;
speaker_as_interface_alt_1_desc.iInterface = us[STR_AS_IF_ALT1].id;
f_audio_build_desc(audio);
/* allocate instance-specific interface IDs, and patch descriptors */
status = usb_interface_id(c, f);
if (status < 0) {
pr_err("%s: failed to allocate desc interface", __func__);
goto fail;
}
uac1_interface_desc.bInterfaceNumber = status;
audio_iad_descriptor.bFirstInterface = status;
status = usb_interface_id(c, f);
if (status < 0) {
pr_err("%s: failed to allocate alt interface", __func__);
goto fail;
}
microphone_as_interface_alt_0_desc.bInterfaceNumber = status;
microphone_as_interface_alt_1_desc.bInterfaceNumber = status;
uac1_header_desc.baInterfaceNr[0] = status;
audio->alt_intf[0] = 0;
status = usb_interface_id(c, f);
if (status < 0) {
pr_err("%s: failed to allocate alt interface", __func__);
goto fail;
}
speaker_as_interface_alt_0_desc.bInterfaceNumber = status;
speaker_as_interface_alt_1_desc.bInterfaceNumber = status;
uac1_header_desc.baInterfaceNr[1] = status;
audio->alt_intf[1] = 0;
status = -ENODEV;
/* allocate instance-specific endpoints */
ep = usb_ep_autoconfig(cdev->gadget, µphone_as_ep_in_desc);
if (!ep) {
pr_err("%s: failed to autoconfig in endpoint", __func__);
goto fail;
}
audio->in_ep = ep;
ep->desc = µphone_as_ep_in_desc;
ep->driver_data = cdev;
status = -ENODEV;
ep = usb_ep_autoconfig(cdev->gadget, &speaker_as_ep_out_desc);
if (!ep) {
pr_err("%s: failed to autoconfig out endpoint", __func__);
goto fail;
}
audio->out_ep = ep;
ep->desc = &speaker_as_ep_out_desc;
ep->driver_data = cdev; /* claim */
/* associate bEndpointAddress with usb_function */
epaddr = microphone_as_ep_in_desc.bEndpointAddress & ~USB_DIR_IN;
microphone_as_iso_in.id = epaddr;
epaddr = speaker_as_ep_out_desc.bEndpointAddress & ~USB_DIR_IN;
speaker_as_iso_out.id = epaddr;
/* copy descriptors, and track endpoint copies */
status = usb_assign_descriptors(f, f_audio_desc, f_audio_desc,
f_audio_ss_desc);
if (status)
goto fail;
return 0;
fail:
gaudio_cleanup(&audio->card);
if (ep)
ep->driver_data = NULL;
return status;
}
/*-------------------------------------------------------------------------*/
static int generic_set_cmd(struct usb_audio_control *con, u8 cmd, int value)
{
con->data[cmd] = value;
return 0;
}
static int generic_get_cmd(struct usb_audio_control *con, u8 cmd)
{
return con->data[cmd];
}
/* Todo: add more control selecotor dynamically */
static int control_selector_init(struct f_audio *audio)
{
INIT_LIST_HEAD(&audio->fu_cs);
list_add(µphone_fu_controls.list, &audio->fu_cs);
list_add(&speaker_fu_controls.list, &audio->fu_cs);
INIT_LIST_HEAD(µphone_fu_controls.control);
list_add(µphone_mute_control.list,
µphone_fu_controls.control);
list_add(µphone_volume_control.list,
µphone_fu_controls.control);
INIT_LIST_HEAD(&speaker_fu_controls.control);
list_add(&speaker_mute_control.list,
&speaker_fu_controls.control);
list_add(&speaker_volume_control.list,
&speaker_fu_controls.control);
microphone_volume_control.data[UAC__CUR] = 0xffc0;
microphone_volume_control.data[UAC__MIN] = 0xe3a0;
microphone_volume_control.data[UAC__MAX] = 0xfff0;
microphone_volume_control.data[UAC__RES] = 0x0030;
speaker_volume_control.data[UAC__CUR] = 0xffc0;
speaker_volume_control.data[UAC__MIN] = 0xe3a0;
speaker_volume_control.data[UAC__MAX] = 0xfff0;
speaker_volume_control.data[UAC__RES] = 0x0030;
INIT_LIST_HEAD(&audio->ep_cs);
list_add(&speaker_as_iso_out.list, &audio->ep_cs);
list_add(µphone_as_iso_in.list, &audio->ep_cs);
INIT_LIST_HEAD(µphone_as_iso_in.control);
list_add(µphone_sample_freq_control.list,
µphone_as_iso_in.control);
INIT_LIST_HEAD(&speaker_as_iso_out.control);
list_add(&speaker_sample_freq_control.list,
&speaker_as_iso_out.control);
return 0;
}
static inline struct f_uac1_opts *to_f_uac1_opts(struct config_item *item)
{
return container_of(to_config_group(item), struct f_uac1_opts,
func_inst.group);
}
CONFIGFS_ATTR_STRUCT(f_uac1_opts);
CONFIGFS_ATTR_OPS(f_uac1_opts);
static void f_uac1_attr_release(struct config_item *item)
{
struct f_uac1_opts *opts = to_f_uac1_opts(item);
usb_put_function_instance(&opts->func_inst);
}
static struct configfs_item_operations f_uac1_item_ops = {
.release = f_uac1_attr_release,
.show_attribute = f_uac1_opts_attr_show,
.store_attribute = f_uac1_opts_attr_store,
};
#define UAC1_INT_ATTRIBUTE(name) \
static ssize_t f_uac1_opts_##name##_show(struct f_uac1_opts *opts, \
char *page) \
{ \
int result; \
\
mutex_lock(&opts->lock); \
result = sprintf(page, "%u\n", opts->name); \
mutex_unlock(&opts->lock); \
\
return result; \
} \
\
static ssize_t f_uac1_opts_##name##_store(struct f_uac1_opts *opts, \
const char *page, size_t len) \
{ \
int ret; \
u32 num; \
\
mutex_lock(&opts->lock); \
if (opts->refcnt) { \
ret = -EBUSY; \
goto end; \
} \
\
ret = kstrtou32(page, 0, &num); \
if (ret) \
goto end; \
\
opts->name = num; \
ret = len; \
\
end: \
mutex_unlock(&opts->lock); \
return ret; \
} \
\
static struct f_uac1_opts_attribute f_uac1_opts_##name = \
__CONFIGFS_ATTR(name, S_IRUGO | S_IWUSR, \
f_uac1_opts_##name##_show, \
f_uac1_opts_##name##_store)
UAC1_INT_ATTRIBUTE(req_playback_buf_size);
UAC1_INT_ATTRIBUTE(req_capture_buf_size);
UAC1_INT_ATTRIBUTE(req_playback_count);
UAC1_INT_ATTRIBUTE(req_capture_count);
UAC1_INT_ATTRIBUTE(audio_playback_buf_size);
UAC1_INT_ATTRIBUTE(audio_capture_buf_size);
UAC1_INT_ATTRIBUTE(audio_playback_realtime);
UAC1_INT_ATTRIBUTE(sample_rate);
#define UAC1_STR_ATTRIBUTE(name) \
static ssize_t f_uac1_opts_##name##_show(struct f_uac1_opts *opts, \
char *page) \
{ \
int result; \
\
mutex_lock(&opts->lock); \
result = sprintf(page, "%s\n", opts->name); \
mutex_unlock(&opts->lock); \
\
return result; \
} \
\
static ssize_t f_uac1_opts_##name##_store(struct f_uac1_opts *opts, \
const char *page, size_t len) \
{ \
int ret = -EBUSY; \
char *tmp; \
\
mutex_lock(&opts->lock); \
if (opts->refcnt) \
goto end; \
\
tmp = kstrndup(page, len, GFP_KERNEL); \
if (tmp) { \
ret = -ENOMEM; \
goto end; \
} \
if (opts->name##_alloc) \
kfree(opts->name); \
opts->name##_alloc = true; \
opts->name = tmp; \
ret = len; \
\
end: \
mutex_unlock(&opts->lock); \
return ret; \
} \
\
static struct f_uac1_opts_attribute f_uac1_opts_##name = \
__CONFIGFS_ATTR(name, S_IRUGO | S_IWUSR, \
f_uac1_opts_##name##_show, \
f_uac1_opts_##name##_store)
UAC1_STR_ATTRIBUTE(fn_play);
UAC1_STR_ATTRIBUTE(fn_cap);
UAC1_STR_ATTRIBUTE(fn_cntl);
static struct configfs_attribute *f_uac1_attrs[] = {
&f_uac1_opts_req_playback_buf_size.attr,
&f_uac1_opts_req_capture_buf_size.attr,
&f_uac1_opts_req_playback_count.attr,
&f_uac1_opts_req_capture_count.attr,
&f_uac1_opts_audio_playback_buf_size.attr,
&f_uac1_opts_audio_capture_buf_size.attr,
&f_uac1_opts_audio_playback_realtime.attr,
&f_uac1_opts_sample_rate.attr,
&f_uac1_opts_fn_play.attr,
&f_uac1_opts_fn_cap.attr,
&f_uac1_opts_fn_cntl.attr,
NULL,
};
static struct config_item_type f_uac1_func_type = {
.ct_item_ops = &f_uac1_item_ops,
.ct_attrs = f_uac1_attrs,
.ct_owner = THIS_MODULE,
};
static void f_audio_free_inst(struct usb_function_instance *f)
{
struct f_uac1_opts *opts;
opts = container_of(f, struct f_uac1_opts, func_inst);
gaudio_cleanup(opts->card);
if (opts->fn_play_alloc)
kfree(opts->fn_play);
if (opts->fn_cap_alloc)
kfree(opts->fn_cap);
if (opts->fn_cntl_alloc)
kfree(opts->fn_cntl);
kfree(opts);
}
static struct usb_function_instance *f_audio_alloc_inst(void)
{
struct f_uac1_opts *opts;
opts = kzalloc(sizeof(*opts), GFP_KERNEL);
if (!opts)
return ERR_PTR(-ENOMEM);
mutex_init(&opts->lock);
opts->func_inst.free_func_inst = f_audio_free_inst;
config_group_init_type_name(&opts->func_inst.group, "",
&f_uac1_func_type);
opts->req_playback_buf_size = UAC1_OUT_EP_MAX_PACKET_SIZE;
opts->req_capture_buf_size = UAC1_IN_EP_MAX_PACKET_SIZE;
opts->req_playback_count = UAC1_OUT_REQ_COUNT;
opts->req_capture_count = UAC1_IN_REQ_COUNT;
opts->audio_playback_buf_size = UAC1_AUDIO_PLAYBACK_BUF_SIZE;
opts->audio_capture_buf_size = UAC1_AUDIO_CAPTURE_BUF_SIZE;
opts->audio_playback_realtime = 1;
opts->sample_rate = UAC1_SAMPLE_RATE;
opts->fn_play = FILE_PCM_PLAYBACK;
opts->fn_cap = FILE_PCM_CAPTURE;
opts->fn_cntl = FILE_CONTROL;
return &opts->func_inst;
}
static void f_audio_free(struct usb_function *f)
{
struct f_audio *audio = func_to_audio(f);
struct f_uac1_opts *opts;
opts = container_of(f->fi, struct f_uac1_opts, func_inst);
kfree(audio);
mutex_lock(&opts->lock);
--opts->refcnt;
mutex_unlock(&opts->lock);
}
static void f_audio_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct f_audio *audio = func_to_audio(f);
flush_work(&audio->playback_work);
flush_work(&audio->capture_work);
flush_work(&audio->close_work);
gaudio_cleanup(&audio->card);
usb_free_all_descriptors(f);
}
static struct usb_function *f_audio_alloc(struct usb_function_instance *fi)
{
struct f_audio *audio;
struct f_uac1_opts *opts;
/* allocate and initialize one new instance */
audio = kzalloc(sizeof(*audio), GFP_KERNEL);
if (!audio)
return ERR_PTR(-ENOMEM);
audio->card.func.name = "g_audio";
opts = container_of(fi, struct f_uac1_opts, func_inst);
mutex_lock(&opts->lock);
++opts->refcnt;
mutex_unlock(&opts->lock);
INIT_LIST_HEAD(&audio->play_queue);
spin_lock_init(&audio->playback_lock);
INIT_LIST_HEAD(&audio->capture_queue);
spin_lock_init(&audio->capture_lock);
audio->card.func.bind = f_audio_bind;
audio->card.func.unbind = f_audio_unbind;
audio->card.func.get_alt = f_audio_get_alt;
audio->card.func.set_alt = f_audio_set_alt;
audio->card.func.setup = f_audio_setup;
audio->card.func.disable = f_audio_disable;
audio->card.func.free_func = f_audio_free;
control_selector_init(audio);
INIT_WORK(&audio->playback_work, f_audio_playback_work);
INIT_WORK(&audio->capture_work, f_audio_capture_work);
INIT_WORK(&audio->close_work, f_audio_close_work);
mutex_init(&audio->mutex);
return &audio->card.func;
}
DECLARE_USB_FUNCTION_INIT(uac1, f_audio_alloc_inst, f_audio_alloc);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Bryan Wu");
| gpl-2.0 |
Validus-Kernel/android_kernel_motorola_msm8226 | sound/pci/hda/hda_intel.c | 361 | 89025 | /*
*
* hda_intel.c - Implementation of primary alsa driver code base
* for Intel HD Audio.
*
* Copyright(c) 2004 Intel Corporation. All rights reserved.
*
* Copyright (c) 2004 Takashi Iwai <tiwai@suse.de>
* PeiSen Hou <pshou@realtek.com.tw>
*
* 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.
*
* CONTACTS:
*
* Matt Jared matt.jared@intel.com
* Andy Kopp andy.kopp@intel.com
* Dan Kogan dan.d.kogan@intel.com
*
* CHANGES:
*
* 2004.12.01 Major rewrite by tiwai, merged the work of pshou
*
*/
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/dma-mapping.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/mutex.h>
#include <linux/reboot.h>
#include <linux/io.h>
#ifdef CONFIG_X86
/* for snoop control */
#include <asm/pgtable.h>
#include <asm/cacheflush.h>
#endif
#include <sound/core.h>
#include <sound/initval.h>
#include "hda_codec.h"
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
static char *model[SNDRV_CARDS];
static int position_fix[SNDRV_CARDS];
static int bdl_pos_adj[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS-1)] = -1};
static int probe_mask[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS-1)] = -1};
static int probe_only[SNDRV_CARDS];
static bool single_cmd;
static int enable_msi = -1;
#ifdef CONFIG_SND_HDA_PATCH_LOADER
static char *patch[SNDRV_CARDS];
#endif
#ifdef CONFIG_SND_HDA_INPUT_BEEP
static int beep_mode[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS-1)] =
CONFIG_SND_HDA_INPUT_BEEP_MODE};
#endif
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for Intel HD audio interface.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for Intel HD audio interface.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable Intel HD audio interface.");
module_param_array(model, charp, NULL, 0444);
MODULE_PARM_DESC(model, "Use the given board model.");
module_param_array(position_fix, int, NULL, 0444);
MODULE_PARM_DESC(position_fix, "DMA pointer read method."
"(0 = auto, 1 = LPIB, 2 = POSBUF, 3 = VIACOMBO, 4 = COMBO).");
module_param_array(bdl_pos_adj, int, NULL, 0644);
MODULE_PARM_DESC(bdl_pos_adj, "BDL position adjustment offset.");
module_param_array(probe_mask, int, NULL, 0444);
MODULE_PARM_DESC(probe_mask, "Bitmask to probe codecs (default = -1).");
module_param_array(probe_only, int, NULL, 0444);
MODULE_PARM_DESC(probe_only, "Only probing and no codec initialization.");
module_param(single_cmd, bool, 0444);
MODULE_PARM_DESC(single_cmd, "Use single command to communicate with codecs "
"(for debugging only).");
module_param(enable_msi, bint, 0444);
MODULE_PARM_DESC(enable_msi, "Enable Message Signaled Interrupt (MSI)");
#ifdef CONFIG_SND_HDA_PATCH_LOADER
module_param_array(patch, charp, NULL, 0444);
MODULE_PARM_DESC(patch, "Patch file for Intel HD audio interface.");
#endif
#ifdef CONFIG_SND_HDA_INPUT_BEEP
module_param_array(beep_mode, int, NULL, 0444);
MODULE_PARM_DESC(beep_mode, "Select HDA Beep registration mode "
"(0=off, 1=on, 2=mute switch on/off) (default=1).");
#endif
#ifdef CONFIG_SND_HDA_POWER_SAVE
static int power_save = CONFIG_SND_HDA_POWER_SAVE_DEFAULT;
module_param(power_save, int, 0644);
MODULE_PARM_DESC(power_save, "Automatic power-saving timeout "
"(in second, 0 = disable).");
/* reset the HD-audio controller in power save mode.
* this may give more power-saving, but will take longer time to
* wake up.
*/
static bool power_save_controller = 1;
module_param(power_save_controller, bool, 0644);
MODULE_PARM_DESC(power_save_controller, "Reset controller in power save mode.");
#endif
static int align_buffer_size = -1;
module_param(align_buffer_size, bint, 0644);
MODULE_PARM_DESC(align_buffer_size,
"Force buffer and period sizes to be multiple of 128 bytes.");
#ifdef CONFIG_X86
static bool hda_snoop = true;
module_param_named(snoop, hda_snoop, bool, 0444);
MODULE_PARM_DESC(snoop, "Enable/disable snooping");
#define azx_snoop(chip) (chip)->snoop
#else
#define hda_snoop true
#define azx_snoop(chip) true
#endif
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Intel, ICH6},"
"{Intel, ICH6M},"
"{Intel, ICH7},"
"{Intel, ESB2},"
"{Intel, ICH8},"
"{Intel, ICH9},"
"{Intel, ICH10},"
"{Intel, PCH},"
"{Intel, CPT},"
"{Intel, PPT},"
"{Intel, LPT},"
"{Intel, PBG},"
"{Intel, SCH},"
"{ATI, SB450},"
"{ATI, SB600},"
"{ATI, RS600},"
"{ATI, RS690},"
"{ATI, RS780},"
"{ATI, R600},"
"{ATI, RV630},"
"{ATI, RV610},"
"{ATI, RV670},"
"{ATI, RV635},"
"{ATI, RV620},"
"{ATI, RV770},"
"{VIA, VT8251},"
"{VIA, VT8237A},"
"{SiS, SIS966},"
"{ULI, M5461}}");
MODULE_DESCRIPTION("Intel HDA driver");
#ifdef CONFIG_SND_VERBOSE_PRINTK
#define SFX /* nop */
#else
#define SFX "hda-intel: "
#endif
/*
* registers
*/
#define ICH6_REG_GCAP 0x00
#define ICH6_GCAP_64OK (1 << 0) /* 64bit address support */
#define ICH6_GCAP_NSDO (3 << 1) /* # of serial data out signals */
#define ICH6_GCAP_BSS (31 << 3) /* # of bidirectional streams */
#define ICH6_GCAP_ISS (15 << 8) /* # of input streams */
#define ICH6_GCAP_OSS (15 << 12) /* # of output streams */
#define ICH6_REG_VMIN 0x02
#define ICH6_REG_VMAJ 0x03
#define ICH6_REG_OUTPAY 0x04
#define ICH6_REG_INPAY 0x06
#define ICH6_REG_GCTL 0x08
#define ICH6_GCTL_RESET (1 << 0) /* controller reset */
#define ICH6_GCTL_FCNTRL (1 << 1) /* flush control */
#define ICH6_GCTL_UNSOL (1 << 8) /* accept unsol. response enable */
#define ICH6_REG_WAKEEN 0x0c
#define ICH6_REG_STATESTS 0x0e
#define ICH6_REG_GSTS 0x10
#define ICH6_GSTS_FSTS (1 << 1) /* flush status */
#define ICH6_REG_INTCTL 0x20
#define ICH6_REG_INTSTS 0x24
#define ICH6_REG_WALLCLK 0x30 /* 24Mhz source */
#define ICH6_REG_OLD_SSYNC 0x34 /* SSYNC for old ICH */
#define ICH6_REG_SSYNC 0x38
#define ICH6_REG_CORBLBASE 0x40
#define ICH6_REG_CORBUBASE 0x44
#define ICH6_REG_CORBWP 0x48
#define ICH6_REG_CORBRP 0x4a
#define ICH6_CORBRP_RST (1 << 15) /* read pointer reset */
#define ICH6_REG_CORBCTL 0x4c
#define ICH6_CORBCTL_RUN (1 << 1) /* enable DMA */
#define ICH6_CORBCTL_CMEIE (1 << 0) /* enable memory error irq */
#define ICH6_REG_CORBSTS 0x4d
#define ICH6_CORBSTS_CMEI (1 << 0) /* memory error indication */
#define ICH6_REG_CORBSIZE 0x4e
#define ICH6_REG_RIRBLBASE 0x50
#define ICH6_REG_RIRBUBASE 0x54
#define ICH6_REG_RIRBWP 0x58
#define ICH6_RIRBWP_RST (1 << 15) /* write pointer reset */
#define ICH6_REG_RINTCNT 0x5a
#define ICH6_REG_RIRBCTL 0x5c
#define ICH6_RBCTL_IRQ_EN (1 << 0) /* enable IRQ */
#define ICH6_RBCTL_DMA_EN (1 << 1) /* enable DMA */
#define ICH6_RBCTL_OVERRUN_EN (1 << 2) /* enable overrun irq */
#define ICH6_REG_RIRBSTS 0x5d
#define ICH6_RBSTS_IRQ (1 << 0) /* response irq */
#define ICH6_RBSTS_OVERRUN (1 << 2) /* overrun irq */
#define ICH6_REG_RIRBSIZE 0x5e
#define ICH6_REG_IC 0x60
#define ICH6_REG_IR 0x64
#define ICH6_REG_IRS 0x68
#define ICH6_IRS_VALID (1<<1)
#define ICH6_IRS_BUSY (1<<0)
#define ICH6_REG_DPLBASE 0x70
#define ICH6_REG_DPUBASE 0x74
#define ICH6_DPLBASE_ENABLE 0x1 /* Enable position buffer */
/* SD offset: SDI0=0x80, SDI1=0xa0, ... SDO3=0x160 */
enum { SDI0, SDI1, SDI2, SDI3, SDO0, SDO1, SDO2, SDO3 };
/* stream register offsets from stream base */
#define ICH6_REG_SD_CTL 0x00
#define ICH6_REG_SD_STS 0x03
#define ICH6_REG_SD_LPIB 0x04
#define ICH6_REG_SD_CBL 0x08
#define ICH6_REG_SD_LVI 0x0c
#define ICH6_REG_SD_FIFOW 0x0e
#define ICH6_REG_SD_FIFOSIZE 0x10
#define ICH6_REG_SD_FORMAT 0x12
#define ICH6_REG_SD_BDLPL 0x18
#define ICH6_REG_SD_BDLPU 0x1c
/* PCI space */
#define ICH6_PCIREG_TCSEL 0x44
/*
* other constants
*/
/* max number of SDs */
/* ICH, ATI and VIA have 4 playback and 4 capture */
#define ICH6_NUM_CAPTURE 4
#define ICH6_NUM_PLAYBACK 4
/* ULI has 6 playback and 5 capture */
#define ULI_NUM_CAPTURE 5
#define ULI_NUM_PLAYBACK 6
/* ATI HDMI has 1 playback and 0 capture */
#define ATIHDMI_NUM_CAPTURE 0
#define ATIHDMI_NUM_PLAYBACK 1
/* TERA has 4 playback and 3 capture */
#define TERA_NUM_CAPTURE 3
#define TERA_NUM_PLAYBACK 4
/* this number is statically defined for simplicity */
#define MAX_AZX_DEV 16
/* max number of fragments - we may use more if allocating more pages for BDL */
#define BDL_SIZE 4096
#define AZX_MAX_BDL_ENTRIES (BDL_SIZE / 16)
#define AZX_MAX_FRAG 32
/* max buffer size - no h/w limit, you can increase as you like */
#define AZX_MAX_BUF_SIZE (1024*1024*1024)
/* RIRB int mask: overrun[2], response[0] */
#define RIRB_INT_RESPONSE 0x01
#define RIRB_INT_OVERRUN 0x04
#define RIRB_INT_MASK 0x05
/* STATESTS int mask: S3,SD2,SD1,SD0 */
#define AZX_MAX_CODECS 8
#define AZX_DEFAULT_CODECS 4
#define STATESTS_INT_MASK ((1 << AZX_MAX_CODECS) - 1)
/* SD_CTL bits */
#define SD_CTL_STREAM_RESET 0x01 /* stream reset bit */
#define SD_CTL_DMA_START 0x02 /* stream DMA start bit */
#define SD_CTL_STRIPE (3 << 16) /* stripe control */
#define SD_CTL_TRAFFIC_PRIO (1 << 18) /* traffic priority */
#define SD_CTL_DIR (1 << 19) /* bi-directional stream */
#define SD_CTL_STREAM_TAG_MASK (0xf << 20)
#define SD_CTL_STREAM_TAG_SHIFT 20
/* SD_CTL and SD_STS */
#define SD_INT_DESC_ERR 0x10 /* descriptor error interrupt */
#define SD_INT_FIFO_ERR 0x08 /* FIFO error interrupt */
#define SD_INT_COMPLETE 0x04 /* completion interrupt */
#define SD_INT_MASK (SD_INT_DESC_ERR|SD_INT_FIFO_ERR|\
SD_INT_COMPLETE)
/* SD_STS */
#define SD_STS_FIFO_READY 0x20 /* FIFO ready */
/* INTCTL and INTSTS */
#define ICH6_INT_ALL_STREAM 0xff /* all stream interrupts */
#define ICH6_INT_CTRL_EN 0x40000000 /* controller interrupt enable bit */
#define ICH6_INT_GLOBAL_EN 0x80000000 /* global interrupt enable bit */
/* below are so far hardcoded - should read registers in future */
#define ICH6_MAX_CORB_ENTRIES 256
#define ICH6_MAX_RIRB_ENTRIES 256
/* position fix mode */
enum {
POS_FIX_AUTO,
POS_FIX_LPIB,
POS_FIX_POSBUF,
POS_FIX_VIACOMBO,
POS_FIX_COMBO,
};
/* Defines for ATI HD Audio support in SB450 south bridge */
#define ATI_SB450_HDAUDIO_MISC_CNTR2_ADDR 0x42
#define ATI_SB450_HDAUDIO_ENABLE_SNOOP 0x02
/* Defines for Nvidia HDA support */
#define NVIDIA_HDA_TRANSREG_ADDR 0x4e
#define NVIDIA_HDA_ENABLE_COHBITS 0x0f
#define NVIDIA_HDA_ISTRM_COH 0x4d
#define NVIDIA_HDA_OSTRM_COH 0x4c
#define NVIDIA_HDA_ENABLE_COHBIT 0x01
/* Defines for Intel SCH HDA snoop control */
#define INTEL_SCH_HDA_DEVC 0x78
#define INTEL_SCH_HDA_DEVC_NOSNOOP (0x1<<11)
/* Define IN stream 0 FIFO size offset in VIA controller */
#define VIA_IN_STREAM0_FIFO_SIZE_OFFSET 0x90
/* Define VIA HD Audio Device ID*/
#define VIA_HDAC_DEVICE_ID 0x3288
/* HD Audio class code */
#define PCI_CLASS_MULTIMEDIA_HD_AUDIO 0x0403
/*
*/
struct azx_dev {
struct snd_dma_buffer bdl; /* BDL buffer */
u32 *posbuf; /* position buffer pointer */
unsigned int bufsize; /* size of the play buffer in bytes */
unsigned int period_bytes; /* size of the period in bytes */
unsigned int frags; /* number for period in the play buffer */
unsigned int fifo_size; /* FIFO size */
unsigned long start_wallclk; /* start + minimum wallclk */
unsigned long period_wallclk; /* wallclk for period */
void __iomem *sd_addr; /* stream descriptor pointer */
u32 sd_int_sta_mask; /* stream int status mask */
/* pcm support */
struct snd_pcm_substream *substream; /* assigned substream,
* set in PCM open
*/
unsigned int format_val; /* format value to be set in the
* controller and the codec
*/
unsigned char stream_tag; /* assigned stream */
unsigned char index; /* stream index */
int assigned_key; /* last device# key assigned to */
unsigned int opened :1;
unsigned int running :1;
unsigned int irq_pending :1;
/*
* For VIA:
* A flag to ensure DMA position is 0
* when link position is not greater than FIFO size
*/
unsigned int insufficient :1;
unsigned int wc_marked:1;
};
/* CORB/RIRB */
struct azx_rb {
u32 *buf; /* CORB/RIRB buffer
* Each CORB entry is 4byte, RIRB is 8byte
*/
dma_addr_t addr; /* physical address of CORB/RIRB buffer */
/* for RIRB */
unsigned short rp, wp; /* read/write pointers */
int cmds[AZX_MAX_CODECS]; /* number of pending requests */
u32 res[AZX_MAX_CODECS]; /* last read value */
};
struct azx_pcm {
struct azx *chip;
struct snd_pcm *pcm;
struct hda_codec *codec;
struct hda_pcm_stream *hinfo[2];
struct list_head list;
};
struct azx {
struct snd_card *card;
struct pci_dev *pci;
int dev_index;
/* chip type specific */
int driver_type;
unsigned int driver_caps;
int playback_streams;
int playback_index_offset;
int capture_streams;
int capture_index_offset;
int num_streams;
/* pci resources */
unsigned long addr;
void __iomem *remap_addr;
int irq;
/* locks */
spinlock_t reg_lock;
struct mutex open_mutex;
/* streams (x num_streams) */
struct azx_dev *azx_dev;
/* PCM */
struct list_head pcm_list; /* azx_pcm list */
/* HD codec */
unsigned short codec_mask;
int codec_probe_mask; /* copied from probe_mask option */
struct hda_bus *bus;
unsigned int beep_mode;
/* CORB/RIRB */
struct azx_rb corb;
struct azx_rb rirb;
/* CORB/RIRB and position buffers */
struct snd_dma_buffer rb;
struct snd_dma_buffer posbuf;
/* flags */
int position_fix[2]; /* for both playback/capture streams */
int poll_count;
unsigned int running :1;
unsigned int initialized :1;
unsigned int single_cmd :1;
unsigned int polling_mode :1;
unsigned int msi :1;
unsigned int irq_pending_warned :1;
unsigned int probing :1; /* codec probing phase */
unsigned int snoop:1;
unsigned int align_buffer_size:1;
/* for debugging */
unsigned int last_cmd[AZX_MAX_CODECS];
/* for pending irqs */
struct work_struct irq_pending_work;
/* reboot notifier (for mysterious hangup problem at power-down) */
struct notifier_block reboot_notifier;
};
/* driver types */
enum {
AZX_DRIVER_ICH,
AZX_DRIVER_PCH,
AZX_DRIVER_SCH,
AZX_DRIVER_ATI,
AZX_DRIVER_ATIHDMI,
AZX_DRIVER_ATIHDMI_NS,
AZX_DRIVER_VIA,
AZX_DRIVER_SIS,
AZX_DRIVER_ULI,
AZX_DRIVER_NVIDIA,
AZX_DRIVER_TERA,
AZX_DRIVER_CTX,
AZX_DRIVER_GENERIC,
AZX_NUM_DRIVERS, /* keep this as last entry */
};
/* driver quirks (capabilities) */
/* bits 0-7 are used for indicating driver type */
#define AZX_DCAPS_NO_TCSEL (1 << 8) /* No Intel TCSEL bit */
#define AZX_DCAPS_NO_MSI (1 << 9) /* No MSI support */
#define AZX_DCAPS_ATI_SNOOP (1 << 10) /* ATI snoop enable */
#define AZX_DCAPS_NVIDIA_SNOOP (1 << 11) /* Nvidia snoop enable */
#define AZX_DCAPS_SCH_SNOOP (1 << 12) /* SCH/PCH snoop enable */
#define AZX_DCAPS_RIRB_DELAY (1 << 13) /* Long delay in read loop */
#define AZX_DCAPS_RIRB_PRE_DELAY (1 << 14) /* Put a delay before read */
#define AZX_DCAPS_CTX_WORKAROUND (1 << 15) /* X-Fi workaround */
#define AZX_DCAPS_POSFIX_LPIB (1 << 16) /* Use LPIB as default */
#define AZX_DCAPS_POSFIX_VIA (1 << 17) /* Use VIACOMBO as default */
#define AZX_DCAPS_NO_64BIT (1 << 18) /* No 64bit address */
#define AZX_DCAPS_SYNC_WRITE (1 << 19) /* sync each cmd write */
#define AZX_DCAPS_OLD_SSYNC (1 << 20) /* Old SSYNC reg for ICH */
#define AZX_DCAPS_BUFSIZE (1 << 21) /* no buffer size alignment */
#define AZX_DCAPS_ALIGN_BUFSIZE (1 << 22) /* buffer size alignment */
/* quirks for ATI SB / AMD Hudson */
#define AZX_DCAPS_PRESET_ATI_SB \
(AZX_DCAPS_ATI_SNOOP | AZX_DCAPS_NO_TCSEL | \
AZX_DCAPS_SYNC_WRITE | AZX_DCAPS_POSFIX_LPIB)
/* quirks for ATI/AMD HDMI */
#define AZX_DCAPS_PRESET_ATI_HDMI \
(AZX_DCAPS_NO_TCSEL | AZX_DCAPS_SYNC_WRITE | AZX_DCAPS_POSFIX_LPIB)
/* quirks for Nvidia */
#define AZX_DCAPS_PRESET_NVIDIA \
(AZX_DCAPS_NVIDIA_SNOOP | AZX_DCAPS_RIRB_DELAY | AZX_DCAPS_NO_MSI |\
AZX_DCAPS_ALIGN_BUFSIZE)
static char *driver_short_names[] __devinitdata = {
[AZX_DRIVER_ICH] = "HDA Intel",
[AZX_DRIVER_PCH] = "HDA Intel PCH",
[AZX_DRIVER_SCH] = "HDA Intel MID",
[AZX_DRIVER_ATI] = "HDA ATI SB",
[AZX_DRIVER_ATIHDMI] = "HDA ATI HDMI",
[AZX_DRIVER_ATIHDMI_NS] = "HDA ATI HDMI",
[AZX_DRIVER_VIA] = "HDA VIA VT82xx",
[AZX_DRIVER_SIS] = "HDA SIS966",
[AZX_DRIVER_ULI] = "HDA ULI M5461",
[AZX_DRIVER_NVIDIA] = "HDA NVidia",
[AZX_DRIVER_TERA] = "HDA Teradici",
[AZX_DRIVER_CTX] = "HDA Creative",
[AZX_DRIVER_GENERIC] = "HD-Audio Generic",
};
/*
* macros for easy use
*/
#define azx_writel(chip,reg,value) \
writel(value, (chip)->remap_addr + ICH6_REG_##reg)
#define azx_readl(chip,reg) \
readl((chip)->remap_addr + ICH6_REG_##reg)
#define azx_writew(chip,reg,value) \
writew(value, (chip)->remap_addr + ICH6_REG_##reg)
#define azx_readw(chip,reg) \
readw((chip)->remap_addr + ICH6_REG_##reg)
#define azx_writeb(chip,reg,value) \
writeb(value, (chip)->remap_addr + ICH6_REG_##reg)
#define azx_readb(chip,reg) \
readb((chip)->remap_addr + ICH6_REG_##reg)
#define azx_sd_writel(dev,reg,value) \
writel(value, (dev)->sd_addr + ICH6_REG_##reg)
#define azx_sd_readl(dev,reg) \
readl((dev)->sd_addr + ICH6_REG_##reg)
#define azx_sd_writew(dev,reg,value) \
writew(value, (dev)->sd_addr + ICH6_REG_##reg)
#define azx_sd_readw(dev,reg) \
readw((dev)->sd_addr + ICH6_REG_##reg)
#define azx_sd_writeb(dev,reg,value) \
writeb(value, (dev)->sd_addr + ICH6_REG_##reg)
#define azx_sd_readb(dev,reg) \
readb((dev)->sd_addr + ICH6_REG_##reg)
/* for pcm support */
#define get_azx_dev(substream) (substream->runtime->private_data)
#ifdef CONFIG_X86
static void __mark_pages_wc(struct azx *chip, struct snd_dma_buffer *dmab, bool on)
{
int pages;
if (azx_snoop(chip))
return;
if (!dmab || !dmab->area || !dmab->bytes)
return;
#ifdef CONFIG_SND_DMA_SGBUF
if (dmab->dev.type == SNDRV_DMA_TYPE_DEV_SG) {
struct snd_sg_buf *sgbuf = dmab->private_data;
if (on)
set_pages_array_wc(sgbuf->page_table, sgbuf->pages);
else
set_pages_array_wb(sgbuf->page_table, sgbuf->pages);
return;
}
#endif
pages = (dmab->bytes + PAGE_SIZE - 1) >> PAGE_SHIFT;
if (on)
set_memory_wc((unsigned long)dmab->area, pages);
else
set_memory_wb((unsigned long)dmab->area, pages);
}
static inline void mark_pages_wc(struct azx *chip, struct snd_dma_buffer *buf,
bool on)
{
__mark_pages_wc(chip, buf, on);
}
static inline void mark_runtime_wc(struct azx *chip, struct azx_dev *azx_dev,
struct snd_pcm_substream *substream, bool on)
{
if (azx_dev->wc_marked != on) {
__mark_pages_wc(chip, substream->runtime->dma_buffer_p, on);
azx_dev->wc_marked = on;
}
}
#else
/* NOP for other archs */
static inline void mark_pages_wc(struct azx *chip, struct snd_dma_buffer *buf,
bool on)
{
}
static inline void mark_runtime_wc(struct azx *chip, struct azx_dev *azx_dev,
struct snd_pcm_substream *substream, bool on)
{
}
#endif
static int azx_acquire_irq(struct azx *chip, int do_disconnect);
static int azx_send_cmd(struct hda_bus *bus, unsigned int val);
/*
* Interface for HD codec
*/
/*
* CORB / RIRB interface
*/
static int azx_alloc_cmd_io(struct azx *chip)
{
int err;
/* single page (at least 4096 bytes) must suffice for both ringbuffes */
err = snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci),
PAGE_SIZE, &chip->rb);
if (err < 0) {
snd_printk(KERN_ERR SFX "cannot allocate CORB/RIRB\n");
return err;
}
mark_pages_wc(chip, &chip->rb, true);
return 0;
}
static void azx_init_cmd_io(struct azx *chip)
{
spin_lock_irq(&chip->reg_lock);
/* CORB set up */
chip->corb.addr = chip->rb.addr;
chip->corb.buf = (u32 *)chip->rb.area;
azx_writel(chip, CORBLBASE, (u32)chip->corb.addr);
azx_writel(chip, CORBUBASE, upper_32_bits(chip->corb.addr));
/* set the corb size to 256 entries (ULI requires explicitly) */
azx_writeb(chip, CORBSIZE, 0x02);
/* set the corb write pointer to 0 */
azx_writew(chip, CORBWP, 0);
/* reset the corb hw read pointer */
azx_writew(chip, CORBRP, ICH6_CORBRP_RST);
/* enable corb dma */
azx_writeb(chip, CORBCTL, ICH6_CORBCTL_RUN);
/* RIRB set up */
chip->rirb.addr = chip->rb.addr + 2048;
chip->rirb.buf = (u32 *)(chip->rb.area + 2048);
chip->rirb.wp = chip->rirb.rp = 0;
memset(chip->rirb.cmds, 0, sizeof(chip->rirb.cmds));
azx_writel(chip, RIRBLBASE, (u32)chip->rirb.addr);
azx_writel(chip, RIRBUBASE, upper_32_bits(chip->rirb.addr));
/* set the rirb size to 256 entries (ULI requires explicitly) */
azx_writeb(chip, RIRBSIZE, 0x02);
/* reset the rirb hw write pointer */
azx_writew(chip, RIRBWP, ICH6_RIRBWP_RST);
/* set N=1, get RIRB response interrupt for new entry */
if (chip->driver_caps & AZX_DCAPS_CTX_WORKAROUND)
azx_writew(chip, RINTCNT, 0xc0);
else
azx_writew(chip, RINTCNT, 1);
/* enable rirb dma and response irq */
azx_writeb(chip, RIRBCTL, ICH6_RBCTL_DMA_EN | ICH6_RBCTL_IRQ_EN);
spin_unlock_irq(&chip->reg_lock);
}
static void azx_free_cmd_io(struct azx *chip)
{
spin_lock_irq(&chip->reg_lock);
/* disable ringbuffer DMAs */
azx_writeb(chip, RIRBCTL, 0);
azx_writeb(chip, CORBCTL, 0);
spin_unlock_irq(&chip->reg_lock);
}
static unsigned int azx_command_addr(u32 cmd)
{
unsigned int addr = cmd >> 28;
if (addr >= AZX_MAX_CODECS) {
snd_BUG();
addr = 0;
}
return addr;
}
static unsigned int azx_response_addr(u32 res)
{
unsigned int addr = res & 0xf;
if (addr >= AZX_MAX_CODECS) {
snd_BUG();
addr = 0;
}
return addr;
}
/* send a command */
static int azx_corb_send_cmd(struct hda_bus *bus, u32 val)
{
struct azx *chip = bus->private_data;
unsigned int addr = azx_command_addr(val);
unsigned int wp;
spin_lock_irq(&chip->reg_lock);
/* add command to corb */
wp = azx_readb(chip, CORBWP);
wp++;
wp %= ICH6_MAX_CORB_ENTRIES;
chip->rirb.cmds[addr]++;
chip->corb.buf[wp] = cpu_to_le32(val);
azx_writel(chip, CORBWP, wp);
spin_unlock_irq(&chip->reg_lock);
return 0;
}
#define ICH6_RIRB_EX_UNSOL_EV (1<<4)
/* retrieve RIRB entry - called from interrupt handler */
static void azx_update_rirb(struct azx *chip)
{
unsigned int rp, wp;
unsigned int addr;
u32 res, res_ex;
wp = azx_readb(chip, RIRBWP);
if (wp == chip->rirb.wp)
return;
chip->rirb.wp = wp;
while (chip->rirb.rp != wp) {
chip->rirb.rp++;
chip->rirb.rp %= ICH6_MAX_RIRB_ENTRIES;
rp = chip->rirb.rp << 1; /* an RIRB entry is 8-bytes */
res_ex = le32_to_cpu(chip->rirb.buf[rp + 1]);
res = le32_to_cpu(chip->rirb.buf[rp]);
addr = azx_response_addr(res_ex);
if (res_ex & ICH6_RIRB_EX_UNSOL_EV)
snd_hda_queue_unsol_event(chip->bus, res, res_ex);
else if (chip->rirb.cmds[addr]) {
chip->rirb.res[addr] = res;
smp_wmb();
chip->rirb.cmds[addr]--;
} else
snd_printk(KERN_ERR SFX "spurious response %#x:%#x, "
"last cmd=%#08x\n",
res, res_ex,
chip->last_cmd[addr]);
}
}
/* receive a response */
static unsigned int azx_rirb_get_response(struct hda_bus *bus,
unsigned int addr)
{
struct azx *chip = bus->private_data;
unsigned long timeout;
unsigned long loopcounter;
int do_poll = 0;
again:
timeout = jiffies + msecs_to_jiffies(1000);
for (loopcounter = 0;; loopcounter++) {
if (chip->polling_mode || do_poll) {
spin_lock_irq(&chip->reg_lock);
azx_update_rirb(chip);
spin_unlock_irq(&chip->reg_lock);
}
if (!chip->rirb.cmds[addr]) {
smp_rmb();
bus->rirb_error = 0;
if (!do_poll)
chip->poll_count = 0;
return chip->rirb.res[addr]; /* the last value */
}
if (time_after(jiffies, timeout))
break;
if (bus->needs_damn_long_delay || loopcounter > 3000)
msleep(2); /* temporary workaround */
else {
udelay(10);
cond_resched();
}
}
if (!chip->polling_mode && chip->poll_count < 2) {
snd_printdd(SFX "azx_get_response timeout, "
"polling the codec once: last cmd=0x%08x\n",
chip->last_cmd[addr]);
do_poll = 1;
chip->poll_count++;
goto again;
}
if (!chip->polling_mode) {
snd_printk(KERN_WARNING SFX "azx_get_response timeout, "
"switching to polling mode: last cmd=0x%08x\n",
chip->last_cmd[addr]);
chip->polling_mode = 1;
goto again;
}
if (chip->msi) {
snd_printk(KERN_WARNING SFX "No response from codec, "
"disabling MSI: last cmd=0x%08x\n",
chip->last_cmd[addr]);
free_irq(chip->irq, chip);
chip->irq = -1;
pci_disable_msi(chip->pci);
chip->msi = 0;
if (azx_acquire_irq(chip, 1) < 0) {
bus->rirb_error = 1;
return -1;
}
goto again;
}
if (chip->probing) {
/* If this critical timeout happens during the codec probing
* phase, this is likely an access to a non-existing codec
* slot. Better to return an error and reset the system.
*/
return -1;
}
/* a fatal communication error; need either to reset or to fallback
* to the single_cmd mode
*/
bus->rirb_error = 1;
if (bus->allow_bus_reset && !bus->response_reset && !bus->in_reset) {
bus->response_reset = 1;
return -1; /* give a chance to retry */
}
snd_printk(KERN_ERR "hda_intel: azx_get_response timeout, "
"switching to single_cmd mode: last cmd=0x%08x\n",
chip->last_cmd[addr]);
chip->single_cmd = 1;
bus->response_reset = 0;
/* release CORB/RIRB */
azx_free_cmd_io(chip);
/* disable unsolicited responses */
azx_writel(chip, GCTL, azx_readl(chip, GCTL) & ~ICH6_GCTL_UNSOL);
return -1;
}
/*
* Use the single immediate command instead of CORB/RIRB for simplicity
*
* Note: according to Intel, this is not preferred use. The command was
* intended for the BIOS only, and may get confused with unsolicited
* responses. So, we shouldn't use it for normal operation from the
* driver.
* I left the codes, however, for debugging/testing purposes.
*/
/* receive a response */
static int azx_single_wait_for_response(struct azx *chip, unsigned int addr)
{
int timeout = 50;
while (timeout--) {
/* check IRV busy bit */
if (azx_readw(chip, IRS) & ICH6_IRS_VALID) {
/* reuse rirb.res as the response return value */
chip->rirb.res[addr] = azx_readl(chip, IR);
return 0;
}
udelay(1);
}
if (printk_ratelimit())
snd_printd(SFX "get_response timeout: IRS=0x%x\n",
azx_readw(chip, IRS));
chip->rirb.res[addr] = -1;
return -EIO;
}
/* send a command */
static int azx_single_send_cmd(struct hda_bus *bus, u32 val)
{
struct azx *chip = bus->private_data;
unsigned int addr = azx_command_addr(val);
int timeout = 50;
bus->rirb_error = 0;
while (timeout--) {
/* check ICB busy bit */
if (!((azx_readw(chip, IRS) & ICH6_IRS_BUSY))) {
/* Clear IRV valid bit */
azx_writew(chip, IRS, azx_readw(chip, IRS) |
ICH6_IRS_VALID);
azx_writel(chip, IC, val);
azx_writew(chip, IRS, azx_readw(chip, IRS) |
ICH6_IRS_BUSY);
return azx_single_wait_for_response(chip, addr);
}
udelay(1);
}
if (printk_ratelimit())
snd_printd(SFX "send_cmd timeout: IRS=0x%x, val=0x%x\n",
azx_readw(chip, IRS), val);
return -EIO;
}
/* receive a response */
static unsigned int azx_single_get_response(struct hda_bus *bus,
unsigned int addr)
{
struct azx *chip = bus->private_data;
return chip->rirb.res[addr];
}
/*
* The below are the main callbacks from hda_codec.
*
* They are just the skeleton to call sub-callbacks according to the
* current setting of chip->single_cmd.
*/
/* send a command */
static int azx_send_cmd(struct hda_bus *bus, unsigned int val)
{
struct azx *chip = bus->private_data;
chip->last_cmd[azx_command_addr(val)] = val;
if (chip->single_cmd)
return azx_single_send_cmd(bus, val);
else
return azx_corb_send_cmd(bus, val);
}
/* get a response */
static unsigned int azx_get_response(struct hda_bus *bus,
unsigned int addr)
{
struct azx *chip = bus->private_data;
if (chip->single_cmd)
return azx_single_get_response(bus, addr);
else
return azx_rirb_get_response(bus, addr);
}
#ifdef CONFIG_SND_HDA_POWER_SAVE
static void azx_power_notify(struct hda_bus *bus);
#endif
/* reset codec link */
static int azx_reset(struct azx *chip, int full_reset)
{
int count;
if (!full_reset)
goto __skip;
/* clear STATESTS */
azx_writeb(chip, STATESTS, STATESTS_INT_MASK);
/* reset controller */
azx_writel(chip, GCTL, azx_readl(chip, GCTL) & ~ICH6_GCTL_RESET);
count = 50;
while (azx_readb(chip, GCTL) && --count)
msleep(1);
/* delay for >= 100us for codec PLL to settle per spec
* Rev 0.9 section 5.5.1
*/
msleep(1);
/* Bring controller out of reset */
azx_writeb(chip, GCTL, azx_readb(chip, GCTL) | ICH6_GCTL_RESET);
count = 50;
while (!azx_readb(chip, GCTL) && --count)
msleep(1);
/* Brent Chartrand said to wait >= 540us for codecs to initialize */
msleep(1);
__skip:
/* check to see if controller is ready */
if (!azx_readb(chip, GCTL)) {
snd_printd(SFX "azx_reset: controller not ready!\n");
return -EBUSY;
}
/* Accept unsolicited responses */
if (!chip->single_cmd)
azx_writel(chip, GCTL, azx_readl(chip, GCTL) |
ICH6_GCTL_UNSOL);
/* detect codecs */
if (!chip->codec_mask) {
chip->codec_mask = azx_readw(chip, STATESTS);
snd_printdd(SFX "codec_mask = 0x%x\n", chip->codec_mask);
}
return 0;
}
/*
* Lowlevel interface
*/
/* enable interrupts */
static void azx_int_enable(struct azx *chip)
{
/* enable controller CIE and GIE */
azx_writel(chip, INTCTL, azx_readl(chip, INTCTL) |
ICH6_INT_CTRL_EN | ICH6_INT_GLOBAL_EN);
}
/* disable interrupts */
static void azx_int_disable(struct azx *chip)
{
int i;
/* disable interrupts in stream descriptor */
for (i = 0; i < chip->num_streams; i++) {
struct azx_dev *azx_dev = &chip->azx_dev[i];
azx_sd_writeb(azx_dev, SD_CTL,
azx_sd_readb(azx_dev, SD_CTL) & ~SD_INT_MASK);
}
/* disable SIE for all streams */
azx_writeb(chip, INTCTL, 0);
/* disable controller CIE and GIE */
azx_writel(chip, INTCTL, azx_readl(chip, INTCTL) &
~(ICH6_INT_CTRL_EN | ICH6_INT_GLOBAL_EN));
}
/* clear interrupts */
static void azx_int_clear(struct azx *chip)
{
int i;
/* clear stream status */
for (i = 0; i < chip->num_streams; i++) {
struct azx_dev *azx_dev = &chip->azx_dev[i];
azx_sd_writeb(azx_dev, SD_STS, SD_INT_MASK);
}
/* clear STATESTS */
azx_writeb(chip, STATESTS, STATESTS_INT_MASK);
/* clear rirb status */
azx_writeb(chip, RIRBSTS, RIRB_INT_MASK);
/* clear int status */
azx_writel(chip, INTSTS, ICH6_INT_CTRL_EN | ICH6_INT_ALL_STREAM);
}
/* start a stream */
static void azx_stream_start(struct azx *chip, struct azx_dev *azx_dev)
{
/*
* Before stream start, initialize parameter
*/
azx_dev->insufficient = 1;
/* enable SIE */
azx_writel(chip, INTCTL,
azx_readl(chip, INTCTL) | (1 << azx_dev->index));
/* set DMA start and interrupt mask */
azx_sd_writeb(azx_dev, SD_CTL, azx_sd_readb(azx_dev, SD_CTL) |
SD_CTL_DMA_START | SD_INT_MASK);
}
/* stop DMA */
static void azx_stream_clear(struct azx *chip, struct azx_dev *azx_dev)
{
azx_sd_writeb(azx_dev, SD_CTL, azx_sd_readb(azx_dev, SD_CTL) &
~(SD_CTL_DMA_START | SD_INT_MASK));
azx_sd_writeb(azx_dev, SD_STS, SD_INT_MASK); /* to be sure */
}
/* stop a stream */
static void azx_stream_stop(struct azx *chip, struct azx_dev *azx_dev)
{
azx_stream_clear(chip, azx_dev);
/* disable SIE */
azx_writel(chip, INTCTL,
azx_readl(chip, INTCTL) & ~(1 << azx_dev->index));
}
/*
* reset and start the controller registers
*/
static void azx_init_chip(struct azx *chip, int full_reset)
{
if (chip->initialized)
return;
/* reset controller */
azx_reset(chip, full_reset);
/* initialize interrupts */
azx_int_clear(chip);
azx_int_enable(chip);
/* initialize the codec command I/O */
if (!chip->single_cmd)
azx_init_cmd_io(chip);
/* program the position buffer */
azx_writel(chip, DPLBASE, (u32)chip->posbuf.addr);
azx_writel(chip, DPUBASE, upper_32_bits(chip->posbuf.addr));
chip->initialized = 1;
}
/*
* initialize the PCI registers
*/
/* update bits in a PCI register byte */
static void update_pci_byte(struct pci_dev *pci, unsigned int reg,
unsigned char mask, unsigned char val)
{
unsigned char data;
pci_read_config_byte(pci, reg, &data);
data &= ~mask;
data |= (val & mask);
pci_write_config_byte(pci, reg, data);
}
static void azx_init_pci(struct azx *chip)
{
/* Clear bits 0-2 of PCI register TCSEL (at offset 0x44)
* TCSEL == Traffic Class Select Register, which sets PCI express QOS
* Ensuring these bits are 0 clears playback static on some HD Audio
* codecs.
* The PCI register TCSEL is defined in the Intel manuals.
*/
if (!(chip->driver_caps & AZX_DCAPS_NO_TCSEL)) {
snd_printdd(SFX "Clearing TCSEL\n");
update_pci_byte(chip->pci, ICH6_PCIREG_TCSEL, 0x07, 0);
}
/* For ATI SB450/600/700/800/900 and AMD Hudson azalia HD audio,
* we need to enable snoop.
*/
if (chip->driver_caps & AZX_DCAPS_ATI_SNOOP) {
snd_printdd(SFX "Setting ATI snoop: %d\n", azx_snoop(chip));
update_pci_byte(chip->pci,
ATI_SB450_HDAUDIO_MISC_CNTR2_ADDR, 0x07,
azx_snoop(chip) ? ATI_SB450_HDAUDIO_ENABLE_SNOOP : 0);
}
/* For NVIDIA HDA, enable snoop */
if (chip->driver_caps & AZX_DCAPS_NVIDIA_SNOOP) {
snd_printdd(SFX "Setting Nvidia snoop: %d\n", azx_snoop(chip));
update_pci_byte(chip->pci,
NVIDIA_HDA_TRANSREG_ADDR,
0x0f, NVIDIA_HDA_ENABLE_COHBITS);
update_pci_byte(chip->pci,
NVIDIA_HDA_ISTRM_COH,
0x01, NVIDIA_HDA_ENABLE_COHBIT);
update_pci_byte(chip->pci,
NVIDIA_HDA_OSTRM_COH,
0x01, NVIDIA_HDA_ENABLE_COHBIT);
}
/* Enable SCH/PCH snoop if needed */
if (chip->driver_caps & AZX_DCAPS_SCH_SNOOP) {
unsigned short snoop;
pci_read_config_word(chip->pci, INTEL_SCH_HDA_DEVC, &snoop);
if ((!azx_snoop(chip) && !(snoop & INTEL_SCH_HDA_DEVC_NOSNOOP)) ||
(azx_snoop(chip) && (snoop & INTEL_SCH_HDA_DEVC_NOSNOOP))) {
snoop &= ~INTEL_SCH_HDA_DEVC_NOSNOOP;
if (!azx_snoop(chip))
snoop |= INTEL_SCH_HDA_DEVC_NOSNOOP;
pci_write_config_word(chip->pci, INTEL_SCH_HDA_DEVC, snoop);
pci_read_config_word(chip->pci,
INTEL_SCH_HDA_DEVC, &snoop);
}
snd_printdd(SFX "SCH snoop: %s\n",
(snoop & INTEL_SCH_HDA_DEVC_NOSNOOP)
? "Disabled" : "Enabled");
}
}
static int azx_position_ok(struct azx *chip, struct azx_dev *azx_dev);
/*
* interrupt handler
*/
static irqreturn_t azx_interrupt(int irq, void *dev_id)
{
struct azx *chip = dev_id;
struct azx_dev *azx_dev;
u32 status;
u8 sd_status;
int i, ok;
spin_lock(&chip->reg_lock);
status = azx_readl(chip, INTSTS);
if (status == 0) {
spin_unlock(&chip->reg_lock);
return IRQ_NONE;
}
for (i = 0; i < chip->num_streams; i++) {
azx_dev = &chip->azx_dev[i];
if (status & azx_dev->sd_int_sta_mask) {
sd_status = azx_sd_readb(azx_dev, SD_STS);
azx_sd_writeb(azx_dev, SD_STS, SD_INT_MASK);
if (!azx_dev->substream || !azx_dev->running ||
!(sd_status & SD_INT_COMPLETE))
continue;
/* check whether this IRQ is really acceptable */
ok = azx_position_ok(chip, azx_dev);
if (ok == 1) {
azx_dev->irq_pending = 0;
spin_unlock(&chip->reg_lock);
snd_pcm_period_elapsed(azx_dev->substream);
spin_lock(&chip->reg_lock);
} else if (ok == 0 && chip->bus && chip->bus->workq) {
/* bogus IRQ, process it later */
azx_dev->irq_pending = 1;
queue_work(chip->bus->workq,
&chip->irq_pending_work);
}
}
}
/* clear rirb int */
status = azx_readb(chip, RIRBSTS);
if (status & RIRB_INT_MASK) {
if (status & RIRB_INT_RESPONSE) {
if (chip->driver_caps & AZX_DCAPS_RIRB_PRE_DELAY)
udelay(80);
azx_update_rirb(chip);
}
azx_writeb(chip, RIRBSTS, RIRB_INT_MASK);
}
#if 0
/* clear state status int */
if (azx_readb(chip, STATESTS) & 0x04)
azx_writeb(chip, STATESTS, 0x04);
#endif
spin_unlock(&chip->reg_lock);
return IRQ_HANDLED;
}
/*
* set up a BDL entry
*/
static int setup_bdle(struct snd_pcm_substream *substream,
struct azx_dev *azx_dev, u32 **bdlp,
int ofs, int size, int with_ioc)
{
u32 *bdl = *bdlp;
while (size > 0) {
dma_addr_t addr;
int chunk;
if (azx_dev->frags >= AZX_MAX_BDL_ENTRIES)
return -EINVAL;
addr = snd_pcm_sgbuf_get_addr(substream, ofs);
/* program the address field of the BDL entry */
bdl[0] = cpu_to_le32((u32)addr);
bdl[1] = cpu_to_le32(upper_32_bits(addr));
/* program the size field of the BDL entry */
chunk = snd_pcm_sgbuf_get_chunk_size(substream, ofs, size);
bdl[2] = cpu_to_le32(chunk);
/* program the IOC to enable interrupt
* only when the whole fragment is processed
*/
size -= chunk;
bdl[3] = (size || !with_ioc) ? 0 : cpu_to_le32(0x01);
bdl += 4;
azx_dev->frags++;
ofs += chunk;
}
*bdlp = bdl;
return ofs;
}
/*
* set up BDL entries
*/
static int azx_setup_periods(struct azx *chip,
struct snd_pcm_substream *substream,
struct azx_dev *azx_dev)
{
u32 *bdl;
int i, ofs, periods, period_bytes;
int pos_adj;
/* reset BDL address */
azx_sd_writel(azx_dev, SD_BDLPL, 0);
azx_sd_writel(azx_dev, SD_BDLPU, 0);
period_bytes = azx_dev->period_bytes;
periods = azx_dev->bufsize / period_bytes;
/* program the initial BDL entries */
bdl = (u32 *)azx_dev->bdl.area;
ofs = 0;
azx_dev->frags = 0;
pos_adj = bdl_pos_adj[chip->dev_index];
if (pos_adj > 0) {
struct snd_pcm_runtime *runtime = substream->runtime;
int pos_align = pos_adj;
pos_adj = (pos_adj * runtime->rate + 47999) / 48000;
if (!pos_adj)
pos_adj = pos_align;
else
pos_adj = ((pos_adj + pos_align - 1) / pos_align) *
pos_align;
pos_adj = frames_to_bytes(runtime, pos_adj);
if (pos_adj >= period_bytes) {
snd_printk(KERN_WARNING SFX "Too big adjustment %d\n",
bdl_pos_adj[chip->dev_index]);
pos_adj = 0;
} else {
ofs = setup_bdle(substream, azx_dev,
&bdl, ofs, pos_adj,
!substream->runtime->no_period_wakeup);
if (ofs < 0)
goto error;
}
} else
pos_adj = 0;
for (i = 0; i < periods; i++) {
if (i == periods - 1 && pos_adj)
ofs = setup_bdle(substream, azx_dev, &bdl, ofs,
period_bytes - pos_adj, 0);
else
ofs = setup_bdle(substream, azx_dev, &bdl, ofs,
period_bytes,
!substream->runtime->no_period_wakeup);
if (ofs < 0)
goto error;
}
return 0;
error:
snd_printk(KERN_ERR SFX "Too many BDL entries: buffer=%d, period=%d\n",
azx_dev->bufsize, period_bytes);
return -EINVAL;
}
/* reset stream */
static void azx_stream_reset(struct azx *chip, struct azx_dev *azx_dev)
{
unsigned char val;
int timeout;
azx_stream_clear(chip, azx_dev);
azx_sd_writeb(azx_dev, SD_CTL, azx_sd_readb(azx_dev, SD_CTL) |
SD_CTL_STREAM_RESET);
udelay(3);
timeout = 300;
while (!((val = azx_sd_readb(azx_dev, SD_CTL)) & SD_CTL_STREAM_RESET) &&
--timeout)
;
val &= ~SD_CTL_STREAM_RESET;
azx_sd_writeb(azx_dev, SD_CTL, val);
udelay(3);
timeout = 300;
/* waiting for hardware to report that the stream is out of reset */
while (((val = azx_sd_readb(azx_dev, SD_CTL)) & SD_CTL_STREAM_RESET) &&
--timeout)
;
/* reset first position - may not be synced with hw at this time */
*azx_dev->posbuf = 0;
}
/*
* set up the SD for streaming
*/
static int azx_setup_controller(struct azx *chip, struct azx_dev *azx_dev)
{
unsigned int val;
/* make sure the run bit is zero for SD */
azx_stream_clear(chip, azx_dev);
/* program the stream_tag */
val = azx_sd_readl(azx_dev, SD_CTL);
val = (val & ~SD_CTL_STREAM_TAG_MASK) |
(azx_dev->stream_tag << SD_CTL_STREAM_TAG_SHIFT);
if (!azx_snoop(chip))
val |= SD_CTL_TRAFFIC_PRIO;
azx_sd_writel(azx_dev, SD_CTL, val);
/* program the length of samples in cyclic buffer */
azx_sd_writel(azx_dev, SD_CBL, azx_dev->bufsize);
/* program the stream format */
/* this value needs to be the same as the one programmed */
azx_sd_writew(azx_dev, SD_FORMAT, azx_dev->format_val);
/* program the stream LVI (last valid index) of the BDL */
azx_sd_writew(azx_dev, SD_LVI, azx_dev->frags - 1);
/* program the BDL address */
/* lower BDL address */
azx_sd_writel(azx_dev, SD_BDLPL, (u32)azx_dev->bdl.addr);
/* upper BDL address */
azx_sd_writel(azx_dev, SD_BDLPU, upper_32_bits(azx_dev->bdl.addr));
/* enable the position buffer */
if (chip->position_fix[0] != POS_FIX_LPIB ||
chip->position_fix[1] != POS_FIX_LPIB) {
if (!(azx_readl(chip, DPLBASE) & ICH6_DPLBASE_ENABLE))
azx_writel(chip, DPLBASE,
(u32)chip->posbuf.addr | ICH6_DPLBASE_ENABLE);
}
/* set the interrupt enable bits in the descriptor control register */
azx_sd_writel(azx_dev, SD_CTL,
azx_sd_readl(azx_dev, SD_CTL) | SD_INT_MASK);
return 0;
}
/*
* Probe the given codec address
*/
static int probe_codec(struct azx *chip, int addr)
{
unsigned int cmd = (addr << 28) | (AC_NODE_ROOT << 20) |
(AC_VERB_PARAMETERS << 8) | AC_PAR_VENDOR_ID;
unsigned int res;
mutex_lock(&chip->bus->cmd_mutex);
chip->probing = 1;
azx_send_cmd(chip->bus, cmd);
res = azx_get_response(chip->bus, addr);
chip->probing = 0;
mutex_unlock(&chip->bus->cmd_mutex);
if (res == -1)
return -EIO;
snd_printdd(SFX "codec #%d probed OK\n", addr);
return 0;
}
static int azx_attach_pcm_stream(struct hda_bus *bus, struct hda_codec *codec,
struct hda_pcm *cpcm);
static void azx_stop_chip(struct azx *chip);
static void azx_bus_reset(struct hda_bus *bus)
{
struct azx *chip = bus->private_data;
bus->in_reset = 1;
azx_stop_chip(chip);
azx_init_chip(chip, 1);
#ifdef CONFIG_PM
if (chip->initialized) {
struct azx_pcm *p;
list_for_each_entry(p, &chip->pcm_list, list)
snd_pcm_suspend_all(p->pcm);
snd_hda_suspend(chip->bus);
snd_hda_resume(chip->bus);
}
#endif
bus->in_reset = 0;
}
/*
* Codec initialization
*/
/* number of codec slots for each chipset: 0 = default slots (i.e. 4) */
static unsigned int azx_max_codecs[AZX_NUM_DRIVERS] __devinitdata = {
[AZX_DRIVER_NVIDIA] = 8,
[AZX_DRIVER_TERA] = 1,
};
static int __devinit azx_codec_create(struct azx *chip, const char *model)
{
struct hda_bus_template bus_temp;
int c, codecs, err;
int max_slots;
memset(&bus_temp, 0, sizeof(bus_temp));
bus_temp.private_data = chip;
bus_temp.modelname = model;
bus_temp.pci = chip->pci;
bus_temp.ops.command = azx_send_cmd;
bus_temp.ops.get_response = azx_get_response;
bus_temp.ops.attach_pcm = azx_attach_pcm_stream;
bus_temp.ops.bus_reset = azx_bus_reset;
#ifdef CONFIG_SND_HDA_POWER_SAVE
bus_temp.power_save = &power_save;
bus_temp.ops.pm_notify = azx_power_notify;
#endif
err = snd_hda_bus_new(chip->card, &bus_temp, &chip->bus);
if (err < 0)
return err;
if (chip->driver_caps & AZX_DCAPS_RIRB_DELAY) {
snd_printd(SFX "Enable delay in RIRB handling\n");
chip->bus->needs_damn_long_delay = 1;
}
codecs = 0;
max_slots = azx_max_codecs[chip->driver_type];
if (!max_slots)
max_slots = AZX_DEFAULT_CODECS;
/* First try to probe all given codec slots */
for (c = 0; c < max_slots; c++) {
if ((chip->codec_mask & (1 << c)) & chip->codec_probe_mask) {
if (probe_codec(chip, c) < 0) {
/* Some BIOSen give you wrong codec addresses
* that don't exist
*/
snd_printk(KERN_WARNING SFX
"Codec #%d probe error; "
"disabling it...\n", c);
chip->codec_mask &= ~(1 << c);
/* More badly, accessing to a non-existing
* codec often screws up the controller chip,
* and disturbs the further communications.
* Thus if an error occurs during probing,
* better to reset the controller chip to
* get back to the sanity state.
*/
azx_stop_chip(chip);
azx_init_chip(chip, 1);
}
}
}
/* AMD chipsets often cause the communication stalls upon certain
* sequence like the pin-detection. It seems that forcing the synced
* access works around the stall. Grrr...
*/
if (chip->driver_caps & AZX_DCAPS_SYNC_WRITE) {
snd_printd(SFX "Enable sync_write for stable communication\n");
chip->bus->sync_write = 1;
chip->bus->allow_bus_reset = 1;
}
/* Then create codec instances */
for (c = 0; c < max_slots; c++) {
if ((chip->codec_mask & (1 << c)) & chip->codec_probe_mask) {
struct hda_codec *codec;
err = snd_hda_codec_new(chip->bus, c, &codec);
if (err < 0)
continue;
codec->beep_mode = chip->beep_mode;
codecs++;
}
}
if (!codecs) {
snd_printk(KERN_ERR SFX "no codecs initialized\n");
return -ENXIO;
}
return 0;
}
/* configure each codec instance */
static int __devinit azx_codec_configure(struct azx *chip)
{
struct hda_codec *codec;
list_for_each_entry(codec, &chip->bus->codec_list, list) {
snd_hda_codec_configure(codec);
}
return 0;
}
/*
* PCM support
*/
/* assign a stream for the PCM */
static inline struct azx_dev *
azx_assign_device(struct azx *chip, struct snd_pcm_substream *substream)
{
int dev, i, nums;
struct azx_dev *res = NULL;
/* make a non-zero unique key for the substream */
int key = (substream->pcm->device << 16) | (substream->number << 2) |
(substream->stream + 1);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
dev = chip->playback_index_offset;
nums = chip->playback_streams;
} else {
dev = chip->capture_index_offset;
nums = chip->capture_streams;
}
for (i = 0; i < nums; i++, dev++)
if (!chip->azx_dev[dev].opened) {
res = &chip->azx_dev[dev];
if (res->assigned_key == key)
break;
}
if (res) {
res->opened = 1;
res->assigned_key = key;
}
return res;
}
/* release the assigned stream */
static inline void azx_release_device(struct azx_dev *azx_dev)
{
azx_dev->opened = 0;
}
static struct snd_pcm_hardware azx_pcm_hw = {
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID |
/* No full-resume yet implemented */
/* SNDRV_PCM_INFO_RESUME |*/
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_SYNC_START |
SNDRV_PCM_INFO_NO_PERIOD_WAKEUP),
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_48000,
.rate_min = 48000,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = AZX_MAX_BUF_SIZE,
.period_bytes_min = 128,
.period_bytes_max = AZX_MAX_BUF_SIZE / 2,
.periods_min = 2,
.periods_max = AZX_MAX_FRAG,
.fifo_size = 0,
};
static int azx_pcm_open(struct snd_pcm_substream *substream)
{
struct azx_pcm *apcm = snd_pcm_substream_chip(substream);
struct hda_pcm_stream *hinfo = apcm->hinfo[substream->stream];
struct azx *chip = apcm->chip;
struct azx_dev *azx_dev;
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned long flags;
int err;
int buff_step;
mutex_lock(&chip->open_mutex);
azx_dev = azx_assign_device(chip, substream);
if (azx_dev == NULL) {
mutex_unlock(&chip->open_mutex);
return -EBUSY;
}
runtime->hw = azx_pcm_hw;
runtime->hw.channels_min = hinfo->channels_min;
runtime->hw.channels_max = hinfo->channels_max;
runtime->hw.formats = hinfo->formats;
runtime->hw.rates = hinfo->rates;
snd_pcm_limit_hw_rates(runtime);
snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
if (chip->align_buffer_size)
/* constrain buffer sizes to be multiple of 128
bytes. This is more efficient in terms of memory
access but isn't required by the HDA spec and
prevents users from specifying exact period/buffer
sizes. For example for 44.1kHz, a period size set
to 20ms will be rounded to 19.59ms. */
buff_step = 128;
else
/* Don't enforce steps on buffer sizes, still need to
be multiple of 4 bytes (HDA spec). Tested on Intel
HDA controllers, may not work on all devices where
option needs to be disabled */
buff_step = 4;
snd_pcm_hw_constraint_step(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_BYTES,
buff_step);
snd_pcm_hw_constraint_step(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_BYTES,
buff_step);
snd_hda_power_up(apcm->codec);
err = hinfo->ops.open(hinfo, apcm->codec, substream);
if (err < 0) {
azx_release_device(azx_dev);
snd_hda_power_down(apcm->codec);
mutex_unlock(&chip->open_mutex);
return err;
}
snd_pcm_limit_hw_rates(runtime);
/* sanity check */
if (snd_BUG_ON(!runtime->hw.channels_min) ||
snd_BUG_ON(!runtime->hw.channels_max) ||
snd_BUG_ON(!runtime->hw.formats) ||
snd_BUG_ON(!runtime->hw.rates)) {
azx_release_device(azx_dev);
hinfo->ops.close(hinfo, apcm->codec, substream);
snd_hda_power_down(apcm->codec);
mutex_unlock(&chip->open_mutex);
return -EINVAL;
}
spin_lock_irqsave(&chip->reg_lock, flags);
azx_dev->substream = substream;
azx_dev->running = 0;
spin_unlock_irqrestore(&chip->reg_lock, flags);
runtime->private_data = azx_dev;
snd_pcm_set_sync(substream);
mutex_unlock(&chip->open_mutex);
return 0;
}
static int azx_pcm_close(struct snd_pcm_substream *substream)
{
struct azx_pcm *apcm = snd_pcm_substream_chip(substream);
struct hda_pcm_stream *hinfo = apcm->hinfo[substream->stream];
struct azx *chip = apcm->chip;
struct azx_dev *azx_dev = get_azx_dev(substream);
unsigned long flags;
mutex_lock(&chip->open_mutex);
spin_lock_irqsave(&chip->reg_lock, flags);
azx_dev->substream = NULL;
azx_dev->running = 0;
spin_unlock_irqrestore(&chip->reg_lock, flags);
azx_release_device(azx_dev);
hinfo->ops.close(hinfo, apcm->codec, substream);
snd_hda_power_down(apcm->codec);
mutex_unlock(&chip->open_mutex);
return 0;
}
static int azx_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct azx_pcm *apcm = snd_pcm_substream_chip(substream);
struct azx *chip = apcm->chip;
struct azx_dev *azx_dev = get_azx_dev(substream);
int ret;
mark_runtime_wc(chip, azx_dev, substream, false);
azx_dev->bufsize = 0;
azx_dev->period_bytes = 0;
azx_dev->format_val = 0;
ret = snd_pcm_lib_malloc_pages(substream,
params_buffer_bytes(hw_params));
if (ret < 0)
return ret;
mark_runtime_wc(chip, azx_dev, substream, true);
return ret;
}
static int azx_pcm_hw_free(struct snd_pcm_substream *substream)
{
struct azx_pcm *apcm = snd_pcm_substream_chip(substream);
struct azx_dev *azx_dev = get_azx_dev(substream);
struct azx *chip = apcm->chip;
struct hda_pcm_stream *hinfo = apcm->hinfo[substream->stream];
/* reset BDL address */
azx_sd_writel(azx_dev, SD_BDLPL, 0);
azx_sd_writel(azx_dev, SD_BDLPU, 0);
azx_sd_writel(azx_dev, SD_CTL, 0);
azx_dev->bufsize = 0;
azx_dev->period_bytes = 0;
azx_dev->format_val = 0;
snd_hda_codec_cleanup(apcm->codec, hinfo, substream);
mark_runtime_wc(chip, azx_dev, substream, false);
return snd_pcm_lib_free_pages(substream);
}
static int azx_pcm_prepare(struct snd_pcm_substream *substream)
{
struct azx_pcm *apcm = snd_pcm_substream_chip(substream);
struct azx *chip = apcm->chip;
struct azx_dev *azx_dev = get_azx_dev(substream);
struct hda_pcm_stream *hinfo = apcm->hinfo[substream->stream];
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned int bufsize, period_bytes, format_val, stream_tag;
int err;
struct hda_spdif_out *spdif =
snd_hda_spdif_out_of_nid(apcm->codec, hinfo->nid);
unsigned short ctls = spdif ? spdif->ctls : 0;
azx_stream_reset(chip, azx_dev);
format_val = snd_hda_calc_stream_format(runtime->rate,
runtime->channels,
runtime->format,
hinfo->maxbps,
ctls);
if (!format_val) {
snd_printk(KERN_ERR SFX
"invalid format_val, rate=%d, ch=%d, format=%d\n",
runtime->rate, runtime->channels, runtime->format);
return -EINVAL;
}
bufsize = snd_pcm_lib_buffer_bytes(substream);
period_bytes = snd_pcm_lib_period_bytes(substream);
snd_printdd(SFX "azx_pcm_prepare: bufsize=0x%x, format=0x%x\n",
bufsize, format_val);
if (bufsize != azx_dev->bufsize ||
period_bytes != azx_dev->period_bytes ||
format_val != azx_dev->format_val) {
azx_dev->bufsize = bufsize;
azx_dev->period_bytes = period_bytes;
azx_dev->format_val = format_val;
err = azx_setup_periods(chip, substream, azx_dev);
if (err < 0)
return err;
}
/* wallclk has 24Mhz clock source */
azx_dev->period_wallclk = (((runtime->period_size * 24000) /
runtime->rate) * 1000);
azx_setup_controller(chip, azx_dev);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
azx_dev->fifo_size = azx_sd_readw(azx_dev, SD_FIFOSIZE) + 1;
else
azx_dev->fifo_size = 0;
stream_tag = azx_dev->stream_tag;
/* CA-IBG chips need the playback stream starting from 1 */
if ((chip->driver_caps & AZX_DCAPS_CTX_WORKAROUND) &&
stream_tag > chip->capture_streams)
stream_tag -= chip->capture_streams;
return snd_hda_codec_prepare(apcm->codec, hinfo, stream_tag,
azx_dev->format_val, substream);
}
static int azx_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct azx_pcm *apcm = snd_pcm_substream_chip(substream);
struct azx *chip = apcm->chip;
struct azx_dev *azx_dev;
struct snd_pcm_substream *s;
int rstart = 0, start, nsync = 0, sbits = 0;
int nwait, timeout;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
rstart = 1;
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
start = 1;
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_STOP:
start = 0;
break;
default:
return -EINVAL;
}
snd_pcm_group_for_each_entry(s, substream) {
if (s->pcm->card != substream->pcm->card)
continue;
azx_dev = get_azx_dev(s);
sbits |= 1 << azx_dev->index;
nsync++;
snd_pcm_trigger_done(s, substream);
}
spin_lock(&chip->reg_lock);
if (nsync > 1) {
/* first, set SYNC bits of corresponding streams */
if (chip->driver_caps & AZX_DCAPS_OLD_SSYNC)
azx_writel(chip, OLD_SSYNC,
azx_readl(chip, OLD_SSYNC) | sbits);
else
azx_writel(chip, SSYNC, azx_readl(chip, SSYNC) | sbits);
}
snd_pcm_group_for_each_entry(s, substream) {
if (s->pcm->card != substream->pcm->card)
continue;
azx_dev = get_azx_dev(s);
if (start) {
azx_dev->start_wallclk = azx_readl(chip, WALLCLK);
if (!rstart)
azx_dev->start_wallclk -=
azx_dev->period_wallclk;
azx_stream_start(chip, azx_dev);
} else {
azx_stream_stop(chip, azx_dev);
}
azx_dev->running = start;
}
spin_unlock(&chip->reg_lock);
if (start) {
if (nsync == 1)
return 0;
/* wait until all FIFOs get ready */
for (timeout = 5000; timeout; timeout--) {
nwait = 0;
snd_pcm_group_for_each_entry(s, substream) {
if (s->pcm->card != substream->pcm->card)
continue;
azx_dev = get_azx_dev(s);
if (!(azx_sd_readb(azx_dev, SD_STS) &
SD_STS_FIFO_READY))
nwait++;
}
if (!nwait)
break;
cpu_relax();
}
} else {
/* wait until all RUN bits are cleared */
for (timeout = 5000; timeout; timeout--) {
nwait = 0;
snd_pcm_group_for_each_entry(s, substream) {
if (s->pcm->card != substream->pcm->card)
continue;
azx_dev = get_azx_dev(s);
if (azx_sd_readb(azx_dev, SD_CTL) &
SD_CTL_DMA_START)
nwait++;
}
if (!nwait)
break;
cpu_relax();
}
}
if (nsync > 1) {
spin_lock(&chip->reg_lock);
/* reset SYNC bits */
if (chip->driver_caps & AZX_DCAPS_OLD_SSYNC)
azx_writel(chip, OLD_SSYNC,
azx_readl(chip, OLD_SSYNC) & ~sbits);
else
azx_writel(chip, SSYNC, azx_readl(chip, SSYNC) & ~sbits);
spin_unlock(&chip->reg_lock);
}
return 0;
}
/* get the current DMA position with correction on VIA chips */
static unsigned int azx_via_get_position(struct azx *chip,
struct azx_dev *azx_dev)
{
unsigned int link_pos, mini_pos, bound_pos;
unsigned int mod_link_pos, mod_dma_pos, mod_mini_pos;
unsigned int fifo_size;
link_pos = azx_sd_readl(azx_dev, SD_LPIB);
if (azx_dev->substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
/* Playback, no problem using link position */
return link_pos;
}
/* Capture */
/* For new chipset,
* use mod to get the DMA position just like old chipset
*/
mod_dma_pos = le32_to_cpu(*azx_dev->posbuf);
mod_dma_pos %= azx_dev->period_bytes;
/* azx_dev->fifo_size can't get FIFO size of in stream.
* Get from base address + offset.
*/
fifo_size = readw(chip->remap_addr + VIA_IN_STREAM0_FIFO_SIZE_OFFSET);
if (azx_dev->insufficient) {
/* Link position never gather than FIFO size */
if (link_pos <= fifo_size)
return 0;
azx_dev->insufficient = 0;
}
if (link_pos <= fifo_size)
mini_pos = azx_dev->bufsize + link_pos - fifo_size;
else
mini_pos = link_pos - fifo_size;
/* Find nearest previous boudary */
mod_mini_pos = mini_pos % azx_dev->period_bytes;
mod_link_pos = link_pos % azx_dev->period_bytes;
if (mod_link_pos >= fifo_size)
bound_pos = link_pos - mod_link_pos;
else if (mod_dma_pos >= mod_mini_pos)
bound_pos = mini_pos - mod_mini_pos;
else {
bound_pos = mini_pos - mod_mini_pos + azx_dev->period_bytes;
if (bound_pos >= azx_dev->bufsize)
bound_pos = 0;
}
/* Calculate real DMA position we want */
return bound_pos + mod_dma_pos;
}
static unsigned int azx_get_position(struct azx *chip,
struct azx_dev *azx_dev,
bool with_check)
{
unsigned int pos;
int stream = azx_dev->substream->stream;
switch (chip->position_fix[stream]) {
case POS_FIX_LPIB:
/* read LPIB */
pos = azx_sd_readl(azx_dev, SD_LPIB);
break;
case POS_FIX_VIACOMBO:
pos = azx_via_get_position(chip, azx_dev);
break;
default:
/* use the position buffer */
pos = le32_to_cpu(*azx_dev->posbuf);
if (with_check && chip->position_fix[stream] == POS_FIX_AUTO) {
if (!pos || pos == (u32)-1) {
printk(KERN_WARNING
"hda-intel: Invalid position buffer, "
"using LPIB read method instead.\n");
chip->position_fix[stream] = POS_FIX_LPIB;
pos = azx_sd_readl(azx_dev, SD_LPIB);
} else
chip->position_fix[stream] = POS_FIX_POSBUF;
}
break;
}
if (pos >= azx_dev->bufsize)
pos = 0;
return pos;
}
static snd_pcm_uframes_t azx_pcm_pointer(struct snd_pcm_substream *substream)
{
struct azx_pcm *apcm = snd_pcm_substream_chip(substream);
struct azx *chip = apcm->chip;
struct azx_dev *azx_dev = get_azx_dev(substream);
return bytes_to_frames(substream->runtime,
azx_get_position(chip, azx_dev, false));
}
/*
* Check whether the current DMA position is acceptable for updating
* periods. Returns non-zero if it's OK.
*
* Many HD-audio controllers appear pretty inaccurate about
* the update-IRQ timing. The IRQ is issued before actually the
* data is processed. So, we need to process it afterwords in a
* workqueue.
*/
static int azx_position_ok(struct azx *chip, struct azx_dev *azx_dev)
{
u32 wallclk;
unsigned int pos;
int stream;
wallclk = azx_readl(chip, WALLCLK) - azx_dev->start_wallclk;
if (wallclk < (azx_dev->period_wallclk * 2) / 3)
return -1; /* bogus (too early) interrupt */
stream = azx_dev->substream->stream;
pos = azx_get_position(chip, azx_dev, true);
if (WARN_ONCE(!azx_dev->period_bytes,
"hda-intel: zero azx_dev->period_bytes"))
return -1; /* this shouldn't happen! */
if (wallclk < (azx_dev->period_wallclk * 5) / 4 &&
pos % azx_dev->period_bytes > azx_dev->period_bytes / 2)
/* NG - it's below the first next period boundary */
return bdl_pos_adj[chip->dev_index] ? 0 : -1;
azx_dev->start_wallclk += wallclk;
return 1; /* OK, it's fine */
}
/*
* The work for pending PCM period updates.
*/
static void azx_irq_pending_work(struct work_struct *work)
{
struct azx *chip = container_of(work, struct azx, irq_pending_work);
int i, pending, ok;
if (!chip->irq_pending_warned) {
printk(KERN_WARNING
"hda-intel: IRQ timing workaround is activated "
"for card #%d. Suggest a bigger bdl_pos_adj.\n",
chip->card->number);
chip->irq_pending_warned = 1;
}
for (;;) {
pending = 0;
spin_lock_irq(&chip->reg_lock);
for (i = 0; i < chip->num_streams; i++) {
struct azx_dev *azx_dev = &chip->azx_dev[i];
if (!azx_dev->irq_pending ||
!azx_dev->substream ||
!azx_dev->running)
continue;
ok = azx_position_ok(chip, azx_dev);
if (ok > 0) {
azx_dev->irq_pending = 0;
spin_unlock(&chip->reg_lock);
snd_pcm_period_elapsed(azx_dev->substream);
spin_lock(&chip->reg_lock);
} else if (ok < 0) {
pending = 0; /* too early */
} else
pending++;
}
spin_unlock_irq(&chip->reg_lock);
if (!pending)
return;
msleep(1);
}
}
/* clear irq_pending flags and assure no on-going workq */
static void azx_clear_irq_pending(struct azx *chip)
{
int i;
spin_lock_irq(&chip->reg_lock);
for (i = 0; i < chip->num_streams; i++)
chip->azx_dev[i].irq_pending = 0;
spin_unlock_irq(&chip->reg_lock);
}
#ifdef CONFIG_X86
static int azx_pcm_mmap(struct snd_pcm_substream *substream,
struct vm_area_struct *area)
{
struct azx_pcm *apcm = snd_pcm_substream_chip(substream);
struct azx *chip = apcm->chip;
if (!azx_snoop(chip))
area->vm_page_prot = pgprot_writecombine(area->vm_page_prot);
return snd_pcm_lib_default_mmap(substream, area);
}
#else
#define azx_pcm_mmap NULL
#endif
static struct snd_pcm_ops azx_pcm_ops = {
.open = azx_pcm_open,
.close = azx_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = azx_pcm_hw_params,
.hw_free = azx_pcm_hw_free,
.prepare = azx_pcm_prepare,
.trigger = azx_pcm_trigger,
.pointer = azx_pcm_pointer,
.mmap = azx_pcm_mmap,
.page = snd_pcm_sgbuf_ops_page,
};
static void azx_pcm_free(struct snd_pcm *pcm)
{
struct azx_pcm *apcm = pcm->private_data;
if (apcm) {
list_del(&apcm->list);
kfree(apcm);
}
}
#define MAX_PREALLOC_SIZE (32 * 1024 * 1024)
static int
azx_attach_pcm_stream(struct hda_bus *bus, struct hda_codec *codec,
struct hda_pcm *cpcm)
{
struct azx *chip = bus->private_data;
struct snd_pcm *pcm;
struct azx_pcm *apcm;
int pcm_dev = cpcm->device;
unsigned int size;
int s, err;
list_for_each_entry(apcm, &chip->pcm_list, list) {
if (apcm->pcm->device == pcm_dev) {
snd_printk(KERN_ERR SFX "PCM %d already exists\n", pcm_dev);
return -EBUSY;
}
}
err = snd_pcm_new(chip->card, cpcm->name, pcm_dev,
cpcm->stream[SNDRV_PCM_STREAM_PLAYBACK].substreams,
cpcm->stream[SNDRV_PCM_STREAM_CAPTURE].substreams,
&pcm);
if (err < 0)
return err;
strlcpy(pcm->name, cpcm->name, sizeof(pcm->name));
apcm = kzalloc(sizeof(*apcm), GFP_KERNEL);
if (apcm == NULL)
return -ENOMEM;
apcm->chip = chip;
apcm->pcm = pcm;
apcm->codec = codec;
pcm->private_data = apcm;
pcm->private_free = azx_pcm_free;
if (cpcm->pcm_type == HDA_PCM_TYPE_MODEM)
pcm->dev_class = SNDRV_PCM_CLASS_MODEM;
list_add_tail(&apcm->list, &chip->pcm_list);
cpcm->pcm = pcm;
for (s = 0; s < 2; s++) {
apcm->hinfo[s] = &cpcm->stream[s];
if (cpcm->stream[s].substreams)
snd_pcm_set_ops(pcm, s, &azx_pcm_ops);
}
/* buffer pre-allocation */
size = CONFIG_SND_HDA_PREALLOC_SIZE * 1024;
if (size > MAX_PREALLOC_SIZE)
size = MAX_PREALLOC_SIZE;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV_SG,
snd_dma_pci_data(chip->pci),
size, MAX_PREALLOC_SIZE);
return 0;
}
/*
* mixer creation - all stuff is implemented in hda module
*/
static int __devinit azx_mixer_create(struct azx *chip)
{
return snd_hda_build_controls(chip->bus);
}
/*
* initialize SD streams
*/
static int __devinit azx_init_stream(struct azx *chip)
{
int i;
/* initialize each stream (aka device)
* assign the starting bdl address to each stream (device)
* and initialize
*/
for (i = 0; i < chip->num_streams; i++) {
struct azx_dev *azx_dev = &chip->azx_dev[i];
azx_dev->posbuf = (u32 __iomem *)(chip->posbuf.area + i * 8);
/* offset: SDI0=0x80, SDI1=0xa0, ... SDO3=0x160 */
azx_dev->sd_addr = chip->remap_addr + (0x20 * i + 0x80);
/* int mask: SDI0=0x01, SDI1=0x02, ... SDO3=0x80 */
azx_dev->sd_int_sta_mask = 1 << i;
/* stream tag: must be non-zero and unique */
azx_dev->index = i;
azx_dev->stream_tag = i + 1;
}
return 0;
}
static int azx_acquire_irq(struct azx *chip, int do_disconnect)
{
if (request_irq(chip->pci->irq, azx_interrupt,
chip->msi ? 0 : IRQF_SHARED,
KBUILD_MODNAME, chip)) {
printk(KERN_ERR "hda-intel: unable to grab IRQ %d, "
"disabling device\n", chip->pci->irq);
if (do_disconnect)
snd_card_disconnect(chip->card);
return -1;
}
chip->irq = chip->pci->irq;
pci_intx(chip->pci, !chip->msi);
return 0;
}
static void azx_stop_chip(struct azx *chip)
{
if (!chip->initialized)
return;
/* disable interrupts */
azx_int_disable(chip);
azx_int_clear(chip);
/* disable CORB/RIRB */
azx_free_cmd_io(chip);
/* disable position buffer */
azx_writel(chip, DPLBASE, 0);
azx_writel(chip, DPUBASE, 0);
chip->initialized = 0;
}
#ifdef CONFIG_SND_HDA_POWER_SAVE
/* power-up/down the controller */
static void azx_power_notify(struct hda_bus *bus)
{
struct azx *chip = bus->private_data;
struct hda_codec *c;
int power_on = 0;
list_for_each_entry(c, &bus->codec_list, list) {
if (c->power_on) {
power_on = 1;
break;
}
}
if (power_on)
azx_init_chip(chip, 1);
else if (chip->running && power_save_controller &&
!bus->power_keep_link_on)
azx_stop_chip(chip);
}
#endif /* CONFIG_SND_HDA_POWER_SAVE */
#ifdef CONFIG_PM
/*
* power management
*/
static int snd_hda_codecs_inuse(struct hda_bus *bus)
{
struct hda_codec *codec;
list_for_each_entry(codec, &bus->codec_list, list) {
if (snd_hda_codec_needs_resume(codec))
return 1;
}
return 0;
}
static int azx_suspend(struct pci_dev *pci, pm_message_t state)
{
struct snd_card *card = pci_get_drvdata(pci);
struct azx *chip = card->private_data;
struct azx_pcm *p;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
azx_clear_irq_pending(chip);
list_for_each_entry(p, &chip->pcm_list, list)
snd_pcm_suspend_all(p->pcm);
if (chip->initialized)
snd_hda_suspend(chip->bus);
azx_stop_chip(chip);
if (chip->irq >= 0) {
free_irq(chip->irq, chip);
chip->irq = -1;
}
if (chip->msi)
pci_disable_msi(chip->pci);
pci_disable_device(pci);
pci_save_state(pci);
pci_set_power_state(pci, pci_choose_state(pci, state));
return 0;
}
static int azx_resume(struct pci_dev *pci)
{
struct snd_card *card = pci_get_drvdata(pci);
struct azx *chip = card->private_data;
pci_set_power_state(pci, PCI_D0);
pci_restore_state(pci);
if (pci_enable_device(pci) < 0) {
printk(KERN_ERR "hda-intel: pci_enable_device failed, "
"disabling device\n");
snd_card_disconnect(card);
return -EIO;
}
pci_set_master(pci);
if (chip->msi)
if (pci_enable_msi(pci) < 0)
chip->msi = 0;
if (azx_acquire_irq(chip, 1) < 0)
return -EIO;
azx_init_pci(chip);
if (snd_hda_codecs_inuse(chip->bus))
azx_init_chip(chip, 1);
snd_hda_resume(chip->bus);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif /* CONFIG_PM */
/*
* reboot notifier for hang-up problem at power-down
*/
static int azx_halt(struct notifier_block *nb, unsigned long event, void *buf)
{
struct azx *chip = container_of(nb, struct azx, reboot_notifier);
snd_hda_bus_reboot_notify(chip->bus);
azx_stop_chip(chip);
return NOTIFY_OK;
}
static void azx_notifier_register(struct azx *chip)
{
chip->reboot_notifier.notifier_call = azx_halt;
register_reboot_notifier(&chip->reboot_notifier);
}
static void azx_notifier_unregister(struct azx *chip)
{
if (chip->reboot_notifier.notifier_call)
unregister_reboot_notifier(&chip->reboot_notifier);
}
/*
* destructor
*/
static int azx_free(struct azx *chip)
{
int i;
azx_notifier_unregister(chip);
if (chip->initialized) {
azx_clear_irq_pending(chip);
for (i = 0; i < chip->num_streams; i++)
azx_stream_stop(chip, &chip->azx_dev[i]);
azx_stop_chip(chip);
}
if (chip->irq >= 0)
free_irq(chip->irq, (void*)chip);
if (chip->msi)
pci_disable_msi(chip->pci);
if (chip->remap_addr)
iounmap(chip->remap_addr);
if (chip->azx_dev) {
for (i = 0; i < chip->num_streams; i++)
if (chip->azx_dev[i].bdl.area) {
mark_pages_wc(chip, &chip->azx_dev[i].bdl, false);
snd_dma_free_pages(&chip->azx_dev[i].bdl);
}
}
if (chip->rb.area) {
mark_pages_wc(chip, &chip->rb, false);
snd_dma_free_pages(&chip->rb);
}
if (chip->posbuf.area) {
mark_pages_wc(chip, &chip->posbuf, false);
snd_dma_free_pages(&chip->posbuf);
}
pci_release_regions(chip->pci);
pci_disable_device(chip->pci);
kfree(chip->azx_dev);
kfree(chip);
return 0;
}
static int azx_dev_free(struct snd_device *device)
{
return azx_free(device->device_data);
}
/*
* white/black-listing for position_fix
*/
static struct snd_pci_quirk position_fix_list[] __devinitdata = {
SND_PCI_QUIRK(0x1028, 0x01cc, "Dell D820", POS_FIX_LPIB),
SND_PCI_QUIRK(0x1028, 0x01de, "Dell Precision 390", POS_FIX_LPIB),
SND_PCI_QUIRK(0x103c, 0x306d, "HP dv3", POS_FIX_LPIB),
SND_PCI_QUIRK(0x1043, 0x813d, "ASUS P5AD2", POS_FIX_LPIB),
SND_PCI_QUIRK(0x1043, 0x81b3, "ASUS", POS_FIX_LPIB),
SND_PCI_QUIRK(0x1043, 0x81e7, "ASUS M2V", POS_FIX_LPIB),
SND_PCI_QUIRK(0x104d, 0x9069, "Sony VPCS11V9E", POS_FIX_LPIB),
SND_PCI_QUIRK(0x10de, 0xcb89, "Macbook Pro 7,1", POS_FIX_LPIB),
SND_PCI_QUIRK(0x1297, 0x3166, "Shuttle", POS_FIX_LPIB),
SND_PCI_QUIRK(0x1458, 0xa022, "ga-ma770-ud3", POS_FIX_LPIB),
SND_PCI_QUIRK(0x1462, 0x1002, "MSI Wind U115", POS_FIX_LPIB),
SND_PCI_QUIRK(0x1565, 0x8218, "Biostar Microtech", POS_FIX_LPIB),
SND_PCI_QUIRK(0x1849, 0x0888, "775Dual-VSTA", POS_FIX_LPIB),
SND_PCI_QUIRK(0x8086, 0x2503, "DG965OT AAD63733-203", POS_FIX_LPIB),
{}
};
static int __devinit check_position_fix(struct azx *chip, int fix)
{
const struct snd_pci_quirk *q;
switch (fix) {
case POS_FIX_LPIB:
case POS_FIX_POSBUF:
case POS_FIX_VIACOMBO:
case POS_FIX_COMBO:
return fix;
}
q = snd_pci_quirk_lookup(chip->pci, position_fix_list);
if (q) {
printk(KERN_INFO
"hda_intel: position_fix set to %d "
"for device %04x:%04x\n",
q->value, q->subvendor, q->subdevice);
return q->value;
}
/* Check VIA/ATI HD Audio Controller exist */
if (chip->driver_caps & AZX_DCAPS_POSFIX_VIA) {
snd_printd(SFX "Using VIACOMBO position fix\n");
return POS_FIX_VIACOMBO;
}
if (chip->driver_caps & AZX_DCAPS_POSFIX_LPIB) {
snd_printd(SFX "Using LPIB position fix\n");
return POS_FIX_LPIB;
}
return POS_FIX_AUTO;
}
/*
* black-lists for probe_mask
*/
static struct snd_pci_quirk probe_mask_list[] __devinitdata = {
/* Thinkpad often breaks the controller communication when accessing
* to the non-working (or non-existing) modem codec slot.
*/
SND_PCI_QUIRK(0x1014, 0x05b7, "Thinkpad Z60", 0x01),
SND_PCI_QUIRK(0x17aa, 0x2010, "Thinkpad X/T/R60", 0x01),
SND_PCI_QUIRK(0x17aa, 0x20ac, "Thinkpad X/T/R61", 0x01),
/* broken BIOS */
SND_PCI_QUIRK(0x1028, 0x20ac, "Dell Studio Desktop", 0x01),
/* including bogus ALC268 in slot#2 that conflicts with ALC888 */
SND_PCI_QUIRK(0x17c0, 0x4085, "Medion MD96630", 0x01),
/* forced codec slots */
SND_PCI_QUIRK(0x1043, 0x1262, "ASUS W5Fm", 0x103),
SND_PCI_QUIRK(0x1046, 0x1262, "ASUS W5F", 0x103),
{}
};
#define AZX_FORCE_CODEC_MASK 0x100
static void __devinit check_probe_mask(struct azx *chip, int dev)
{
const struct snd_pci_quirk *q;
chip->codec_probe_mask = probe_mask[dev];
if (chip->codec_probe_mask == -1) {
q = snd_pci_quirk_lookup(chip->pci, probe_mask_list);
if (q) {
printk(KERN_INFO
"hda_intel: probe_mask set to 0x%x "
"for device %04x:%04x\n",
q->value, q->subvendor, q->subdevice);
chip->codec_probe_mask = q->value;
}
}
/* check forced option */
if (chip->codec_probe_mask != -1 &&
(chip->codec_probe_mask & AZX_FORCE_CODEC_MASK)) {
chip->codec_mask = chip->codec_probe_mask & 0xff;
printk(KERN_INFO "hda_intel: codec_mask forced to 0x%x\n",
chip->codec_mask);
}
}
/*
* white/black-list for enable_msi
*/
static struct snd_pci_quirk msi_black_list[] __devinitdata = {
SND_PCI_QUIRK(0x1043, 0x81f2, "ASUS", 0), /* Athlon64 X2 + nvidia */
SND_PCI_QUIRK(0x1043, 0x81f6, "ASUS", 0), /* nvidia */
SND_PCI_QUIRK(0x1043, 0x822d, "ASUS", 0), /* Athlon64 X2 + nvidia MCP55 */
SND_PCI_QUIRK(0x1179, 0xfb44, "Toshiba Satellite C870", 0), /* AMD Hudson */
SND_PCI_QUIRK(0x1849, 0x0888, "ASRock", 0), /* Athlon64 X2 + nvidia */
SND_PCI_QUIRK(0xa0a0, 0x0575, "Aopen MZ915-M", 0), /* ICH6 */
{}
};
static void __devinit check_msi(struct azx *chip)
{
const struct snd_pci_quirk *q;
if (enable_msi >= 0) {
chip->msi = !!enable_msi;
return;
}
chip->msi = 1; /* enable MSI as default */
q = snd_pci_quirk_lookup(chip->pci, msi_black_list);
if (q) {
printk(KERN_INFO
"hda_intel: msi for device %04x:%04x set to %d\n",
q->subvendor, q->subdevice, q->value);
chip->msi = q->value;
return;
}
/* NVidia chipsets seem to cause troubles with MSI */
if (chip->driver_caps & AZX_DCAPS_NO_MSI) {
printk(KERN_INFO "hda_intel: Disabling MSI\n");
chip->msi = 0;
}
}
/* check the snoop mode availability */
static void __devinit azx_check_snoop_available(struct azx *chip)
{
bool snoop = chip->snoop;
switch (chip->driver_type) {
case AZX_DRIVER_VIA:
/* force to non-snoop mode for a new VIA controller
* when BIOS is set
*/
if (snoop) {
u8 val;
pci_read_config_byte(chip->pci, 0x42, &val);
if (!(val & 0x80) && chip->pci->revision == 0x30)
snoop = false;
}
break;
case AZX_DRIVER_ATIHDMI_NS:
/* new ATI HDMI requires non-snoop */
snoop = false;
break;
}
if (snoop != chip->snoop) {
snd_printk(KERN_INFO SFX "Force to %s mode\n",
snoop ? "snoop" : "non-snoop");
chip->snoop = snoop;
}
}
/*
* constructor
*/
static int __devinit azx_create(struct snd_card *card, struct pci_dev *pci,
int dev, unsigned int driver_caps,
struct azx **rchip)
{
struct azx *chip;
int i, err;
unsigned short gcap;
unsigned int dma_bits = 64;
static struct snd_device_ops ops = {
.dev_free = azx_dev_free,
};
*rchip = NULL;
err = pci_enable_device(pci);
if (err < 0)
return err;
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (!chip) {
snd_printk(KERN_ERR SFX "cannot allocate chip\n");
pci_disable_device(pci);
return -ENOMEM;
}
spin_lock_init(&chip->reg_lock);
mutex_init(&chip->open_mutex);
chip->card = card;
chip->pci = pci;
chip->irq = -1;
chip->driver_caps = driver_caps;
chip->driver_type = driver_caps & 0xff;
check_msi(chip);
chip->dev_index = dev;
INIT_WORK(&chip->irq_pending_work, azx_irq_pending_work);
INIT_LIST_HEAD(&chip->pcm_list);
chip->position_fix[0] = chip->position_fix[1] =
check_position_fix(chip, position_fix[dev]);
/* combo mode uses LPIB for playback */
if (chip->position_fix[0] == POS_FIX_COMBO) {
chip->position_fix[0] = POS_FIX_LPIB;
chip->position_fix[1] = POS_FIX_AUTO;
}
check_probe_mask(chip, dev);
chip->single_cmd = single_cmd;
chip->snoop = hda_snoop;
azx_check_snoop_available(chip);
if (bdl_pos_adj[dev] < 0) {
switch (chip->driver_type) {
case AZX_DRIVER_ICH:
case AZX_DRIVER_PCH:
bdl_pos_adj[dev] = 1;
break;
default:
bdl_pos_adj[dev] = 32;
break;
}
}
#if BITS_PER_LONG != 64
/* Fix up base address on ULI M5461 */
if (chip->driver_type == AZX_DRIVER_ULI) {
u16 tmp3;
pci_read_config_word(pci, 0x40, &tmp3);
pci_write_config_word(pci, 0x40, tmp3 | 0x10);
pci_write_config_dword(pci, PCI_BASE_ADDRESS_1, 0);
}
#endif
err = pci_request_regions(pci, "ICH HD audio");
if (err < 0) {
kfree(chip);
pci_disable_device(pci);
return err;
}
chip->addr = pci_resource_start(pci, 0);
chip->remap_addr = pci_ioremap_bar(pci, 0);
if (chip->remap_addr == NULL) {
snd_printk(KERN_ERR SFX "ioremap error\n");
err = -ENXIO;
goto errout;
}
if (chip->msi)
if (pci_enable_msi(pci) < 0)
chip->msi = 0;
if (azx_acquire_irq(chip, 0) < 0) {
err = -EBUSY;
goto errout;
}
pci_set_master(pci);
synchronize_irq(chip->irq);
gcap = azx_readw(chip, GCAP);
snd_printdd(SFX "chipset global capabilities = 0x%x\n", gcap);
/* AMD devices support 40 or 48bit DMA, take the safe one */
if (chip->pci->vendor == PCI_VENDOR_ID_AMD)
dma_bits = 40;
/* disable SB600 64bit support for safety */
if (chip->pci->vendor == PCI_VENDOR_ID_ATI) {
struct pci_dev *p_smbus;
dma_bits = 40;
p_smbus = pci_get_device(PCI_VENDOR_ID_ATI,
PCI_DEVICE_ID_ATI_SBX00_SMBUS,
NULL);
if (p_smbus) {
if (p_smbus->revision < 0x30)
gcap &= ~ICH6_GCAP_64OK;
pci_dev_put(p_smbus);
}
}
/* disable 64bit DMA address on some devices */
if (chip->driver_caps & AZX_DCAPS_NO_64BIT) {
snd_printd(SFX "Disabling 64bit DMA\n");
gcap &= ~ICH6_GCAP_64OK;
}
/* disable buffer size rounding to 128-byte multiples if supported */
if (align_buffer_size >= 0)
chip->align_buffer_size = !!align_buffer_size;
else {
if (chip->driver_caps & AZX_DCAPS_BUFSIZE)
chip->align_buffer_size = 0;
else if (chip->driver_caps & AZX_DCAPS_ALIGN_BUFSIZE)
chip->align_buffer_size = 1;
else
chip->align_buffer_size = 1;
}
/* allow 64bit DMA address if supported by H/W */
if (!(gcap & ICH6_GCAP_64OK))
dma_bits = 32;
if (!pci_set_dma_mask(pci, DMA_BIT_MASK(dma_bits))) {
pci_set_consistent_dma_mask(pci, DMA_BIT_MASK(dma_bits));
} else {
pci_set_dma_mask(pci, DMA_BIT_MASK(32));
pci_set_consistent_dma_mask(pci, DMA_BIT_MASK(32));
}
/* read number of streams from GCAP register instead of using
* hardcoded value
*/
chip->capture_streams = (gcap >> 8) & 0x0f;
chip->playback_streams = (gcap >> 12) & 0x0f;
if (!chip->playback_streams && !chip->capture_streams) {
/* gcap didn't give any info, switching to old method */
switch (chip->driver_type) {
case AZX_DRIVER_ULI:
chip->playback_streams = ULI_NUM_PLAYBACK;
chip->capture_streams = ULI_NUM_CAPTURE;
break;
case AZX_DRIVER_ATIHDMI:
case AZX_DRIVER_ATIHDMI_NS:
chip->playback_streams = ATIHDMI_NUM_PLAYBACK;
chip->capture_streams = ATIHDMI_NUM_CAPTURE;
break;
case AZX_DRIVER_GENERIC:
default:
chip->playback_streams = ICH6_NUM_PLAYBACK;
chip->capture_streams = ICH6_NUM_CAPTURE;
break;
}
}
chip->capture_index_offset = 0;
chip->playback_index_offset = chip->capture_streams;
chip->num_streams = chip->playback_streams + chip->capture_streams;
chip->azx_dev = kcalloc(chip->num_streams, sizeof(*chip->azx_dev),
GFP_KERNEL);
if (!chip->azx_dev) {
snd_printk(KERN_ERR SFX "cannot malloc azx_dev\n");
goto errout;
}
for (i = 0; i < chip->num_streams; i++) {
/* allocate memory for the BDL for each stream */
err = snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci),
BDL_SIZE, &chip->azx_dev[i].bdl);
if (err < 0) {
snd_printk(KERN_ERR SFX "cannot allocate BDL\n");
goto errout;
}
mark_pages_wc(chip, &chip->azx_dev[i].bdl, true);
}
/* allocate memory for the position buffer */
err = snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci),
chip->num_streams * 8, &chip->posbuf);
if (err < 0) {
snd_printk(KERN_ERR SFX "cannot allocate posbuf\n");
goto errout;
}
mark_pages_wc(chip, &chip->posbuf, true);
/* allocate CORB/RIRB */
err = azx_alloc_cmd_io(chip);
if (err < 0)
goto errout;
/* initialize streams */
azx_init_stream(chip);
/* initialize chip */
azx_init_pci(chip);
azx_init_chip(chip, (probe_only[dev] & 2) == 0);
/* codec detection */
if (!chip->codec_mask) {
snd_printk(KERN_ERR SFX "no codecs found!\n");
err = -ENODEV;
goto errout;
}
err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
if (err <0) {
snd_printk(KERN_ERR SFX "Error creating device [card]!\n");
goto errout;
}
strcpy(card->driver, "HDA-Intel");
strlcpy(card->shortname, driver_short_names[chip->driver_type],
sizeof(card->shortname));
snprintf(card->longname, sizeof(card->longname),
"%s at 0x%lx irq %i",
card->shortname, chip->addr, chip->irq);
*rchip = chip;
return 0;
errout:
azx_free(chip);
return err;
}
static void power_down_all_codecs(struct azx *chip)
{
#ifdef CONFIG_SND_HDA_POWER_SAVE
/* The codecs were powered up in snd_hda_codec_new().
* Now all initialization done, so turn them down if possible
*/
struct hda_codec *codec;
list_for_each_entry(codec, &chip->bus->codec_list, list) {
snd_hda_power_down(codec);
}
#endif
}
static int __devinit azx_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
struct snd_card *card;
struct azx *chip;
int err;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0) {
snd_printk(KERN_ERR SFX "Error creating card!\n");
return err;
}
/* set this here since it's referred in snd_hda_load_patch() */
snd_card_set_dev(card, &pci->dev);
err = azx_create(card, pci, dev, pci_id->driver_data, &chip);
if (err < 0)
goto out_free;
card->private_data = chip;
#ifdef CONFIG_SND_HDA_INPUT_BEEP
chip->beep_mode = beep_mode[dev];
#endif
/* create codec instances */
err = azx_codec_create(chip, model[dev]);
if (err < 0)
goto out_free;
#ifdef CONFIG_SND_HDA_PATCH_LOADER
if (patch[dev] && *patch[dev]) {
snd_printk(KERN_ERR SFX "Applying patch firmware '%s'\n",
patch[dev]);
err = snd_hda_load_patch(chip->bus, patch[dev]);
if (err < 0)
goto out_free;
}
#endif
if ((probe_only[dev] & 1) == 0) {
err = azx_codec_configure(chip);
if (err < 0)
goto out_free;
}
/* create PCM streams */
err = snd_hda_build_pcms(chip->bus);
if (err < 0)
goto out_free;
/* create mixer controls */
err = azx_mixer_create(chip);
if (err < 0)
goto out_free;
err = snd_card_register(card);
if (err < 0)
goto out_free;
pci_set_drvdata(pci, card);
chip->running = 1;
power_down_all_codecs(chip);
azx_notifier_register(chip);
dev++;
return err;
out_free:
snd_card_free(card);
return err;
}
static void __devexit azx_remove(struct pci_dev *pci)
{
snd_card_free(pci_get_drvdata(pci));
pci_set_drvdata(pci, NULL);
}
/* PCI IDs */
static DEFINE_PCI_DEVICE_TABLE(azx_ids) = {
/* CPT */
{ PCI_DEVICE(0x8086, 0x1c20),
.driver_data = AZX_DRIVER_PCH | AZX_DCAPS_SCH_SNOOP |
AZX_DCAPS_BUFSIZE },
/* PBG */
{ PCI_DEVICE(0x8086, 0x1d20),
.driver_data = AZX_DRIVER_PCH | AZX_DCAPS_SCH_SNOOP |
AZX_DCAPS_BUFSIZE},
/* Panther Point */
{ PCI_DEVICE(0x8086, 0x1e20),
.driver_data = AZX_DRIVER_PCH | AZX_DCAPS_SCH_SNOOP |
AZX_DCAPS_BUFSIZE},
/* Lynx Point */
{ PCI_DEVICE(0x8086, 0x8c20),
.driver_data = AZX_DRIVER_PCH | AZX_DCAPS_SCH_SNOOP |
AZX_DCAPS_BUFSIZE},
/* SCH */
{ PCI_DEVICE(0x8086, 0x811b),
.driver_data = AZX_DRIVER_SCH | AZX_DCAPS_SCH_SNOOP |
AZX_DCAPS_BUFSIZE | AZX_DCAPS_POSFIX_LPIB }, /* Poulsbo */
{ PCI_DEVICE(0x8086, 0x080a),
.driver_data = AZX_DRIVER_SCH | AZX_DCAPS_SCH_SNOOP |
AZX_DCAPS_BUFSIZE | AZX_DCAPS_POSFIX_LPIB }, /* Oaktrail */
/* ICH */
{ PCI_DEVICE(0x8086, 0x2668),
.driver_data = AZX_DRIVER_ICH | AZX_DCAPS_OLD_SSYNC |
AZX_DCAPS_BUFSIZE }, /* ICH6 */
{ PCI_DEVICE(0x8086, 0x27d8),
.driver_data = AZX_DRIVER_ICH | AZX_DCAPS_OLD_SSYNC |
AZX_DCAPS_BUFSIZE }, /* ICH7 */
{ PCI_DEVICE(0x8086, 0x269a),
.driver_data = AZX_DRIVER_ICH | AZX_DCAPS_OLD_SSYNC |
AZX_DCAPS_BUFSIZE }, /* ESB2 */
{ PCI_DEVICE(0x8086, 0x284b),
.driver_data = AZX_DRIVER_ICH | AZX_DCAPS_OLD_SSYNC |
AZX_DCAPS_BUFSIZE }, /* ICH8 */
{ PCI_DEVICE(0x8086, 0x293e),
.driver_data = AZX_DRIVER_ICH | AZX_DCAPS_OLD_SSYNC |
AZX_DCAPS_BUFSIZE }, /* ICH9 */
{ PCI_DEVICE(0x8086, 0x293f),
.driver_data = AZX_DRIVER_ICH | AZX_DCAPS_OLD_SSYNC |
AZX_DCAPS_BUFSIZE }, /* ICH9 */
{ PCI_DEVICE(0x8086, 0x3a3e),
.driver_data = AZX_DRIVER_ICH | AZX_DCAPS_OLD_SSYNC |
AZX_DCAPS_BUFSIZE }, /* ICH10 */
{ PCI_DEVICE(0x8086, 0x3a6e),
.driver_data = AZX_DRIVER_ICH | AZX_DCAPS_OLD_SSYNC |
AZX_DCAPS_BUFSIZE }, /* ICH10 */
/* Generic Intel */
{ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_ANY_ID),
.class = PCI_CLASS_MULTIMEDIA_HD_AUDIO << 8,
.class_mask = 0xffffff,
.driver_data = AZX_DRIVER_ICH | AZX_DCAPS_BUFSIZE },
/* ATI SB 450/600/700/800/900 */
{ PCI_DEVICE(0x1002, 0x437b),
.driver_data = AZX_DRIVER_ATI | AZX_DCAPS_PRESET_ATI_SB },
{ PCI_DEVICE(0x1002, 0x4383),
.driver_data = AZX_DRIVER_ATI | AZX_DCAPS_PRESET_ATI_SB },
/* AMD Hudson */
{ PCI_DEVICE(0x1022, 0x780d),
.driver_data = AZX_DRIVER_GENERIC | AZX_DCAPS_PRESET_ATI_SB },
/* ATI HDMI */
{ PCI_DEVICE(0x1002, 0x793b),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0x7919),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0x960f),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0x970f),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0xaa00),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0xaa08),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0xaa10),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0xaa18),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0xaa20),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0xaa28),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0xaa30),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0xaa38),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0xaa40),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0xaa48),
.driver_data = AZX_DRIVER_ATIHDMI | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0x9902),
.driver_data = AZX_DRIVER_ATIHDMI_NS | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0xaaa0),
.driver_data = AZX_DRIVER_ATIHDMI_NS | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0xaaa8),
.driver_data = AZX_DRIVER_ATIHDMI_NS | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(0x1002, 0xaab0),
.driver_data = AZX_DRIVER_ATIHDMI_NS | AZX_DCAPS_PRESET_ATI_HDMI },
/* VIA VT8251/VT8237A */
{ PCI_DEVICE(0x1106, 0x3288),
.driver_data = AZX_DRIVER_VIA | AZX_DCAPS_POSFIX_VIA },
/* SIS966 */
{ PCI_DEVICE(0x1039, 0x7502), .driver_data = AZX_DRIVER_SIS },
/* ULI M5461 */
{ PCI_DEVICE(0x10b9, 0x5461), .driver_data = AZX_DRIVER_ULI },
/* NVIDIA MCP */
{ PCI_DEVICE(PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID),
.class = PCI_CLASS_MULTIMEDIA_HD_AUDIO << 8,
.class_mask = 0xffffff,
.driver_data = AZX_DRIVER_NVIDIA | AZX_DCAPS_PRESET_NVIDIA },
/* Teradici */
{ PCI_DEVICE(0x6549, 0x1200),
.driver_data = AZX_DRIVER_TERA | AZX_DCAPS_NO_64BIT },
/* Creative X-Fi (CA0110-IBG) */
#if !defined(CONFIG_SND_CTXFI) && !defined(CONFIG_SND_CTXFI_MODULE)
/* the following entry conflicts with snd-ctxfi driver,
* as ctxfi driver mutates from HD-audio to native mode with
* a special command sequence.
*/
{ PCI_DEVICE(PCI_VENDOR_ID_CREATIVE, PCI_ANY_ID),
.class = PCI_CLASS_MULTIMEDIA_HD_AUDIO << 8,
.class_mask = 0xffffff,
.driver_data = AZX_DRIVER_CTX | AZX_DCAPS_CTX_WORKAROUND |
AZX_DCAPS_RIRB_PRE_DELAY | AZX_DCAPS_POSFIX_LPIB },
#else
/* this entry seems still valid -- i.e. without emu20kx chip */
{ PCI_DEVICE(0x1102, 0x0009),
.driver_data = AZX_DRIVER_CTX | AZX_DCAPS_CTX_WORKAROUND |
AZX_DCAPS_RIRB_PRE_DELAY | AZX_DCAPS_POSFIX_LPIB },
#endif
/* Vortex86MX */
{ PCI_DEVICE(0x17f3, 0x3010), .driver_data = AZX_DRIVER_GENERIC },
/* VMware HDAudio */
{ PCI_DEVICE(0x15ad, 0x1977), .driver_data = AZX_DRIVER_GENERIC },
/* AMD/ATI Generic, PCI class code and Vendor ID for HD Audio */
{ PCI_DEVICE(PCI_VENDOR_ID_ATI, PCI_ANY_ID),
.class = PCI_CLASS_MULTIMEDIA_HD_AUDIO << 8,
.class_mask = 0xffffff,
.driver_data = AZX_DRIVER_GENERIC | AZX_DCAPS_PRESET_ATI_HDMI },
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_ANY_ID),
.class = PCI_CLASS_MULTIMEDIA_HD_AUDIO << 8,
.class_mask = 0xffffff,
.driver_data = AZX_DRIVER_GENERIC | AZX_DCAPS_PRESET_ATI_HDMI },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, azx_ids);
/* pci_driver definition */
static struct pci_driver driver = {
.name = KBUILD_MODNAME,
.id_table = azx_ids,
.probe = azx_probe,
.remove = __devexit_p(azx_remove),
#ifdef CONFIG_PM
.suspend = azx_suspend,
.resume = azx_resume,
#endif
};
static int __init alsa_card_azx_init(void)
{
return pci_register_driver(&driver);
}
static void __exit alsa_card_azx_exit(void)
{
pci_unregister_driver(&driver);
}
module_init(alsa_card_azx_init)
module_exit(alsa_card_azx_exit)
| gpl-2.0 |
GuardianRG/linux | drivers/i2c/busses/i2c-ismt.c | 617 | 28233 | /*
* 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.
* 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 2 /* 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 const struct pci_device_id 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;
unsigned long time_left;
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 */
time_left = 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(!time_left)) {
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 |
blindi/LameSung-Kernel | fs/nfs/objlayout/objlayout.c | 1641 | 18571 | /*
* pNFS Objects layout driver high level definitions
*
* Copyright (C) 2007 Panasas Inc. [year of first publication]
* All rights reserved.
*
* Benny Halevy <bhalevy@panasas.com>
* Boaz Harrosh <bharrosh@panasas.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
* See the file COPYING included with this distribution for more details.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Panasas company 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 ``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 REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <scsi/osd_initiator.h>
#include "objlayout.h"
#define NFSDBG_FACILITY NFSDBG_PNFS_LD
/*
* Create a objlayout layout structure for the given inode and return it.
*/
struct pnfs_layout_hdr *
objlayout_alloc_layout_hdr(struct inode *inode, gfp_t gfp_flags)
{
struct objlayout *objlay;
objlay = kzalloc(sizeof(struct objlayout), gfp_flags);
if (objlay) {
spin_lock_init(&objlay->lock);
INIT_LIST_HEAD(&objlay->err_list);
}
dprintk("%s: Return %p\n", __func__, objlay);
return &objlay->pnfs_layout;
}
/*
* Free an objlayout layout structure
*/
void
objlayout_free_layout_hdr(struct pnfs_layout_hdr *lo)
{
struct objlayout *objlay = OBJLAYOUT(lo);
dprintk("%s: objlay %p\n", __func__, objlay);
WARN_ON(!list_empty(&objlay->err_list));
kfree(objlay);
}
/*
* Unmarshall layout and store it in pnfslay.
*/
struct pnfs_layout_segment *
objlayout_alloc_lseg(struct pnfs_layout_hdr *pnfslay,
struct nfs4_layoutget_res *lgr,
gfp_t gfp_flags)
{
int status = -ENOMEM;
struct xdr_stream stream;
struct xdr_buf buf = {
.pages = lgr->layoutp->pages,
.page_len = lgr->layoutp->len,
.buflen = lgr->layoutp->len,
.len = lgr->layoutp->len,
};
struct page *scratch;
struct pnfs_layout_segment *lseg;
dprintk("%s: Begin pnfslay %p\n", __func__, pnfslay);
scratch = alloc_page(gfp_flags);
if (!scratch)
goto err_nofree;
xdr_init_decode(&stream, &buf, NULL);
xdr_set_scratch_buffer(&stream, page_address(scratch), PAGE_SIZE);
status = objio_alloc_lseg(&lseg, pnfslay, &lgr->range, &stream, gfp_flags);
if (unlikely(status)) {
dprintk("%s: objio_alloc_lseg Return err %d\n", __func__,
status);
goto err;
}
__free_page(scratch);
dprintk("%s: Return %p\n", __func__, lseg);
return lseg;
err:
__free_page(scratch);
err_nofree:
dprintk("%s: Err Return=>%d\n", __func__, status);
return ERR_PTR(status);
}
/*
* Free a layout segement
*/
void
objlayout_free_lseg(struct pnfs_layout_segment *lseg)
{
dprintk("%s: freeing layout segment %p\n", __func__, lseg);
if (unlikely(!lseg))
return;
objio_free_lseg(lseg);
}
/*
* I/O Operations
*/
static inline u64
end_offset(u64 start, u64 len)
{
u64 end;
end = start + len;
return end >= start ? end : NFS4_MAX_UINT64;
}
/* last octet in a range */
static inline u64
last_byte_offset(u64 start, u64 len)
{
u64 end;
BUG_ON(!len);
end = start + len;
return end > start ? end - 1 : NFS4_MAX_UINT64;
}
static struct objlayout_io_state *
objlayout_alloc_io_state(struct pnfs_layout_hdr *pnfs_layout_type,
struct page **pages,
unsigned pgbase,
loff_t offset,
size_t count,
struct pnfs_layout_segment *lseg,
void *rpcdata,
gfp_t gfp_flags)
{
struct objlayout_io_state *state;
u64 lseg_end_offset;
dprintk("%s: allocating io_state\n", __func__);
if (objio_alloc_io_state(lseg, &state, gfp_flags))
return NULL;
BUG_ON(offset < lseg->pls_range.offset);
lseg_end_offset = end_offset(lseg->pls_range.offset,
lseg->pls_range.length);
BUG_ON(offset >= lseg_end_offset);
if (offset + count > lseg_end_offset) {
count = lseg->pls_range.length -
(offset - lseg->pls_range.offset);
dprintk("%s: truncated count %Zd\n", __func__, count);
}
if (pgbase > PAGE_SIZE) {
pages += pgbase >> PAGE_SHIFT;
pgbase &= ~PAGE_MASK;
}
INIT_LIST_HEAD(&state->err_list);
state->lseg = lseg;
state->rpcdata = rpcdata;
state->pages = pages;
state->pgbase = pgbase;
state->nr_pages = (pgbase + count + PAGE_SIZE - 1) >> PAGE_SHIFT;
state->offset = offset;
state->count = count;
state->sync = 0;
return state;
}
static void
objlayout_free_io_state(struct objlayout_io_state *state)
{
dprintk("%s: freeing io_state\n", __func__);
if (unlikely(!state))
return;
objio_free_io_state(state);
}
/*
* I/O done common code
*/
static void
objlayout_iodone(struct objlayout_io_state *state)
{
dprintk("%s: state %p status\n", __func__, state);
if (likely(state->status >= 0)) {
objlayout_free_io_state(state);
} else {
struct objlayout *objlay = OBJLAYOUT(state->lseg->pls_layout);
spin_lock(&objlay->lock);
objlay->delta_space_valid = OBJ_DSU_INVALID;
list_add(&objlay->err_list, &state->err_list);
spin_unlock(&objlay->lock);
}
}
/*
* objlayout_io_set_result - Set an osd_error code on a specific osd comp.
*
* The @index component IO failed (error returned from target). Register
* the error for later reporting at layout-return.
*/
void
objlayout_io_set_result(struct objlayout_io_state *state, unsigned index,
struct pnfs_osd_objid *pooid, int osd_error,
u64 offset, u64 length, bool is_write)
{
struct pnfs_osd_ioerr *ioerr = &state->ioerrs[index];
BUG_ON(index >= state->num_comps);
if (osd_error) {
ioerr->oer_component = *pooid;
ioerr->oer_comp_offset = offset;
ioerr->oer_comp_length = length;
ioerr->oer_iswrite = is_write;
ioerr->oer_errno = osd_error;
dprintk("%s: err[%d]: errno=%d is_write=%d dev(%llx:%llx) "
"par=0x%llx obj=0x%llx offset=0x%llx length=0x%llx\n",
__func__, index, ioerr->oer_errno,
ioerr->oer_iswrite,
_DEVID_LO(&ioerr->oer_component.oid_device_id),
_DEVID_HI(&ioerr->oer_component.oid_device_id),
ioerr->oer_component.oid_partition_id,
ioerr->oer_component.oid_object_id,
ioerr->oer_comp_offset,
ioerr->oer_comp_length);
} else {
/* User need not call if no error is reported */
ioerr->oer_errno = 0;
}
}
/* Function scheduled on rpc workqueue to call ->nfs_readlist_complete().
* This is because the osd completion is called with ints-off from
* the block layer
*/
static void _rpc_read_complete(struct work_struct *work)
{
struct rpc_task *task;
struct nfs_read_data *rdata;
dprintk("%s enter\n", __func__);
task = container_of(work, struct rpc_task, u.tk_work);
rdata = container_of(task, struct nfs_read_data, task);
pnfs_ld_read_done(rdata);
}
void
objlayout_read_done(struct objlayout_io_state *state, ssize_t status, bool sync)
{
int eof = state->eof;
struct nfs_read_data *rdata;
state->status = status;
dprintk("%s: Begin status=%zd eof=%d\n", __func__, status, eof);
rdata = state->rpcdata;
rdata->task.tk_status = status;
if (likely(status >= 0)) {
rdata->res.count = status;
rdata->res.eof = eof;
} else {
rdata->pnfs_error = status;
}
objlayout_iodone(state);
/* must not use state after this point */
if (sync)
pnfs_ld_read_done(rdata);
else {
INIT_WORK(&rdata->task.u.tk_work, _rpc_read_complete);
schedule_work(&rdata->task.u.tk_work);
}
}
/*
* Perform sync or async reads.
*/
enum pnfs_try_status
objlayout_read_pagelist(struct nfs_read_data *rdata)
{
loff_t offset = rdata->args.offset;
size_t count = rdata->args.count;
struct objlayout_io_state *state;
ssize_t status = 0;
loff_t eof;
dprintk("%s: Begin inode %p offset %llu count %d\n",
__func__, rdata->inode, offset, (int)count);
eof = i_size_read(rdata->inode);
if (unlikely(offset + count > eof)) {
if (offset >= eof) {
status = 0;
rdata->res.count = 0;
rdata->res.eof = 1;
goto out;
}
count = eof - offset;
}
state = objlayout_alloc_io_state(NFS_I(rdata->inode)->layout,
rdata->args.pages, rdata->args.pgbase,
offset, count,
rdata->lseg, rdata,
GFP_KERNEL);
if (unlikely(!state)) {
status = -ENOMEM;
goto out;
}
state->eof = state->offset + state->count >= eof;
status = objio_read_pagelist(state);
out:
dprintk("%s: Return status %Zd\n", __func__, status);
rdata->pnfs_error = status;
return PNFS_ATTEMPTED;
}
/* Function scheduled on rpc workqueue to call ->nfs_writelist_complete().
* This is because the osd completion is called with ints-off from
* the block layer
*/
static void _rpc_write_complete(struct work_struct *work)
{
struct rpc_task *task;
struct nfs_write_data *wdata;
dprintk("%s enter\n", __func__);
task = container_of(work, struct rpc_task, u.tk_work);
wdata = container_of(task, struct nfs_write_data, task);
pnfs_ld_write_done(wdata);
}
void
objlayout_write_done(struct objlayout_io_state *state, ssize_t status,
bool sync)
{
struct nfs_write_data *wdata;
dprintk("%s: Begin\n", __func__);
wdata = state->rpcdata;
state->status = status;
wdata->task.tk_status = status;
if (likely(status >= 0)) {
wdata->res.count = status;
wdata->verf.committed = state->committed;
dprintk("%s: Return status %d committed %d\n",
__func__, wdata->task.tk_status,
wdata->verf.committed);
} else {
wdata->pnfs_error = status;
dprintk("%s: Return status %d\n",
__func__, wdata->task.tk_status);
}
objlayout_iodone(state);
/* must not use state after this point */
if (sync)
pnfs_ld_write_done(wdata);
else {
INIT_WORK(&wdata->task.u.tk_work, _rpc_write_complete);
schedule_work(&wdata->task.u.tk_work);
}
}
/*
* Perform sync or async writes.
*/
enum pnfs_try_status
objlayout_write_pagelist(struct nfs_write_data *wdata,
int how)
{
struct objlayout_io_state *state;
ssize_t status;
dprintk("%s: Begin inode %p offset %llu count %u\n",
__func__, wdata->inode, wdata->args.offset, wdata->args.count);
state = objlayout_alloc_io_state(NFS_I(wdata->inode)->layout,
wdata->args.pages,
wdata->args.pgbase,
wdata->args.offset,
wdata->args.count,
wdata->lseg, wdata,
GFP_NOFS);
if (unlikely(!state)) {
status = -ENOMEM;
goto out;
}
state->sync = how & FLUSH_SYNC;
status = objio_write_pagelist(state, how & FLUSH_STABLE);
out:
dprintk("%s: Return status %Zd\n", __func__, status);
wdata->pnfs_error = status;
return PNFS_ATTEMPTED;
}
void
objlayout_encode_layoutcommit(struct pnfs_layout_hdr *pnfslay,
struct xdr_stream *xdr,
const struct nfs4_layoutcommit_args *args)
{
struct objlayout *objlay = OBJLAYOUT(pnfslay);
struct pnfs_osd_layoutupdate lou;
__be32 *start;
dprintk("%s: Begin\n", __func__);
spin_lock(&objlay->lock);
lou.dsu_valid = (objlay->delta_space_valid == OBJ_DSU_VALID);
lou.dsu_delta = objlay->delta_space_used;
objlay->delta_space_used = 0;
objlay->delta_space_valid = OBJ_DSU_INIT;
lou.olu_ioerr_flag = !list_empty(&objlay->err_list);
spin_unlock(&objlay->lock);
start = xdr_reserve_space(xdr, 4);
BUG_ON(pnfs_osd_xdr_encode_layoutupdate(xdr, &lou));
*start = cpu_to_be32((xdr->p - start - 1) * 4);
dprintk("%s: Return delta_space_used %lld err %d\n", __func__,
lou.dsu_delta, lou.olu_ioerr_flag);
}
static int
err_prio(u32 oer_errno)
{
switch (oer_errno) {
case 0:
return 0;
case PNFS_OSD_ERR_RESOURCE:
return OSD_ERR_PRI_RESOURCE;
case PNFS_OSD_ERR_BAD_CRED:
return OSD_ERR_PRI_BAD_CRED;
case PNFS_OSD_ERR_NO_ACCESS:
return OSD_ERR_PRI_NO_ACCESS;
case PNFS_OSD_ERR_UNREACHABLE:
return OSD_ERR_PRI_UNREACHABLE;
case PNFS_OSD_ERR_NOT_FOUND:
return OSD_ERR_PRI_NOT_FOUND;
case PNFS_OSD_ERR_NO_SPACE:
return OSD_ERR_PRI_NO_SPACE;
default:
WARN_ON(1);
/* fallthrough */
case PNFS_OSD_ERR_EIO:
return OSD_ERR_PRI_EIO;
}
}
static void
merge_ioerr(struct pnfs_osd_ioerr *dest_err,
const struct pnfs_osd_ioerr *src_err)
{
u64 dest_end, src_end;
if (!dest_err->oer_errno) {
*dest_err = *src_err;
/* accumulated device must be blank */
memset(&dest_err->oer_component.oid_device_id, 0,
sizeof(dest_err->oer_component.oid_device_id));
return;
}
if (dest_err->oer_component.oid_partition_id !=
src_err->oer_component.oid_partition_id)
dest_err->oer_component.oid_partition_id = 0;
if (dest_err->oer_component.oid_object_id !=
src_err->oer_component.oid_object_id)
dest_err->oer_component.oid_object_id = 0;
if (dest_err->oer_comp_offset > src_err->oer_comp_offset)
dest_err->oer_comp_offset = src_err->oer_comp_offset;
dest_end = end_offset(dest_err->oer_comp_offset,
dest_err->oer_comp_length);
src_end = end_offset(src_err->oer_comp_offset,
src_err->oer_comp_length);
if (dest_end < src_end)
dest_end = src_end;
dest_err->oer_comp_length = dest_end - dest_err->oer_comp_offset;
if ((src_err->oer_iswrite == dest_err->oer_iswrite) &&
(err_prio(src_err->oer_errno) > err_prio(dest_err->oer_errno))) {
dest_err->oer_errno = src_err->oer_errno;
} else if (src_err->oer_iswrite) {
dest_err->oer_iswrite = true;
dest_err->oer_errno = src_err->oer_errno;
}
}
static void
encode_accumulated_error(struct objlayout *objlay, __be32 *p)
{
struct objlayout_io_state *state, *tmp;
struct pnfs_osd_ioerr accumulated_err = {.oer_errno = 0};
list_for_each_entry_safe(state, tmp, &objlay->err_list, err_list) {
unsigned i;
for (i = 0; i < state->num_comps; i++) {
struct pnfs_osd_ioerr *ioerr = &state->ioerrs[i];
if (!ioerr->oer_errno)
continue;
printk(KERN_ERR "%s: err[%d]: errno=%d is_write=%d "
"dev(%llx:%llx) par=0x%llx obj=0x%llx "
"offset=0x%llx length=0x%llx\n",
__func__, i, ioerr->oer_errno,
ioerr->oer_iswrite,
_DEVID_LO(&ioerr->oer_component.oid_device_id),
_DEVID_HI(&ioerr->oer_component.oid_device_id),
ioerr->oer_component.oid_partition_id,
ioerr->oer_component.oid_object_id,
ioerr->oer_comp_offset,
ioerr->oer_comp_length);
merge_ioerr(&accumulated_err, ioerr);
}
list_del(&state->err_list);
objlayout_free_io_state(state);
}
pnfs_osd_xdr_encode_ioerr(p, &accumulated_err);
}
void
objlayout_encode_layoutreturn(struct pnfs_layout_hdr *pnfslay,
struct xdr_stream *xdr,
const struct nfs4_layoutreturn_args *args)
{
struct objlayout *objlay = OBJLAYOUT(pnfslay);
struct objlayout_io_state *state, *tmp;
__be32 *start;
dprintk("%s: Begin\n", __func__);
start = xdr_reserve_space(xdr, 4);
BUG_ON(!start);
spin_lock(&objlay->lock);
list_for_each_entry_safe(state, tmp, &objlay->err_list, err_list) {
__be32 *last_xdr = NULL, *p;
unsigned i;
int res = 0;
for (i = 0; i < state->num_comps; i++) {
struct pnfs_osd_ioerr *ioerr = &state->ioerrs[i];
if (!ioerr->oer_errno)
continue;
dprintk("%s: err[%d]: errno=%d is_write=%d "
"dev(%llx:%llx) par=0x%llx obj=0x%llx "
"offset=0x%llx length=0x%llx\n",
__func__, i, ioerr->oer_errno,
ioerr->oer_iswrite,
_DEVID_LO(&ioerr->oer_component.oid_device_id),
_DEVID_HI(&ioerr->oer_component.oid_device_id),
ioerr->oer_component.oid_partition_id,
ioerr->oer_component.oid_object_id,
ioerr->oer_comp_offset,
ioerr->oer_comp_length);
p = pnfs_osd_xdr_ioerr_reserve_space(xdr);
if (unlikely(!p)) {
res = -E2BIG;
break; /* accumulated_error */
}
last_xdr = p;
pnfs_osd_xdr_encode_ioerr(p, &state->ioerrs[i]);
}
/* TODO: use xdr_write_pages */
if (unlikely(res)) {
/* no space for even one error descriptor */
BUG_ON(!last_xdr);
/* we've encountered a situation with lots and lots of
* errors and no space to encode them all. Use the last
* available slot to report the union of all the
* remaining errors.
*/
encode_accumulated_error(objlay, last_xdr);
goto loop_done;
}
list_del(&state->err_list);
objlayout_free_io_state(state);
}
loop_done:
spin_unlock(&objlay->lock);
*start = cpu_to_be32((xdr->p - start - 1) * 4);
dprintk("%s: Return\n", __func__);
}
/*
* Get Device Info API for io engines
*/
struct objlayout_deviceinfo {
struct page *page;
struct pnfs_osd_deviceaddr da; /* This must be last */
};
/* Initialize and call nfs_getdeviceinfo, then decode and return a
* "struct pnfs_osd_deviceaddr *" Eventually objlayout_put_deviceinfo()
* should be called.
*/
int objlayout_get_deviceinfo(struct pnfs_layout_hdr *pnfslay,
struct nfs4_deviceid *d_id, struct pnfs_osd_deviceaddr **deviceaddr,
gfp_t gfp_flags)
{
struct objlayout_deviceinfo *odi;
struct pnfs_device pd;
struct super_block *sb;
struct page *page, **pages;
u32 *p;
int err;
page = alloc_page(gfp_flags);
if (!page)
return -ENOMEM;
pages = &page;
pd.pages = pages;
memcpy(&pd.dev_id, d_id, sizeof(*d_id));
pd.layout_type = LAYOUT_OSD2_OBJECTS;
pd.pages = &page;
pd.pgbase = 0;
pd.pglen = PAGE_SIZE;
pd.mincount = 0;
sb = pnfslay->plh_inode->i_sb;
err = nfs4_proc_getdeviceinfo(NFS_SERVER(pnfslay->plh_inode), &pd);
dprintk("%s nfs_getdeviceinfo returned %d\n", __func__, err);
if (err)
goto err_out;
p = page_address(page);
odi = kzalloc(sizeof(*odi), gfp_flags);
if (!odi) {
err = -ENOMEM;
goto err_out;
}
pnfs_osd_xdr_decode_deviceaddr(&odi->da, p);
odi->page = page;
*deviceaddr = &odi->da;
return 0;
err_out:
__free_page(page);
return err;
}
void objlayout_put_deviceinfo(struct pnfs_osd_deviceaddr *deviceaddr)
{
struct objlayout_deviceinfo *odi = container_of(deviceaddr,
struct objlayout_deviceinfo,
da);
__free_page(odi->page);
kfree(odi);
}
| gpl-2.0 |
savoca/h811 | arch/mips/powertv/asic/asic-gaia.c | 2153 | 4282 | /*
* Locations of devices in the Gaia ASIC
*
* Copyright (C) 2005-2009 Scientific-Atlanta, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Author: David VomLehn
*/
#include <linux/init.h>
#include <asm/mach-powertv/asic.h>
const struct register_map gaia_register_map __initconst = {
.eic_slow0_strt_add = {.phys = GAIA_IO_BASE + 0x000000},
.eic_cfg_bits = {.phys = GAIA_IO_BASE + 0x000038},
.eic_ready_status = {.phys = GAIA_IO_BASE + 0x00004C},
.chipver3 = {.phys = GAIA_IO_BASE + 0x2A0800},
.chipver2 = {.phys = GAIA_IO_BASE + 0x2A0804},
.chipver1 = {.phys = GAIA_IO_BASE + 0x2A0808},
.chipver0 = {.phys = GAIA_IO_BASE + 0x2A080C},
/* The registers of IRBlaster */
.uart1_intstat = {.phys = GAIA_IO_BASE + 0x2A1800},
.uart1_inten = {.phys = GAIA_IO_BASE + 0x2A1804},
.uart1_config1 = {.phys = GAIA_IO_BASE + 0x2A1808},
.uart1_config2 = {.phys = GAIA_IO_BASE + 0x2A180C},
.uart1_divisorhi = {.phys = GAIA_IO_BASE + 0x2A1810},
.uart1_divisorlo = {.phys = GAIA_IO_BASE + 0x2A1814},
.uart1_data = {.phys = GAIA_IO_BASE + 0x2A1818},
.uart1_status = {.phys = GAIA_IO_BASE + 0x2A181C},
.int_stat_3 = {.phys = GAIA_IO_BASE + 0x2A2800},
.int_stat_2 = {.phys = GAIA_IO_BASE + 0x2A2804},
.int_stat_1 = {.phys = GAIA_IO_BASE + 0x2A2808},
.int_stat_0 = {.phys = GAIA_IO_BASE + 0x2A280C},
.int_config = {.phys = GAIA_IO_BASE + 0x2A2810},
.int_int_scan = {.phys = GAIA_IO_BASE + 0x2A2818},
.ien_int_3 = {.phys = GAIA_IO_BASE + 0x2A2830},
.ien_int_2 = {.phys = GAIA_IO_BASE + 0x2A2834},
.ien_int_1 = {.phys = GAIA_IO_BASE + 0x2A2838},
.ien_int_0 = {.phys = GAIA_IO_BASE + 0x2A283C},
.int_level_3_3 = {.phys = GAIA_IO_BASE + 0x2A2880},
.int_level_3_2 = {.phys = GAIA_IO_BASE + 0x2A2884},
.int_level_3_1 = {.phys = GAIA_IO_BASE + 0x2A2888},
.int_level_3_0 = {.phys = GAIA_IO_BASE + 0x2A288C},
.int_level_2_3 = {.phys = GAIA_IO_BASE + 0x2A2890},
.int_level_2_2 = {.phys = GAIA_IO_BASE + 0x2A2894},
.int_level_2_1 = {.phys = GAIA_IO_BASE + 0x2A2898},
.int_level_2_0 = {.phys = GAIA_IO_BASE + 0x2A289C},
.int_level_1_3 = {.phys = GAIA_IO_BASE + 0x2A28A0},
.int_level_1_2 = {.phys = GAIA_IO_BASE + 0x2A28A4},
.int_level_1_1 = {.phys = GAIA_IO_BASE + 0x2A28A8},
.int_level_1_0 = {.phys = GAIA_IO_BASE + 0x2A28AC},
.int_level_0_3 = {.phys = GAIA_IO_BASE + 0x2A28B0},
.int_level_0_2 = {.phys = GAIA_IO_BASE + 0x2A28B4},
.int_level_0_1 = {.phys = GAIA_IO_BASE + 0x2A28B8},
.int_level_0_0 = {.phys = GAIA_IO_BASE + 0x2A28BC},
.int_docsis_en = {.phys = GAIA_IO_BASE + 0x2A28F4},
.mips_pll_setup = {.phys = GAIA_IO_BASE + 0x1C0000},
.fs432x4b4_usb_ctl = {.phys = GAIA_IO_BASE + 0x1C0024},
.test_bus = {.phys = GAIA_IO_BASE + 0x1C00CC},
.crt_spare = {.phys = GAIA_IO_BASE + 0x1c0108},
.usb2_ohci_int_mask = {.phys = GAIA_IO_BASE + 0x20000C},
.usb2_strap = {.phys = GAIA_IO_BASE + 0x200014},
.ehci_hcapbase = {.phys = GAIA_IO_BASE + 0x21FE00},
.ohci_hc_revision = {.phys = GAIA_IO_BASE + 0x21fc00},
.bcm1_bs_lmi_steer = {.phys = GAIA_IO_BASE + 0x2E0004},
.usb2_control = {.phys = GAIA_IO_BASE + 0x2E004C},
.usb2_stbus_obc = {.phys = GAIA_IO_BASE + 0x21FF00},
.usb2_stbus_mess_size = {.phys = GAIA_IO_BASE + 0x21FF04},
.usb2_stbus_chunk_size = {.phys = GAIA_IO_BASE + 0x21FF08},
.pcie_regs = {.phys = GAIA_IO_BASE + 0x220000},
.tim_ch = {.phys = GAIA_IO_BASE + 0x2A2C10},
.tim_cl = {.phys = GAIA_IO_BASE + 0x2A2C14},
.gpio_dout = {.phys = GAIA_IO_BASE + 0x2A2C20},
.gpio_din = {.phys = GAIA_IO_BASE + 0x2A2C24},
.gpio_dir = {.phys = GAIA_IO_BASE + 0x2A2C2C},
.watchdog = {.phys = GAIA_IO_BASE + 0x2A2C30},
.front_panel = {.phys = GAIA_IO_BASE + 0x2A3800},
};
| gpl-2.0 |
arn4v/yu_msm8916 | drivers/net/ethernet/pasemi/pasemi_mac.c | 2153 | 48346 | /*
* Copyright (C) 2006-2007 PA Semi, Inc
*
* Driver for the PA Semi PWRficient onchip 1G/10G Ethernet MACs
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/dmaengine.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/of_mdio.h>
#include <linux/etherdevice.h>
#include <asm/dma-mapping.h>
#include <linux/in.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <net/checksum.h>
#include <linux/inet_lro.h>
#include <linux/prefetch.h>
#include <asm/irq.h>
#include <asm/firmware.h>
#include <asm/pasemi_dma.h>
#include "pasemi_mac.h"
/* We have our own align, since ppc64 in general has it at 0 because
* of design flaws in some of the server bridge chips. However, for
* PWRficient doing the unaligned copies is more expensive than doing
* unaligned DMA, so make sure the data is aligned instead.
*/
#define LOCAL_SKB_ALIGN 2
/* TODO list
*
* - Multicast support
* - Large MTU support
* - SW LRO
* - Multiqueue RX/TX
*/
#define LRO_MAX_AGGR 64
#define PE_MIN_MTU 64
#define PE_MAX_MTU 9000
#define PE_DEF_MTU ETH_DATA_LEN
#define DEFAULT_MSG_ENABLE \
(NETIF_MSG_DRV | \
NETIF_MSG_PROBE | \
NETIF_MSG_LINK | \
NETIF_MSG_TIMER | \
NETIF_MSG_IFDOWN | \
NETIF_MSG_IFUP | \
NETIF_MSG_RX_ERR | \
NETIF_MSG_TX_ERR)
MODULE_LICENSE("GPL");
MODULE_AUTHOR ("Olof Johansson <olof@lixom.net>");
MODULE_DESCRIPTION("PA Semi PWRficient Ethernet driver");
static int debug = -1; /* -1 == use DEFAULT_MSG_ENABLE as value */
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "PA Semi MAC bitmapped debugging message enable value");
extern const struct ethtool_ops pasemi_mac_ethtool_ops;
static int translation_enabled(void)
{
#if defined(CONFIG_PPC_PASEMI_IOMMU_DMA_FORCE)
return 1;
#else
return firmware_has_feature(FW_FEATURE_LPAR);
#endif
}
static void write_iob_reg(unsigned int reg, unsigned int val)
{
pasemi_write_iob_reg(reg, val);
}
static unsigned int read_mac_reg(const struct pasemi_mac *mac, unsigned int reg)
{
return pasemi_read_mac_reg(mac->dma_if, reg);
}
static void write_mac_reg(const struct pasemi_mac *mac, unsigned int reg,
unsigned int val)
{
pasemi_write_mac_reg(mac->dma_if, reg, val);
}
static unsigned int read_dma_reg(unsigned int reg)
{
return pasemi_read_dma_reg(reg);
}
static void write_dma_reg(unsigned int reg, unsigned int val)
{
pasemi_write_dma_reg(reg, val);
}
static struct pasemi_mac_rxring *rx_ring(const struct pasemi_mac *mac)
{
return mac->rx;
}
static struct pasemi_mac_txring *tx_ring(const struct pasemi_mac *mac)
{
return mac->tx;
}
static inline void prefetch_skb(const struct sk_buff *skb)
{
const void *d = skb;
prefetch(d);
prefetch(d+64);
prefetch(d+128);
prefetch(d+192);
}
static int mac_to_intf(struct pasemi_mac *mac)
{
struct pci_dev *pdev = mac->pdev;
u32 tmp;
int nintf, off, i, j;
int devfn = pdev->devfn;
tmp = read_dma_reg(PAS_DMA_CAP_IFI);
nintf = (tmp & PAS_DMA_CAP_IFI_NIN_M) >> PAS_DMA_CAP_IFI_NIN_S;
off = (tmp & PAS_DMA_CAP_IFI_IOFF_M) >> PAS_DMA_CAP_IFI_IOFF_S;
/* IOFF contains the offset to the registers containing the
* DMA interface-to-MAC-pci-id mappings, and NIN contains number
* of total interfaces. Each register contains 4 devfns.
* Just do a linear search until we find the devfn of the MAC
* we're trying to look up.
*/
for (i = 0; i < (nintf+3)/4; i++) {
tmp = read_dma_reg(off+4*i);
for (j = 0; j < 4; j++) {
if (((tmp >> (8*j)) & 0xff) == devfn)
return i*4 + j;
}
}
return -1;
}
static void pasemi_mac_intf_disable(struct pasemi_mac *mac)
{
unsigned int flags;
flags = read_mac_reg(mac, PAS_MAC_CFG_PCFG);
flags &= ~PAS_MAC_CFG_PCFG_PE;
write_mac_reg(mac, PAS_MAC_CFG_PCFG, flags);
}
static void pasemi_mac_intf_enable(struct pasemi_mac *mac)
{
unsigned int flags;
flags = read_mac_reg(mac, PAS_MAC_CFG_PCFG);
flags |= PAS_MAC_CFG_PCFG_PE;
write_mac_reg(mac, PAS_MAC_CFG_PCFG, flags);
}
static int pasemi_get_mac_addr(struct pasemi_mac *mac)
{
struct pci_dev *pdev = mac->pdev;
struct device_node *dn = pci_device_to_OF_node(pdev);
int len;
const u8 *maddr;
u8 addr[6];
if (!dn) {
dev_dbg(&pdev->dev,
"No device node for mac, not configuring\n");
return -ENOENT;
}
maddr = of_get_property(dn, "local-mac-address", &len);
if (maddr && len == 6) {
memcpy(mac->mac_addr, maddr, 6);
return 0;
}
/* Some old versions of firmware mistakenly uses mac-address
* (and as a string) instead of a byte array in local-mac-address.
*/
if (maddr == NULL)
maddr = of_get_property(dn, "mac-address", NULL);
if (maddr == NULL) {
dev_warn(&pdev->dev,
"no mac address in device tree, not configuring\n");
return -ENOENT;
}
if (sscanf(maddr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &addr[0],
&addr[1], &addr[2], &addr[3], &addr[4], &addr[5]) != 6) {
dev_warn(&pdev->dev,
"can't parse mac address, not configuring\n");
return -EINVAL;
}
memcpy(mac->mac_addr, addr, 6);
return 0;
}
static int pasemi_mac_set_mac_addr(struct net_device *dev, void *p)
{
struct pasemi_mac *mac = netdev_priv(dev);
struct sockaddr *addr = p;
unsigned int adr0, adr1;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
adr0 = dev->dev_addr[2] << 24 |
dev->dev_addr[3] << 16 |
dev->dev_addr[4] << 8 |
dev->dev_addr[5];
adr1 = read_mac_reg(mac, PAS_MAC_CFG_ADR1);
adr1 &= ~0xffff;
adr1 |= dev->dev_addr[0] << 8 | dev->dev_addr[1];
pasemi_mac_intf_disable(mac);
write_mac_reg(mac, PAS_MAC_CFG_ADR0, adr0);
write_mac_reg(mac, PAS_MAC_CFG_ADR1, adr1);
pasemi_mac_intf_enable(mac);
return 0;
}
static int get_skb_hdr(struct sk_buff *skb, void **iphdr,
void **tcph, u64 *hdr_flags, void *data)
{
u64 macrx = (u64) data;
unsigned int ip_len;
struct iphdr *iph;
/* IPv4 header checksum failed */
if ((macrx & XCT_MACRX_HTY_M) != XCT_MACRX_HTY_IPV4_OK)
return -1;
/* non tcp packet */
skb_reset_network_header(skb);
iph = ip_hdr(skb);
if (iph->protocol != IPPROTO_TCP)
return -1;
ip_len = ip_hdrlen(skb);
skb_set_transport_header(skb, ip_len);
*tcph = tcp_hdr(skb);
/* check if ip header and tcp header are complete */
if (ntohs(iph->tot_len) < ip_len + tcp_hdrlen(skb))
return -1;
*hdr_flags = LRO_IPV4 | LRO_TCP;
*iphdr = iph;
return 0;
}
static int pasemi_mac_unmap_tx_skb(struct pasemi_mac *mac,
const int nfrags,
struct sk_buff *skb,
const dma_addr_t *dmas)
{
int f;
struct pci_dev *pdev = mac->dma_pdev;
pci_unmap_single(pdev, dmas[0], skb_headlen(skb), PCI_DMA_TODEVICE);
for (f = 0; f < nfrags; f++) {
const skb_frag_t *frag = &skb_shinfo(skb)->frags[f];
pci_unmap_page(pdev, dmas[f+1], skb_frag_size(frag), PCI_DMA_TODEVICE);
}
dev_kfree_skb_irq(skb);
/* Freed descriptor slot + main SKB ptr + nfrags additional ptrs,
* aligned up to a power of 2
*/
return (nfrags + 3) & ~1;
}
static struct pasemi_mac_csring *pasemi_mac_setup_csring(struct pasemi_mac *mac)
{
struct pasemi_mac_csring *ring;
u32 val;
unsigned int cfg;
int chno;
ring = pasemi_dma_alloc_chan(TXCHAN, sizeof(struct pasemi_mac_csring),
offsetof(struct pasemi_mac_csring, chan));
if (!ring) {
dev_err(&mac->pdev->dev, "Can't allocate checksum channel\n");
goto out_chan;
}
chno = ring->chan.chno;
ring->size = CS_RING_SIZE;
ring->next_to_fill = 0;
/* Allocate descriptors */
if (pasemi_dma_alloc_ring(&ring->chan, CS_RING_SIZE))
goto out_ring_desc;
write_dma_reg(PAS_DMA_TXCHAN_BASEL(chno),
PAS_DMA_TXCHAN_BASEL_BRBL(ring->chan.ring_dma));
val = PAS_DMA_TXCHAN_BASEU_BRBH(ring->chan.ring_dma >> 32);
val |= PAS_DMA_TXCHAN_BASEU_SIZ(CS_RING_SIZE >> 3);
write_dma_reg(PAS_DMA_TXCHAN_BASEU(chno), val);
ring->events[0] = pasemi_dma_alloc_flag();
ring->events[1] = pasemi_dma_alloc_flag();
if (ring->events[0] < 0 || ring->events[1] < 0)
goto out_flags;
pasemi_dma_clear_flag(ring->events[0]);
pasemi_dma_clear_flag(ring->events[1]);
ring->fun = pasemi_dma_alloc_fun();
if (ring->fun < 0)
goto out_fun;
cfg = PAS_DMA_TXCHAN_CFG_TY_FUNC | PAS_DMA_TXCHAN_CFG_UP |
PAS_DMA_TXCHAN_CFG_TATTR(ring->fun) |
PAS_DMA_TXCHAN_CFG_LPSQ | PAS_DMA_TXCHAN_CFG_LPDQ;
if (translation_enabled())
cfg |= PAS_DMA_TXCHAN_CFG_TRD | PAS_DMA_TXCHAN_CFG_TRR;
write_dma_reg(PAS_DMA_TXCHAN_CFG(chno), cfg);
/* enable channel */
pasemi_dma_start_chan(&ring->chan, PAS_DMA_TXCHAN_TCMDSTA_SZ |
PAS_DMA_TXCHAN_TCMDSTA_DB |
PAS_DMA_TXCHAN_TCMDSTA_DE |
PAS_DMA_TXCHAN_TCMDSTA_DA);
return ring;
out_fun:
out_flags:
if (ring->events[0] >= 0)
pasemi_dma_free_flag(ring->events[0]);
if (ring->events[1] >= 0)
pasemi_dma_free_flag(ring->events[1]);
pasemi_dma_free_ring(&ring->chan);
out_ring_desc:
pasemi_dma_free_chan(&ring->chan);
out_chan:
return NULL;
}
static void pasemi_mac_setup_csrings(struct pasemi_mac *mac)
{
int i;
mac->cs[0] = pasemi_mac_setup_csring(mac);
if (mac->type == MAC_TYPE_XAUI)
mac->cs[1] = pasemi_mac_setup_csring(mac);
else
mac->cs[1] = 0;
for (i = 0; i < MAX_CS; i++)
if (mac->cs[i])
mac->num_cs++;
}
static void pasemi_mac_free_csring(struct pasemi_mac_csring *csring)
{
pasemi_dma_stop_chan(&csring->chan);
pasemi_dma_free_flag(csring->events[0]);
pasemi_dma_free_flag(csring->events[1]);
pasemi_dma_free_ring(&csring->chan);
pasemi_dma_free_chan(&csring->chan);
pasemi_dma_free_fun(csring->fun);
}
static int pasemi_mac_setup_rx_resources(const struct net_device *dev)
{
struct pasemi_mac_rxring *ring;
struct pasemi_mac *mac = netdev_priv(dev);
int chno;
unsigned int cfg;
ring = pasemi_dma_alloc_chan(RXCHAN, sizeof(struct pasemi_mac_rxring),
offsetof(struct pasemi_mac_rxring, chan));
if (!ring) {
dev_err(&mac->pdev->dev, "Can't allocate RX channel\n");
goto out_chan;
}
chno = ring->chan.chno;
spin_lock_init(&ring->lock);
ring->size = RX_RING_SIZE;
ring->ring_info = kzalloc(sizeof(struct pasemi_mac_buffer) *
RX_RING_SIZE, GFP_KERNEL);
if (!ring->ring_info)
goto out_ring_info;
/* Allocate descriptors */
if (pasemi_dma_alloc_ring(&ring->chan, RX_RING_SIZE))
goto out_ring_desc;
ring->buffers = dma_alloc_coherent(&mac->dma_pdev->dev,
RX_RING_SIZE * sizeof(u64),
&ring->buf_dma,
GFP_KERNEL | __GFP_ZERO);
if (!ring->buffers)
goto out_ring_desc;
write_dma_reg(PAS_DMA_RXCHAN_BASEL(chno),
PAS_DMA_RXCHAN_BASEL_BRBL(ring->chan.ring_dma));
write_dma_reg(PAS_DMA_RXCHAN_BASEU(chno),
PAS_DMA_RXCHAN_BASEU_BRBH(ring->chan.ring_dma >> 32) |
PAS_DMA_RXCHAN_BASEU_SIZ(RX_RING_SIZE >> 3));
cfg = PAS_DMA_RXCHAN_CFG_HBU(2);
if (translation_enabled())
cfg |= PAS_DMA_RXCHAN_CFG_CTR;
write_dma_reg(PAS_DMA_RXCHAN_CFG(chno), cfg);
write_dma_reg(PAS_DMA_RXINT_BASEL(mac->dma_if),
PAS_DMA_RXINT_BASEL_BRBL(ring->buf_dma));
write_dma_reg(PAS_DMA_RXINT_BASEU(mac->dma_if),
PAS_DMA_RXINT_BASEU_BRBH(ring->buf_dma >> 32) |
PAS_DMA_RXINT_BASEU_SIZ(RX_RING_SIZE >> 3));
cfg = PAS_DMA_RXINT_CFG_DHL(2) | PAS_DMA_RXINT_CFG_L2 |
PAS_DMA_RXINT_CFG_LW | PAS_DMA_RXINT_CFG_RBP |
PAS_DMA_RXINT_CFG_HEN;
if (translation_enabled())
cfg |= PAS_DMA_RXINT_CFG_ITRR | PAS_DMA_RXINT_CFG_ITR;
write_dma_reg(PAS_DMA_RXINT_CFG(mac->dma_if), cfg);
ring->next_to_fill = 0;
ring->next_to_clean = 0;
ring->mac = mac;
mac->rx = ring;
return 0;
out_ring_desc:
kfree(ring->ring_info);
out_ring_info:
pasemi_dma_free_chan(&ring->chan);
out_chan:
return -ENOMEM;
}
static struct pasemi_mac_txring *
pasemi_mac_setup_tx_resources(const struct net_device *dev)
{
struct pasemi_mac *mac = netdev_priv(dev);
u32 val;
struct pasemi_mac_txring *ring;
unsigned int cfg;
int chno;
ring = pasemi_dma_alloc_chan(TXCHAN, sizeof(struct pasemi_mac_txring),
offsetof(struct pasemi_mac_txring, chan));
if (!ring) {
dev_err(&mac->pdev->dev, "Can't allocate TX channel\n");
goto out_chan;
}
chno = ring->chan.chno;
spin_lock_init(&ring->lock);
ring->size = TX_RING_SIZE;
ring->ring_info = kzalloc(sizeof(struct pasemi_mac_buffer) *
TX_RING_SIZE, GFP_KERNEL);
if (!ring->ring_info)
goto out_ring_info;
/* Allocate descriptors */
if (pasemi_dma_alloc_ring(&ring->chan, TX_RING_SIZE))
goto out_ring_desc;
write_dma_reg(PAS_DMA_TXCHAN_BASEL(chno),
PAS_DMA_TXCHAN_BASEL_BRBL(ring->chan.ring_dma));
val = PAS_DMA_TXCHAN_BASEU_BRBH(ring->chan.ring_dma >> 32);
val |= PAS_DMA_TXCHAN_BASEU_SIZ(TX_RING_SIZE >> 3);
write_dma_reg(PAS_DMA_TXCHAN_BASEU(chno), val);
cfg = PAS_DMA_TXCHAN_CFG_TY_IFACE |
PAS_DMA_TXCHAN_CFG_TATTR(mac->dma_if) |
PAS_DMA_TXCHAN_CFG_UP |
PAS_DMA_TXCHAN_CFG_WT(4);
if (translation_enabled())
cfg |= PAS_DMA_TXCHAN_CFG_TRD | PAS_DMA_TXCHAN_CFG_TRR;
write_dma_reg(PAS_DMA_TXCHAN_CFG(chno), cfg);
ring->next_to_fill = 0;
ring->next_to_clean = 0;
ring->mac = mac;
return ring;
out_ring_desc:
kfree(ring->ring_info);
out_ring_info:
pasemi_dma_free_chan(&ring->chan);
out_chan:
return NULL;
}
static void pasemi_mac_free_tx_resources(struct pasemi_mac *mac)
{
struct pasemi_mac_txring *txring = tx_ring(mac);
unsigned int i, j;
struct pasemi_mac_buffer *info;
dma_addr_t dmas[MAX_SKB_FRAGS+1];
int freed, nfrags;
int start, limit;
start = txring->next_to_clean;
limit = txring->next_to_fill;
/* Compensate for when fill has wrapped and clean has not */
if (start > limit)
limit += TX_RING_SIZE;
for (i = start; i < limit; i += freed) {
info = &txring->ring_info[(i+1) & (TX_RING_SIZE-1)];
if (info->dma && info->skb) {
nfrags = skb_shinfo(info->skb)->nr_frags;
for (j = 0; j <= nfrags; j++)
dmas[j] = txring->ring_info[(i+1+j) &
(TX_RING_SIZE-1)].dma;
freed = pasemi_mac_unmap_tx_skb(mac, nfrags,
info->skb, dmas);
} else {
freed = 2;
}
}
kfree(txring->ring_info);
pasemi_dma_free_chan(&txring->chan);
}
static void pasemi_mac_free_rx_buffers(struct pasemi_mac *mac)
{
struct pasemi_mac_rxring *rx = rx_ring(mac);
unsigned int i;
struct pasemi_mac_buffer *info;
for (i = 0; i < RX_RING_SIZE; i++) {
info = &RX_DESC_INFO(rx, i);
if (info->skb && info->dma) {
pci_unmap_single(mac->dma_pdev,
info->dma,
info->skb->len,
PCI_DMA_FROMDEVICE);
dev_kfree_skb_any(info->skb);
}
info->dma = 0;
info->skb = NULL;
}
for (i = 0; i < RX_RING_SIZE; i++)
RX_BUFF(rx, i) = 0;
}
static void pasemi_mac_free_rx_resources(struct pasemi_mac *mac)
{
pasemi_mac_free_rx_buffers(mac);
dma_free_coherent(&mac->dma_pdev->dev, RX_RING_SIZE * sizeof(u64),
rx_ring(mac)->buffers, rx_ring(mac)->buf_dma);
kfree(rx_ring(mac)->ring_info);
pasemi_dma_free_chan(&rx_ring(mac)->chan);
mac->rx = NULL;
}
static void pasemi_mac_replenish_rx_ring(struct net_device *dev,
const int limit)
{
const struct pasemi_mac *mac = netdev_priv(dev);
struct pasemi_mac_rxring *rx = rx_ring(mac);
int fill, count;
if (limit <= 0)
return;
fill = rx_ring(mac)->next_to_fill;
for (count = 0; count < limit; count++) {
struct pasemi_mac_buffer *info = &RX_DESC_INFO(rx, fill);
u64 *buff = &RX_BUFF(rx, fill);
struct sk_buff *skb;
dma_addr_t dma;
/* Entry in use? */
WARN_ON(*buff);
skb = netdev_alloc_skb(dev, mac->bufsz);
skb_reserve(skb, LOCAL_SKB_ALIGN);
if (unlikely(!skb))
break;
dma = pci_map_single(mac->dma_pdev, skb->data,
mac->bufsz - LOCAL_SKB_ALIGN,
PCI_DMA_FROMDEVICE);
if (unlikely(pci_dma_mapping_error(mac->dma_pdev, dma))) {
dev_kfree_skb_irq(info->skb);
break;
}
info->skb = skb;
info->dma = dma;
*buff = XCT_RXB_LEN(mac->bufsz) | XCT_RXB_ADDR(dma);
fill++;
}
wmb();
write_dma_reg(PAS_DMA_RXINT_INCR(mac->dma_if), count);
rx_ring(mac)->next_to_fill = (rx_ring(mac)->next_to_fill + count) &
(RX_RING_SIZE - 1);
}
static void pasemi_mac_restart_rx_intr(const struct pasemi_mac *mac)
{
struct pasemi_mac_rxring *rx = rx_ring(mac);
unsigned int reg, pcnt;
/* Re-enable packet count interrupts: finally
* ack the packet count interrupt we got in rx_intr.
*/
pcnt = *rx->chan.status & PAS_STATUS_PCNT_M;
reg = PAS_IOB_DMA_RXCH_RESET_PCNT(pcnt) | PAS_IOB_DMA_RXCH_RESET_PINTC;
if (*rx->chan.status & PAS_STATUS_TIMER)
reg |= PAS_IOB_DMA_RXCH_RESET_TINTC;
write_iob_reg(PAS_IOB_DMA_RXCH_RESET(mac->rx->chan.chno), reg);
}
static void pasemi_mac_restart_tx_intr(const struct pasemi_mac *mac)
{
unsigned int reg, pcnt;
/* Re-enable packet count interrupts */
pcnt = *tx_ring(mac)->chan.status & PAS_STATUS_PCNT_M;
reg = PAS_IOB_DMA_TXCH_RESET_PCNT(pcnt) | PAS_IOB_DMA_TXCH_RESET_PINTC;
write_iob_reg(PAS_IOB_DMA_TXCH_RESET(tx_ring(mac)->chan.chno), reg);
}
static inline void pasemi_mac_rx_error(const struct pasemi_mac *mac,
const u64 macrx)
{
unsigned int rcmdsta, ccmdsta;
struct pasemi_dmachan *chan = &rx_ring(mac)->chan;
if (!netif_msg_rx_err(mac))
return;
rcmdsta = read_dma_reg(PAS_DMA_RXINT_RCMDSTA(mac->dma_if));
ccmdsta = read_dma_reg(PAS_DMA_RXCHAN_CCMDSTA(chan->chno));
printk(KERN_ERR "pasemi_mac: rx error. macrx %016llx, rx status %llx\n",
macrx, *chan->status);
printk(KERN_ERR "pasemi_mac: rcmdsta %08x ccmdsta %08x\n",
rcmdsta, ccmdsta);
}
static inline void pasemi_mac_tx_error(const struct pasemi_mac *mac,
const u64 mactx)
{
unsigned int cmdsta;
struct pasemi_dmachan *chan = &tx_ring(mac)->chan;
if (!netif_msg_tx_err(mac))
return;
cmdsta = read_dma_reg(PAS_DMA_TXCHAN_TCMDSTA(chan->chno));
printk(KERN_ERR "pasemi_mac: tx error. mactx 0x%016llx, "\
"tx status 0x%016llx\n", mactx, *chan->status);
printk(KERN_ERR "pasemi_mac: tcmdsta 0x%08x\n", cmdsta);
}
static int pasemi_mac_clean_rx(struct pasemi_mac_rxring *rx,
const int limit)
{
const struct pasemi_dmachan *chan = &rx->chan;
struct pasemi_mac *mac = rx->mac;
struct pci_dev *pdev = mac->dma_pdev;
unsigned int n;
int count, buf_index, tot_bytes, packets;
struct pasemi_mac_buffer *info;
struct sk_buff *skb;
unsigned int len;
u64 macrx, eval;
dma_addr_t dma;
tot_bytes = 0;
packets = 0;
spin_lock(&rx->lock);
n = rx->next_to_clean;
prefetch(&RX_DESC(rx, n));
for (count = 0; count < limit; count++) {
macrx = RX_DESC(rx, n);
prefetch(&RX_DESC(rx, n+4));
if ((macrx & XCT_MACRX_E) ||
(*chan->status & PAS_STATUS_ERROR))
pasemi_mac_rx_error(mac, macrx);
if (!(macrx & XCT_MACRX_O))
break;
info = NULL;
BUG_ON(!(macrx & XCT_MACRX_RR_8BRES));
eval = (RX_DESC(rx, n+1) & XCT_RXRES_8B_EVAL_M) >>
XCT_RXRES_8B_EVAL_S;
buf_index = eval-1;
dma = (RX_DESC(rx, n+2) & XCT_PTR_ADDR_M);
info = &RX_DESC_INFO(rx, buf_index);
skb = info->skb;
prefetch_skb(skb);
len = (macrx & XCT_MACRX_LLEN_M) >> XCT_MACRX_LLEN_S;
pci_unmap_single(pdev, dma, mac->bufsz - LOCAL_SKB_ALIGN,
PCI_DMA_FROMDEVICE);
if (macrx & XCT_MACRX_CRC) {
/* CRC error flagged */
mac->netdev->stats.rx_errors++;
mac->netdev->stats.rx_crc_errors++;
/* No need to free skb, it'll be reused */
goto next;
}
info->skb = NULL;
info->dma = 0;
if (likely((macrx & XCT_MACRX_HTY_M) == XCT_MACRX_HTY_IPV4_OK)) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
skb->csum = (macrx & XCT_MACRX_CSUM_M) >>
XCT_MACRX_CSUM_S;
} else {
skb_checksum_none_assert(skb);
}
packets++;
tot_bytes += len;
/* Don't include CRC */
skb_put(skb, len-4);
skb->protocol = eth_type_trans(skb, mac->netdev);
lro_receive_skb(&mac->lro_mgr, skb, (void *)macrx);
next:
RX_DESC(rx, n) = 0;
RX_DESC(rx, n+1) = 0;
/* Need to zero it out since hardware doesn't, since the
* replenish loop uses it to tell when it's done.
*/
RX_BUFF(rx, buf_index) = 0;
n += 4;
}
if (n > RX_RING_SIZE) {
/* Errata 5971 workaround: L2 target of headers */
write_iob_reg(PAS_IOB_COM_PKTHDRCNT, 0);
n &= (RX_RING_SIZE-1);
}
rx_ring(mac)->next_to_clean = n;
lro_flush_all(&mac->lro_mgr);
/* Increase is in number of 16-byte entries, and since each descriptor
* with an 8BRES takes up 3x8 bytes (padded to 4x8), increase with
* count*2.
*/
write_dma_reg(PAS_DMA_RXCHAN_INCR(mac->rx->chan.chno), count << 1);
pasemi_mac_replenish_rx_ring(mac->netdev, count);
mac->netdev->stats.rx_bytes += tot_bytes;
mac->netdev->stats.rx_packets += packets;
spin_unlock(&rx_ring(mac)->lock);
return count;
}
/* Can't make this too large or we blow the kernel stack limits */
#define TX_CLEAN_BATCHSIZE (128/MAX_SKB_FRAGS)
static int pasemi_mac_clean_tx(struct pasemi_mac_txring *txring)
{
struct pasemi_dmachan *chan = &txring->chan;
struct pasemi_mac *mac = txring->mac;
int i, j;
unsigned int start, descr_count, buf_count, batch_limit;
unsigned int ring_limit;
unsigned int total_count;
unsigned long flags;
struct sk_buff *skbs[TX_CLEAN_BATCHSIZE];
dma_addr_t dmas[TX_CLEAN_BATCHSIZE][MAX_SKB_FRAGS+1];
int nf[TX_CLEAN_BATCHSIZE];
int nr_frags;
total_count = 0;
batch_limit = TX_CLEAN_BATCHSIZE;
restart:
spin_lock_irqsave(&txring->lock, flags);
start = txring->next_to_clean;
ring_limit = txring->next_to_fill;
prefetch(&TX_DESC_INFO(txring, start+1).skb);
/* Compensate for when fill has wrapped but clean has not */
if (start > ring_limit)
ring_limit += TX_RING_SIZE;
buf_count = 0;
descr_count = 0;
for (i = start;
descr_count < batch_limit && i < ring_limit;
i += buf_count) {
u64 mactx = TX_DESC(txring, i);
struct sk_buff *skb;
if ((mactx & XCT_MACTX_E) ||
(*chan->status & PAS_STATUS_ERROR))
pasemi_mac_tx_error(mac, mactx);
/* Skip over control descriptors */
if (!(mactx & XCT_MACTX_LLEN_M)) {
TX_DESC(txring, i) = 0;
TX_DESC(txring, i+1) = 0;
buf_count = 2;
continue;
}
skb = TX_DESC_INFO(txring, i+1).skb;
nr_frags = TX_DESC_INFO(txring, i).dma;
if (unlikely(mactx & XCT_MACTX_O))
/* Not yet transmitted */
break;
buf_count = 2 + nr_frags;
/* Since we always fill with an even number of entries, make
* sure we skip any unused one at the end as well.
*/
if (buf_count & 1)
buf_count++;
for (j = 0; j <= nr_frags; j++)
dmas[descr_count][j] = TX_DESC_INFO(txring, i+1+j).dma;
skbs[descr_count] = skb;
nf[descr_count] = nr_frags;
TX_DESC(txring, i) = 0;
TX_DESC(txring, i+1) = 0;
descr_count++;
}
txring->next_to_clean = i & (TX_RING_SIZE-1);
spin_unlock_irqrestore(&txring->lock, flags);
netif_wake_queue(mac->netdev);
for (i = 0; i < descr_count; i++)
pasemi_mac_unmap_tx_skb(mac, nf[i], skbs[i], dmas[i]);
total_count += descr_count;
/* If the batch was full, try to clean more */
if (descr_count == batch_limit)
goto restart;
return total_count;
}
static irqreturn_t pasemi_mac_rx_intr(int irq, void *data)
{
const struct pasemi_mac_rxring *rxring = data;
struct pasemi_mac *mac = rxring->mac;
const struct pasemi_dmachan *chan = &rxring->chan;
unsigned int reg;
if (!(*chan->status & PAS_STATUS_CAUSE_M))
return IRQ_NONE;
/* Don't reset packet count so it won't fire again but clear
* all others.
*/
reg = 0;
if (*chan->status & PAS_STATUS_SOFT)
reg |= PAS_IOB_DMA_RXCH_RESET_SINTC;
if (*chan->status & PAS_STATUS_ERROR)
reg |= PAS_IOB_DMA_RXCH_RESET_DINTC;
napi_schedule(&mac->napi);
write_iob_reg(PAS_IOB_DMA_RXCH_RESET(chan->chno), reg);
return IRQ_HANDLED;
}
#define TX_CLEAN_INTERVAL HZ
static void pasemi_mac_tx_timer(unsigned long data)
{
struct pasemi_mac_txring *txring = (struct pasemi_mac_txring *)data;
struct pasemi_mac *mac = txring->mac;
pasemi_mac_clean_tx(txring);
mod_timer(&txring->clean_timer, jiffies + TX_CLEAN_INTERVAL);
pasemi_mac_restart_tx_intr(mac);
}
static irqreturn_t pasemi_mac_tx_intr(int irq, void *data)
{
struct pasemi_mac_txring *txring = data;
const struct pasemi_dmachan *chan = &txring->chan;
struct pasemi_mac *mac = txring->mac;
unsigned int reg;
if (!(*chan->status & PAS_STATUS_CAUSE_M))
return IRQ_NONE;
reg = 0;
if (*chan->status & PAS_STATUS_SOFT)
reg |= PAS_IOB_DMA_TXCH_RESET_SINTC;
if (*chan->status & PAS_STATUS_ERROR)
reg |= PAS_IOB_DMA_TXCH_RESET_DINTC;
mod_timer(&txring->clean_timer, jiffies + (TX_CLEAN_INTERVAL)*2);
napi_schedule(&mac->napi);
if (reg)
write_iob_reg(PAS_IOB_DMA_TXCH_RESET(chan->chno), reg);
return IRQ_HANDLED;
}
static void pasemi_adjust_link(struct net_device *dev)
{
struct pasemi_mac *mac = netdev_priv(dev);
int msg;
unsigned int flags;
unsigned int new_flags;
if (!mac->phydev->link) {
/* If no link, MAC speed settings don't matter. Just report
* link down and return.
*/
if (mac->link && netif_msg_link(mac))
printk(KERN_INFO "%s: Link is down.\n", dev->name);
netif_carrier_off(dev);
pasemi_mac_intf_disable(mac);
mac->link = 0;
return;
} else {
pasemi_mac_intf_enable(mac);
netif_carrier_on(dev);
}
flags = read_mac_reg(mac, PAS_MAC_CFG_PCFG);
new_flags = flags & ~(PAS_MAC_CFG_PCFG_HD | PAS_MAC_CFG_PCFG_SPD_M |
PAS_MAC_CFG_PCFG_TSR_M);
if (!mac->phydev->duplex)
new_flags |= PAS_MAC_CFG_PCFG_HD;
switch (mac->phydev->speed) {
case 1000:
new_flags |= PAS_MAC_CFG_PCFG_SPD_1G |
PAS_MAC_CFG_PCFG_TSR_1G;
break;
case 100:
new_flags |= PAS_MAC_CFG_PCFG_SPD_100M |
PAS_MAC_CFG_PCFG_TSR_100M;
break;
case 10:
new_flags |= PAS_MAC_CFG_PCFG_SPD_10M |
PAS_MAC_CFG_PCFG_TSR_10M;
break;
default:
printk("Unsupported speed %d\n", mac->phydev->speed);
}
/* Print on link or speed/duplex change */
msg = mac->link != mac->phydev->link || flags != new_flags;
mac->duplex = mac->phydev->duplex;
mac->speed = mac->phydev->speed;
mac->link = mac->phydev->link;
if (new_flags != flags)
write_mac_reg(mac, PAS_MAC_CFG_PCFG, new_flags);
if (msg && netif_msg_link(mac))
printk(KERN_INFO "%s: Link is up at %d Mbps, %s duplex.\n",
dev->name, mac->speed, mac->duplex ? "full" : "half");
}
static int pasemi_mac_phy_init(struct net_device *dev)
{
struct pasemi_mac *mac = netdev_priv(dev);
struct device_node *dn, *phy_dn;
struct phy_device *phydev;
dn = pci_device_to_OF_node(mac->pdev);
phy_dn = of_parse_phandle(dn, "phy-handle", 0);
of_node_put(phy_dn);
mac->link = 0;
mac->speed = 0;
mac->duplex = -1;
phydev = of_phy_connect(dev, phy_dn, &pasemi_adjust_link, 0,
PHY_INTERFACE_MODE_SGMII);
if (!phydev) {
printk(KERN_ERR "%s: Could not attach to phy\n", dev->name);
return -ENODEV;
}
mac->phydev = phydev;
return 0;
}
static int pasemi_mac_open(struct net_device *dev)
{
struct pasemi_mac *mac = netdev_priv(dev);
unsigned int flags;
int i, ret;
flags = PAS_MAC_CFG_TXP_FCE | PAS_MAC_CFG_TXP_FPC(3) |
PAS_MAC_CFG_TXP_SL(3) | PAS_MAC_CFG_TXP_COB(0xf) |
PAS_MAC_CFG_TXP_TIFT(8) | PAS_MAC_CFG_TXP_TIFG(12);
write_mac_reg(mac, PAS_MAC_CFG_TXP, flags);
ret = pasemi_mac_setup_rx_resources(dev);
if (ret)
goto out_rx_resources;
mac->tx = pasemi_mac_setup_tx_resources(dev);
if (!mac->tx)
goto out_tx_ring;
/* We might already have allocated rings in case mtu was changed
* before interface was brought up.
*/
if (dev->mtu > 1500 && !mac->num_cs) {
pasemi_mac_setup_csrings(mac);
if (!mac->num_cs)
goto out_tx_ring;
}
/* Zero out rmon counters */
for (i = 0; i < 32; i++)
write_mac_reg(mac, PAS_MAC_RMON(i), 0);
/* 0x3ff with 33MHz clock is about 31us */
write_iob_reg(PAS_IOB_DMA_COM_TIMEOUTCFG,
PAS_IOB_DMA_COM_TIMEOUTCFG_TCNT(0x3ff));
write_iob_reg(PAS_IOB_DMA_RXCH_CFG(mac->rx->chan.chno),
PAS_IOB_DMA_RXCH_CFG_CNTTH(256));
write_iob_reg(PAS_IOB_DMA_TXCH_CFG(mac->tx->chan.chno),
PAS_IOB_DMA_TXCH_CFG_CNTTH(32));
write_mac_reg(mac, PAS_MAC_IPC_CHNL,
PAS_MAC_IPC_CHNL_DCHNO(mac->rx->chan.chno) |
PAS_MAC_IPC_CHNL_BCH(mac->rx->chan.chno));
/* enable rx if */
write_dma_reg(PAS_DMA_RXINT_RCMDSTA(mac->dma_if),
PAS_DMA_RXINT_RCMDSTA_EN |
PAS_DMA_RXINT_RCMDSTA_DROPS_M |
PAS_DMA_RXINT_RCMDSTA_BP |
PAS_DMA_RXINT_RCMDSTA_OO |
PAS_DMA_RXINT_RCMDSTA_BT);
/* enable rx channel */
pasemi_dma_start_chan(&rx_ring(mac)->chan, PAS_DMA_RXCHAN_CCMDSTA_DU |
PAS_DMA_RXCHAN_CCMDSTA_OD |
PAS_DMA_RXCHAN_CCMDSTA_FD |
PAS_DMA_RXCHAN_CCMDSTA_DT);
/* enable tx channel */
pasemi_dma_start_chan(&tx_ring(mac)->chan, PAS_DMA_TXCHAN_TCMDSTA_SZ |
PAS_DMA_TXCHAN_TCMDSTA_DB |
PAS_DMA_TXCHAN_TCMDSTA_DE |
PAS_DMA_TXCHAN_TCMDSTA_DA);
pasemi_mac_replenish_rx_ring(dev, RX_RING_SIZE);
write_dma_reg(PAS_DMA_RXCHAN_INCR(rx_ring(mac)->chan.chno),
RX_RING_SIZE>>1);
/* Clear out any residual packet count state from firmware */
pasemi_mac_restart_rx_intr(mac);
pasemi_mac_restart_tx_intr(mac);
flags = PAS_MAC_CFG_PCFG_S1 | PAS_MAC_CFG_PCFG_PR | PAS_MAC_CFG_PCFG_CE;
if (mac->type == MAC_TYPE_GMAC)
flags |= PAS_MAC_CFG_PCFG_TSR_1G | PAS_MAC_CFG_PCFG_SPD_1G;
else
flags |= PAS_MAC_CFG_PCFG_TSR_10G | PAS_MAC_CFG_PCFG_SPD_10G;
/* Enable interface in MAC */
write_mac_reg(mac, PAS_MAC_CFG_PCFG, flags);
ret = pasemi_mac_phy_init(dev);
if (ret) {
/* Since we won't get link notification, just enable RX */
pasemi_mac_intf_enable(mac);
if (mac->type == MAC_TYPE_GMAC) {
/* Warn for missing PHY on SGMII (1Gig) ports */
dev_warn(&mac->pdev->dev,
"PHY init failed: %d.\n", ret);
dev_warn(&mac->pdev->dev,
"Defaulting to 1Gbit full duplex\n");
}
}
netif_start_queue(dev);
napi_enable(&mac->napi);
snprintf(mac->tx_irq_name, sizeof(mac->tx_irq_name), "%s tx",
dev->name);
ret = request_irq(mac->tx->chan.irq, pasemi_mac_tx_intr, IRQF_DISABLED,
mac->tx_irq_name, mac->tx);
if (ret) {
dev_err(&mac->pdev->dev, "request_irq of irq %d failed: %d\n",
mac->tx->chan.irq, ret);
goto out_tx_int;
}
snprintf(mac->rx_irq_name, sizeof(mac->rx_irq_name), "%s rx",
dev->name);
ret = request_irq(mac->rx->chan.irq, pasemi_mac_rx_intr, IRQF_DISABLED,
mac->rx_irq_name, mac->rx);
if (ret) {
dev_err(&mac->pdev->dev, "request_irq of irq %d failed: %d\n",
mac->rx->chan.irq, ret);
goto out_rx_int;
}
if (mac->phydev)
phy_start(mac->phydev);
init_timer(&mac->tx->clean_timer);
mac->tx->clean_timer.function = pasemi_mac_tx_timer;
mac->tx->clean_timer.data = (unsigned long)mac->tx;
mac->tx->clean_timer.expires = jiffies+HZ;
add_timer(&mac->tx->clean_timer);
return 0;
out_rx_int:
free_irq(mac->tx->chan.irq, mac->tx);
out_tx_int:
napi_disable(&mac->napi);
netif_stop_queue(dev);
out_tx_ring:
if (mac->tx)
pasemi_mac_free_tx_resources(mac);
pasemi_mac_free_rx_resources(mac);
out_rx_resources:
return ret;
}
#define MAX_RETRIES 5000
static void pasemi_mac_pause_txchan(struct pasemi_mac *mac)
{
unsigned int sta, retries;
int txch = tx_ring(mac)->chan.chno;
write_dma_reg(PAS_DMA_TXCHAN_TCMDSTA(txch),
PAS_DMA_TXCHAN_TCMDSTA_ST);
for (retries = 0; retries < MAX_RETRIES; retries++) {
sta = read_dma_reg(PAS_DMA_TXCHAN_TCMDSTA(txch));
if (!(sta & PAS_DMA_TXCHAN_TCMDSTA_ACT))
break;
cond_resched();
}
if (sta & PAS_DMA_TXCHAN_TCMDSTA_ACT)
dev_err(&mac->dma_pdev->dev,
"Failed to stop tx channel, tcmdsta %08x\n", sta);
write_dma_reg(PAS_DMA_TXCHAN_TCMDSTA(txch), 0);
}
static void pasemi_mac_pause_rxchan(struct pasemi_mac *mac)
{
unsigned int sta, retries;
int rxch = rx_ring(mac)->chan.chno;
write_dma_reg(PAS_DMA_RXCHAN_CCMDSTA(rxch),
PAS_DMA_RXCHAN_CCMDSTA_ST);
for (retries = 0; retries < MAX_RETRIES; retries++) {
sta = read_dma_reg(PAS_DMA_RXCHAN_CCMDSTA(rxch));
if (!(sta & PAS_DMA_RXCHAN_CCMDSTA_ACT))
break;
cond_resched();
}
if (sta & PAS_DMA_RXCHAN_CCMDSTA_ACT)
dev_err(&mac->dma_pdev->dev,
"Failed to stop rx channel, ccmdsta 08%x\n", sta);
write_dma_reg(PAS_DMA_RXCHAN_CCMDSTA(rxch), 0);
}
static void pasemi_mac_pause_rxint(struct pasemi_mac *mac)
{
unsigned int sta, retries;
write_dma_reg(PAS_DMA_RXINT_RCMDSTA(mac->dma_if),
PAS_DMA_RXINT_RCMDSTA_ST);
for (retries = 0; retries < MAX_RETRIES; retries++) {
sta = read_dma_reg(PAS_DMA_RXINT_RCMDSTA(mac->dma_if));
if (!(sta & PAS_DMA_RXINT_RCMDSTA_ACT))
break;
cond_resched();
}
if (sta & PAS_DMA_RXINT_RCMDSTA_ACT)
dev_err(&mac->dma_pdev->dev,
"Failed to stop rx interface, rcmdsta %08x\n", sta);
write_dma_reg(PAS_DMA_RXINT_RCMDSTA(mac->dma_if), 0);
}
static int pasemi_mac_close(struct net_device *dev)
{
struct pasemi_mac *mac = netdev_priv(dev);
unsigned int sta;
int rxch, txch, i;
rxch = rx_ring(mac)->chan.chno;
txch = tx_ring(mac)->chan.chno;
if (mac->phydev) {
phy_stop(mac->phydev);
phy_disconnect(mac->phydev);
}
del_timer_sync(&mac->tx->clean_timer);
netif_stop_queue(dev);
napi_disable(&mac->napi);
sta = read_dma_reg(PAS_DMA_RXINT_RCMDSTA(mac->dma_if));
if (sta & (PAS_DMA_RXINT_RCMDSTA_BP |
PAS_DMA_RXINT_RCMDSTA_OO |
PAS_DMA_RXINT_RCMDSTA_BT))
printk(KERN_DEBUG "pasemi_mac: rcmdsta error: 0x%08x\n", sta);
sta = read_dma_reg(PAS_DMA_RXCHAN_CCMDSTA(rxch));
if (sta & (PAS_DMA_RXCHAN_CCMDSTA_DU |
PAS_DMA_RXCHAN_CCMDSTA_OD |
PAS_DMA_RXCHAN_CCMDSTA_FD |
PAS_DMA_RXCHAN_CCMDSTA_DT))
printk(KERN_DEBUG "pasemi_mac: ccmdsta error: 0x%08x\n", sta);
sta = read_dma_reg(PAS_DMA_TXCHAN_TCMDSTA(txch));
if (sta & (PAS_DMA_TXCHAN_TCMDSTA_SZ | PAS_DMA_TXCHAN_TCMDSTA_DB |
PAS_DMA_TXCHAN_TCMDSTA_DE | PAS_DMA_TXCHAN_TCMDSTA_DA))
printk(KERN_DEBUG "pasemi_mac: tcmdsta error: 0x%08x\n", sta);
/* Clean out any pending buffers */
pasemi_mac_clean_tx(tx_ring(mac));
pasemi_mac_clean_rx(rx_ring(mac), RX_RING_SIZE);
pasemi_mac_pause_txchan(mac);
pasemi_mac_pause_rxint(mac);
pasemi_mac_pause_rxchan(mac);
pasemi_mac_intf_disable(mac);
free_irq(mac->tx->chan.irq, mac->tx);
free_irq(mac->rx->chan.irq, mac->rx);
for (i = 0; i < mac->num_cs; i++) {
pasemi_mac_free_csring(mac->cs[i]);
mac->cs[i] = NULL;
}
mac->num_cs = 0;
/* Free resources */
pasemi_mac_free_rx_resources(mac);
pasemi_mac_free_tx_resources(mac);
return 0;
}
static void pasemi_mac_queue_csdesc(const struct sk_buff *skb,
const dma_addr_t *map,
const unsigned int *map_size,
struct pasemi_mac_txring *txring,
struct pasemi_mac_csring *csring)
{
u64 fund;
dma_addr_t cs_dest;
const int nh_off = skb_network_offset(skb);
const int nh_len = skb_network_header_len(skb);
const int nfrags = skb_shinfo(skb)->nr_frags;
int cs_size, i, fill, hdr, cpyhdr, evt;
dma_addr_t csdma;
fund = XCT_FUN_ST | XCT_FUN_RR_8BRES |
XCT_FUN_O | XCT_FUN_FUN(csring->fun) |
XCT_FUN_CRM_SIG | XCT_FUN_LLEN(skb->len - nh_off) |
XCT_FUN_SHL(nh_len >> 2) | XCT_FUN_SE;
switch (ip_hdr(skb)->protocol) {
case IPPROTO_TCP:
fund |= XCT_FUN_SIG_TCP4;
/* TCP checksum is 16 bytes into the header */
cs_dest = map[0] + skb_transport_offset(skb) + 16;
break;
case IPPROTO_UDP:
fund |= XCT_FUN_SIG_UDP4;
/* UDP checksum is 6 bytes into the header */
cs_dest = map[0] + skb_transport_offset(skb) + 6;
break;
default:
BUG();
}
/* Do the checksum offloaded */
fill = csring->next_to_fill;
hdr = fill;
CS_DESC(csring, fill++) = fund;
/* Room for 8BRES. Checksum result is really 2 bytes into it */
csdma = csring->chan.ring_dma + (fill & (CS_RING_SIZE-1)) * 8 + 2;
CS_DESC(csring, fill++) = 0;
CS_DESC(csring, fill) = XCT_PTR_LEN(map_size[0]-nh_off) | XCT_PTR_ADDR(map[0]+nh_off);
for (i = 1; i <= nfrags; i++)
CS_DESC(csring, fill+i) = XCT_PTR_LEN(map_size[i]) | XCT_PTR_ADDR(map[i]);
fill += i;
if (fill & 1)
fill++;
/* Copy the result into the TCP packet */
cpyhdr = fill;
CS_DESC(csring, fill++) = XCT_FUN_O | XCT_FUN_FUN(csring->fun) |
XCT_FUN_LLEN(2) | XCT_FUN_SE;
CS_DESC(csring, fill++) = XCT_PTR_LEN(2) | XCT_PTR_ADDR(cs_dest) | XCT_PTR_T;
CS_DESC(csring, fill++) = XCT_PTR_LEN(2) | XCT_PTR_ADDR(csdma);
fill++;
evt = !csring->last_event;
csring->last_event = evt;
/* Event handshaking with MAC TX */
CS_DESC(csring, fill++) = CTRL_CMD_T | CTRL_CMD_META_EVT | CTRL_CMD_O |
CTRL_CMD_ETYPE_SET | CTRL_CMD_REG(csring->events[evt]);
CS_DESC(csring, fill++) = 0;
CS_DESC(csring, fill++) = CTRL_CMD_T | CTRL_CMD_META_EVT | CTRL_CMD_O |
CTRL_CMD_ETYPE_WCLR | CTRL_CMD_REG(csring->events[!evt]);
CS_DESC(csring, fill++) = 0;
csring->next_to_fill = fill & (CS_RING_SIZE-1);
cs_size = fill - hdr;
write_dma_reg(PAS_DMA_TXCHAN_INCR(csring->chan.chno), (cs_size) >> 1);
/* TX-side event handshaking */
fill = txring->next_to_fill;
TX_DESC(txring, fill++) = CTRL_CMD_T | CTRL_CMD_META_EVT | CTRL_CMD_O |
CTRL_CMD_ETYPE_WSET | CTRL_CMD_REG(csring->events[evt]);
TX_DESC(txring, fill++) = 0;
TX_DESC(txring, fill++) = CTRL_CMD_T | CTRL_CMD_META_EVT | CTRL_CMD_O |
CTRL_CMD_ETYPE_CLR | CTRL_CMD_REG(csring->events[!evt]);
TX_DESC(txring, fill++) = 0;
txring->next_to_fill = fill;
write_dma_reg(PAS_DMA_TXCHAN_INCR(txring->chan.chno), 2);
}
static int pasemi_mac_start_tx(struct sk_buff *skb, struct net_device *dev)
{
struct pasemi_mac * const mac = netdev_priv(dev);
struct pasemi_mac_txring * const txring = tx_ring(mac);
struct pasemi_mac_csring *csring;
u64 dflags = 0;
u64 mactx;
dma_addr_t map[MAX_SKB_FRAGS+1];
unsigned int map_size[MAX_SKB_FRAGS+1];
unsigned long flags;
int i, nfrags;
int fill;
const int nh_off = skb_network_offset(skb);
const int nh_len = skb_network_header_len(skb);
prefetch(&txring->ring_info);
dflags = XCT_MACTX_O | XCT_MACTX_ST | XCT_MACTX_CRC_PAD;
nfrags = skb_shinfo(skb)->nr_frags;
map[0] = pci_map_single(mac->dma_pdev, skb->data, skb_headlen(skb),
PCI_DMA_TODEVICE);
map_size[0] = skb_headlen(skb);
if (pci_dma_mapping_error(mac->dma_pdev, map[0]))
goto out_err_nolock;
for (i = 0; i < nfrags; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
map[i + 1] = skb_frag_dma_map(&mac->dma_pdev->dev, frag, 0,
skb_frag_size(frag), DMA_TO_DEVICE);
map_size[i+1] = skb_frag_size(frag);
if (dma_mapping_error(&mac->dma_pdev->dev, map[i + 1])) {
nfrags = i;
goto out_err_nolock;
}
}
if (skb->ip_summed == CHECKSUM_PARTIAL && skb->len <= 1540) {
switch (ip_hdr(skb)->protocol) {
case IPPROTO_TCP:
dflags |= XCT_MACTX_CSUM_TCP;
dflags |= XCT_MACTX_IPH(nh_len >> 2);
dflags |= XCT_MACTX_IPO(nh_off);
break;
case IPPROTO_UDP:
dflags |= XCT_MACTX_CSUM_UDP;
dflags |= XCT_MACTX_IPH(nh_len >> 2);
dflags |= XCT_MACTX_IPO(nh_off);
break;
default:
WARN_ON(1);
}
}
mactx = dflags | XCT_MACTX_LLEN(skb->len);
spin_lock_irqsave(&txring->lock, flags);
/* Avoid stepping on the same cache line that the DMA controller
* is currently about to send, so leave at least 8 words available.
* Total free space needed is mactx + fragments + 8
*/
if (RING_AVAIL(txring) < nfrags + 14) {
/* no room -- stop the queue and wait for tx intr */
netif_stop_queue(dev);
goto out_err;
}
/* Queue up checksum + event descriptors, if needed */
if (mac->num_cs && skb->ip_summed == CHECKSUM_PARTIAL && skb->len > 1540) {
csring = mac->cs[mac->last_cs];
mac->last_cs = (mac->last_cs + 1) % mac->num_cs;
pasemi_mac_queue_csdesc(skb, map, map_size, txring, csring);
}
fill = txring->next_to_fill;
TX_DESC(txring, fill) = mactx;
TX_DESC_INFO(txring, fill).dma = nfrags;
fill++;
TX_DESC_INFO(txring, fill).skb = skb;
for (i = 0; i <= nfrags; i++) {
TX_DESC(txring, fill+i) =
XCT_PTR_LEN(map_size[i]) | XCT_PTR_ADDR(map[i]);
TX_DESC_INFO(txring, fill+i).dma = map[i];
}
/* We have to add an even number of 8-byte entries to the ring
* even if the last one is unused. That means always an odd number
* of pointers + one mactx descriptor.
*/
if (nfrags & 1)
nfrags++;
txring->next_to_fill = (fill + nfrags + 1) & (TX_RING_SIZE-1);
dev->stats.tx_packets++;
dev->stats.tx_bytes += skb->len;
spin_unlock_irqrestore(&txring->lock, flags);
write_dma_reg(PAS_DMA_TXCHAN_INCR(txring->chan.chno), (nfrags+2) >> 1);
return NETDEV_TX_OK;
out_err:
spin_unlock_irqrestore(&txring->lock, flags);
out_err_nolock:
while (nfrags--)
pci_unmap_single(mac->dma_pdev, map[nfrags], map_size[nfrags],
PCI_DMA_TODEVICE);
return NETDEV_TX_BUSY;
}
static void pasemi_mac_set_rx_mode(struct net_device *dev)
{
const struct pasemi_mac *mac = netdev_priv(dev);
unsigned int flags;
flags = read_mac_reg(mac, PAS_MAC_CFG_PCFG);
/* Set promiscuous */
if (dev->flags & IFF_PROMISC)
flags |= PAS_MAC_CFG_PCFG_PR;
else
flags &= ~PAS_MAC_CFG_PCFG_PR;
write_mac_reg(mac, PAS_MAC_CFG_PCFG, flags);
}
static int pasemi_mac_poll(struct napi_struct *napi, int budget)
{
struct pasemi_mac *mac = container_of(napi, struct pasemi_mac, napi);
int pkts;
pasemi_mac_clean_tx(tx_ring(mac));
pkts = pasemi_mac_clean_rx(rx_ring(mac), budget);
if (pkts < budget) {
/* all done, no more packets present */
napi_complete(napi);
pasemi_mac_restart_rx_intr(mac);
pasemi_mac_restart_tx_intr(mac);
}
return pkts;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* Polling 'interrupt' - used by things like netconsole to send skbs
* without having to re-enable interrupts. It's not called while
* the interrupt routine is executing.
*/
static void pasemi_mac_netpoll(struct net_device *dev)
{
const struct pasemi_mac *mac = netdev_priv(dev);
disable_irq(mac->tx->chan.irq);
pasemi_mac_tx_intr(mac->tx->chan.irq, mac->tx);
enable_irq(mac->tx->chan.irq);
disable_irq(mac->rx->chan.irq);
pasemi_mac_rx_intr(mac->rx->chan.irq, mac->rx);
enable_irq(mac->rx->chan.irq);
}
#endif
static int pasemi_mac_change_mtu(struct net_device *dev, int new_mtu)
{
struct pasemi_mac *mac = netdev_priv(dev);
unsigned int reg;
unsigned int rcmdsta = 0;
int running;
int ret = 0;
if (new_mtu < PE_MIN_MTU || new_mtu > PE_MAX_MTU)
return -EINVAL;
running = netif_running(dev);
if (running) {
/* Need to stop the interface, clean out all already
* received buffers, free all unused buffers on the RX
* interface ring, then finally re-fill the rx ring with
* the new-size buffers and restart.
*/
napi_disable(&mac->napi);
netif_tx_disable(dev);
pasemi_mac_intf_disable(mac);
rcmdsta = read_dma_reg(PAS_DMA_RXINT_RCMDSTA(mac->dma_if));
pasemi_mac_pause_rxint(mac);
pasemi_mac_clean_rx(rx_ring(mac), RX_RING_SIZE);
pasemi_mac_free_rx_buffers(mac);
}
/* Setup checksum channels if large MTU and none already allocated */
if (new_mtu > 1500 && !mac->num_cs) {
pasemi_mac_setup_csrings(mac);
if (!mac->num_cs) {
ret = -ENOMEM;
goto out;
}
}
/* Change maxf, i.e. what size frames are accepted.
* Need room for ethernet header and CRC word
*/
reg = read_mac_reg(mac, PAS_MAC_CFG_MACCFG);
reg &= ~PAS_MAC_CFG_MACCFG_MAXF_M;
reg |= PAS_MAC_CFG_MACCFG_MAXF(new_mtu + ETH_HLEN + 4);
write_mac_reg(mac, PAS_MAC_CFG_MACCFG, reg);
dev->mtu = new_mtu;
/* MTU + ETH_HLEN + VLAN_HLEN + 2 64B cachelines */
mac->bufsz = new_mtu + ETH_HLEN + ETH_FCS_LEN + LOCAL_SKB_ALIGN + 128;
out:
if (running) {
write_dma_reg(PAS_DMA_RXINT_RCMDSTA(mac->dma_if),
rcmdsta | PAS_DMA_RXINT_RCMDSTA_EN);
rx_ring(mac)->next_to_fill = 0;
pasemi_mac_replenish_rx_ring(dev, RX_RING_SIZE-1);
napi_enable(&mac->napi);
netif_start_queue(dev);
pasemi_mac_intf_enable(mac);
}
return ret;
}
static const struct net_device_ops pasemi_netdev_ops = {
.ndo_open = pasemi_mac_open,
.ndo_stop = pasemi_mac_close,
.ndo_start_xmit = pasemi_mac_start_tx,
.ndo_set_rx_mode = pasemi_mac_set_rx_mode,
.ndo_set_mac_address = pasemi_mac_set_mac_addr,
.ndo_change_mtu = pasemi_mac_change_mtu,
.ndo_validate_addr = eth_validate_addr,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = pasemi_mac_netpoll,
#endif
};
static int
pasemi_mac_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct net_device *dev;
struct pasemi_mac *mac;
int err, ret;
err = pci_enable_device(pdev);
if (err)
return err;
dev = alloc_etherdev(sizeof(struct pasemi_mac));
if (dev == NULL) {
err = -ENOMEM;
goto out_disable_device;
}
pci_set_drvdata(pdev, dev);
SET_NETDEV_DEV(dev, &pdev->dev);
mac = netdev_priv(dev);
mac->pdev = pdev;
mac->netdev = dev;
netif_napi_add(dev, &mac->napi, pasemi_mac_poll, 64);
dev->features = NETIF_F_IP_CSUM | NETIF_F_LLTX | NETIF_F_SG |
NETIF_F_HIGHDMA | NETIF_F_GSO;
mac->lro_mgr.max_aggr = LRO_MAX_AGGR;
mac->lro_mgr.max_desc = MAX_LRO_DESCRIPTORS;
mac->lro_mgr.lro_arr = mac->lro_desc;
mac->lro_mgr.get_skb_header = get_skb_hdr;
mac->lro_mgr.features = LRO_F_NAPI | LRO_F_EXTRACT_VLAN_ID;
mac->lro_mgr.dev = mac->netdev;
mac->lro_mgr.ip_summed = CHECKSUM_UNNECESSARY;
mac->lro_mgr.ip_summed_aggr = CHECKSUM_UNNECESSARY;
mac->dma_pdev = pci_get_device(PCI_VENDOR_ID_PASEMI, 0xa007, NULL);
if (!mac->dma_pdev) {
dev_err(&mac->pdev->dev, "Can't find DMA Controller\n");
err = -ENODEV;
goto out;
}
mac->iob_pdev = pci_get_device(PCI_VENDOR_ID_PASEMI, 0xa001, NULL);
if (!mac->iob_pdev) {
dev_err(&mac->pdev->dev, "Can't find I/O Bridge\n");
err = -ENODEV;
goto out;
}
/* get mac addr from device tree */
if (pasemi_get_mac_addr(mac) || !is_valid_ether_addr(mac->mac_addr)) {
err = -ENODEV;
goto out;
}
memcpy(dev->dev_addr, mac->mac_addr, sizeof(mac->mac_addr));
ret = mac_to_intf(mac);
if (ret < 0) {
dev_err(&mac->pdev->dev, "Can't map DMA interface\n");
err = -ENODEV;
goto out;
}
mac->dma_if = ret;
switch (pdev->device) {
case 0xa005:
mac->type = MAC_TYPE_GMAC;
break;
case 0xa006:
mac->type = MAC_TYPE_XAUI;
break;
default:
err = -ENODEV;
goto out;
}
dev->netdev_ops = &pasemi_netdev_ops;
dev->mtu = PE_DEF_MTU;
/* 1500 MTU + ETH_HLEN + VLAN_HLEN + 2 64B cachelines */
mac->bufsz = dev->mtu + ETH_HLEN + ETH_FCS_LEN + LOCAL_SKB_ALIGN + 128;
dev->ethtool_ops = &pasemi_mac_ethtool_ops;
if (err)
goto out;
mac->msg_enable = netif_msg_init(debug, DEFAULT_MSG_ENABLE);
/* Enable most messages by default */
mac->msg_enable = (NETIF_MSG_IFUP << 1 ) - 1;
err = register_netdev(dev);
if (err) {
dev_err(&mac->pdev->dev, "register_netdev failed with error %d\n",
err);
goto out;
} else if (netif_msg_probe(mac)) {
printk(KERN_INFO "%s: PA Semi %s: intf %d, hw addr %pM\n",
dev->name, mac->type == MAC_TYPE_GMAC ? "GMAC" : "XAUI",
mac->dma_if, dev->dev_addr);
}
return err;
out:
if (mac->iob_pdev)
pci_dev_put(mac->iob_pdev);
if (mac->dma_pdev)
pci_dev_put(mac->dma_pdev);
free_netdev(dev);
out_disable_device:
pci_disable_device(pdev);
return err;
}
static void pasemi_mac_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct pasemi_mac *mac;
if (!netdev)
return;
mac = netdev_priv(netdev);
unregister_netdev(netdev);
pci_disable_device(pdev);
pci_dev_put(mac->dma_pdev);
pci_dev_put(mac->iob_pdev);
pasemi_dma_free_chan(&mac->tx->chan);
pasemi_dma_free_chan(&mac->rx->chan);
pci_set_drvdata(pdev, NULL);
free_netdev(netdev);
}
static DEFINE_PCI_DEVICE_TABLE(pasemi_mac_pci_tbl) = {
{ PCI_DEVICE(PCI_VENDOR_ID_PASEMI, 0xa005) },
{ PCI_DEVICE(PCI_VENDOR_ID_PASEMI, 0xa006) },
{ },
};
MODULE_DEVICE_TABLE(pci, pasemi_mac_pci_tbl);
static struct pci_driver pasemi_mac_driver = {
.name = "pasemi_mac",
.id_table = pasemi_mac_pci_tbl,
.probe = pasemi_mac_probe,
.remove = pasemi_mac_remove,
};
static void __exit pasemi_mac_cleanup_module(void)
{
pci_unregister_driver(&pasemi_mac_driver);
}
int pasemi_mac_init_module(void)
{
int err;
err = pasemi_dma_init();
if (err)
return err;
return pci_register_driver(&pasemi_mac_driver);
}
module_init(pasemi_mac_init_module);
module_exit(pasemi_mac_cleanup_module);
| gpl-2.0 |
elettronicagf/kernel-am335x | drivers/input/keyboard/adp5589-keys.c | 2409 | 30335 | /*
* Description: keypad driver for ADP5589, ADP5585
* I2C QWERTY Keypad and IO Expander
* Bugs: Enter bugs at http://blackfin.uclinux.org/
*
* Copyright (C) 2010-2011 Analog Devices Inc.
* Licensed under the GPL-2.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/workqueue.h>
#include <linux/errno.h>
#include <linux/pm.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/i2c.h>
#include <linux/gpio.h>
#include <linux/slab.h>
#include <linux/input/adp5589.h>
/* ADP5589/ADP5585 Common Registers */
#define ADP5589_5_ID 0x00
#define ADP5589_5_INT_STATUS 0x01
#define ADP5589_5_STATUS 0x02
#define ADP5589_5_FIFO_1 0x03
#define ADP5589_5_FIFO_2 0x04
#define ADP5589_5_FIFO_3 0x05
#define ADP5589_5_FIFO_4 0x06
#define ADP5589_5_FIFO_5 0x07
#define ADP5589_5_FIFO_6 0x08
#define ADP5589_5_FIFO_7 0x09
#define ADP5589_5_FIFO_8 0x0A
#define ADP5589_5_FIFO_9 0x0B
#define ADP5589_5_FIFO_10 0x0C
#define ADP5589_5_FIFO_11 0x0D
#define ADP5589_5_FIFO_12 0x0E
#define ADP5589_5_FIFO_13 0x0F
#define ADP5589_5_FIFO_14 0x10
#define ADP5589_5_FIFO_15 0x11
#define ADP5589_5_FIFO_16 0x12
#define ADP5589_5_GPI_INT_STAT_A 0x13
#define ADP5589_5_GPI_INT_STAT_B 0x14
/* ADP5589 Registers */
#define ADP5589_GPI_INT_STAT_C 0x15
#define ADP5589_GPI_STATUS_A 0x16
#define ADP5589_GPI_STATUS_B 0x17
#define ADP5589_GPI_STATUS_C 0x18
#define ADP5589_RPULL_CONFIG_A 0x19
#define ADP5589_RPULL_CONFIG_B 0x1A
#define ADP5589_RPULL_CONFIG_C 0x1B
#define ADP5589_RPULL_CONFIG_D 0x1C
#define ADP5589_RPULL_CONFIG_E 0x1D
#define ADP5589_GPI_INT_LEVEL_A 0x1E
#define ADP5589_GPI_INT_LEVEL_B 0x1F
#define ADP5589_GPI_INT_LEVEL_C 0x20
#define ADP5589_GPI_EVENT_EN_A 0x21
#define ADP5589_GPI_EVENT_EN_B 0x22
#define ADP5589_GPI_EVENT_EN_C 0x23
#define ADP5589_GPI_INTERRUPT_EN_A 0x24
#define ADP5589_GPI_INTERRUPT_EN_B 0x25
#define ADP5589_GPI_INTERRUPT_EN_C 0x26
#define ADP5589_DEBOUNCE_DIS_A 0x27
#define ADP5589_DEBOUNCE_DIS_B 0x28
#define ADP5589_DEBOUNCE_DIS_C 0x29
#define ADP5589_GPO_DATA_OUT_A 0x2A
#define ADP5589_GPO_DATA_OUT_B 0x2B
#define ADP5589_GPO_DATA_OUT_C 0x2C
#define ADP5589_GPO_OUT_MODE_A 0x2D
#define ADP5589_GPO_OUT_MODE_B 0x2E
#define ADP5589_GPO_OUT_MODE_C 0x2F
#define ADP5589_GPIO_DIRECTION_A 0x30
#define ADP5589_GPIO_DIRECTION_B 0x31
#define ADP5589_GPIO_DIRECTION_C 0x32
#define ADP5589_UNLOCK1 0x33
#define ADP5589_UNLOCK2 0x34
#define ADP5589_EXT_LOCK_EVENT 0x35
#define ADP5589_UNLOCK_TIMERS 0x36
#define ADP5589_LOCK_CFG 0x37
#define ADP5589_RESET1_EVENT_A 0x38
#define ADP5589_RESET1_EVENT_B 0x39
#define ADP5589_RESET1_EVENT_C 0x3A
#define ADP5589_RESET2_EVENT_A 0x3B
#define ADP5589_RESET2_EVENT_B 0x3C
#define ADP5589_RESET_CFG 0x3D
#define ADP5589_PWM_OFFT_LOW 0x3E
#define ADP5589_PWM_OFFT_HIGH 0x3F
#define ADP5589_PWM_ONT_LOW 0x40
#define ADP5589_PWM_ONT_HIGH 0x41
#define ADP5589_PWM_CFG 0x42
#define ADP5589_CLOCK_DIV_CFG 0x43
#define ADP5589_LOGIC_1_CFG 0x44
#define ADP5589_LOGIC_2_CFG 0x45
#define ADP5589_LOGIC_FF_CFG 0x46
#define ADP5589_LOGIC_INT_EVENT_EN 0x47
#define ADP5589_POLL_PTIME_CFG 0x48
#define ADP5589_PIN_CONFIG_A 0x49
#define ADP5589_PIN_CONFIG_B 0x4A
#define ADP5589_PIN_CONFIG_C 0x4B
#define ADP5589_PIN_CONFIG_D 0x4C
#define ADP5589_GENERAL_CFG 0x4D
#define ADP5589_INT_EN 0x4E
/* ADP5585 Registers */
#define ADP5585_GPI_STATUS_A 0x15
#define ADP5585_GPI_STATUS_B 0x16
#define ADP5585_RPULL_CONFIG_A 0x17
#define ADP5585_RPULL_CONFIG_B 0x18
#define ADP5585_RPULL_CONFIG_C 0x19
#define ADP5585_RPULL_CONFIG_D 0x1A
#define ADP5585_GPI_INT_LEVEL_A 0x1B
#define ADP5585_GPI_INT_LEVEL_B 0x1C
#define ADP5585_GPI_EVENT_EN_A 0x1D
#define ADP5585_GPI_EVENT_EN_B 0x1E
#define ADP5585_GPI_INTERRUPT_EN_A 0x1F
#define ADP5585_GPI_INTERRUPT_EN_B 0x20
#define ADP5585_DEBOUNCE_DIS_A 0x21
#define ADP5585_DEBOUNCE_DIS_B 0x22
#define ADP5585_GPO_DATA_OUT_A 0x23
#define ADP5585_GPO_DATA_OUT_B 0x24
#define ADP5585_GPO_OUT_MODE_A 0x25
#define ADP5585_GPO_OUT_MODE_B 0x26
#define ADP5585_GPIO_DIRECTION_A 0x27
#define ADP5585_GPIO_DIRECTION_B 0x28
#define ADP5585_RESET1_EVENT_A 0x29
#define ADP5585_RESET1_EVENT_B 0x2A
#define ADP5585_RESET1_EVENT_C 0x2B
#define ADP5585_RESET2_EVENT_A 0x2C
#define ADP5585_RESET2_EVENT_B 0x2D
#define ADP5585_RESET_CFG 0x2E
#define ADP5585_PWM_OFFT_LOW 0x2F
#define ADP5585_PWM_OFFT_HIGH 0x30
#define ADP5585_PWM_ONT_LOW 0x31
#define ADP5585_PWM_ONT_HIGH 0x32
#define ADP5585_PWM_CFG 0x33
#define ADP5585_LOGIC_CFG 0x34
#define ADP5585_LOGIC_FF_CFG 0x35
#define ADP5585_LOGIC_INT_EVENT_EN 0x36
#define ADP5585_POLL_PTIME_CFG 0x37
#define ADP5585_PIN_CONFIG_A 0x38
#define ADP5585_PIN_CONFIG_B 0x39
#define ADP5585_PIN_CONFIG_D 0x3A
#define ADP5585_GENERAL_CFG 0x3B
#define ADP5585_INT_EN 0x3C
/* ID Register */
#define ADP5589_5_DEVICE_ID_MASK 0xF
#define ADP5589_5_MAN_ID_MASK 0xF
#define ADP5589_5_MAN_ID_SHIFT 4
#define ADP5589_5_MAN_ID 0x02
/* GENERAL_CFG Register */
#define OSC_EN (1 << 7)
#define CORE_CLK(x) (((x) & 0x3) << 5)
#define LCK_TRK_LOGIC (1 << 4) /* ADP5589 only */
#define LCK_TRK_GPI (1 << 3) /* ADP5589 only */
#define INT_CFG (1 << 1)
#define RST_CFG (1 << 0)
/* INT_EN Register */
#define LOGIC2_IEN (1 << 5) /* ADP5589 only */
#define LOGIC1_IEN (1 << 4)
#define LOCK_IEN (1 << 3) /* ADP5589 only */
#define OVRFLOW_IEN (1 << 2)
#define GPI_IEN (1 << 1)
#define EVENT_IEN (1 << 0)
/* Interrupt Status Register */
#define LOGIC2_INT (1 << 5) /* ADP5589 only */
#define LOGIC1_INT (1 << 4)
#define LOCK_INT (1 << 3) /* ADP5589 only */
#define OVRFLOW_INT (1 << 2)
#define GPI_INT (1 << 1)
#define EVENT_INT (1 << 0)
/* STATUS Register */
#define LOGIC2_STAT (1 << 7) /* ADP5589 only */
#define LOGIC1_STAT (1 << 6)
#define LOCK_STAT (1 << 5) /* ADP5589 only */
#define KEC 0xF
/* PIN_CONFIG_D Register */
#define C4_EXTEND_CFG (1 << 6) /* RESET2 */
#define R4_EXTEND_CFG (1 << 5) /* RESET1 */
/* LOCK_CFG */
#define LOCK_EN (1 << 0)
#define PTIME_MASK 0x3
#define LTIME_MASK 0x3 /* ADP5589 only */
/* Key Event Register xy */
#define KEY_EV_PRESSED (1 << 7)
#define KEY_EV_MASK (0x7F)
#define KEYP_MAX_EVENT 16
#define ADP5589_MAXGPIO 19
#define ADP5585_MAXGPIO 11 /* 10 on the ADP5585-01, 11 on ADP5585-02 */
enum {
ADP5589,
ADP5585_01,
ADP5585_02
};
struct adp_constants {
u8 maxgpio;
u8 keymapsize;
u8 gpi_pin_row_base;
u8 gpi_pin_row_end;
u8 gpi_pin_col_base;
u8 gpi_pin_base;
u8 gpi_pin_end;
u8 gpimapsize_max;
u8 max_row_num;
u8 max_col_num;
u8 row_mask;
u8 col_mask;
u8 col_shift;
u8 c4_extend_cfg;
u8 (*bank) (u8 offset);
u8 (*bit) (u8 offset);
u8 (*reg) (u8 reg);
};
struct adp5589_kpad {
struct i2c_client *client;
struct input_dev *input;
const struct adp_constants *var;
unsigned short keycode[ADP5589_KEYMAPSIZE];
const struct adp5589_gpi_map *gpimap;
unsigned short gpimapsize;
unsigned extend_cfg;
bool is_adp5585;
bool adp5585_support_row5;
#ifdef CONFIG_GPIOLIB
unsigned char gpiomap[ADP5589_MAXGPIO];
bool export_gpio;
struct gpio_chip gc;
struct mutex gpio_lock; /* Protect cached dir, dat_out */
u8 dat_out[3];
u8 dir[3];
#endif
};
/*
* ADP5589 / ADP5585 derivative / variant handling
*/
/* ADP5589 */
static unsigned char adp5589_bank(unsigned char offset)
{
return offset >> 3;
}
static unsigned char adp5589_bit(unsigned char offset)
{
return 1u << (offset & 0x7);
}
static unsigned char adp5589_reg(unsigned char reg)
{
return reg;
}
static const struct adp_constants const_adp5589 = {
.maxgpio = ADP5589_MAXGPIO,
.keymapsize = ADP5589_KEYMAPSIZE,
.gpi_pin_row_base = ADP5589_GPI_PIN_ROW_BASE,
.gpi_pin_row_end = ADP5589_GPI_PIN_ROW_END,
.gpi_pin_col_base = ADP5589_GPI_PIN_COL_BASE,
.gpi_pin_base = ADP5589_GPI_PIN_BASE,
.gpi_pin_end = ADP5589_GPI_PIN_END,
.gpimapsize_max = ADP5589_GPIMAPSIZE_MAX,
.c4_extend_cfg = 12,
.max_row_num = ADP5589_MAX_ROW_NUM,
.max_col_num = ADP5589_MAX_COL_NUM,
.row_mask = ADP5589_ROW_MASK,
.col_mask = ADP5589_COL_MASK,
.col_shift = ADP5589_COL_SHIFT,
.bank = adp5589_bank,
.bit = adp5589_bit,
.reg = adp5589_reg,
};
/* ADP5585 */
static unsigned char adp5585_bank(unsigned char offset)
{
return offset > ADP5585_MAX_ROW_NUM;
}
static unsigned char adp5585_bit(unsigned char offset)
{
return (offset > ADP5585_MAX_ROW_NUM) ?
1u << (offset - ADP5585_COL_SHIFT) : 1u << offset;
}
static const unsigned char adp5585_reg_lut[] = {
[ADP5589_GPI_STATUS_A] = ADP5585_GPI_STATUS_A,
[ADP5589_GPI_STATUS_B] = ADP5585_GPI_STATUS_B,
[ADP5589_RPULL_CONFIG_A] = ADP5585_RPULL_CONFIG_A,
[ADP5589_RPULL_CONFIG_B] = ADP5585_RPULL_CONFIG_B,
[ADP5589_RPULL_CONFIG_C] = ADP5585_RPULL_CONFIG_C,
[ADP5589_RPULL_CONFIG_D] = ADP5585_RPULL_CONFIG_D,
[ADP5589_GPI_INT_LEVEL_A] = ADP5585_GPI_INT_LEVEL_A,
[ADP5589_GPI_INT_LEVEL_B] = ADP5585_GPI_INT_LEVEL_B,
[ADP5589_GPI_EVENT_EN_A] = ADP5585_GPI_EVENT_EN_A,
[ADP5589_GPI_EVENT_EN_B] = ADP5585_GPI_EVENT_EN_B,
[ADP5589_GPI_INTERRUPT_EN_A] = ADP5585_GPI_INTERRUPT_EN_A,
[ADP5589_GPI_INTERRUPT_EN_B] = ADP5585_GPI_INTERRUPT_EN_B,
[ADP5589_DEBOUNCE_DIS_A] = ADP5585_DEBOUNCE_DIS_A,
[ADP5589_DEBOUNCE_DIS_B] = ADP5585_DEBOUNCE_DIS_B,
[ADP5589_GPO_DATA_OUT_A] = ADP5585_GPO_DATA_OUT_A,
[ADP5589_GPO_DATA_OUT_B] = ADP5585_GPO_DATA_OUT_B,
[ADP5589_GPO_OUT_MODE_A] = ADP5585_GPO_OUT_MODE_A,
[ADP5589_GPO_OUT_MODE_B] = ADP5585_GPO_OUT_MODE_B,
[ADP5589_GPIO_DIRECTION_A] = ADP5585_GPIO_DIRECTION_A,
[ADP5589_GPIO_DIRECTION_B] = ADP5585_GPIO_DIRECTION_B,
[ADP5589_RESET1_EVENT_A] = ADP5585_RESET1_EVENT_A,
[ADP5589_RESET1_EVENT_B] = ADP5585_RESET1_EVENT_B,
[ADP5589_RESET1_EVENT_C] = ADP5585_RESET1_EVENT_C,
[ADP5589_RESET2_EVENT_A] = ADP5585_RESET2_EVENT_A,
[ADP5589_RESET2_EVENT_B] = ADP5585_RESET2_EVENT_B,
[ADP5589_RESET_CFG] = ADP5585_RESET_CFG,
[ADP5589_PWM_OFFT_LOW] = ADP5585_PWM_OFFT_LOW,
[ADP5589_PWM_OFFT_HIGH] = ADP5585_PWM_OFFT_HIGH,
[ADP5589_PWM_ONT_LOW] = ADP5585_PWM_ONT_LOW,
[ADP5589_PWM_ONT_HIGH] = ADP5585_PWM_ONT_HIGH,
[ADP5589_PWM_CFG] = ADP5585_PWM_CFG,
[ADP5589_LOGIC_1_CFG] = ADP5585_LOGIC_CFG,
[ADP5589_LOGIC_FF_CFG] = ADP5585_LOGIC_FF_CFG,
[ADP5589_LOGIC_INT_EVENT_EN] = ADP5585_LOGIC_INT_EVENT_EN,
[ADP5589_POLL_PTIME_CFG] = ADP5585_POLL_PTIME_CFG,
[ADP5589_PIN_CONFIG_A] = ADP5585_PIN_CONFIG_A,
[ADP5589_PIN_CONFIG_B] = ADP5585_PIN_CONFIG_B,
[ADP5589_PIN_CONFIG_D] = ADP5585_PIN_CONFIG_D,
[ADP5589_GENERAL_CFG] = ADP5585_GENERAL_CFG,
[ADP5589_INT_EN] = ADP5585_INT_EN,
};
static unsigned char adp5585_reg(unsigned char reg)
{
return adp5585_reg_lut[reg];
}
static const struct adp_constants const_adp5585 = {
.maxgpio = ADP5585_MAXGPIO,
.keymapsize = ADP5585_KEYMAPSIZE,
.gpi_pin_row_base = ADP5585_GPI_PIN_ROW_BASE,
.gpi_pin_row_end = ADP5585_GPI_PIN_ROW_END,
.gpi_pin_col_base = ADP5585_GPI_PIN_COL_BASE,
.gpi_pin_base = ADP5585_GPI_PIN_BASE,
.gpi_pin_end = ADP5585_GPI_PIN_END,
.gpimapsize_max = ADP5585_GPIMAPSIZE_MAX,
.c4_extend_cfg = 10,
.max_row_num = ADP5585_MAX_ROW_NUM,
.max_col_num = ADP5585_MAX_COL_NUM,
.row_mask = ADP5585_ROW_MASK,
.col_mask = ADP5585_COL_MASK,
.col_shift = ADP5585_COL_SHIFT,
.bank = adp5585_bank,
.bit = adp5585_bit,
.reg = adp5585_reg,
};
static int adp5589_read(struct i2c_client *client, u8 reg)
{
int ret = i2c_smbus_read_byte_data(client, reg);
if (ret < 0)
dev_err(&client->dev, "Read Error\n");
return ret;
}
static int adp5589_write(struct i2c_client *client, u8 reg, u8 val)
{
return i2c_smbus_write_byte_data(client, reg, val);
}
#ifdef CONFIG_GPIOLIB
static int adp5589_gpio_get_value(struct gpio_chip *chip, unsigned off)
{
struct adp5589_kpad *kpad = container_of(chip, struct adp5589_kpad, gc);
unsigned int bank = kpad->var->bank(kpad->gpiomap[off]);
unsigned int bit = kpad->var->bit(kpad->gpiomap[off]);
return !!(adp5589_read(kpad->client,
kpad->var->reg(ADP5589_GPI_STATUS_A) + bank) &
bit);
}
static void adp5589_gpio_set_value(struct gpio_chip *chip,
unsigned off, int val)
{
struct adp5589_kpad *kpad = container_of(chip, struct adp5589_kpad, gc);
unsigned int bank = kpad->var->bank(kpad->gpiomap[off]);
unsigned int bit = kpad->var->bit(kpad->gpiomap[off]);
mutex_lock(&kpad->gpio_lock);
if (val)
kpad->dat_out[bank] |= bit;
else
kpad->dat_out[bank] &= ~bit;
adp5589_write(kpad->client, kpad->var->reg(ADP5589_GPO_DATA_OUT_A) +
bank, kpad->dat_out[bank]);
mutex_unlock(&kpad->gpio_lock);
}
static int adp5589_gpio_direction_input(struct gpio_chip *chip, unsigned off)
{
struct adp5589_kpad *kpad = container_of(chip, struct adp5589_kpad, gc);
unsigned int bank = kpad->var->bank(kpad->gpiomap[off]);
unsigned int bit = kpad->var->bit(kpad->gpiomap[off]);
int ret;
mutex_lock(&kpad->gpio_lock);
kpad->dir[bank] &= ~bit;
ret = adp5589_write(kpad->client,
kpad->var->reg(ADP5589_GPIO_DIRECTION_A) + bank,
kpad->dir[bank]);
mutex_unlock(&kpad->gpio_lock);
return ret;
}
static int adp5589_gpio_direction_output(struct gpio_chip *chip,
unsigned off, int val)
{
struct adp5589_kpad *kpad = container_of(chip, struct adp5589_kpad, gc);
unsigned int bank = kpad->var->bank(kpad->gpiomap[off]);
unsigned int bit = kpad->var->bit(kpad->gpiomap[off]);
int ret;
mutex_lock(&kpad->gpio_lock);
kpad->dir[bank] |= bit;
if (val)
kpad->dat_out[bank] |= bit;
else
kpad->dat_out[bank] &= ~bit;
ret = adp5589_write(kpad->client, kpad->var->reg(ADP5589_GPO_DATA_OUT_A)
+ bank, kpad->dat_out[bank]);
ret |= adp5589_write(kpad->client,
kpad->var->reg(ADP5589_GPIO_DIRECTION_A) + bank,
kpad->dir[bank]);
mutex_unlock(&kpad->gpio_lock);
return ret;
}
static int adp5589_build_gpiomap(struct adp5589_kpad *kpad,
const struct adp5589_kpad_platform_data *pdata)
{
bool pin_used[ADP5589_MAXGPIO];
int n_unused = 0;
int i;
memset(pin_used, false, sizeof(pin_used));
for (i = 0; i < kpad->var->maxgpio; i++)
if (pdata->keypad_en_mask & (1 << i))
pin_used[i] = true;
for (i = 0; i < kpad->gpimapsize; i++)
pin_used[kpad->gpimap[i].pin - kpad->var->gpi_pin_base] = true;
if (kpad->extend_cfg & R4_EXTEND_CFG)
pin_used[4] = true;
if (kpad->extend_cfg & C4_EXTEND_CFG)
pin_used[kpad->var->c4_extend_cfg] = true;
if (!kpad->adp5585_support_row5)
pin_used[5] = true;
for (i = 0; i < kpad->var->maxgpio; i++)
if (!pin_used[i])
kpad->gpiomap[n_unused++] = i;
return n_unused;
}
static int adp5589_gpio_add(struct adp5589_kpad *kpad)
{
struct device *dev = &kpad->client->dev;
const struct adp5589_kpad_platform_data *pdata = dev->platform_data;
const struct adp5589_gpio_platform_data *gpio_data = pdata->gpio_data;
int i, error;
if (!gpio_data)
return 0;
kpad->gc.ngpio = adp5589_build_gpiomap(kpad, pdata);
if (kpad->gc.ngpio == 0) {
dev_info(dev, "No unused gpios left to export\n");
return 0;
}
kpad->export_gpio = true;
kpad->gc.direction_input = adp5589_gpio_direction_input;
kpad->gc.direction_output = adp5589_gpio_direction_output;
kpad->gc.get = adp5589_gpio_get_value;
kpad->gc.set = adp5589_gpio_set_value;
kpad->gc.can_sleep = 1;
kpad->gc.base = gpio_data->gpio_start;
kpad->gc.label = kpad->client->name;
kpad->gc.owner = THIS_MODULE;
mutex_init(&kpad->gpio_lock);
error = gpiochip_add(&kpad->gc);
if (error) {
dev_err(dev, "gpiochip_add failed, err: %d\n", error);
return error;
}
for (i = 0; i <= kpad->var->bank(kpad->var->maxgpio); i++) {
kpad->dat_out[i] = adp5589_read(kpad->client, kpad->var->reg(
ADP5589_GPO_DATA_OUT_A) + i);
kpad->dir[i] = adp5589_read(kpad->client, kpad->var->reg(
ADP5589_GPIO_DIRECTION_A) + i);
}
if (gpio_data->setup) {
error = gpio_data->setup(kpad->client,
kpad->gc.base, kpad->gc.ngpio,
gpio_data->context);
if (error)
dev_warn(dev, "setup failed, %d\n", error);
}
return 0;
}
static void adp5589_gpio_remove(struct adp5589_kpad *kpad)
{
struct device *dev = &kpad->client->dev;
const struct adp5589_kpad_platform_data *pdata = dev->platform_data;
const struct adp5589_gpio_platform_data *gpio_data = pdata->gpio_data;
int error;
if (!kpad->export_gpio)
return;
if (gpio_data->teardown) {
error = gpio_data->teardown(kpad->client,
kpad->gc.base, kpad->gc.ngpio,
gpio_data->context);
if (error)
dev_warn(dev, "teardown failed %d\n", error);
}
error = gpiochip_remove(&kpad->gc);
if (error)
dev_warn(dev, "gpiochip_remove failed %d\n", error);
}
#else
static inline int adp5589_gpio_add(struct adp5589_kpad *kpad)
{
return 0;
}
static inline void adp5589_gpio_remove(struct adp5589_kpad *kpad)
{
}
#endif
static void adp5589_report_switches(struct adp5589_kpad *kpad,
int key, int key_val)
{
int i;
for (i = 0; i < kpad->gpimapsize; i++) {
if (key_val == kpad->gpimap[i].pin) {
input_report_switch(kpad->input,
kpad->gpimap[i].sw_evt,
key & KEY_EV_PRESSED);
break;
}
}
}
static void adp5589_report_events(struct adp5589_kpad *kpad, int ev_cnt)
{
int i;
for (i = 0; i < ev_cnt; i++) {
int key = adp5589_read(kpad->client, ADP5589_5_FIFO_1 + i);
int key_val = key & KEY_EV_MASK;
if (key_val >= kpad->var->gpi_pin_base &&
key_val <= kpad->var->gpi_pin_end) {
adp5589_report_switches(kpad, key, key_val);
} else {
input_report_key(kpad->input,
kpad->keycode[key_val - 1],
key & KEY_EV_PRESSED);
}
}
}
static irqreturn_t adp5589_irq(int irq, void *handle)
{
struct adp5589_kpad *kpad = handle;
struct i2c_client *client = kpad->client;
int status, ev_cnt;
status = adp5589_read(client, ADP5589_5_INT_STATUS);
if (status & OVRFLOW_INT) /* Unlikely and should never happen */
dev_err(&client->dev, "Event Overflow Error\n");
if (status & EVENT_INT) {
ev_cnt = adp5589_read(client, ADP5589_5_STATUS) & KEC;
if (ev_cnt) {
adp5589_report_events(kpad, ev_cnt);
input_sync(kpad->input);
}
}
adp5589_write(client, ADP5589_5_INT_STATUS, status); /* Status is W1C */
return IRQ_HANDLED;
}
static int adp5589_get_evcode(struct adp5589_kpad *kpad, unsigned short key)
{
int i;
for (i = 0; i < kpad->var->keymapsize; i++)
if (key == kpad->keycode[i])
return (i + 1) | KEY_EV_PRESSED;
dev_err(&kpad->client->dev, "RESET/UNLOCK key not in keycode map\n");
return -EINVAL;
}
static int adp5589_setup(struct adp5589_kpad *kpad)
{
struct i2c_client *client = kpad->client;
const struct adp5589_kpad_platform_data *pdata =
client->dev.platform_data;
u8 (*reg) (u8) = kpad->var->reg;
unsigned char evt_mode1 = 0, evt_mode2 = 0, evt_mode3 = 0;
unsigned char pull_mask = 0;
int i, ret;
ret = adp5589_write(client, reg(ADP5589_PIN_CONFIG_A),
pdata->keypad_en_mask & kpad->var->row_mask);
ret |= adp5589_write(client, reg(ADP5589_PIN_CONFIG_B),
(pdata->keypad_en_mask >> kpad->var->col_shift) &
kpad->var->col_mask);
if (!kpad->is_adp5585)
ret |= adp5589_write(client, ADP5589_PIN_CONFIG_C,
(pdata->keypad_en_mask >> 16) & 0xFF);
if (!kpad->is_adp5585 && pdata->en_keylock) {
ret |= adp5589_write(client, ADP5589_UNLOCK1,
pdata->unlock_key1);
ret |= adp5589_write(client, ADP5589_UNLOCK2,
pdata->unlock_key2);
ret |= adp5589_write(client, ADP5589_UNLOCK_TIMERS,
pdata->unlock_timer & LTIME_MASK);
ret |= adp5589_write(client, ADP5589_LOCK_CFG, LOCK_EN);
}
for (i = 0; i < KEYP_MAX_EVENT; i++)
ret |= adp5589_read(client, ADP5589_5_FIFO_1 + i);
for (i = 0; i < pdata->gpimapsize; i++) {
unsigned short pin = pdata->gpimap[i].pin;
if (pin <= kpad->var->gpi_pin_row_end) {
evt_mode1 |= (1 << (pin - kpad->var->gpi_pin_row_base));
} else {
evt_mode2 |=
((1 << (pin - kpad->var->gpi_pin_col_base)) & 0xFF);
if (!kpad->is_adp5585)
evt_mode3 |= ((1 << (pin -
kpad->var->gpi_pin_col_base)) >> 8);
}
}
if (pdata->gpimapsize) {
ret |= adp5589_write(client, reg(ADP5589_GPI_EVENT_EN_A),
evt_mode1);
ret |= adp5589_write(client, reg(ADP5589_GPI_EVENT_EN_B),
evt_mode2);
if (!kpad->is_adp5585)
ret |= adp5589_write(client,
reg(ADP5589_GPI_EVENT_EN_C),
evt_mode3);
}
if (pdata->pull_dis_mask & pdata->pullup_en_100k &
pdata->pullup_en_300k & pdata->pulldown_en_300k)
dev_warn(&client->dev, "Conflicting pull resistor config\n");
for (i = 0; i <= kpad->var->max_row_num; i++) {
unsigned val = 0, bit = (1 << i);
if (pdata->pullup_en_300k & bit)
val = 0;
else if (pdata->pulldown_en_300k & bit)
val = 1;
else if (pdata->pullup_en_100k & bit)
val = 2;
else if (pdata->pull_dis_mask & bit)
val = 3;
pull_mask |= val << (2 * (i & 0x3));
if (i == 3 || i == kpad->var->max_row_num) {
ret |= adp5589_write(client, reg(ADP5585_RPULL_CONFIG_A)
+ (i >> 2), pull_mask);
pull_mask = 0;
}
}
for (i = 0; i <= kpad->var->max_col_num; i++) {
unsigned val = 0, bit = 1 << (i + kpad->var->col_shift);
if (pdata->pullup_en_300k & bit)
val = 0;
else if (pdata->pulldown_en_300k & bit)
val = 1;
else if (pdata->pullup_en_100k & bit)
val = 2;
else if (pdata->pull_dis_mask & bit)
val = 3;
pull_mask |= val << (2 * (i & 0x3));
if (i == 3 || i == kpad->var->max_col_num) {
ret |= adp5589_write(client,
reg(ADP5585_RPULL_CONFIG_C) +
(i >> 2), pull_mask);
pull_mask = 0;
}
}
if (pdata->reset1_key_1 && pdata->reset1_key_2 && pdata->reset1_key_3) {
ret |= adp5589_write(client, reg(ADP5589_RESET1_EVENT_A),
adp5589_get_evcode(kpad,
pdata->reset1_key_1));
ret |= adp5589_write(client, reg(ADP5589_RESET1_EVENT_B),
adp5589_get_evcode(kpad,
pdata->reset1_key_2));
ret |= adp5589_write(client, reg(ADP5589_RESET1_EVENT_C),
adp5589_get_evcode(kpad,
pdata->reset1_key_3));
kpad->extend_cfg |= R4_EXTEND_CFG;
}
if (pdata->reset2_key_1 && pdata->reset2_key_2) {
ret |= adp5589_write(client, reg(ADP5589_RESET2_EVENT_A),
adp5589_get_evcode(kpad,
pdata->reset2_key_1));
ret |= adp5589_write(client, reg(ADP5589_RESET2_EVENT_B),
adp5589_get_evcode(kpad,
pdata->reset2_key_2));
kpad->extend_cfg |= C4_EXTEND_CFG;
}
if (kpad->extend_cfg) {
ret |= adp5589_write(client, reg(ADP5589_RESET_CFG),
pdata->reset_cfg);
ret |= adp5589_write(client, reg(ADP5589_PIN_CONFIG_D),
kpad->extend_cfg);
}
ret |= adp5589_write(client, reg(ADP5589_DEBOUNCE_DIS_A),
pdata->debounce_dis_mask & kpad->var->row_mask);
ret |= adp5589_write(client, reg(ADP5589_DEBOUNCE_DIS_B),
(pdata->debounce_dis_mask >> kpad->var->col_shift)
& kpad->var->col_mask);
if (!kpad->is_adp5585)
ret |= adp5589_write(client, reg(ADP5589_DEBOUNCE_DIS_C),
(pdata->debounce_dis_mask >> 16) & 0xFF);
ret |= adp5589_write(client, reg(ADP5589_POLL_PTIME_CFG),
pdata->scan_cycle_time & PTIME_MASK);
ret |= adp5589_write(client, ADP5589_5_INT_STATUS,
(kpad->is_adp5585 ? 0 : LOGIC2_INT) |
LOGIC1_INT | OVRFLOW_INT |
(kpad->is_adp5585 ? 0 : LOCK_INT) |
GPI_INT | EVENT_INT); /* Status is W1C */
ret |= adp5589_write(client, reg(ADP5589_GENERAL_CFG),
INT_CFG | OSC_EN | CORE_CLK(3));
ret |= adp5589_write(client, reg(ADP5589_INT_EN),
OVRFLOW_IEN | GPI_IEN | EVENT_IEN);
if (ret < 0) {
dev_err(&client->dev, "Write Error\n");
return ret;
}
return 0;
}
static void adp5589_report_switch_state(struct adp5589_kpad *kpad)
{
int gpi_stat_tmp, pin_loc;
int i;
int gpi_stat1 = adp5589_read(kpad->client,
kpad->var->reg(ADP5589_GPI_STATUS_A));
int gpi_stat2 = adp5589_read(kpad->client,
kpad->var->reg(ADP5589_GPI_STATUS_B));
int gpi_stat3 = !kpad->is_adp5585 ?
adp5589_read(kpad->client, ADP5589_GPI_STATUS_C) : 0;
for (i = 0; i < kpad->gpimapsize; i++) {
unsigned short pin = kpad->gpimap[i].pin;
if (pin <= kpad->var->gpi_pin_row_end) {
gpi_stat_tmp = gpi_stat1;
pin_loc = pin - kpad->var->gpi_pin_row_base;
} else if ((pin - kpad->var->gpi_pin_col_base) < 8) {
gpi_stat_tmp = gpi_stat2;
pin_loc = pin - kpad->var->gpi_pin_col_base;
} else {
gpi_stat_tmp = gpi_stat3;
pin_loc = pin - kpad->var->gpi_pin_col_base - 8;
}
if (gpi_stat_tmp < 0) {
dev_err(&kpad->client->dev,
"Can't read GPIO_DAT_STAT switch %d, default to OFF\n",
pin);
gpi_stat_tmp = 0;
}
input_report_switch(kpad->input,
kpad->gpimap[i].sw_evt,
!(gpi_stat_tmp & (1 << pin_loc)));
}
input_sync(kpad->input);
}
static int adp5589_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct adp5589_kpad *kpad;
const struct adp5589_kpad_platform_data *pdata =
client->dev.platform_data;
struct input_dev *input;
unsigned int revid;
int ret, i;
int error;
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE_DATA)) {
dev_err(&client->dev, "SMBUS Byte Data not Supported\n");
return -EIO;
}
if (!pdata) {
dev_err(&client->dev, "no platform data?\n");
return -EINVAL;
}
kpad = kzalloc(sizeof(*kpad), GFP_KERNEL);
if (!kpad)
return -ENOMEM;
switch (id->driver_data) {
case ADP5585_02:
kpad->adp5585_support_row5 = true;
case ADP5585_01:
kpad->is_adp5585 = true;
kpad->var = &const_adp5585;
break;
case ADP5589:
kpad->var = &const_adp5589;
break;
}
if (!((pdata->keypad_en_mask & kpad->var->row_mask) &&
(pdata->keypad_en_mask >> kpad->var->col_shift)) ||
!pdata->keymap) {
dev_err(&client->dev, "no rows, cols or keymap from pdata\n");
error = -EINVAL;
goto err_free_mem;
}
if (pdata->keymapsize != kpad->var->keymapsize) {
dev_err(&client->dev, "invalid keymapsize\n");
error = -EINVAL;
goto err_free_mem;
}
if (!pdata->gpimap && pdata->gpimapsize) {
dev_err(&client->dev, "invalid gpimap from pdata\n");
error = -EINVAL;
goto err_free_mem;
}
if (pdata->gpimapsize > kpad->var->gpimapsize_max) {
dev_err(&client->dev, "invalid gpimapsize\n");
error = -EINVAL;
goto err_free_mem;
}
for (i = 0; i < pdata->gpimapsize; i++) {
unsigned short pin = pdata->gpimap[i].pin;
if (pin < kpad->var->gpi_pin_base ||
pin > kpad->var->gpi_pin_end) {
dev_err(&client->dev, "invalid gpi pin data\n");
error = -EINVAL;
goto err_free_mem;
}
if ((1 << (pin - kpad->var->gpi_pin_row_base)) &
pdata->keypad_en_mask) {
dev_err(&client->dev, "invalid gpi row/col data\n");
error = -EINVAL;
goto err_free_mem;
}
}
if (!client->irq) {
dev_err(&client->dev, "no IRQ?\n");
error = -EINVAL;
goto err_free_mem;
}
input = input_allocate_device();
if (!input) {
error = -ENOMEM;
goto err_free_mem;
}
kpad->client = client;
kpad->input = input;
ret = adp5589_read(client, ADP5589_5_ID);
if (ret < 0) {
error = ret;
goto err_free_input;
}
revid = (u8) ret & ADP5589_5_DEVICE_ID_MASK;
input->name = client->name;
input->phys = "adp5589-keys/input0";
input->dev.parent = &client->dev;
input_set_drvdata(input, kpad);
input->id.bustype = BUS_I2C;
input->id.vendor = 0x0001;
input->id.product = 0x0001;
input->id.version = revid;
input->keycodesize = sizeof(kpad->keycode[0]);
input->keycodemax = pdata->keymapsize;
input->keycode = kpad->keycode;
memcpy(kpad->keycode, pdata->keymap,
pdata->keymapsize * input->keycodesize);
kpad->gpimap = pdata->gpimap;
kpad->gpimapsize = pdata->gpimapsize;
/* setup input device */
__set_bit(EV_KEY, input->evbit);
if (pdata->repeat)
__set_bit(EV_REP, input->evbit);
for (i = 0; i < input->keycodemax; i++)
__set_bit(kpad->keycode[i] & KEY_MAX, input->keybit);
__clear_bit(KEY_RESERVED, input->keybit);
if (kpad->gpimapsize)
__set_bit(EV_SW, input->evbit);
for (i = 0; i < kpad->gpimapsize; i++)
__set_bit(kpad->gpimap[i].sw_evt, input->swbit);
error = input_register_device(input);
if (error) {
dev_err(&client->dev, "unable to register input device\n");
goto err_free_input;
}
error = request_threaded_irq(client->irq, NULL, adp5589_irq,
IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
client->dev.driver->name, kpad);
if (error) {
dev_err(&client->dev, "irq %d busy?\n", client->irq);
goto err_unreg_dev;
}
error = adp5589_setup(kpad);
if (error)
goto err_free_irq;
if (kpad->gpimapsize)
adp5589_report_switch_state(kpad);
error = adp5589_gpio_add(kpad);
if (error)
goto err_free_irq;
device_init_wakeup(&client->dev, 1);
i2c_set_clientdata(client, kpad);
dev_info(&client->dev, "Rev.%d keypad, irq %d\n", revid, client->irq);
return 0;
err_free_irq:
free_irq(client->irq, kpad);
err_unreg_dev:
input_unregister_device(input);
input = NULL;
err_free_input:
input_free_device(input);
err_free_mem:
kfree(kpad);
return error;
}
static int adp5589_remove(struct i2c_client *client)
{
struct adp5589_kpad *kpad = i2c_get_clientdata(client);
adp5589_write(client, kpad->var->reg(ADP5589_GENERAL_CFG), 0);
free_irq(client->irq, kpad);
input_unregister_device(kpad->input);
adp5589_gpio_remove(kpad);
kfree(kpad);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int adp5589_suspend(struct device *dev)
{
struct adp5589_kpad *kpad = dev_get_drvdata(dev);
struct i2c_client *client = kpad->client;
disable_irq(client->irq);
if (device_may_wakeup(&client->dev))
enable_irq_wake(client->irq);
return 0;
}
static int adp5589_resume(struct device *dev)
{
struct adp5589_kpad *kpad = dev_get_drvdata(dev);
struct i2c_client *client = kpad->client;
if (device_may_wakeup(&client->dev))
disable_irq_wake(client->irq);
enable_irq(client->irq);
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(adp5589_dev_pm_ops, adp5589_suspend, adp5589_resume);
static const struct i2c_device_id adp5589_id[] = {
{"adp5589-keys", ADP5589},
{"adp5585-keys", ADP5585_01},
{"adp5585-02-keys", ADP5585_02}, /* Adds ROW5 to ADP5585 */
{}
};
MODULE_DEVICE_TABLE(i2c, adp5589_id);
static struct i2c_driver adp5589_driver = {
.driver = {
.name = KBUILD_MODNAME,
.owner = THIS_MODULE,
.pm = &adp5589_dev_pm_ops,
},
.probe = adp5589_probe,
.remove = adp5589_remove,
.id_table = adp5589_id,
};
module_i2c_driver(adp5589_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>");
MODULE_DESCRIPTION("ADP5589/ADP5585 Keypad driver");
| gpl-2.0 |
DecimalMan/dkp-tw | arch/x86/mm/memtest.c | 3177 | 3094 | #include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/init.h>
#include <linux/pfn.h>
#include <linux/memblock.h>
static u64 patterns[] __initdata = {
0,
0xffffffffffffffffULL,
0x5555555555555555ULL,
0xaaaaaaaaaaaaaaaaULL,
0x1111111111111111ULL,
0x2222222222222222ULL,
0x4444444444444444ULL,
0x8888888888888888ULL,
0x3333333333333333ULL,
0x6666666666666666ULL,
0x9999999999999999ULL,
0xccccccccccccccccULL,
0x7777777777777777ULL,
0xbbbbbbbbbbbbbbbbULL,
0xddddddddddddddddULL,
0xeeeeeeeeeeeeeeeeULL,
0x7a6c7258554e494cULL, /* yeah ;-) */
};
static void __init reserve_bad_mem(u64 pattern, u64 start_bad, u64 end_bad)
{
printk(KERN_INFO " %016llx bad mem addr %010llx - %010llx reserved\n",
(unsigned long long) pattern,
(unsigned long long) start_bad,
(unsigned long long) end_bad);
memblock_x86_reserve_range(start_bad, end_bad, "BAD RAM");
}
static void __init memtest(u64 pattern, u64 start_phys, u64 size)
{
u64 *p, *start, *end;
u64 start_bad, last_bad;
u64 start_phys_aligned;
const size_t incr = sizeof(pattern);
start_phys_aligned = ALIGN(start_phys, incr);
start = __va(start_phys_aligned);
end = start + (size - (start_phys_aligned - start_phys)) / incr;
start_bad = 0;
last_bad = 0;
for (p = start; p < end; p++)
*p = pattern;
for (p = start; p < end; p++, start_phys_aligned += incr) {
if (*p == pattern)
continue;
if (start_phys_aligned == last_bad + incr) {
last_bad += incr;
continue;
}
if (start_bad)
reserve_bad_mem(pattern, start_bad, last_bad + incr);
start_bad = last_bad = start_phys_aligned;
}
if (start_bad)
reserve_bad_mem(pattern, start_bad, last_bad + incr);
}
static void __init do_one_pass(u64 pattern, u64 start, u64 end)
{
u64 size = 0;
while (start < end) {
start = memblock_x86_find_in_range_size(start, &size, 1);
/* done ? */
if (start >= end)
break;
if (start + size > end)
size = end - start;
printk(KERN_INFO " %010llx - %010llx pattern %016llx\n",
(unsigned long long) start,
(unsigned long long) start + size,
(unsigned long long) cpu_to_be64(pattern));
memtest(pattern, start, size);
start += size;
}
}
/* default is disabled */
static int memtest_pattern __initdata;
static int __init parse_memtest(char *arg)
{
if (arg)
memtest_pattern = simple_strtoul(arg, NULL, 0);
else
memtest_pattern = ARRAY_SIZE(patterns);
return 0;
}
early_param("memtest", parse_memtest);
void __init early_memtest(unsigned long start, unsigned long end)
{
unsigned int i;
unsigned int idx = 0;
if (!memtest_pattern)
return;
printk(KERN_INFO "early_memtest: # of tests: %d\n", memtest_pattern);
for (i = 0; i < memtest_pattern; i++) {
idx = i % ARRAY_SIZE(patterns);
do_one_pass(patterns[idx], start, end);
}
if (idx > 0) {
printk(KERN_INFO "early_memtest: wipe out "
"test pattern from memory\n");
/* additional test with pattern 0 will do this */
do_one_pass(0, start, end);
}
}
| gpl-2.0 |
abgoyal/zen_u105_kernel | drivers/ssb/driver_mipscore.c | 3689 | 7051 | /*
* Sonics Silicon Backplane
* Broadcom MIPS core driver
*
* Copyright 2005, Broadcom Corporation
* Copyright 2006, 2007, Michael Buesch <mb@bu3sch.de>
*
* Licensed under the GNU/GPL. See COPYING for details.
*/
#include <linux/ssb/ssb.h>
#include <linux/serial.h>
#include <linux/serial_core.h>
#include <linux/serial_reg.h>
#include <linux/time.h>
#include "ssb_private.h"
static inline u32 mips_read32(struct ssb_mipscore *mcore,
u16 offset)
{
return ssb_read32(mcore->dev, offset);
}
static inline void mips_write32(struct ssb_mipscore *mcore,
u16 offset,
u32 value)
{
ssb_write32(mcore->dev, offset, value);
}
static const u32 ipsflag_irq_mask[] = {
0,
SSB_IPSFLAG_IRQ1,
SSB_IPSFLAG_IRQ2,
SSB_IPSFLAG_IRQ3,
SSB_IPSFLAG_IRQ4,
};
static const u32 ipsflag_irq_shift[] = {
0,
SSB_IPSFLAG_IRQ1_SHIFT,
SSB_IPSFLAG_IRQ2_SHIFT,
SSB_IPSFLAG_IRQ3_SHIFT,
SSB_IPSFLAG_IRQ4_SHIFT,
};
static inline u32 ssb_irqflag(struct ssb_device *dev)
{
u32 tpsflag = ssb_read32(dev, SSB_TPSFLAG);
if (tpsflag)
return ssb_read32(dev, SSB_TPSFLAG) & SSB_TPSFLAG_BPFLAG;
else
/* not irq supported */
return 0x3f;
}
static struct ssb_device *find_device(struct ssb_device *rdev, int irqflag)
{
struct ssb_bus *bus = rdev->bus;
int i;
for (i = 0; i < bus->nr_devices; i++) {
struct ssb_device *dev;
dev = &(bus->devices[i]);
if (ssb_irqflag(dev) == irqflag)
return dev;
}
return NULL;
}
/* Get the MIPS IRQ assignment for a specified device.
* If unassigned, 0 is returned.
* If disabled, 5 is returned.
* If not supported, 6 is returned.
*/
unsigned int ssb_mips_irq(struct ssb_device *dev)
{
struct ssb_bus *bus = dev->bus;
struct ssb_device *mdev = bus->mipscore.dev;
u32 irqflag;
u32 ipsflag;
u32 tmp;
unsigned int irq;
irqflag = ssb_irqflag(dev);
if (irqflag == 0x3f)
return 6;
ipsflag = ssb_read32(bus->mipscore.dev, SSB_IPSFLAG);
for (irq = 1; irq <= 4; irq++) {
tmp = ((ipsflag & ipsflag_irq_mask[irq]) >> ipsflag_irq_shift[irq]);
if (tmp == irqflag)
break;
}
if (irq == 5) {
if ((1 << irqflag) & ssb_read32(mdev, SSB_INTVEC))
irq = 0;
}
return irq;
}
static void clear_irq(struct ssb_bus *bus, unsigned int irq)
{
struct ssb_device *dev = bus->mipscore.dev;
/* Clear the IRQ in the MIPScore backplane registers */
if (irq == 0) {
ssb_write32(dev, SSB_INTVEC, 0);
} else {
ssb_write32(dev, SSB_IPSFLAG,
ssb_read32(dev, SSB_IPSFLAG) |
ipsflag_irq_mask[irq]);
}
}
static void set_irq(struct ssb_device *dev, unsigned int irq)
{
unsigned int oldirq = ssb_mips_irq(dev);
struct ssb_bus *bus = dev->bus;
struct ssb_device *mdev = bus->mipscore.dev;
u32 irqflag = ssb_irqflag(dev);
BUG_ON(oldirq == 6);
dev->irq = irq + 2;
/* clear the old irq */
if (oldirq == 0)
ssb_write32(mdev, SSB_INTVEC, (~(1 << irqflag) & ssb_read32(mdev, SSB_INTVEC)));
else if (oldirq != 5)
clear_irq(bus, oldirq);
/* assign the new one */
if (irq == 0) {
ssb_write32(mdev, SSB_INTVEC, ((1 << irqflag) | ssb_read32(mdev, SSB_INTVEC)));
} else {
u32 ipsflag = ssb_read32(mdev, SSB_IPSFLAG);
if ((ipsflag & ipsflag_irq_mask[irq]) != ipsflag_irq_mask[irq]) {
u32 oldipsflag = (ipsflag & ipsflag_irq_mask[irq]) >> ipsflag_irq_shift[irq];
struct ssb_device *olddev = find_device(dev, oldipsflag);
if (olddev)
set_irq(olddev, 0);
}
irqflag <<= ipsflag_irq_shift[irq];
irqflag |= (ipsflag & ~ipsflag_irq_mask[irq]);
ssb_write32(mdev, SSB_IPSFLAG, irqflag);
}
ssb_dprintk(KERN_INFO PFX
"set_irq: core 0x%04x, irq %d => %d\n",
dev->id.coreid, oldirq+2, irq+2);
}
static void print_irq(struct ssb_device *dev, unsigned int irq)
{
int i;
static const char *irq_name[] = {"2(S)", "3", "4", "5", "6", "D", "I"};
ssb_dprintk(KERN_INFO PFX
"core 0x%04x, irq :", dev->id.coreid);
for (i = 0; i <= 6; i++) {
ssb_dprintk(" %s%s", irq_name[i], i==irq?"*":" ");
}
ssb_dprintk("\n");
}
static void dump_irq(struct ssb_bus *bus)
{
int i;
for (i = 0; i < bus->nr_devices; i++) {
struct ssb_device *dev;
dev = &(bus->devices[i]);
print_irq(dev, ssb_mips_irq(dev));
}
}
static void ssb_mips_serial_init(struct ssb_mipscore *mcore)
{
struct ssb_bus *bus = mcore->dev->bus;
if (bus->extif.dev)
mcore->nr_serial_ports = ssb_extif_serial_init(&bus->extif, mcore->serial_ports);
else if (bus->chipco.dev)
mcore->nr_serial_ports = ssb_chipco_serial_init(&bus->chipco, mcore->serial_ports);
else
mcore->nr_serial_ports = 0;
}
static void ssb_mips_flash_detect(struct ssb_mipscore *mcore)
{
struct ssb_bus *bus = mcore->dev->bus;
mcore->flash_buswidth = 2;
if (bus->chipco.dev) {
mcore->flash_window = 0x1c000000;
mcore->flash_window_size = 0x02000000;
if ((ssb_read32(bus->chipco.dev, SSB_CHIPCO_FLASH_CFG)
& SSB_CHIPCO_CFG_DS16) == 0)
mcore->flash_buswidth = 1;
} else {
mcore->flash_window = 0x1fc00000;
mcore->flash_window_size = 0x00400000;
}
}
u32 ssb_cpu_clock(struct ssb_mipscore *mcore)
{
struct ssb_bus *bus = mcore->dev->bus;
u32 pll_type, n, m, rate = 0;
if (bus->extif.dev) {
ssb_extif_get_clockcontrol(&bus->extif, &pll_type, &n, &m);
} else if (bus->chipco.dev) {
ssb_chipco_get_clockcpu(&bus->chipco, &pll_type, &n, &m);
} else
return 0;
if ((pll_type == SSB_PLLTYPE_5) || (bus->chip_id == 0x5365)) {
rate = 200000000;
} else {
rate = ssb_calc_clock_rate(pll_type, n, m);
}
if (pll_type == SSB_PLLTYPE_6) {
rate *= 2;
}
return rate;
}
void ssb_mipscore_init(struct ssb_mipscore *mcore)
{
struct ssb_bus *bus;
struct ssb_device *dev;
unsigned long hz, ns;
unsigned int irq, i;
if (!mcore->dev)
return; /* We don't have a MIPS core */
ssb_dprintk(KERN_INFO PFX "Initializing MIPS core...\n");
bus = mcore->dev->bus;
hz = ssb_clockspeed(bus);
if (!hz)
hz = 100000000;
ns = 1000000000 / hz;
if (bus->extif.dev)
ssb_extif_timing_init(&bus->extif, ns);
else if (bus->chipco.dev)
ssb_chipco_timing_init(&bus->chipco, ns);
/* Assign IRQs to all cores on the bus, start with irq line 2, because serial usually takes 1 */
for (irq = 2, i = 0; i < bus->nr_devices; i++) {
int mips_irq;
dev = &(bus->devices[i]);
mips_irq = ssb_mips_irq(dev);
if (mips_irq > 4)
dev->irq = 0;
else
dev->irq = mips_irq + 2;
if (dev->irq > 5)
continue;
switch (dev->id.coreid) {
case SSB_DEV_USB11_HOST:
/* shouldn't need a separate irq line for non-4710, most of them have a proper
* external usb controller on the pci */
if ((bus->chip_id == 0x4710) && (irq <= 4)) {
set_irq(dev, irq++);
}
break;
case SSB_DEV_PCI:
case SSB_DEV_ETHERNET:
case SSB_DEV_ETHERNET_GBIT:
case SSB_DEV_80211:
case SSB_DEV_USB20_HOST:
/* These devices get their own IRQ line if available, the rest goes on IRQ0 */
if (irq <= 4) {
set_irq(dev, irq++);
break;
}
/* fallthrough */
case SSB_DEV_EXTIF:
set_irq(dev, 0);
break;
}
}
ssb_dprintk(KERN_INFO PFX "after irq reconfiguration\n");
dump_irq(bus);
ssb_mips_serial_init(mcore);
ssb_mips_flash_detect(mcore);
}
| gpl-2.0 |
ragepekr/RageKernel | drivers/ssb/driver_mipscore.c | 3689 | 7051 | /*
* Sonics Silicon Backplane
* Broadcom MIPS core driver
*
* Copyright 2005, Broadcom Corporation
* Copyright 2006, 2007, Michael Buesch <mb@bu3sch.de>
*
* Licensed under the GNU/GPL. See COPYING for details.
*/
#include <linux/ssb/ssb.h>
#include <linux/serial.h>
#include <linux/serial_core.h>
#include <linux/serial_reg.h>
#include <linux/time.h>
#include "ssb_private.h"
static inline u32 mips_read32(struct ssb_mipscore *mcore,
u16 offset)
{
return ssb_read32(mcore->dev, offset);
}
static inline void mips_write32(struct ssb_mipscore *mcore,
u16 offset,
u32 value)
{
ssb_write32(mcore->dev, offset, value);
}
static const u32 ipsflag_irq_mask[] = {
0,
SSB_IPSFLAG_IRQ1,
SSB_IPSFLAG_IRQ2,
SSB_IPSFLAG_IRQ3,
SSB_IPSFLAG_IRQ4,
};
static const u32 ipsflag_irq_shift[] = {
0,
SSB_IPSFLAG_IRQ1_SHIFT,
SSB_IPSFLAG_IRQ2_SHIFT,
SSB_IPSFLAG_IRQ3_SHIFT,
SSB_IPSFLAG_IRQ4_SHIFT,
};
static inline u32 ssb_irqflag(struct ssb_device *dev)
{
u32 tpsflag = ssb_read32(dev, SSB_TPSFLAG);
if (tpsflag)
return ssb_read32(dev, SSB_TPSFLAG) & SSB_TPSFLAG_BPFLAG;
else
/* not irq supported */
return 0x3f;
}
static struct ssb_device *find_device(struct ssb_device *rdev, int irqflag)
{
struct ssb_bus *bus = rdev->bus;
int i;
for (i = 0; i < bus->nr_devices; i++) {
struct ssb_device *dev;
dev = &(bus->devices[i]);
if (ssb_irqflag(dev) == irqflag)
return dev;
}
return NULL;
}
/* Get the MIPS IRQ assignment for a specified device.
* If unassigned, 0 is returned.
* If disabled, 5 is returned.
* If not supported, 6 is returned.
*/
unsigned int ssb_mips_irq(struct ssb_device *dev)
{
struct ssb_bus *bus = dev->bus;
struct ssb_device *mdev = bus->mipscore.dev;
u32 irqflag;
u32 ipsflag;
u32 tmp;
unsigned int irq;
irqflag = ssb_irqflag(dev);
if (irqflag == 0x3f)
return 6;
ipsflag = ssb_read32(bus->mipscore.dev, SSB_IPSFLAG);
for (irq = 1; irq <= 4; irq++) {
tmp = ((ipsflag & ipsflag_irq_mask[irq]) >> ipsflag_irq_shift[irq]);
if (tmp == irqflag)
break;
}
if (irq == 5) {
if ((1 << irqflag) & ssb_read32(mdev, SSB_INTVEC))
irq = 0;
}
return irq;
}
static void clear_irq(struct ssb_bus *bus, unsigned int irq)
{
struct ssb_device *dev = bus->mipscore.dev;
/* Clear the IRQ in the MIPScore backplane registers */
if (irq == 0) {
ssb_write32(dev, SSB_INTVEC, 0);
} else {
ssb_write32(dev, SSB_IPSFLAG,
ssb_read32(dev, SSB_IPSFLAG) |
ipsflag_irq_mask[irq]);
}
}
static void set_irq(struct ssb_device *dev, unsigned int irq)
{
unsigned int oldirq = ssb_mips_irq(dev);
struct ssb_bus *bus = dev->bus;
struct ssb_device *mdev = bus->mipscore.dev;
u32 irqflag = ssb_irqflag(dev);
BUG_ON(oldirq == 6);
dev->irq = irq + 2;
/* clear the old irq */
if (oldirq == 0)
ssb_write32(mdev, SSB_INTVEC, (~(1 << irqflag) & ssb_read32(mdev, SSB_INTVEC)));
else if (oldirq != 5)
clear_irq(bus, oldirq);
/* assign the new one */
if (irq == 0) {
ssb_write32(mdev, SSB_INTVEC, ((1 << irqflag) | ssb_read32(mdev, SSB_INTVEC)));
} else {
u32 ipsflag = ssb_read32(mdev, SSB_IPSFLAG);
if ((ipsflag & ipsflag_irq_mask[irq]) != ipsflag_irq_mask[irq]) {
u32 oldipsflag = (ipsflag & ipsflag_irq_mask[irq]) >> ipsflag_irq_shift[irq];
struct ssb_device *olddev = find_device(dev, oldipsflag);
if (olddev)
set_irq(olddev, 0);
}
irqflag <<= ipsflag_irq_shift[irq];
irqflag |= (ipsflag & ~ipsflag_irq_mask[irq]);
ssb_write32(mdev, SSB_IPSFLAG, irqflag);
}
ssb_dprintk(KERN_INFO PFX
"set_irq: core 0x%04x, irq %d => %d\n",
dev->id.coreid, oldirq+2, irq+2);
}
static void print_irq(struct ssb_device *dev, unsigned int irq)
{
int i;
static const char *irq_name[] = {"2(S)", "3", "4", "5", "6", "D", "I"};
ssb_dprintk(KERN_INFO PFX
"core 0x%04x, irq :", dev->id.coreid);
for (i = 0; i <= 6; i++) {
ssb_dprintk(" %s%s", irq_name[i], i==irq?"*":" ");
}
ssb_dprintk("\n");
}
static void dump_irq(struct ssb_bus *bus)
{
int i;
for (i = 0; i < bus->nr_devices; i++) {
struct ssb_device *dev;
dev = &(bus->devices[i]);
print_irq(dev, ssb_mips_irq(dev));
}
}
static void ssb_mips_serial_init(struct ssb_mipscore *mcore)
{
struct ssb_bus *bus = mcore->dev->bus;
if (bus->extif.dev)
mcore->nr_serial_ports = ssb_extif_serial_init(&bus->extif, mcore->serial_ports);
else if (bus->chipco.dev)
mcore->nr_serial_ports = ssb_chipco_serial_init(&bus->chipco, mcore->serial_ports);
else
mcore->nr_serial_ports = 0;
}
static void ssb_mips_flash_detect(struct ssb_mipscore *mcore)
{
struct ssb_bus *bus = mcore->dev->bus;
mcore->flash_buswidth = 2;
if (bus->chipco.dev) {
mcore->flash_window = 0x1c000000;
mcore->flash_window_size = 0x02000000;
if ((ssb_read32(bus->chipco.dev, SSB_CHIPCO_FLASH_CFG)
& SSB_CHIPCO_CFG_DS16) == 0)
mcore->flash_buswidth = 1;
} else {
mcore->flash_window = 0x1fc00000;
mcore->flash_window_size = 0x00400000;
}
}
u32 ssb_cpu_clock(struct ssb_mipscore *mcore)
{
struct ssb_bus *bus = mcore->dev->bus;
u32 pll_type, n, m, rate = 0;
if (bus->extif.dev) {
ssb_extif_get_clockcontrol(&bus->extif, &pll_type, &n, &m);
} else if (bus->chipco.dev) {
ssb_chipco_get_clockcpu(&bus->chipco, &pll_type, &n, &m);
} else
return 0;
if ((pll_type == SSB_PLLTYPE_5) || (bus->chip_id == 0x5365)) {
rate = 200000000;
} else {
rate = ssb_calc_clock_rate(pll_type, n, m);
}
if (pll_type == SSB_PLLTYPE_6) {
rate *= 2;
}
return rate;
}
void ssb_mipscore_init(struct ssb_mipscore *mcore)
{
struct ssb_bus *bus;
struct ssb_device *dev;
unsigned long hz, ns;
unsigned int irq, i;
if (!mcore->dev)
return; /* We don't have a MIPS core */
ssb_dprintk(KERN_INFO PFX "Initializing MIPS core...\n");
bus = mcore->dev->bus;
hz = ssb_clockspeed(bus);
if (!hz)
hz = 100000000;
ns = 1000000000 / hz;
if (bus->extif.dev)
ssb_extif_timing_init(&bus->extif, ns);
else if (bus->chipco.dev)
ssb_chipco_timing_init(&bus->chipco, ns);
/* Assign IRQs to all cores on the bus, start with irq line 2, because serial usually takes 1 */
for (irq = 2, i = 0; i < bus->nr_devices; i++) {
int mips_irq;
dev = &(bus->devices[i]);
mips_irq = ssb_mips_irq(dev);
if (mips_irq > 4)
dev->irq = 0;
else
dev->irq = mips_irq + 2;
if (dev->irq > 5)
continue;
switch (dev->id.coreid) {
case SSB_DEV_USB11_HOST:
/* shouldn't need a separate irq line for non-4710, most of them have a proper
* external usb controller on the pci */
if ((bus->chip_id == 0x4710) && (irq <= 4)) {
set_irq(dev, irq++);
}
break;
case SSB_DEV_PCI:
case SSB_DEV_ETHERNET:
case SSB_DEV_ETHERNET_GBIT:
case SSB_DEV_80211:
case SSB_DEV_USB20_HOST:
/* These devices get their own IRQ line if available, the rest goes on IRQ0 */
if (irq <= 4) {
set_irq(dev, irq++);
break;
}
/* fallthrough */
case SSB_DEV_EXTIF:
set_irq(dev, 0);
break;
}
}
ssb_dprintk(KERN_INFO PFX "after irq reconfiguration\n");
dump_irq(bus);
ssb_mips_serial_init(mcore);
ssb_mips_flash_detect(mcore);
}
| gpl-2.0 |
bio4554/android-4.1 | arch/powerpc/platforms/ps3/repository.c | 4201 | 33511 | /*
* PS3 repository routines.
*
* Copyright (C) 2006 Sony Computer Entertainment Inc.
* Copyright 2006 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <asm/lv1call.h>
#include "platform.h"
enum ps3_vendor_id {
PS3_VENDOR_ID_NONE = 0,
PS3_VENDOR_ID_SONY = 0x8000000000000000UL,
};
enum ps3_lpar_id {
PS3_LPAR_ID_CURRENT = 0,
PS3_LPAR_ID_PME = 1,
};
#define dump_field(_a, _b) _dump_field(_a, _b, __func__, __LINE__)
static void _dump_field(const char *hdr, u64 n, const char *func, int line)
{
#if defined(DEBUG)
char s[16];
const char *const in = (const char *)&n;
unsigned int i;
for (i = 0; i < 8; i++)
s[i] = (in[i] <= 126 && in[i] >= 32) ? in[i] : '.';
s[i] = 0;
pr_devel("%s:%d: %s%016llx : %s\n", func, line, hdr, n, s);
#endif
}
#define dump_node_name(_a, _b, _c, _d, _e) \
_dump_node_name(_a, _b, _c, _d, _e, __func__, __LINE__)
static void _dump_node_name(unsigned int lpar_id, u64 n1, u64 n2, u64 n3,
u64 n4, const char *func, int line)
{
pr_devel("%s:%d: lpar: %u\n", func, line, lpar_id);
_dump_field("n1: ", n1, func, line);
_dump_field("n2: ", n2, func, line);
_dump_field("n3: ", n3, func, line);
_dump_field("n4: ", n4, func, line);
}
#define dump_node(_a, _b, _c, _d, _e, _f, _g) \
_dump_node(_a, _b, _c, _d, _e, _f, _g, __func__, __LINE__)
static void _dump_node(unsigned int lpar_id, u64 n1, u64 n2, u64 n3, u64 n4,
u64 v1, u64 v2, const char *func, int line)
{
pr_devel("%s:%d: lpar: %u\n", func, line, lpar_id);
_dump_field("n1: ", n1, func, line);
_dump_field("n2: ", n2, func, line);
_dump_field("n3: ", n3, func, line);
_dump_field("n4: ", n4, func, line);
pr_devel("%s:%d: v1: %016llx\n", func, line, v1);
pr_devel("%s:%d: v2: %016llx\n", func, line, v2);
}
/**
* make_first_field - Make the first field of a repository node name.
* @text: Text portion of the field.
* @index: Numeric index portion of the field. Use zero for 'don't care'.
*
* This routine sets the vendor id to zero (non-vendor specific).
* Returns field value.
*/
static u64 make_first_field(const char *text, u64 index)
{
u64 n;
strncpy((char *)&n, text, 8);
return PS3_VENDOR_ID_NONE + (n >> 32) + index;
}
/**
* make_field - Make subsequent fields of a repository node name.
* @text: Text portion of the field. Use "" for 'don't care'.
* @index: Numeric index portion of the field. Use zero for 'don't care'.
*
* Returns field value.
*/
static u64 make_field(const char *text, u64 index)
{
u64 n;
strncpy((char *)&n, text, 8);
return n + index;
}
/**
* read_node - Read a repository node from raw fields.
* @n1: First field of node name.
* @n2: Second field of node name. Use zero for 'don't care'.
* @n3: Third field of node name. Use zero for 'don't care'.
* @n4: Fourth field of node name. Use zero for 'don't care'.
* @v1: First repository value (high word).
* @v2: Second repository value (low word). Optional parameter, use zero
* for 'don't care'.
*/
static int read_node(unsigned int lpar_id, u64 n1, u64 n2, u64 n3, u64 n4,
u64 *_v1, u64 *_v2)
{
int result;
u64 v1;
u64 v2;
if (lpar_id == PS3_LPAR_ID_CURRENT) {
u64 id;
lv1_get_logical_partition_id(&id);
lpar_id = id;
}
result = lv1_read_repository_node(lpar_id, n1, n2, n3, n4, &v1,
&v2);
if (result) {
pr_warn("%s:%d: lv1_read_repository_node failed: %s\n",
__func__, __LINE__, ps3_result(result));
dump_node_name(lpar_id, n1, n2, n3, n4);
return -ENOENT;
}
dump_node(lpar_id, n1, n2, n3, n4, v1, v2);
if (_v1)
*_v1 = v1;
if (_v2)
*_v2 = v2;
if (v1 && !_v1)
pr_devel("%s:%d: warning: discarding non-zero v1: %016llx\n",
__func__, __LINE__, v1);
if (v2 && !_v2)
pr_devel("%s:%d: warning: discarding non-zero v2: %016llx\n",
__func__, __LINE__, v2);
return 0;
}
int ps3_repository_read_bus_str(unsigned int bus_index, const char *bus_str,
u64 *value)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field(bus_str, 0),
0, 0,
value, NULL);
}
int ps3_repository_read_bus_id(unsigned int bus_index, u64 *bus_id)
{
int result;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("id", 0),
0, 0,
bus_id, NULL);
return result;
}
int ps3_repository_read_bus_type(unsigned int bus_index,
enum ps3_bus_type *bus_type)
{
int result;
u64 v1 = 0;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("type", 0),
0, 0,
&v1, NULL);
*bus_type = v1;
return result;
}
int ps3_repository_read_bus_num_dev(unsigned int bus_index,
unsigned int *num_dev)
{
int result;
u64 v1 = 0;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("num_dev", 0),
0, 0,
&v1, NULL);
*num_dev = v1;
return result;
}
int ps3_repository_read_dev_str(unsigned int bus_index,
unsigned int dev_index, const char *dev_str, u64 *value)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field(dev_str, 0),
0,
value, NULL);
}
int ps3_repository_read_dev_id(unsigned int bus_index, unsigned int dev_index,
u64 *dev_id)
{
int result;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("id", 0),
0,
dev_id, NULL);
return result;
}
int ps3_repository_read_dev_type(unsigned int bus_index,
unsigned int dev_index, enum ps3_dev_type *dev_type)
{
int result;
u64 v1 = 0;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("type", 0),
0,
&v1, NULL);
*dev_type = v1;
return result;
}
int ps3_repository_read_dev_intr(unsigned int bus_index,
unsigned int dev_index, unsigned int intr_index,
enum ps3_interrupt_type *intr_type, unsigned int *interrupt_id)
{
int result;
u64 v1 = 0;
u64 v2 = 0;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("intr", intr_index),
0,
&v1, &v2);
*intr_type = v1;
*interrupt_id = v2;
return result;
}
int ps3_repository_read_dev_reg_type(unsigned int bus_index,
unsigned int dev_index, unsigned int reg_index,
enum ps3_reg_type *reg_type)
{
int result;
u64 v1 = 0;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("reg", reg_index),
make_field("type", 0),
&v1, NULL);
*reg_type = v1;
return result;
}
int ps3_repository_read_dev_reg_addr(unsigned int bus_index,
unsigned int dev_index, unsigned int reg_index, u64 *bus_addr, u64 *len)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("reg", reg_index),
make_field("data", 0),
bus_addr, len);
}
int ps3_repository_read_dev_reg(unsigned int bus_index,
unsigned int dev_index, unsigned int reg_index,
enum ps3_reg_type *reg_type, u64 *bus_addr, u64 *len)
{
int result = ps3_repository_read_dev_reg_type(bus_index, dev_index,
reg_index, reg_type);
return result ? result
: ps3_repository_read_dev_reg_addr(bus_index, dev_index,
reg_index, bus_addr, len);
}
int ps3_repository_find_device(struct ps3_repository_device *repo)
{
int result;
struct ps3_repository_device tmp = *repo;
unsigned int num_dev;
BUG_ON(repo->bus_index > 10);
BUG_ON(repo->dev_index > 10);
result = ps3_repository_read_bus_num_dev(tmp.bus_index, &num_dev);
if (result) {
pr_devel("%s:%d read_bus_num_dev failed\n", __func__, __LINE__);
return result;
}
pr_devel("%s:%d: bus_type %u, bus_index %u, bus_id %llu, num_dev %u\n",
__func__, __LINE__, tmp.bus_type, tmp.bus_index, tmp.bus_id,
num_dev);
if (tmp.dev_index >= num_dev) {
pr_devel("%s:%d: no device found\n", __func__, __LINE__);
return -ENODEV;
}
result = ps3_repository_read_dev_type(tmp.bus_index, tmp.dev_index,
&tmp.dev_type);
if (result) {
pr_devel("%s:%d read_dev_type failed\n", __func__, __LINE__);
return result;
}
result = ps3_repository_read_dev_id(tmp.bus_index, tmp.dev_index,
&tmp.dev_id);
if (result) {
pr_devel("%s:%d ps3_repository_read_dev_id failed\n", __func__,
__LINE__);
return result;
}
pr_devel("%s:%d: found: dev_type %u, dev_index %u, dev_id %llu\n",
__func__, __LINE__, tmp.dev_type, tmp.dev_index, tmp.dev_id);
*repo = tmp;
return 0;
}
int ps3_repository_find_device_by_id(struct ps3_repository_device *repo,
u64 bus_id, u64 dev_id)
{
int result = -ENODEV;
struct ps3_repository_device tmp;
unsigned int num_dev;
pr_devel(" -> %s:%u: find device by id %llu:%llu\n", __func__, __LINE__,
bus_id, dev_id);
for (tmp.bus_index = 0; tmp.bus_index < 10; tmp.bus_index++) {
result = ps3_repository_read_bus_id(tmp.bus_index,
&tmp.bus_id);
if (result) {
pr_devel("%s:%u read_bus_id(%u) failed\n", __func__,
__LINE__, tmp.bus_index);
return result;
}
if (tmp.bus_id == bus_id)
goto found_bus;
pr_devel("%s:%u: skip, bus_id %llu\n", __func__, __LINE__,
tmp.bus_id);
}
pr_devel(" <- %s:%u: bus not found\n", __func__, __LINE__);
return result;
found_bus:
result = ps3_repository_read_bus_type(tmp.bus_index, &tmp.bus_type);
if (result) {
pr_devel("%s:%u read_bus_type(%u) failed\n", __func__,
__LINE__, tmp.bus_index);
return result;
}
result = ps3_repository_read_bus_num_dev(tmp.bus_index, &num_dev);
if (result) {
pr_devel("%s:%u read_bus_num_dev failed\n", __func__,
__LINE__);
return result;
}
for (tmp.dev_index = 0; tmp.dev_index < num_dev; tmp.dev_index++) {
result = ps3_repository_read_dev_id(tmp.bus_index,
tmp.dev_index,
&tmp.dev_id);
if (result) {
pr_devel("%s:%u read_dev_id(%u:%u) failed\n", __func__,
__LINE__, tmp.bus_index, tmp.dev_index);
return result;
}
if (tmp.dev_id == dev_id)
goto found_dev;
pr_devel("%s:%u: skip, dev_id %llu\n", __func__, __LINE__,
tmp.dev_id);
}
pr_devel(" <- %s:%u: dev not found\n", __func__, __LINE__);
return result;
found_dev:
result = ps3_repository_read_dev_type(tmp.bus_index, tmp.dev_index,
&tmp.dev_type);
if (result) {
pr_devel("%s:%u read_dev_type failed\n", __func__, __LINE__);
return result;
}
pr_devel(" <- %s:%u: found: type (%u:%u) index (%u:%u) id (%llu:%llu)\n",
__func__, __LINE__, tmp.bus_type, tmp.dev_type, tmp.bus_index,
tmp.dev_index, tmp.bus_id, tmp.dev_id);
*repo = tmp;
return 0;
}
int ps3_repository_find_devices(enum ps3_bus_type bus_type,
int (*callback)(const struct ps3_repository_device *repo))
{
int result = 0;
struct ps3_repository_device repo;
pr_devel(" -> %s:%d: find bus_type %u\n", __func__, __LINE__, bus_type);
repo.bus_type = bus_type;
result = ps3_repository_find_bus(repo.bus_type, 0, &repo.bus_index);
if (result) {
pr_devel(" <- %s:%u: bus not found\n", __func__, __LINE__);
return result;
}
result = ps3_repository_read_bus_id(repo.bus_index, &repo.bus_id);
if (result) {
pr_devel("%s:%d read_bus_id(%u) failed\n", __func__, __LINE__,
repo.bus_index);
return result;
}
for (repo.dev_index = 0; ; repo.dev_index++) {
result = ps3_repository_find_device(&repo);
if (result == -ENODEV) {
result = 0;
break;
} else if (result)
break;
result = callback(&repo);
if (result) {
pr_devel("%s:%d: abort at callback\n", __func__,
__LINE__);
break;
}
}
pr_devel(" <- %s:%d\n", __func__, __LINE__);
return result;
}
int ps3_repository_find_bus(enum ps3_bus_type bus_type, unsigned int from,
unsigned int *bus_index)
{
unsigned int i;
enum ps3_bus_type type;
int error;
for (i = from; i < 10; i++) {
error = ps3_repository_read_bus_type(i, &type);
if (error) {
pr_devel("%s:%d read_bus_type failed\n",
__func__, __LINE__);
*bus_index = UINT_MAX;
return error;
}
if (type == bus_type) {
*bus_index = i;
return 0;
}
}
*bus_index = UINT_MAX;
return -ENODEV;
}
int ps3_repository_find_interrupt(const struct ps3_repository_device *repo,
enum ps3_interrupt_type intr_type, unsigned int *interrupt_id)
{
int result = 0;
unsigned int res_index;
pr_devel("%s:%d: find intr_type %u\n", __func__, __LINE__, intr_type);
*interrupt_id = UINT_MAX;
for (res_index = 0; res_index < 10; res_index++) {
enum ps3_interrupt_type t;
unsigned int id;
result = ps3_repository_read_dev_intr(repo->bus_index,
repo->dev_index, res_index, &t, &id);
if (result) {
pr_devel("%s:%d read_dev_intr failed\n",
__func__, __LINE__);
return result;
}
if (t == intr_type) {
*interrupt_id = id;
break;
}
}
if (res_index == 10)
return -ENODEV;
pr_devel("%s:%d: found intr_type %u at res_index %u\n",
__func__, __LINE__, intr_type, res_index);
return result;
}
int ps3_repository_find_reg(const struct ps3_repository_device *repo,
enum ps3_reg_type reg_type, u64 *bus_addr, u64 *len)
{
int result = 0;
unsigned int res_index;
pr_devel("%s:%d: find reg_type %u\n", __func__, __LINE__, reg_type);
*bus_addr = *len = 0;
for (res_index = 0; res_index < 10; res_index++) {
enum ps3_reg_type t;
u64 a;
u64 l;
result = ps3_repository_read_dev_reg(repo->bus_index,
repo->dev_index, res_index, &t, &a, &l);
if (result) {
pr_devel("%s:%d read_dev_reg failed\n",
__func__, __LINE__);
return result;
}
if (t == reg_type) {
*bus_addr = a;
*len = l;
break;
}
}
if (res_index == 10)
return -ENODEV;
pr_devel("%s:%d: found reg_type %u at res_index %u\n",
__func__, __LINE__, reg_type, res_index);
return result;
}
int ps3_repository_read_stor_dev_port(unsigned int bus_index,
unsigned int dev_index, u64 *port)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("port", 0),
0, port, NULL);
}
int ps3_repository_read_stor_dev_blk_size(unsigned int bus_index,
unsigned int dev_index, u64 *blk_size)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("blk_size", 0),
0, blk_size, NULL);
}
int ps3_repository_read_stor_dev_num_blocks(unsigned int bus_index,
unsigned int dev_index, u64 *num_blocks)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("n_blocks", 0),
0, num_blocks, NULL);
}
int ps3_repository_read_stor_dev_num_regions(unsigned int bus_index,
unsigned int dev_index, unsigned int *num_regions)
{
int result;
u64 v1 = 0;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("n_regs", 0),
0, &v1, NULL);
*num_regions = v1;
return result;
}
int ps3_repository_read_stor_dev_region_id(unsigned int bus_index,
unsigned int dev_index, unsigned int region_index,
unsigned int *region_id)
{
int result;
u64 v1 = 0;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("region", region_index),
make_field("id", 0),
&v1, NULL);
*region_id = v1;
return result;
}
int ps3_repository_read_stor_dev_region_size(unsigned int bus_index,
unsigned int dev_index, unsigned int region_index, u64 *region_size)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("region", region_index),
make_field("size", 0),
region_size, NULL);
}
int ps3_repository_read_stor_dev_region_start(unsigned int bus_index,
unsigned int dev_index, unsigned int region_index, u64 *region_start)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("region", region_index),
make_field("start", 0),
region_start, NULL);
}
int ps3_repository_read_stor_dev_info(unsigned int bus_index,
unsigned int dev_index, u64 *port, u64 *blk_size,
u64 *num_blocks, unsigned int *num_regions)
{
int result;
result = ps3_repository_read_stor_dev_port(bus_index, dev_index, port);
if (result)
return result;
result = ps3_repository_read_stor_dev_blk_size(bus_index, dev_index,
blk_size);
if (result)
return result;
result = ps3_repository_read_stor_dev_num_blocks(bus_index, dev_index,
num_blocks);
if (result)
return result;
result = ps3_repository_read_stor_dev_num_regions(bus_index, dev_index,
num_regions);
return result;
}
int ps3_repository_read_stor_dev_region(unsigned int bus_index,
unsigned int dev_index, unsigned int region_index,
unsigned int *region_id, u64 *region_start, u64 *region_size)
{
int result;
result = ps3_repository_read_stor_dev_region_id(bus_index, dev_index,
region_index, region_id);
if (result)
return result;
result = ps3_repository_read_stor_dev_region_start(bus_index, dev_index,
region_index, region_start);
if (result)
return result;
result = ps3_repository_read_stor_dev_region_size(bus_index, dev_index,
region_index, region_size);
return result;
}
/**
* ps3_repository_read_num_pu - Number of logical PU processors for this lpar.
*/
int ps3_repository_read_num_pu(u64 *num_pu)
{
*num_pu = 0;
return read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("pun", 0),
0, 0,
num_pu, NULL);
}
/**
* ps3_repository_read_pu_id - Read the logical PU id.
* @pu_index: Zero based index.
* @pu_id: The logical PU id.
*/
int ps3_repository_read_pu_id(unsigned int pu_index, u64 *pu_id)
{
return read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("pu", pu_index),
0, 0,
pu_id, NULL);
}
int ps3_repository_read_rm_size(unsigned int ppe_id, u64 *rm_size)
{
return read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("pu", 0),
ppe_id,
make_field("rm_size", 0),
rm_size, NULL);
}
int ps3_repository_read_region_total(u64 *region_total)
{
return read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("rgntotal", 0),
0, 0,
region_total, NULL);
}
/**
* ps3_repository_read_mm_info - Read mm info for single pu system.
* @rm_base: Real mode memory base address.
* @rm_size: Real mode memory size.
* @region_total: Maximum memory region size.
*/
int ps3_repository_read_mm_info(u64 *rm_base, u64 *rm_size, u64 *region_total)
{
int result;
u64 ppe_id;
lv1_get_logical_ppe_id(&ppe_id);
*rm_base = 0;
result = ps3_repository_read_rm_size(ppe_id, rm_size);
return result ? result
: ps3_repository_read_region_total(region_total);
}
/**
* ps3_repository_read_highmem_region_count - Read the number of highmem regions
*
* Bootloaders must arrange the repository nodes such that regions are indexed
* with a region_index from 0 to region_count-1.
*/
int ps3_repository_read_highmem_region_count(unsigned int *region_count)
{
int result;
u64 v1 = 0;
result = read_node(PS3_LPAR_ID_CURRENT,
make_first_field("highmem", 0),
make_field("region", 0),
make_field("count", 0),
0,
&v1, NULL);
*region_count = v1;
return result;
}
int ps3_repository_read_highmem_base(unsigned int region_index,
u64 *highmem_base)
{
return read_node(PS3_LPAR_ID_CURRENT,
make_first_field("highmem", 0),
make_field("region", region_index),
make_field("base", 0),
0,
highmem_base, NULL);
}
int ps3_repository_read_highmem_size(unsigned int region_index,
u64 *highmem_size)
{
return read_node(PS3_LPAR_ID_CURRENT,
make_first_field("highmem", 0),
make_field("region", region_index),
make_field("size", 0),
0,
highmem_size, NULL);
}
/**
* ps3_repository_read_highmem_info - Read high memory region info
* @region_index: Region index, {0,..,region_count-1}.
* @highmem_base: High memory base address.
* @highmem_size: High memory size.
*
* Bootloaders that preallocate highmem regions must place the
* region info into the repository at these well known nodes.
*/
int ps3_repository_read_highmem_info(unsigned int region_index,
u64 *highmem_base, u64 *highmem_size)
{
int result;
*highmem_base = 0;
result = ps3_repository_read_highmem_base(region_index, highmem_base);
return result ? result
: ps3_repository_read_highmem_size(region_index, highmem_size);
}
/**
* ps3_repository_read_num_spu_reserved - Number of physical spus reserved.
* @num_spu: Number of physical spus.
*/
int ps3_repository_read_num_spu_reserved(unsigned int *num_spu_reserved)
{
int result;
u64 v1 = 0;
result = read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("spun", 0),
0, 0,
&v1, NULL);
*num_spu_reserved = v1;
return result;
}
/**
* ps3_repository_read_num_spu_resource_id - Number of spu resource reservations.
* @num_resource_id: Number of spu resource ids.
*/
int ps3_repository_read_num_spu_resource_id(unsigned int *num_resource_id)
{
int result;
u64 v1 = 0;
result = read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("spursvn", 0),
0, 0,
&v1, NULL);
*num_resource_id = v1;
return result;
}
/**
* ps3_repository_read_spu_resource_id - spu resource reservation id value.
* @res_index: Resource reservation index.
* @resource_type: Resource reservation type.
* @resource_id: Resource reservation id.
*/
int ps3_repository_read_spu_resource_id(unsigned int res_index,
enum ps3_spu_resource_type *resource_type, unsigned int *resource_id)
{
int result;
u64 v1 = 0;
u64 v2 = 0;
result = read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("spursv", 0),
res_index,
0,
&v1, &v2);
*resource_type = v1;
*resource_id = v2;
return result;
}
static int ps3_repository_read_boot_dat_address(u64 *address)
{
return read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("boot_dat", 0),
make_field("address", 0),
0,
address, NULL);
}
int ps3_repository_read_boot_dat_size(unsigned int *size)
{
int result;
u64 v1 = 0;
result = read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("boot_dat", 0),
make_field("size", 0),
0,
&v1, NULL);
*size = v1;
return result;
}
int ps3_repository_read_vuart_av_port(unsigned int *port)
{
int result;
u64 v1 = 0;
result = read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("vir_uart", 0),
make_field("port", 0),
make_field("avset", 0),
&v1, NULL);
*port = v1;
return result;
}
int ps3_repository_read_vuart_sysmgr_port(unsigned int *port)
{
int result;
u64 v1 = 0;
result = read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("vir_uart", 0),
make_field("port", 0),
make_field("sysmgr", 0),
&v1, NULL);
*port = v1;
return result;
}
/**
* ps3_repository_read_boot_dat_info - Get address and size of cell_ext_os_area.
* address: lpar address of cell_ext_os_area
* @size: size of cell_ext_os_area
*/
int ps3_repository_read_boot_dat_info(u64 *lpar_addr, unsigned int *size)
{
int result;
*size = 0;
result = ps3_repository_read_boot_dat_address(lpar_addr);
return result ? result
: ps3_repository_read_boot_dat_size(size);
}
/**
* ps3_repository_read_num_be - Number of physical BE processors in the system.
*/
int ps3_repository_read_num_be(unsigned int *num_be)
{
int result;
u64 v1 = 0;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("ben", 0),
0,
0,
0,
&v1, NULL);
*num_be = v1;
return result;
}
/**
* ps3_repository_read_be_node_id - Read the physical BE processor node id.
* @be_index: Zero based index.
* @node_id: The BE processor node id.
*/
int ps3_repository_read_be_node_id(unsigned int be_index, u64 *node_id)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("be", be_index),
0,
0,
0,
node_id, NULL);
}
/**
* ps3_repository_read_be_id - Read the physical BE processor id.
* @node_id: The BE processor node id.
* @be_id: The BE processor id.
*/
int ps3_repository_read_be_id(u64 node_id, u64 *be_id)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("be", 0),
node_id,
0,
0,
be_id, NULL);
}
int ps3_repository_read_tb_freq(u64 node_id, u64 *tb_freq)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("be", 0),
node_id,
make_field("clock", 0),
0,
tb_freq, NULL);
}
int ps3_repository_read_be_tb_freq(unsigned int be_index, u64 *tb_freq)
{
int result;
u64 node_id;
*tb_freq = 0;
result = ps3_repository_read_be_node_id(be_index, &node_id);
return result ? result
: ps3_repository_read_tb_freq(node_id, tb_freq);
}
int ps3_repository_read_lpm_privileges(unsigned int be_index, u64 *lpar,
u64 *rights)
{
int result;
u64 node_id;
*lpar = 0;
*rights = 0;
result = ps3_repository_read_be_node_id(be_index, &node_id);
return result ? result
: read_node(PS3_LPAR_ID_PME,
make_first_field("be", 0),
node_id,
make_field("lpm", 0),
make_field("priv", 0),
lpar, rights);
}
#if defined(CONFIG_PS3_REPOSITORY_WRITE)
static int create_node(u64 n1, u64 n2, u64 n3, u64 n4, u64 v1, u64 v2)
{
int result;
dump_node(0, n1, n2, n3, n4, v1, v2);
result = lv1_create_repository_node(n1, n2, n3, n4, v1, v2);
if (result) {
pr_devel("%s:%d: lv1_create_repository_node failed: %s\n",
__func__, __LINE__, ps3_result(result));
return -ENOENT;
}
return 0;
}
static int delete_node(u64 n1, u64 n2, u64 n3, u64 n4)
{
int result;
dump_node(0, n1, n2, n3, n4, 0, 0);
result = lv1_delete_repository_node(n1, n2, n3, n4);
if (result) {
pr_devel("%s:%d: lv1_delete_repository_node failed: %s\n",
__func__, __LINE__, ps3_result(result));
return -ENOENT;
}
return 0;
}
static int write_node(u64 n1, u64 n2, u64 n3, u64 n4, u64 v1, u64 v2)
{
int result;
result = create_node(n1, n2, n3, n4, v1, v2);
if (!result)
return 0;
result = lv1_write_repository_node(n1, n2, n3, n4, v1, v2);
if (result) {
pr_devel("%s:%d: lv1_write_repository_node failed: %s\n",
__func__, __LINE__, ps3_result(result));
return -ENOENT;
}
return 0;
}
int ps3_repository_write_highmem_region_count(unsigned int region_count)
{
int result;
u64 v1 = (u64)region_count;
result = write_node(
make_first_field("highmem", 0),
make_field("region", 0),
make_field("count", 0),
0,
v1, 0);
return result;
}
int ps3_repository_write_highmem_base(unsigned int region_index,
u64 highmem_base)
{
return write_node(
make_first_field("highmem", 0),
make_field("region", region_index),
make_field("base", 0),
0,
highmem_base, 0);
}
int ps3_repository_write_highmem_size(unsigned int region_index,
u64 highmem_size)
{
return write_node(
make_first_field("highmem", 0),
make_field("region", region_index),
make_field("size", 0),
0,
highmem_size, 0);
}
int ps3_repository_write_highmem_info(unsigned int region_index,
u64 highmem_base, u64 highmem_size)
{
int result;
result = ps3_repository_write_highmem_base(region_index, highmem_base);
return result ? result
: ps3_repository_write_highmem_size(region_index, highmem_size);
}
static int ps3_repository_delete_highmem_base(unsigned int region_index)
{
return delete_node(
make_first_field("highmem", 0),
make_field("region", region_index),
make_field("base", 0),
0);
}
static int ps3_repository_delete_highmem_size(unsigned int region_index)
{
return delete_node(
make_first_field("highmem", 0),
make_field("region", region_index),
make_field("size", 0),
0);
}
int ps3_repository_delete_highmem_info(unsigned int region_index)
{
int result;
result = ps3_repository_delete_highmem_base(region_index);
result += ps3_repository_delete_highmem_size(region_index);
return result ? -1 : 0;
}
#endif /* defined(CONFIG_PS3_WRITE_REPOSITORY) */
#if defined(DEBUG)
int ps3_repository_dump_resource_info(const struct ps3_repository_device *repo)
{
int result = 0;
unsigned int res_index;
pr_devel(" -> %s:%d: (%u:%u)\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
for (res_index = 0; res_index < 10; res_index++) {
enum ps3_interrupt_type intr_type;
unsigned int interrupt_id;
result = ps3_repository_read_dev_intr(repo->bus_index,
repo->dev_index, res_index, &intr_type, &interrupt_id);
if (result) {
if (result != LV1_NO_ENTRY)
pr_devel("%s:%d ps3_repository_read_dev_intr"
" (%u:%u) failed\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
break;
}
pr_devel("%s:%d (%u:%u) intr_type %u, interrupt_id %u\n",
__func__, __LINE__, repo->bus_index, repo->dev_index,
intr_type, interrupt_id);
}
for (res_index = 0; res_index < 10; res_index++) {
enum ps3_reg_type reg_type;
u64 bus_addr;
u64 len;
result = ps3_repository_read_dev_reg(repo->bus_index,
repo->dev_index, res_index, ®_type, &bus_addr, &len);
if (result) {
if (result != LV1_NO_ENTRY)
pr_devel("%s:%d ps3_repository_read_dev_reg"
" (%u:%u) failed\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
break;
}
pr_devel("%s:%d (%u:%u) reg_type %u, bus_addr %llxh, len %llxh\n",
__func__, __LINE__, repo->bus_index, repo->dev_index,
reg_type, bus_addr, len);
}
pr_devel(" <- %s:%d\n", __func__, __LINE__);
return result;
}
static int dump_stor_dev_info(struct ps3_repository_device *repo)
{
int result = 0;
unsigned int num_regions, region_index;
u64 port, blk_size, num_blocks;
pr_devel(" -> %s:%d: (%u:%u)\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
result = ps3_repository_read_stor_dev_info(repo->bus_index,
repo->dev_index, &port, &blk_size, &num_blocks, &num_regions);
if (result) {
pr_devel("%s:%d ps3_repository_read_stor_dev_info"
" (%u:%u) failed\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
goto out;
}
pr_devel("%s:%d (%u:%u): port %llu, blk_size %llu, num_blocks "
"%llu, num_regions %u\n",
__func__, __LINE__, repo->bus_index, repo->dev_index,
port, blk_size, num_blocks, num_regions);
for (region_index = 0; region_index < num_regions; region_index++) {
unsigned int region_id;
u64 region_start, region_size;
result = ps3_repository_read_stor_dev_region(repo->bus_index,
repo->dev_index, region_index, ®ion_id,
®ion_start, ®ion_size);
if (result) {
pr_devel("%s:%d ps3_repository_read_stor_dev_region"
" (%u:%u) failed\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
break;
}
pr_devel("%s:%d (%u:%u) region_id %u, start %lxh, size %lxh\n",
__func__, __LINE__, repo->bus_index, repo->dev_index,
region_id, (unsigned long)region_start,
(unsigned long)region_size);
}
out:
pr_devel(" <- %s:%d\n", __func__, __LINE__);
return result;
}
static int dump_device_info(struct ps3_repository_device *repo,
unsigned int num_dev)
{
int result = 0;
pr_devel(" -> %s:%d: bus_%u\n", __func__, __LINE__, repo->bus_index);
for (repo->dev_index = 0; repo->dev_index < num_dev;
repo->dev_index++) {
result = ps3_repository_read_dev_type(repo->bus_index,
repo->dev_index, &repo->dev_type);
if (result) {
pr_devel("%s:%d ps3_repository_read_dev_type"
" (%u:%u) failed\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
break;
}
result = ps3_repository_read_dev_id(repo->bus_index,
repo->dev_index, &repo->dev_id);
if (result) {
pr_devel("%s:%d ps3_repository_read_dev_id"
" (%u:%u) failed\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
continue;
}
pr_devel("%s:%d (%u:%u): dev_type %u, dev_id %lu\n", __func__,
__LINE__, repo->bus_index, repo->dev_index,
repo->dev_type, (unsigned long)repo->dev_id);
ps3_repository_dump_resource_info(repo);
if (repo->bus_type == PS3_BUS_TYPE_STORAGE)
dump_stor_dev_info(repo);
}
pr_devel(" <- %s:%d\n", __func__, __LINE__);
return result;
}
int ps3_repository_dump_bus_info(void)
{
int result = 0;
struct ps3_repository_device repo;
pr_devel(" -> %s:%d\n", __func__, __LINE__);
memset(&repo, 0, sizeof(repo));
for (repo.bus_index = 0; repo.bus_index < 10; repo.bus_index++) {
unsigned int num_dev;
result = ps3_repository_read_bus_type(repo.bus_index,
&repo.bus_type);
if (result) {
pr_devel("%s:%d read_bus_type(%u) failed\n",
__func__, __LINE__, repo.bus_index);
break;
}
result = ps3_repository_read_bus_id(repo.bus_index,
&repo.bus_id);
if (result) {
pr_devel("%s:%d read_bus_id(%u) failed\n",
__func__, __LINE__, repo.bus_index);
continue;
}
if (repo.bus_index != repo.bus_id)
pr_devel("%s:%d bus_index != bus_id\n",
__func__, __LINE__);
result = ps3_repository_read_bus_num_dev(repo.bus_index,
&num_dev);
if (result) {
pr_devel("%s:%d read_bus_num_dev(%u) failed\n",
__func__, __LINE__, repo.bus_index);
continue;
}
pr_devel("%s:%d bus_%u: bus_type %u, bus_id %lu, num_dev %u\n",
__func__, __LINE__, repo.bus_index, repo.bus_type,
(unsigned long)repo.bus_id, num_dev);
dump_device_info(&repo, num_dev);
}
pr_devel(" <- %s:%d\n", __func__, __LINE__);
return result;
}
#endif /* defined(DEBUG) */
| gpl-2.0 |
armani-dev/android_kernel_xiaomi_armani | kernel/power/snapshot.c | 4457 | 61894 | /*
* linux/kernel/power/snapshot.c
*
* This file provides system snapshot/restore functionality for swsusp.
*
* Copyright (C) 1998-2005 Pavel Machek <pavel@ucw.cz>
* Copyright (C) 2006 Rafael J. Wysocki <rjw@sisk.pl>
*
* This file is released under the GPLv2.
*
*/
#include <linux/version.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/suspend.h>
#include <linux/delay.h>
#include <linux/bitops.h>
#include <linux/spinlock.h>
#include <linux/kernel.h>
#include <linux/pm.h>
#include <linux/device.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/syscalls.h>
#include <linux/console.h>
#include <linux/highmem.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <asm/mmu_context.h>
#include <asm/pgtable.h>
#include <asm/tlbflush.h>
#include <asm/io.h>
#include "power.h"
static int swsusp_page_is_free(struct page *);
static void swsusp_set_page_forbidden(struct page *);
static void swsusp_unset_page_forbidden(struct page *);
/*
* Number of bytes to reserve for memory allocations made by device drivers
* from their ->freeze() and ->freeze_noirq() callbacks so that they don't
* cause image creation to fail (tunable via /sys/power/reserved_size).
*/
unsigned long reserved_size;
void __init hibernate_reserved_size_init(void)
{
reserved_size = SPARE_PAGES * PAGE_SIZE;
}
/*
* Preferred image size in bytes (tunable via /sys/power/image_size).
* When it is set to N, swsusp will do its best to ensure the image
* size will not exceed N bytes, but if that is impossible, it will
* try to create the smallest image possible.
*/
unsigned long image_size;
void __init hibernate_image_size_init(void)
{
image_size = ((totalram_pages * 2) / 5) * PAGE_SIZE;
}
/* List of PBEs needed for restoring the pages that were allocated before
* the suspend and included in the suspend image, but have also been
* allocated by the "resume" kernel, so their contents cannot be written
* directly to their "original" page frames.
*/
struct pbe *restore_pblist;
/* Pointer to an auxiliary buffer (1 page) */
static void *buffer;
/**
* @safe_needed - on resume, for storing the PBE list and the image,
* we can only use memory pages that do not conflict with the pages
* used before suspend. The unsafe pages have PageNosaveFree set
* and we count them using unsafe_pages.
*
* Each allocated image page is marked as PageNosave and PageNosaveFree
* so that swsusp_free() can release it.
*/
#define PG_ANY 0
#define PG_SAFE 1
#define PG_UNSAFE_CLEAR 1
#define PG_UNSAFE_KEEP 0
static unsigned int allocated_unsafe_pages;
static void *get_image_page(gfp_t gfp_mask, int safe_needed)
{
void *res;
res = (void *)get_zeroed_page(gfp_mask);
if (safe_needed)
while (res && swsusp_page_is_free(virt_to_page(res))) {
/* The page is unsafe, mark it for swsusp_free() */
swsusp_set_page_forbidden(virt_to_page(res));
allocated_unsafe_pages++;
res = (void *)get_zeroed_page(gfp_mask);
}
if (res) {
swsusp_set_page_forbidden(virt_to_page(res));
swsusp_set_page_free(virt_to_page(res));
}
return res;
}
unsigned long get_safe_page(gfp_t gfp_mask)
{
return (unsigned long)get_image_page(gfp_mask, PG_SAFE);
}
static struct page *alloc_image_page(gfp_t gfp_mask)
{
struct page *page;
page = alloc_page(gfp_mask);
if (page) {
swsusp_set_page_forbidden(page);
swsusp_set_page_free(page);
}
return page;
}
/**
* free_image_page - free page represented by @addr, allocated with
* get_image_page (page flags set by it must be cleared)
*/
static inline void free_image_page(void *addr, int clear_nosave_free)
{
struct page *page;
BUG_ON(!virt_addr_valid(addr));
page = virt_to_page(addr);
swsusp_unset_page_forbidden(page);
if (clear_nosave_free)
swsusp_unset_page_free(page);
__free_page(page);
}
/* struct linked_page is used to build chains of pages */
#define LINKED_PAGE_DATA_SIZE (PAGE_SIZE - sizeof(void *))
struct linked_page {
struct linked_page *next;
char data[LINKED_PAGE_DATA_SIZE];
} __attribute__((packed));
static inline void
free_list_of_pages(struct linked_page *list, int clear_page_nosave)
{
while (list) {
struct linked_page *lp = list->next;
free_image_page(list, clear_page_nosave);
list = lp;
}
}
/**
* struct chain_allocator is used for allocating small objects out of
* a linked list of pages called 'the chain'.
*
* The chain grows each time when there is no room for a new object in
* the current page. The allocated objects cannot be freed individually.
* It is only possible to free them all at once, by freeing the entire
* chain.
*
* NOTE: The chain allocator may be inefficient if the allocated objects
* are not much smaller than PAGE_SIZE.
*/
struct chain_allocator {
struct linked_page *chain; /* the chain */
unsigned int used_space; /* total size of objects allocated out
* of the current page
*/
gfp_t gfp_mask; /* mask for allocating pages */
int safe_needed; /* if set, only "safe" pages are allocated */
};
static void
chain_init(struct chain_allocator *ca, gfp_t gfp_mask, int safe_needed)
{
ca->chain = NULL;
ca->used_space = LINKED_PAGE_DATA_SIZE;
ca->gfp_mask = gfp_mask;
ca->safe_needed = safe_needed;
}
static void *chain_alloc(struct chain_allocator *ca, unsigned int size)
{
void *ret;
if (LINKED_PAGE_DATA_SIZE - ca->used_space < size) {
struct linked_page *lp;
lp = get_image_page(ca->gfp_mask, ca->safe_needed);
if (!lp)
return NULL;
lp->next = ca->chain;
ca->chain = lp;
ca->used_space = 0;
}
ret = ca->chain->data + ca->used_space;
ca->used_space += size;
return ret;
}
/**
* Data types related to memory bitmaps.
*
* Memory bitmap is a structure consiting of many linked lists of
* objects. The main list's elements are of type struct zone_bitmap
* and each of them corresonds to one zone. For each zone bitmap
* object there is a list of objects of type struct bm_block that
* represent each blocks of bitmap in which information is stored.
*
* struct memory_bitmap contains a pointer to the main list of zone
* bitmap objects, a struct bm_position used for browsing the bitmap,
* and a pointer to the list of pages used for allocating all of the
* zone bitmap objects and bitmap block objects.
*
* NOTE: It has to be possible to lay out the bitmap in memory
* using only allocations of order 0. Additionally, the bitmap is
* designed to work with arbitrary number of zones (this is over the
* top for now, but let's avoid making unnecessary assumptions ;-).
*
* struct zone_bitmap contains a pointer to a list of bitmap block
* objects and a pointer to the bitmap block object that has been
* most recently used for setting bits. Additionally, it contains the
* pfns that correspond to the start and end of the represented zone.
*
* struct bm_block contains a pointer to the memory page in which
* information is stored (in the form of a block of bitmap)
* It also contains the pfns that correspond to the start and end of
* the represented memory area.
*/
#define BM_END_OF_MAP (~0UL)
#define BM_BITS_PER_BLOCK (PAGE_SIZE * BITS_PER_BYTE)
struct bm_block {
struct list_head hook; /* hook into a list of bitmap blocks */
unsigned long start_pfn; /* pfn represented by the first bit */
unsigned long end_pfn; /* pfn represented by the last bit plus 1 */
unsigned long *data; /* bitmap representing pages */
};
static inline unsigned long bm_block_bits(struct bm_block *bb)
{
return bb->end_pfn - bb->start_pfn;
}
/* strcut bm_position is used for browsing memory bitmaps */
struct bm_position {
struct bm_block *block;
int bit;
};
struct memory_bitmap {
struct list_head blocks; /* list of bitmap blocks */
struct linked_page *p_list; /* list of pages used to store zone
* bitmap objects and bitmap block
* objects
*/
struct bm_position cur; /* most recently used bit position */
};
/* Functions that operate on memory bitmaps */
static void memory_bm_position_reset(struct memory_bitmap *bm)
{
bm->cur.block = list_entry(bm->blocks.next, struct bm_block, hook);
bm->cur.bit = 0;
}
static void memory_bm_free(struct memory_bitmap *bm, int clear_nosave_free);
/**
* create_bm_block_list - create a list of block bitmap objects
* @pages - number of pages to track
* @list - list to put the allocated blocks into
* @ca - chain allocator to be used for allocating memory
*/
static int create_bm_block_list(unsigned long pages,
struct list_head *list,
struct chain_allocator *ca)
{
unsigned int nr_blocks = DIV_ROUND_UP(pages, BM_BITS_PER_BLOCK);
while (nr_blocks-- > 0) {
struct bm_block *bb;
bb = chain_alloc(ca, sizeof(struct bm_block));
if (!bb)
return -ENOMEM;
list_add(&bb->hook, list);
}
return 0;
}
struct mem_extent {
struct list_head hook;
unsigned long start;
unsigned long end;
};
/**
* free_mem_extents - free a list of memory extents
* @list - list of extents to empty
*/
static void free_mem_extents(struct list_head *list)
{
struct mem_extent *ext, *aux;
list_for_each_entry_safe(ext, aux, list, hook) {
list_del(&ext->hook);
kfree(ext);
}
}
/**
* create_mem_extents - create a list of memory extents representing
* contiguous ranges of PFNs
* @list - list to put the extents into
* @gfp_mask - mask to use for memory allocations
*/
static int create_mem_extents(struct list_head *list, gfp_t gfp_mask)
{
struct zone *zone;
INIT_LIST_HEAD(list);
for_each_populated_zone(zone) {
unsigned long zone_start, zone_end;
struct mem_extent *ext, *cur, *aux;
zone_start = zone->zone_start_pfn;
zone_end = zone->zone_start_pfn + zone->spanned_pages;
list_for_each_entry(ext, list, hook)
if (zone_start <= ext->end)
break;
if (&ext->hook == list || zone_end < ext->start) {
/* New extent is necessary */
struct mem_extent *new_ext;
new_ext = kzalloc(sizeof(struct mem_extent), gfp_mask);
if (!new_ext) {
free_mem_extents(list);
return -ENOMEM;
}
new_ext->start = zone_start;
new_ext->end = zone_end;
list_add_tail(&new_ext->hook, &ext->hook);
continue;
}
/* Merge this zone's range of PFNs with the existing one */
if (zone_start < ext->start)
ext->start = zone_start;
if (zone_end > ext->end)
ext->end = zone_end;
/* More merging may be possible */
cur = ext;
list_for_each_entry_safe_continue(cur, aux, list, hook) {
if (zone_end < cur->start)
break;
if (zone_end < cur->end)
ext->end = cur->end;
list_del(&cur->hook);
kfree(cur);
}
}
return 0;
}
/**
* memory_bm_create - allocate memory for a memory bitmap
*/
static int
memory_bm_create(struct memory_bitmap *bm, gfp_t gfp_mask, int safe_needed)
{
struct chain_allocator ca;
struct list_head mem_extents;
struct mem_extent *ext;
int error;
chain_init(&ca, gfp_mask, safe_needed);
INIT_LIST_HEAD(&bm->blocks);
error = create_mem_extents(&mem_extents, gfp_mask);
if (error)
return error;
list_for_each_entry(ext, &mem_extents, hook) {
struct bm_block *bb;
unsigned long pfn = ext->start;
unsigned long pages = ext->end - ext->start;
bb = list_entry(bm->blocks.prev, struct bm_block, hook);
error = create_bm_block_list(pages, bm->blocks.prev, &ca);
if (error)
goto Error;
list_for_each_entry_continue(bb, &bm->blocks, hook) {
bb->data = get_image_page(gfp_mask, safe_needed);
if (!bb->data) {
error = -ENOMEM;
goto Error;
}
bb->start_pfn = pfn;
if (pages >= BM_BITS_PER_BLOCK) {
pfn += BM_BITS_PER_BLOCK;
pages -= BM_BITS_PER_BLOCK;
} else {
/* This is executed only once in the loop */
pfn += pages;
}
bb->end_pfn = pfn;
}
}
bm->p_list = ca.chain;
memory_bm_position_reset(bm);
Exit:
free_mem_extents(&mem_extents);
return error;
Error:
bm->p_list = ca.chain;
memory_bm_free(bm, PG_UNSAFE_CLEAR);
goto Exit;
}
/**
* memory_bm_free - free memory occupied by the memory bitmap @bm
*/
static void memory_bm_free(struct memory_bitmap *bm, int clear_nosave_free)
{
struct bm_block *bb;
list_for_each_entry(bb, &bm->blocks, hook)
if (bb->data)
free_image_page(bb->data, clear_nosave_free);
free_list_of_pages(bm->p_list, clear_nosave_free);
INIT_LIST_HEAD(&bm->blocks);
}
/**
* memory_bm_find_bit - find the bit in the bitmap @bm that corresponds
* to given pfn. The cur_zone_bm member of @bm and the cur_block member
* of @bm->cur_zone_bm are updated.
*/
static int memory_bm_find_bit(struct memory_bitmap *bm, unsigned long pfn,
void **addr, unsigned int *bit_nr)
{
struct bm_block *bb;
/*
* Check if the pfn corresponds to the current bitmap block and find
* the block where it fits if this is not the case.
*/
bb = bm->cur.block;
if (pfn < bb->start_pfn)
list_for_each_entry_continue_reverse(bb, &bm->blocks, hook)
if (pfn >= bb->start_pfn)
break;
if (pfn >= bb->end_pfn)
list_for_each_entry_continue(bb, &bm->blocks, hook)
if (pfn >= bb->start_pfn && pfn < bb->end_pfn)
break;
if (&bb->hook == &bm->blocks)
return -EFAULT;
/* The block has been found */
bm->cur.block = bb;
pfn -= bb->start_pfn;
bm->cur.bit = pfn + 1;
*bit_nr = pfn;
*addr = bb->data;
return 0;
}
static void memory_bm_set_bit(struct memory_bitmap *bm, unsigned long pfn)
{
void *addr;
unsigned int bit;
int error;
error = memory_bm_find_bit(bm, pfn, &addr, &bit);
BUG_ON(error);
set_bit(bit, addr);
}
static int mem_bm_set_bit_check(struct memory_bitmap *bm, unsigned long pfn)
{
void *addr;
unsigned int bit;
int error;
error = memory_bm_find_bit(bm, pfn, &addr, &bit);
if (!error)
set_bit(bit, addr);
return error;
}
static void memory_bm_clear_bit(struct memory_bitmap *bm, unsigned long pfn)
{
void *addr;
unsigned int bit;
int error;
error = memory_bm_find_bit(bm, pfn, &addr, &bit);
BUG_ON(error);
clear_bit(bit, addr);
}
static int memory_bm_test_bit(struct memory_bitmap *bm, unsigned long pfn)
{
void *addr;
unsigned int bit;
int error;
error = memory_bm_find_bit(bm, pfn, &addr, &bit);
BUG_ON(error);
return test_bit(bit, addr);
}
static bool memory_bm_pfn_present(struct memory_bitmap *bm, unsigned long pfn)
{
void *addr;
unsigned int bit;
return !memory_bm_find_bit(bm, pfn, &addr, &bit);
}
/**
* memory_bm_next_pfn - find the pfn that corresponds to the next set bit
* in the bitmap @bm. If the pfn cannot be found, BM_END_OF_MAP is
* returned.
*
* It is required to run memory_bm_position_reset() before the first call to
* this function.
*/
static unsigned long memory_bm_next_pfn(struct memory_bitmap *bm)
{
struct bm_block *bb;
int bit;
bb = bm->cur.block;
do {
bit = bm->cur.bit;
bit = find_next_bit(bb->data, bm_block_bits(bb), bit);
if (bit < bm_block_bits(bb))
goto Return_pfn;
bb = list_entry(bb->hook.next, struct bm_block, hook);
bm->cur.block = bb;
bm->cur.bit = 0;
} while (&bb->hook != &bm->blocks);
memory_bm_position_reset(bm);
return BM_END_OF_MAP;
Return_pfn:
bm->cur.bit = bit + 1;
return bb->start_pfn + bit;
}
/**
* This structure represents a range of page frames the contents of which
* should not be saved during the suspend.
*/
struct nosave_region {
struct list_head list;
unsigned long start_pfn;
unsigned long end_pfn;
};
static LIST_HEAD(nosave_regions);
/**
* register_nosave_region - register a range of page frames the contents
* of which should not be saved during the suspend (to be used in the early
* initialization code)
*/
void __init
__register_nosave_region(unsigned long start_pfn, unsigned long end_pfn,
int use_kmalloc)
{
struct nosave_region *region;
if (start_pfn >= end_pfn)
return;
if (!list_empty(&nosave_regions)) {
/* Try to extend the previous region (they should be sorted) */
region = list_entry(nosave_regions.prev,
struct nosave_region, list);
if (region->end_pfn == start_pfn) {
region->end_pfn = end_pfn;
goto Report;
}
}
if (use_kmalloc) {
/* during init, this shouldn't fail */
region = kmalloc(sizeof(struct nosave_region), GFP_KERNEL);
BUG_ON(!region);
} else
/* This allocation cannot fail */
region = alloc_bootmem(sizeof(struct nosave_region));
region->start_pfn = start_pfn;
region->end_pfn = end_pfn;
list_add_tail(®ion->list, &nosave_regions);
Report:
printk(KERN_INFO "PM: Registered nosave memory: %016lx - %016lx\n",
start_pfn << PAGE_SHIFT, end_pfn << PAGE_SHIFT);
}
/*
* Set bits in this map correspond to the page frames the contents of which
* should not be saved during the suspend.
*/
static struct memory_bitmap *forbidden_pages_map;
/* Set bits in this map correspond to free page frames. */
static struct memory_bitmap *free_pages_map;
/*
* Each page frame allocated for creating the image is marked by setting the
* corresponding bits in forbidden_pages_map and free_pages_map simultaneously
*/
void swsusp_set_page_free(struct page *page)
{
if (free_pages_map)
memory_bm_set_bit(free_pages_map, page_to_pfn(page));
}
static int swsusp_page_is_free(struct page *page)
{
return free_pages_map ?
memory_bm_test_bit(free_pages_map, page_to_pfn(page)) : 0;
}
void swsusp_unset_page_free(struct page *page)
{
if (free_pages_map)
memory_bm_clear_bit(free_pages_map, page_to_pfn(page));
}
static void swsusp_set_page_forbidden(struct page *page)
{
if (forbidden_pages_map)
memory_bm_set_bit(forbidden_pages_map, page_to_pfn(page));
}
int swsusp_page_is_forbidden(struct page *page)
{
return forbidden_pages_map ?
memory_bm_test_bit(forbidden_pages_map, page_to_pfn(page)) : 0;
}
static void swsusp_unset_page_forbidden(struct page *page)
{
if (forbidden_pages_map)
memory_bm_clear_bit(forbidden_pages_map, page_to_pfn(page));
}
/**
* mark_nosave_pages - set bits corresponding to the page frames the
* contents of which should not be saved in a given bitmap.
*/
static void mark_nosave_pages(struct memory_bitmap *bm)
{
struct nosave_region *region;
if (list_empty(&nosave_regions))
return;
list_for_each_entry(region, &nosave_regions, list) {
unsigned long pfn;
pr_debug("PM: Marking nosave pages: [mem %#010llx-%#010llx]\n",
(unsigned long long) region->start_pfn << PAGE_SHIFT,
((unsigned long long) region->end_pfn << PAGE_SHIFT)
- 1);
for (pfn = region->start_pfn; pfn < region->end_pfn; pfn++)
if (pfn_valid(pfn)) {
/*
* It is safe to ignore the result of
* mem_bm_set_bit_check() here, since we won't
* touch the PFNs for which the error is
* returned anyway.
*/
mem_bm_set_bit_check(bm, pfn);
}
}
}
/**
* create_basic_memory_bitmaps - create bitmaps needed for marking page
* frames that should not be saved and free page frames. The pointers
* forbidden_pages_map and free_pages_map are only modified if everything
* goes well, because we don't want the bits to be used before both bitmaps
* are set up.
*/
int create_basic_memory_bitmaps(void)
{
struct memory_bitmap *bm1, *bm2;
int error = 0;
BUG_ON(forbidden_pages_map || free_pages_map);
bm1 = kzalloc(sizeof(struct memory_bitmap), GFP_KERNEL);
if (!bm1)
return -ENOMEM;
error = memory_bm_create(bm1, GFP_KERNEL, PG_ANY);
if (error)
goto Free_first_object;
bm2 = kzalloc(sizeof(struct memory_bitmap), GFP_KERNEL);
if (!bm2)
goto Free_first_bitmap;
error = memory_bm_create(bm2, GFP_KERNEL, PG_ANY);
if (error)
goto Free_second_object;
forbidden_pages_map = bm1;
free_pages_map = bm2;
mark_nosave_pages(forbidden_pages_map);
pr_debug("PM: Basic memory bitmaps created\n");
return 0;
Free_second_object:
kfree(bm2);
Free_first_bitmap:
memory_bm_free(bm1, PG_UNSAFE_CLEAR);
Free_first_object:
kfree(bm1);
return -ENOMEM;
}
/**
* free_basic_memory_bitmaps - free memory bitmaps allocated by
* create_basic_memory_bitmaps(). The auxiliary pointers are necessary
* so that the bitmaps themselves are not referred to while they are being
* freed.
*/
void free_basic_memory_bitmaps(void)
{
struct memory_bitmap *bm1, *bm2;
BUG_ON(!(forbidden_pages_map && free_pages_map));
bm1 = forbidden_pages_map;
bm2 = free_pages_map;
forbidden_pages_map = NULL;
free_pages_map = NULL;
memory_bm_free(bm1, PG_UNSAFE_CLEAR);
kfree(bm1);
memory_bm_free(bm2, PG_UNSAFE_CLEAR);
kfree(bm2);
pr_debug("PM: Basic memory bitmaps freed\n");
}
/**
* snapshot_additional_pages - estimate the number of additional pages
* be needed for setting up the suspend image data structures for given
* zone (usually the returned value is greater than the exact number)
*/
unsigned int snapshot_additional_pages(struct zone *zone)
{
unsigned int res;
res = DIV_ROUND_UP(zone->spanned_pages, BM_BITS_PER_BLOCK);
res += DIV_ROUND_UP(res * sizeof(struct bm_block),
LINKED_PAGE_DATA_SIZE);
return 2 * res;
}
#ifdef CONFIG_HIGHMEM
/**
* count_free_highmem_pages - compute the total number of free highmem
* pages, system-wide.
*/
static unsigned int count_free_highmem_pages(void)
{
struct zone *zone;
unsigned int cnt = 0;
for_each_populated_zone(zone)
if (is_highmem(zone))
cnt += zone_page_state(zone, NR_FREE_PAGES);
return cnt;
}
/**
* saveable_highmem_page - Determine whether a highmem page should be
* included in the suspend image.
*
* We should save the page if it isn't Nosave or NosaveFree, or Reserved,
* and it isn't a part of a free chunk of pages.
*/
static struct page *saveable_highmem_page(struct zone *zone, unsigned long pfn)
{
struct page *page;
if (!pfn_valid(pfn))
return NULL;
page = pfn_to_page(pfn);
if (page_zone(page) != zone)
return NULL;
BUG_ON(!PageHighMem(page));
if (swsusp_page_is_forbidden(page) || swsusp_page_is_free(page) ||
PageReserved(page))
return NULL;
if (page_is_guard(page))
return NULL;
return page;
}
/**
* count_highmem_pages - compute the total number of saveable highmem
* pages.
*/
static unsigned int count_highmem_pages(void)
{
struct zone *zone;
unsigned int n = 0;
for_each_populated_zone(zone) {
unsigned long pfn, max_zone_pfn;
if (!is_highmem(zone))
continue;
mark_free_pages(zone);
max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
if (saveable_highmem_page(zone, pfn))
n++;
}
return n;
}
#else
static inline void *saveable_highmem_page(struct zone *z, unsigned long p)
{
return NULL;
}
#endif /* CONFIG_HIGHMEM */
/**
* saveable_page - Determine whether a non-highmem page should be included
* in the suspend image.
*
* We should save the page if it isn't Nosave, and is not in the range
* of pages statically defined as 'unsaveable', and it isn't a part of
* a free chunk of pages.
*/
static struct page *saveable_page(struct zone *zone, unsigned long pfn)
{
struct page *page;
if (!pfn_valid(pfn))
return NULL;
page = pfn_to_page(pfn);
if (page_zone(page) != zone)
return NULL;
BUG_ON(PageHighMem(page));
if (swsusp_page_is_forbidden(page) || swsusp_page_is_free(page))
return NULL;
if (PageReserved(page)
&& (!kernel_page_present(page) || pfn_is_nosave(pfn)))
return NULL;
if (page_is_guard(page))
return NULL;
return page;
}
/**
* count_data_pages - compute the total number of saveable non-highmem
* pages.
*/
static unsigned int count_data_pages(void)
{
struct zone *zone;
unsigned long pfn, max_zone_pfn;
unsigned int n = 0;
for_each_populated_zone(zone) {
if (is_highmem(zone))
continue;
mark_free_pages(zone);
max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
if (saveable_page(zone, pfn))
n++;
}
return n;
}
/* This is needed, because copy_page and memcpy are not usable for copying
* task structs.
*/
static inline void do_copy_page(long *dst, long *src)
{
int n;
for (n = PAGE_SIZE / sizeof(long); n; n--)
*dst++ = *src++;
}
/**
* safe_copy_page - check if the page we are going to copy is marked as
* present in the kernel page tables (this always is the case if
* CONFIG_DEBUG_PAGEALLOC is not set and in that case
* kernel_page_present() always returns 'true').
*/
static void safe_copy_page(void *dst, struct page *s_page)
{
if (kernel_page_present(s_page)) {
do_copy_page(dst, page_address(s_page));
} else {
kernel_map_pages(s_page, 1, 1);
do_copy_page(dst, page_address(s_page));
kernel_map_pages(s_page, 1, 0);
}
}
#ifdef CONFIG_HIGHMEM
static inline struct page *
page_is_saveable(struct zone *zone, unsigned long pfn)
{
return is_highmem(zone) ?
saveable_highmem_page(zone, pfn) : saveable_page(zone, pfn);
}
static void copy_data_page(unsigned long dst_pfn, unsigned long src_pfn)
{
struct page *s_page, *d_page;
void *src, *dst;
s_page = pfn_to_page(src_pfn);
d_page = pfn_to_page(dst_pfn);
if (PageHighMem(s_page)) {
src = kmap_atomic(s_page);
dst = kmap_atomic(d_page);
do_copy_page(dst, src);
kunmap_atomic(dst);
kunmap_atomic(src);
} else {
if (PageHighMem(d_page)) {
/* Page pointed to by src may contain some kernel
* data modified by kmap_atomic()
*/
safe_copy_page(buffer, s_page);
dst = kmap_atomic(d_page);
copy_page(dst, buffer);
kunmap_atomic(dst);
} else {
safe_copy_page(page_address(d_page), s_page);
}
}
}
#else
#define page_is_saveable(zone, pfn) saveable_page(zone, pfn)
static inline void copy_data_page(unsigned long dst_pfn, unsigned long src_pfn)
{
safe_copy_page(page_address(pfn_to_page(dst_pfn)),
pfn_to_page(src_pfn));
}
#endif /* CONFIG_HIGHMEM */
static void
copy_data_pages(struct memory_bitmap *copy_bm, struct memory_bitmap *orig_bm)
{
struct zone *zone;
unsigned long pfn;
for_each_populated_zone(zone) {
unsigned long max_zone_pfn;
mark_free_pages(zone);
max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
if (page_is_saveable(zone, pfn))
memory_bm_set_bit(orig_bm, pfn);
}
memory_bm_position_reset(orig_bm);
memory_bm_position_reset(copy_bm);
for(;;) {
pfn = memory_bm_next_pfn(orig_bm);
if (unlikely(pfn == BM_END_OF_MAP))
break;
copy_data_page(memory_bm_next_pfn(copy_bm), pfn);
}
}
/* Total number of image pages */
static unsigned int nr_copy_pages;
/* Number of pages needed for saving the original pfns of the image pages */
static unsigned int nr_meta_pages;
/*
* Numbers of normal and highmem page frames allocated for hibernation image
* before suspending devices.
*/
unsigned int alloc_normal, alloc_highmem;
/*
* Memory bitmap used for marking saveable pages (during hibernation) or
* hibernation image pages (during restore)
*/
static struct memory_bitmap orig_bm;
/*
* Memory bitmap used during hibernation for marking allocated page frames that
* will contain copies of saveable pages. During restore it is initially used
* for marking hibernation image pages, but then the set bits from it are
* duplicated in @orig_bm and it is released. On highmem systems it is next
* used for marking "safe" highmem pages, but it has to be reinitialized for
* this purpose.
*/
static struct memory_bitmap copy_bm;
/**
* swsusp_free - free pages allocated for the suspend.
*
* Suspend pages are alocated before the atomic copy is made, so we
* need to release them after the resume.
*/
void swsusp_free(void)
{
struct zone *zone;
unsigned long pfn, max_zone_pfn;
for_each_populated_zone(zone) {
max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
if (pfn_valid(pfn)) {
struct page *page = pfn_to_page(pfn);
if (swsusp_page_is_forbidden(page) &&
swsusp_page_is_free(page)) {
swsusp_unset_page_forbidden(page);
swsusp_unset_page_free(page);
__free_page(page);
}
}
}
nr_copy_pages = 0;
nr_meta_pages = 0;
restore_pblist = NULL;
buffer = NULL;
alloc_normal = 0;
alloc_highmem = 0;
}
/* Helper functions used for the shrinking of memory. */
#define GFP_IMAGE (GFP_KERNEL | __GFP_NOWARN)
/**
* preallocate_image_pages - Allocate a number of pages for hibernation image
* @nr_pages: Number of page frames to allocate.
* @mask: GFP flags to use for the allocation.
*
* Return value: Number of page frames actually allocated
*/
static unsigned long preallocate_image_pages(unsigned long nr_pages, gfp_t mask)
{
unsigned long nr_alloc = 0;
while (nr_pages > 0) {
struct page *page;
page = alloc_image_page(mask);
if (!page)
break;
memory_bm_set_bit(©_bm, page_to_pfn(page));
if (PageHighMem(page))
alloc_highmem++;
else
alloc_normal++;
nr_pages--;
nr_alloc++;
}
return nr_alloc;
}
static unsigned long preallocate_image_memory(unsigned long nr_pages,
unsigned long avail_normal)
{
unsigned long alloc;
if (avail_normal <= alloc_normal)
return 0;
alloc = avail_normal - alloc_normal;
if (nr_pages < alloc)
alloc = nr_pages;
return preallocate_image_pages(alloc, GFP_IMAGE);
}
#ifdef CONFIG_HIGHMEM
static unsigned long preallocate_image_highmem(unsigned long nr_pages)
{
return preallocate_image_pages(nr_pages, GFP_IMAGE | __GFP_HIGHMEM);
}
/**
* __fraction - Compute (an approximation of) x * (multiplier / base)
*/
static unsigned long __fraction(u64 x, u64 multiplier, u64 base)
{
x *= multiplier;
do_div(x, base);
return (unsigned long)x;
}
static unsigned long preallocate_highmem_fraction(unsigned long nr_pages,
unsigned long highmem,
unsigned long total)
{
unsigned long alloc = __fraction(nr_pages, highmem, total);
return preallocate_image_pages(alloc, GFP_IMAGE | __GFP_HIGHMEM);
}
#else /* CONFIG_HIGHMEM */
static inline unsigned long preallocate_image_highmem(unsigned long nr_pages)
{
return 0;
}
static inline unsigned long preallocate_highmem_fraction(unsigned long nr_pages,
unsigned long highmem,
unsigned long total)
{
return 0;
}
#endif /* CONFIG_HIGHMEM */
/**
* free_unnecessary_pages - Release preallocated pages not needed for the image
*/
static void free_unnecessary_pages(void)
{
unsigned long save, to_free_normal, to_free_highmem;
save = count_data_pages();
if (alloc_normal >= save) {
to_free_normal = alloc_normal - save;
save = 0;
} else {
to_free_normal = 0;
save -= alloc_normal;
}
save += count_highmem_pages();
if (alloc_highmem >= save) {
to_free_highmem = alloc_highmem - save;
} else {
to_free_highmem = 0;
save -= alloc_highmem;
if (to_free_normal > save)
to_free_normal -= save;
else
to_free_normal = 0;
}
memory_bm_position_reset(©_bm);
while (to_free_normal > 0 || to_free_highmem > 0) {
unsigned long pfn = memory_bm_next_pfn(©_bm);
struct page *page = pfn_to_page(pfn);
if (PageHighMem(page)) {
if (!to_free_highmem)
continue;
to_free_highmem--;
alloc_highmem--;
} else {
if (!to_free_normal)
continue;
to_free_normal--;
alloc_normal--;
}
memory_bm_clear_bit(©_bm, pfn);
swsusp_unset_page_forbidden(page);
swsusp_unset_page_free(page);
__free_page(page);
}
}
/**
* minimum_image_size - Estimate the minimum acceptable size of an image
* @saveable: Number of saveable pages in the system.
*
* We want to avoid attempting to free too much memory too hard, so estimate the
* minimum acceptable size of a hibernation image to use as the lower limit for
* preallocating memory.
*
* We assume that the minimum image size should be proportional to
*
* [number of saveable pages] - [number of pages that can be freed in theory]
*
* where the second term is the sum of (1) reclaimable slab pages, (2) active
* and (3) inactive anonymouns pages, (4) active and (5) inactive file pages,
* minus mapped file pages.
*/
static unsigned long minimum_image_size(unsigned long saveable)
{
unsigned long size;
size = global_page_state(NR_SLAB_RECLAIMABLE)
+ global_page_state(NR_ACTIVE_ANON)
+ global_page_state(NR_INACTIVE_ANON)
+ global_page_state(NR_ACTIVE_FILE)
+ global_page_state(NR_INACTIVE_FILE)
- global_page_state(NR_FILE_MAPPED);
return saveable <= size ? 0 : saveable - size;
}
/**
* hibernate_preallocate_memory - Preallocate memory for hibernation image
*
* To create a hibernation image it is necessary to make a copy of every page
* frame in use. We also need a number of page frames to be free during
* hibernation for allocations made while saving the image and for device
* drivers, in case they need to allocate memory from their hibernation
* callbacks (these two numbers are given by PAGES_FOR_IO (which is a rough
* estimate) and reserverd_size divided by PAGE_SIZE (which is tunable through
* /sys/power/reserved_size, respectively). To make this happen, we compute the
* total number of available page frames and allocate at least
*
* ([page frames total] + PAGES_FOR_IO + [metadata pages]) / 2
* + 2 * DIV_ROUND_UP(reserved_size, PAGE_SIZE)
*
* of them, which corresponds to the maximum size of a hibernation image.
*
* If image_size is set below the number following from the above formula,
* the preallocation of memory is continued until the total number of saveable
* pages in the system is below the requested image size or the minimum
* acceptable image size returned by minimum_image_size(), whichever is greater.
*/
int hibernate_preallocate_memory(void)
{
struct zone *zone;
unsigned long saveable, size, max_size, count, highmem, pages = 0;
unsigned long alloc, save_highmem, pages_highmem, avail_normal;
struct timeval start, stop;
int error;
printk(KERN_INFO "PM: Preallocating image memory... ");
do_gettimeofday(&start);
error = memory_bm_create(&orig_bm, GFP_IMAGE, PG_ANY);
if (error)
goto err_out;
error = memory_bm_create(©_bm, GFP_IMAGE, PG_ANY);
if (error)
goto err_out;
alloc_normal = 0;
alloc_highmem = 0;
/* Count the number of saveable data pages. */
save_highmem = count_highmem_pages();
saveable = count_data_pages();
/*
* Compute the total number of page frames we can use (count) and the
* number of pages needed for image metadata (size).
*/
count = saveable;
saveable += save_highmem;
highmem = save_highmem;
size = 0;
for_each_populated_zone(zone) {
size += snapshot_additional_pages(zone);
if (is_highmem(zone))
highmem += zone_page_state(zone, NR_FREE_PAGES);
else
count += zone_page_state(zone, NR_FREE_PAGES);
}
avail_normal = count;
count += highmem;
count -= totalreserve_pages;
/* Add number of pages required for page keys (s390 only). */
size += page_key_additional_pages(saveable);
/* Compute the maximum number of saveable pages to leave in memory. */
max_size = (count - (size + PAGES_FOR_IO)) / 2
- 2 * DIV_ROUND_UP(reserved_size, PAGE_SIZE);
/* Compute the desired number of image pages specified by image_size. */
size = DIV_ROUND_UP(image_size, PAGE_SIZE);
if (size > max_size)
size = max_size;
/*
* If the desired number of image pages is at least as large as the
* current number of saveable pages in memory, allocate page frames for
* the image and we're done.
*/
if (size >= saveable) {
pages = preallocate_image_highmem(save_highmem);
pages += preallocate_image_memory(saveable - pages, avail_normal);
goto out;
}
/* Estimate the minimum size of the image. */
pages = minimum_image_size(saveable);
/*
* To avoid excessive pressure on the normal zone, leave room in it to
* accommodate an image of the minimum size (unless it's already too
* small, in which case don't preallocate pages from it at all).
*/
if (avail_normal > pages)
avail_normal -= pages;
else
avail_normal = 0;
if (size < pages)
size = min_t(unsigned long, pages, max_size);
/*
* Let the memory management subsystem know that we're going to need a
* large number of page frames to allocate and make it free some memory.
* NOTE: If this is not done, performance will be hurt badly in some
* test cases.
*/
shrink_all_memory(saveable - size);
/*
* The number of saveable pages in memory was too high, so apply some
* pressure to decrease it. First, make room for the largest possible
* image and fail if that doesn't work. Next, try to decrease the size
* of the image as much as indicated by 'size' using allocations from
* highmem and non-highmem zones separately.
*/
pages_highmem = preallocate_image_highmem(highmem / 2);
alloc = (count - max_size) - pages_highmem;
pages = preallocate_image_memory(alloc, avail_normal);
if (pages < alloc) {
/* We have exhausted non-highmem pages, try highmem. */
alloc -= pages;
pages += pages_highmem;
pages_highmem = preallocate_image_highmem(alloc);
if (pages_highmem < alloc)
goto err_out;
pages += pages_highmem;
/*
* size is the desired number of saveable pages to leave in
* memory, so try to preallocate (all memory - size) pages.
*/
alloc = (count - pages) - size;
pages += preallocate_image_highmem(alloc);
} else {
/*
* There are approximately max_size saveable pages at this point
* and we want to reduce this number down to size.
*/
alloc = max_size - size;
size = preallocate_highmem_fraction(alloc, highmem, count);
pages_highmem += size;
alloc -= size;
size = preallocate_image_memory(alloc, avail_normal);
pages_highmem += preallocate_image_highmem(alloc - size);
pages += pages_highmem + size;
}
/*
* We only need as many page frames for the image as there are saveable
* pages in memory, but we have allocated more. Release the excessive
* ones now.
*/
free_unnecessary_pages();
out:
do_gettimeofday(&stop);
printk(KERN_CONT "done (allocated %lu pages)\n", pages);
swsusp_show_speed(&start, &stop, pages, "Allocated");
return 0;
err_out:
printk(KERN_CONT "\n");
swsusp_free();
return -ENOMEM;
}
#ifdef CONFIG_HIGHMEM
/**
* count_pages_for_highmem - compute the number of non-highmem pages
* that will be necessary for creating copies of highmem pages.
*/
static unsigned int count_pages_for_highmem(unsigned int nr_highmem)
{
unsigned int free_highmem = count_free_highmem_pages() + alloc_highmem;
if (free_highmem >= nr_highmem)
nr_highmem = 0;
else
nr_highmem -= free_highmem;
return nr_highmem;
}
#else
static unsigned int
count_pages_for_highmem(unsigned int nr_highmem) { return 0; }
#endif /* CONFIG_HIGHMEM */
/**
* enough_free_mem - Make sure we have enough free memory for the
* snapshot image.
*/
static int enough_free_mem(unsigned int nr_pages, unsigned int nr_highmem)
{
struct zone *zone;
unsigned int free = alloc_normal;
for_each_populated_zone(zone)
if (!is_highmem(zone))
free += zone_page_state(zone, NR_FREE_PAGES);
nr_pages += count_pages_for_highmem(nr_highmem);
pr_debug("PM: Normal pages needed: %u + %u, available pages: %u\n",
nr_pages, PAGES_FOR_IO, free);
return free > nr_pages + PAGES_FOR_IO;
}
#ifdef CONFIG_HIGHMEM
/**
* get_highmem_buffer - if there are some highmem pages in the suspend
* image, we may need the buffer to copy them and/or load their data.
*/
static inline int get_highmem_buffer(int safe_needed)
{
buffer = get_image_page(GFP_ATOMIC | __GFP_COLD, safe_needed);
return buffer ? 0 : -ENOMEM;
}
/**
* alloc_highmem_image_pages - allocate some highmem pages for the image.
* Try to allocate as many pages as needed, but if the number of free
* highmem pages is lesser than that, allocate them all.
*/
static inline unsigned int
alloc_highmem_pages(struct memory_bitmap *bm, unsigned int nr_highmem)
{
unsigned int to_alloc = count_free_highmem_pages();
if (to_alloc > nr_highmem)
to_alloc = nr_highmem;
nr_highmem -= to_alloc;
while (to_alloc-- > 0) {
struct page *page;
page = alloc_image_page(__GFP_HIGHMEM);
memory_bm_set_bit(bm, page_to_pfn(page));
}
return nr_highmem;
}
#else
static inline int get_highmem_buffer(int safe_needed) { return 0; }
static inline unsigned int
alloc_highmem_pages(struct memory_bitmap *bm, unsigned int n) { return 0; }
#endif /* CONFIG_HIGHMEM */
/**
* swsusp_alloc - allocate memory for the suspend image
*
* We first try to allocate as many highmem pages as there are
* saveable highmem pages in the system. If that fails, we allocate
* non-highmem pages for the copies of the remaining highmem ones.
*
* In this approach it is likely that the copies of highmem pages will
* also be located in the high memory, because of the way in which
* copy_data_pages() works.
*/
static int
swsusp_alloc(struct memory_bitmap *orig_bm, struct memory_bitmap *copy_bm,
unsigned int nr_pages, unsigned int nr_highmem)
{
if (nr_highmem > 0) {
if (get_highmem_buffer(PG_ANY))
goto err_out;
if (nr_highmem > alloc_highmem) {
nr_highmem -= alloc_highmem;
nr_pages += alloc_highmem_pages(copy_bm, nr_highmem);
}
}
if (nr_pages > alloc_normal) {
nr_pages -= alloc_normal;
while (nr_pages-- > 0) {
struct page *page;
page = alloc_image_page(GFP_ATOMIC | __GFP_COLD);
if (!page)
goto err_out;
memory_bm_set_bit(copy_bm, page_to_pfn(page));
}
}
return 0;
err_out:
swsusp_free();
return -ENOMEM;
}
asmlinkage int swsusp_save(void)
{
unsigned int nr_pages, nr_highmem;
printk(KERN_INFO "PM: Creating hibernation image:\n");
drain_local_pages(NULL);
nr_pages = count_data_pages();
nr_highmem = count_highmem_pages();
printk(KERN_INFO "PM: Need to copy %u pages\n", nr_pages + nr_highmem);
if (!enough_free_mem(nr_pages, nr_highmem)) {
printk(KERN_ERR "PM: Not enough free memory\n");
return -ENOMEM;
}
if (swsusp_alloc(&orig_bm, ©_bm, nr_pages, nr_highmem)) {
printk(KERN_ERR "PM: Memory allocation failed\n");
return -ENOMEM;
}
/* During allocating of suspend pagedir, new cold pages may appear.
* Kill them.
*/
drain_local_pages(NULL);
copy_data_pages(©_bm, &orig_bm);
/*
* End of critical section. From now on, we can write to memory,
* but we should not touch disk. This specially means we must _not_
* touch swap space! Except we must write out our image of course.
*/
nr_pages += nr_highmem;
nr_copy_pages = nr_pages;
nr_meta_pages = DIV_ROUND_UP(nr_pages * sizeof(long), PAGE_SIZE);
printk(KERN_INFO "PM: Hibernation image created (%d pages copied)\n",
nr_pages);
return 0;
}
#ifndef CONFIG_ARCH_HIBERNATION_HEADER
static int init_header_complete(struct swsusp_info *info)
{
memcpy(&info->uts, init_utsname(), sizeof(struct new_utsname));
info->version_code = LINUX_VERSION_CODE;
return 0;
}
static char *check_image_kernel(struct swsusp_info *info)
{
if (info->version_code != LINUX_VERSION_CODE)
return "kernel version";
if (strcmp(info->uts.sysname,init_utsname()->sysname))
return "system type";
if (strcmp(info->uts.release,init_utsname()->release))
return "kernel release";
if (strcmp(info->uts.version,init_utsname()->version))
return "version";
if (strcmp(info->uts.machine,init_utsname()->machine))
return "machine";
return NULL;
}
#endif /* CONFIG_ARCH_HIBERNATION_HEADER */
unsigned long snapshot_get_image_size(void)
{
return nr_copy_pages + nr_meta_pages + 1;
}
static int init_header(struct swsusp_info *info)
{
memset(info, 0, sizeof(struct swsusp_info));
info->num_physpages = num_physpages;
info->image_pages = nr_copy_pages;
info->pages = snapshot_get_image_size();
info->size = info->pages;
info->size <<= PAGE_SHIFT;
return init_header_complete(info);
}
/**
* pack_pfns - pfns corresponding to the set bits found in the bitmap @bm
* are stored in the array @buf[] (1 page at a time)
*/
static inline void
pack_pfns(unsigned long *buf, struct memory_bitmap *bm)
{
int j;
for (j = 0; j < PAGE_SIZE / sizeof(long); j++) {
buf[j] = memory_bm_next_pfn(bm);
if (unlikely(buf[j] == BM_END_OF_MAP))
break;
/* Save page key for data page (s390 only). */
page_key_read(buf + j);
}
}
/**
* snapshot_read_next - used for reading the system memory snapshot.
*
* On the first call to it @handle should point to a zeroed
* snapshot_handle structure. The structure gets updated and a pointer
* to it should be passed to this function every next time.
*
* On success the function returns a positive number. Then, the caller
* is allowed to read up to the returned number of bytes from the memory
* location computed by the data_of() macro.
*
* The function returns 0 to indicate the end of data stream condition,
* and a negative number is returned on error. In such cases the
* structure pointed to by @handle is not updated and should not be used
* any more.
*/
int snapshot_read_next(struct snapshot_handle *handle)
{
if (handle->cur > nr_meta_pages + nr_copy_pages)
return 0;
if (!buffer) {
/* This makes the buffer be freed by swsusp_free() */
buffer = get_image_page(GFP_ATOMIC, PG_ANY);
if (!buffer)
return -ENOMEM;
}
if (!handle->cur) {
int error;
error = init_header((struct swsusp_info *)buffer);
if (error)
return error;
handle->buffer = buffer;
memory_bm_position_reset(&orig_bm);
memory_bm_position_reset(©_bm);
} else if (handle->cur <= nr_meta_pages) {
clear_page(buffer);
pack_pfns(buffer, &orig_bm);
} else {
struct page *page;
page = pfn_to_page(memory_bm_next_pfn(©_bm));
if (PageHighMem(page)) {
/* Highmem pages are copied to the buffer,
* because we can't return with a kmapped
* highmem page (we may not be called again).
*/
void *kaddr;
kaddr = kmap_atomic(page);
copy_page(buffer, kaddr);
kunmap_atomic(kaddr);
handle->buffer = buffer;
} else {
handle->buffer = page_address(page);
}
}
handle->cur++;
return PAGE_SIZE;
}
/**
* mark_unsafe_pages - mark the pages that cannot be used for storing
* the image during resume, because they conflict with the pages that
* had been used before suspend
*/
static int mark_unsafe_pages(struct memory_bitmap *bm)
{
struct zone *zone;
unsigned long pfn, max_zone_pfn;
/* Clear page flags */
for_each_populated_zone(zone) {
max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
if (pfn_valid(pfn))
swsusp_unset_page_free(pfn_to_page(pfn));
}
/* Mark pages that correspond to the "original" pfns as "unsafe" */
memory_bm_position_reset(bm);
do {
pfn = memory_bm_next_pfn(bm);
if (likely(pfn != BM_END_OF_MAP)) {
if (likely(pfn_valid(pfn)))
swsusp_set_page_free(pfn_to_page(pfn));
else
return -EFAULT;
}
} while (pfn != BM_END_OF_MAP);
allocated_unsafe_pages = 0;
return 0;
}
static void
duplicate_memory_bitmap(struct memory_bitmap *dst, struct memory_bitmap *src)
{
unsigned long pfn;
memory_bm_position_reset(src);
pfn = memory_bm_next_pfn(src);
while (pfn != BM_END_OF_MAP) {
memory_bm_set_bit(dst, pfn);
pfn = memory_bm_next_pfn(src);
}
}
static int check_header(struct swsusp_info *info)
{
char *reason;
reason = check_image_kernel(info);
if (!reason && info->num_physpages != num_physpages)
reason = "memory size";
if (reason) {
printk(KERN_ERR "PM: Image mismatch: %s\n", reason);
return -EPERM;
}
return 0;
}
/**
* load header - check the image header and copy data from it
*/
static int
load_header(struct swsusp_info *info)
{
int error;
restore_pblist = NULL;
error = check_header(info);
if (!error) {
nr_copy_pages = info->image_pages;
nr_meta_pages = info->pages - info->image_pages - 1;
}
return error;
}
/**
* unpack_orig_pfns - for each element of @buf[] (1 page at a time) set
* the corresponding bit in the memory bitmap @bm
*/
static int unpack_orig_pfns(unsigned long *buf, struct memory_bitmap *bm)
{
int j;
for (j = 0; j < PAGE_SIZE / sizeof(long); j++) {
if (unlikely(buf[j] == BM_END_OF_MAP))
break;
/* Extract and buffer page key for data page (s390 only). */
page_key_memorize(buf + j);
if (memory_bm_pfn_present(bm, buf[j]))
memory_bm_set_bit(bm, buf[j]);
else
return -EFAULT;
}
return 0;
}
/* List of "safe" pages that may be used to store data loaded from the suspend
* image
*/
static struct linked_page *safe_pages_list;
#ifdef CONFIG_HIGHMEM
/* struct highmem_pbe is used for creating the list of highmem pages that
* should be restored atomically during the resume from disk, because the page
* frames they have occupied before the suspend are in use.
*/
struct highmem_pbe {
struct page *copy_page; /* data is here now */
struct page *orig_page; /* data was here before the suspend */
struct highmem_pbe *next;
};
/* List of highmem PBEs needed for restoring the highmem pages that were
* allocated before the suspend and included in the suspend image, but have
* also been allocated by the "resume" kernel, so their contents cannot be
* written directly to their "original" page frames.
*/
static struct highmem_pbe *highmem_pblist;
/**
* count_highmem_image_pages - compute the number of highmem pages in the
* suspend image. The bits in the memory bitmap @bm that correspond to the
* image pages are assumed to be set.
*/
static unsigned int count_highmem_image_pages(struct memory_bitmap *bm)
{
unsigned long pfn;
unsigned int cnt = 0;
memory_bm_position_reset(bm);
pfn = memory_bm_next_pfn(bm);
while (pfn != BM_END_OF_MAP) {
if (PageHighMem(pfn_to_page(pfn)))
cnt++;
pfn = memory_bm_next_pfn(bm);
}
return cnt;
}
/**
* prepare_highmem_image - try to allocate as many highmem pages as
* there are highmem image pages (@nr_highmem_p points to the variable
* containing the number of highmem image pages). The pages that are
* "safe" (ie. will not be overwritten when the suspend image is
* restored) have the corresponding bits set in @bm (it must be
* unitialized).
*
* NOTE: This function should not be called if there are no highmem
* image pages.
*/
static unsigned int safe_highmem_pages;
static struct memory_bitmap *safe_highmem_bm;
static int
prepare_highmem_image(struct memory_bitmap *bm, unsigned int *nr_highmem_p)
{
unsigned int to_alloc;
if (memory_bm_create(bm, GFP_ATOMIC, PG_SAFE))
return -ENOMEM;
if (get_highmem_buffer(PG_SAFE))
return -ENOMEM;
to_alloc = count_free_highmem_pages();
if (to_alloc > *nr_highmem_p)
to_alloc = *nr_highmem_p;
else
*nr_highmem_p = to_alloc;
safe_highmem_pages = 0;
while (to_alloc-- > 0) {
struct page *page;
page = alloc_page(__GFP_HIGHMEM);
if (!swsusp_page_is_free(page)) {
/* The page is "safe", set its bit the bitmap */
memory_bm_set_bit(bm, page_to_pfn(page));
safe_highmem_pages++;
}
/* Mark the page as allocated */
swsusp_set_page_forbidden(page);
swsusp_set_page_free(page);
}
memory_bm_position_reset(bm);
safe_highmem_bm = bm;
return 0;
}
/**
* get_highmem_page_buffer - for given highmem image page find the buffer
* that suspend_write_next() should set for its caller to write to.
*
* If the page is to be saved to its "original" page frame or a copy of
* the page is to be made in the highmem, @buffer is returned. Otherwise,
* the copy of the page is to be made in normal memory, so the address of
* the copy is returned.
*
* If @buffer is returned, the caller of suspend_write_next() will write
* the page's contents to @buffer, so they will have to be copied to the
* right location on the next call to suspend_write_next() and it is done
* with the help of copy_last_highmem_page(). For this purpose, if
* @buffer is returned, @last_highmem page is set to the page to which
* the data will have to be copied from @buffer.
*/
static struct page *last_highmem_page;
static void *
get_highmem_page_buffer(struct page *page, struct chain_allocator *ca)
{
struct highmem_pbe *pbe;
void *kaddr;
if (swsusp_page_is_forbidden(page) && swsusp_page_is_free(page)) {
/* We have allocated the "original" page frame and we can
* use it directly to store the loaded page.
*/
last_highmem_page = page;
return buffer;
}
/* The "original" page frame has not been allocated and we have to
* use a "safe" page frame to store the loaded page.
*/
pbe = chain_alloc(ca, sizeof(struct highmem_pbe));
if (!pbe) {
swsusp_free();
return ERR_PTR(-ENOMEM);
}
pbe->orig_page = page;
if (safe_highmem_pages > 0) {
struct page *tmp;
/* Copy of the page will be stored in high memory */
kaddr = buffer;
tmp = pfn_to_page(memory_bm_next_pfn(safe_highmem_bm));
safe_highmem_pages--;
last_highmem_page = tmp;
pbe->copy_page = tmp;
} else {
/* Copy of the page will be stored in normal memory */
kaddr = safe_pages_list;
safe_pages_list = safe_pages_list->next;
pbe->copy_page = virt_to_page(kaddr);
}
pbe->next = highmem_pblist;
highmem_pblist = pbe;
return kaddr;
}
/**
* copy_last_highmem_page - copy the contents of a highmem image from
* @buffer, where the caller of snapshot_write_next() has place them,
* to the right location represented by @last_highmem_page .
*/
static void copy_last_highmem_page(void)
{
if (last_highmem_page) {
void *dst;
dst = kmap_atomic(last_highmem_page);
copy_page(dst, buffer);
kunmap_atomic(dst);
last_highmem_page = NULL;
}
}
static inline int last_highmem_page_copied(void)
{
return !last_highmem_page;
}
static inline void free_highmem_data(void)
{
if (safe_highmem_bm)
memory_bm_free(safe_highmem_bm, PG_UNSAFE_CLEAR);
if (buffer)
free_image_page(buffer, PG_UNSAFE_CLEAR);
}
#else
static inline int get_safe_write_buffer(void) { return 0; }
static unsigned int
count_highmem_image_pages(struct memory_bitmap *bm) { return 0; }
static inline int
prepare_highmem_image(struct memory_bitmap *bm, unsigned int *nr_highmem_p)
{
return 0;
}
static inline void *
get_highmem_page_buffer(struct page *page, struct chain_allocator *ca)
{
return ERR_PTR(-EINVAL);
}
static inline void copy_last_highmem_page(void) {}
static inline int last_highmem_page_copied(void) { return 1; }
static inline void free_highmem_data(void) {}
#endif /* CONFIG_HIGHMEM */
/**
* prepare_image - use the memory bitmap @bm to mark the pages that will
* be overwritten in the process of restoring the system memory state
* from the suspend image ("unsafe" pages) and allocate memory for the
* image.
*
* The idea is to allocate a new memory bitmap first and then allocate
* as many pages as needed for the image data, but not to assign these
* pages to specific tasks initially. Instead, we just mark them as
* allocated and create a lists of "safe" pages that will be used
* later. On systems with high memory a list of "safe" highmem pages is
* also created.
*/
#define PBES_PER_LINKED_PAGE (LINKED_PAGE_DATA_SIZE / sizeof(struct pbe))
static int
prepare_image(struct memory_bitmap *new_bm, struct memory_bitmap *bm)
{
unsigned int nr_pages, nr_highmem;
struct linked_page *sp_list, *lp;
int error;
/* If there is no highmem, the buffer will not be necessary */
free_image_page(buffer, PG_UNSAFE_CLEAR);
buffer = NULL;
nr_highmem = count_highmem_image_pages(bm);
error = mark_unsafe_pages(bm);
if (error)
goto Free;
error = memory_bm_create(new_bm, GFP_ATOMIC, PG_SAFE);
if (error)
goto Free;
duplicate_memory_bitmap(new_bm, bm);
memory_bm_free(bm, PG_UNSAFE_KEEP);
if (nr_highmem > 0) {
error = prepare_highmem_image(bm, &nr_highmem);
if (error)
goto Free;
}
/* Reserve some safe pages for potential later use.
*
* NOTE: This way we make sure there will be enough safe pages for the
* chain_alloc() in get_buffer(). It is a bit wasteful, but
* nr_copy_pages cannot be greater than 50% of the memory anyway.
*/
sp_list = NULL;
/* nr_copy_pages cannot be lesser than allocated_unsafe_pages */
nr_pages = nr_copy_pages - nr_highmem - allocated_unsafe_pages;
nr_pages = DIV_ROUND_UP(nr_pages, PBES_PER_LINKED_PAGE);
while (nr_pages > 0) {
lp = get_image_page(GFP_ATOMIC, PG_SAFE);
if (!lp) {
error = -ENOMEM;
goto Free;
}
lp->next = sp_list;
sp_list = lp;
nr_pages--;
}
/* Preallocate memory for the image */
safe_pages_list = NULL;
nr_pages = nr_copy_pages - nr_highmem - allocated_unsafe_pages;
while (nr_pages > 0) {
lp = (struct linked_page *)get_zeroed_page(GFP_ATOMIC);
if (!lp) {
error = -ENOMEM;
goto Free;
}
if (!swsusp_page_is_free(virt_to_page(lp))) {
/* The page is "safe", add it to the list */
lp->next = safe_pages_list;
safe_pages_list = lp;
}
/* Mark the page as allocated */
swsusp_set_page_forbidden(virt_to_page(lp));
swsusp_set_page_free(virt_to_page(lp));
nr_pages--;
}
/* Free the reserved safe pages so that chain_alloc() can use them */
while (sp_list) {
lp = sp_list->next;
free_image_page(sp_list, PG_UNSAFE_CLEAR);
sp_list = lp;
}
return 0;
Free:
swsusp_free();
return error;
}
/**
* get_buffer - compute the address that snapshot_write_next() should
* set for its caller to write to.
*/
static void *get_buffer(struct memory_bitmap *bm, struct chain_allocator *ca)
{
struct pbe *pbe;
struct page *page;
unsigned long pfn = memory_bm_next_pfn(bm);
if (pfn == BM_END_OF_MAP)
return ERR_PTR(-EFAULT);
page = pfn_to_page(pfn);
if (PageHighMem(page))
return get_highmem_page_buffer(page, ca);
if (swsusp_page_is_forbidden(page) && swsusp_page_is_free(page))
/* We have allocated the "original" page frame and we can
* use it directly to store the loaded page.
*/
return page_address(page);
/* The "original" page frame has not been allocated and we have to
* use a "safe" page frame to store the loaded page.
*/
pbe = chain_alloc(ca, sizeof(struct pbe));
if (!pbe) {
swsusp_free();
return ERR_PTR(-ENOMEM);
}
pbe->orig_address = page_address(page);
pbe->address = safe_pages_list;
safe_pages_list = safe_pages_list->next;
pbe->next = restore_pblist;
restore_pblist = pbe;
return pbe->address;
}
/**
* snapshot_write_next - used for writing the system memory snapshot.
*
* On the first call to it @handle should point to a zeroed
* snapshot_handle structure. The structure gets updated and a pointer
* to it should be passed to this function every next time.
*
* On success the function returns a positive number. Then, the caller
* is allowed to write up to the returned number of bytes to the memory
* location computed by the data_of() macro.
*
* The function returns 0 to indicate the "end of file" condition,
* and a negative number is returned on error. In such cases the
* structure pointed to by @handle is not updated and should not be used
* any more.
*/
int snapshot_write_next(struct snapshot_handle *handle)
{
static struct chain_allocator ca;
int error = 0;
/* Check if we have already loaded the entire image */
if (handle->cur > 1 && handle->cur > nr_meta_pages + nr_copy_pages)
return 0;
handle->sync_read = 1;
if (!handle->cur) {
if (!buffer)
/* This makes the buffer be freed by swsusp_free() */
buffer = get_image_page(GFP_ATOMIC, PG_ANY);
if (!buffer)
return -ENOMEM;
handle->buffer = buffer;
} else if (handle->cur == 1) {
error = load_header(buffer);
if (error)
return error;
error = memory_bm_create(©_bm, GFP_ATOMIC, PG_ANY);
if (error)
return error;
/* Allocate buffer for page keys. */
error = page_key_alloc(nr_copy_pages);
if (error)
return error;
} else if (handle->cur <= nr_meta_pages + 1) {
error = unpack_orig_pfns(buffer, ©_bm);
if (error)
return error;
if (handle->cur == nr_meta_pages + 1) {
error = prepare_image(&orig_bm, ©_bm);
if (error)
return error;
chain_init(&ca, GFP_ATOMIC, PG_SAFE);
memory_bm_position_reset(&orig_bm);
restore_pblist = NULL;
handle->buffer = get_buffer(&orig_bm, &ca);
handle->sync_read = 0;
if (IS_ERR(handle->buffer))
return PTR_ERR(handle->buffer);
}
} else {
copy_last_highmem_page();
/* Restore page key for data page (s390 only). */
page_key_write(handle->buffer);
handle->buffer = get_buffer(&orig_bm, &ca);
if (IS_ERR(handle->buffer))
return PTR_ERR(handle->buffer);
if (handle->buffer != buffer)
handle->sync_read = 0;
}
handle->cur++;
return PAGE_SIZE;
}
/**
* snapshot_write_finalize - must be called after the last call to
* snapshot_write_next() in case the last page in the image happens
* to be a highmem page and its contents should be stored in the
* highmem. Additionally, it releases the memory that will not be
* used any more.
*/
void snapshot_write_finalize(struct snapshot_handle *handle)
{
copy_last_highmem_page();
/* Restore page key for data page (s390 only). */
page_key_write(handle->buffer);
page_key_free();
/* Free only if we have loaded the image entirely */
if (handle->cur > 1 && handle->cur > nr_meta_pages + nr_copy_pages) {
memory_bm_free(&orig_bm, PG_UNSAFE_CLEAR);
free_highmem_data();
}
}
int snapshot_image_loaded(struct snapshot_handle *handle)
{
return !(!nr_copy_pages || !last_highmem_page_copied() ||
handle->cur <= nr_meta_pages + nr_copy_pages);
}
#ifdef CONFIG_HIGHMEM
/* Assumes that @buf is ready and points to a "safe" page */
static inline void
swap_two_pages_data(struct page *p1, struct page *p2, void *buf)
{
void *kaddr1, *kaddr2;
kaddr1 = kmap_atomic(p1);
kaddr2 = kmap_atomic(p2);
copy_page(buf, kaddr1);
copy_page(kaddr1, kaddr2);
copy_page(kaddr2, buf);
kunmap_atomic(kaddr2);
kunmap_atomic(kaddr1);
}
/**
* restore_highmem - for each highmem page that was allocated before
* the suspend and included in the suspend image, and also has been
* allocated by the "resume" kernel swap its current (ie. "before
* resume") contents with the previous (ie. "before suspend") one.
*
* If the resume eventually fails, we can call this function once
* again and restore the "before resume" highmem state.
*/
int restore_highmem(void)
{
struct highmem_pbe *pbe = highmem_pblist;
void *buf;
if (!pbe)
return 0;
buf = get_image_page(GFP_ATOMIC, PG_SAFE);
if (!buf)
return -ENOMEM;
while (pbe) {
swap_two_pages_data(pbe->copy_page, pbe->orig_page, buf);
pbe = pbe->next;
}
free_image_page(buf, PG_UNSAFE_CLEAR);
return 0;
}
#endif /* CONFIG_HIGHMEM */
| gpl-2.0 |
Split-Screen/android_kernel_oneplus_msm8974 | arch/sh/kernel/traps.c | 4457 | 2262 | #include <linux/bug.h>
#include <linux/io.h>
#include <linux/types.h>
#include <linux/kdebug.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <linux/hardirq.h>
#include <asm/unwinder.h>
#include <asm/traps.h>
#ifdef CONFIG_GENERIC_BUG
static void handle_BUG(struct pt_regs *regs)
{
const struct bug_entry *bug;
unsigned long bugaddr = regs->pc;
enum bug_trap_type tt;
if (!is_valid_bugaddr(bugaddr))
goto invalid;
bug = find_bug(bugaddr);
/* Switch unwinders when unwind_stack() is called */
if (bug->flags & BUGFLAG_UNWINDER)
unwinder_faulted = 1;
tt = report_bug(bugaddr, regs);
if (tt == BUG_TRAP_TYPE_WARN) {
regs->pc += instruction_size(bugaddr);
return;
}
invalid:
die("Kernel BUG", regs, TRAPA_BUG_OPCODE & 0xff);
}
int is_valid_bugaddr(unsigned long addr)
{
insn_size_t opcode;
if (addr < PAGE_OFFSET)
return 0;
if (probe_kernel_address((insn_size_t *)addr, opcode))
return 0;
if (opcode == TRAPA_BUG_OPCODE)
return 1;
return 0;
}
#endif
/*
* Generic trap handler.
*/
BUILD_TRAP_HANDLER(debug)
{
TRAP_HANDLER_DECL;
/* Rewind */
regs->pc -= instruction_size(__raw_readw(regs->pc - 4));
if (notify_die(DIE_TRAP, "debug trap", regs, 0, vec & 0xff,
SIGTRAP) == NOTIFY_STOP)
return;
force_sig(SIGTRAP, current);
}
/*
* Special handler for BUG() traps.
*/
BUILD_TRAP_HANDLER(bug)
{
TRAP_HANDLER_DECL;
/* Rewind */
regs->pc -= instruction_size(__raw_readw(regs->pc - 4));
if (notify_die(DIE_TRAP, "bug trap", regs, 0, TRAPA_BUG_OPCODE & 0xff,
SIGTRAP) == NOTIFY_STOP)
return;
#ifdef CONFIG_GENERIC_BUG
if (__kernel_text_address(instruction_pointer(regs))) {
insn_size_t insn = *(insn_size_t *)instruction_pointer(regs);
if (insn == TRAPA_BUG_OPCODE)
handle_BUG(regs);
return;
}
#endif
force_sig(SIGTRAP, current);
}
BUILD_TRAP_HANDLER(nmi)
{
unsigned int cpu = smp_processor_id();
TRAP_HANDLER_DECL;
nmi_enter();
nmi_count(cpu)++;
switch (notify_die(DIE_NMI, "NMI", regs, 0, vec & 0xff, SIGINT)) {
case NOTIFY_OK:
case NOTIFY_STOP:
break;
case NOTIFY_BAD:
die("Fatal Non-Maskable Interrupt", regs, SIGINT);
default:
printk(KERN_ALERT "Got NMI, but nobody cared. Ignoring...\n");
break;
}
nmi_exit();
}
| gpl-2.0 |
antaril/AGK-LOLLIPOP | drivers/net/wireless/brcm80211/brcmsmac/antsel.c | 5225 | 9726 | /*
* Copyright (c) 2010 Broadcom Corporation
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <linux/slab.h>
#include <net/mac80211.h>
#include "types.h"
#include "main.h"
#include "phy_shim.h"
#include "antsel.h"
#define ANT_SELCFG_AUTO 0x80 /* bit indicates antenna sel AUTO */
#define ANT_SELCFG_MASK 0x33 /* antenna configuration mask */
#define ANT_SELCFG_TX_UNICAST 0 /* unicast tx antenna configuration */
#define ANT_SELCFG_RX_UNICAST 1 /* unicast rx antenna configuration */
#define ANT_SELCFG_TX_DEF 2 /* default tx antenna configuration */
#define ANT_SELCFG_RX_DEF 3 /* default rx antenna configuration */
/* useful macros */
#define BRCMS_ANTSEL_11N_0(ant) ((((ant) & ANT_SELCFG_MASK) >> 4) & 0xf)
#define BRCMS_ANTSEL_11N_1(ant) (((ant) & ANT_SELCFG_MASK) & 0xf)
#define BRCMS_ANTIDX_11N(ant) (((BRCMS_ANTSEL_11N_0(ant)) << 2) +\
(BRCMS_ANTSEL_11N_1(ant)))
#define BRCMS_ANT_ISAUTO_11N(ant) (((ant) & ANT_SELCFG_AUTO) == ANT_SELCFG_AUTO)
#define BRCMS_ANTSEL_11N(ant) ((ant) & ANT_SELCFG_MASK)
/* antenna switch */
/* defines for no boardlevel antenna diversity */
#define ANT_SELCFG_DEF_2x2 0x01 /* default antenna configuration */
/* 2x3 antdiv defines and tables for GPIO communication */
#define ANT_SELCFG_NUM_2x3 3
#define ANT_SELCFG_DEF_2x3 0x01 /* default antenna configuration */
/* 2x4 antdiv rev4 defines and tables for GPIO communication */
#define ANT_SELCFG_NUM_2x4 4
#define ANT_SELCFG_DEF_2x4 0x02 /* default antenna configuration */
static const u16 mimo_2x4_div_antselpat_tbl[] = {
0, 0, 0x9, 0xa, /* ant0: 0 ant1: 2,3 */
0, 0, 0x5, 0x6, /* ant0: 1 ant1: 2,3 */
0, 0, 0, 0, /* n.a. */
0, 0, 0, 0 /* n.a. */
};
static const u8 mimo_2x4_div_antselid_tbl[16] = {
0, 0, 0, 0, 0, 2, 3, 0,
0, 0, 1, 0, 0, 0, 0, 0 /* pat to antselid */
};
static const u16 mimo_2x3_div_antselpat_tbl[] = {
16, 0, 1, 16, /* ant0: 0 ant1: 1,2 */
16, 16, 16, 16, /* n.a. */
16, 2, 16, 16, /* ant0: 2 ant1: 1 */
16, 16, 16, 16 /* n.a. */
};
static const u8 mimo_2x3_div_antselid_tbl[16] = {
0, 1, 2, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0 /* pat to antselid */
};
/* boardlevel antenna selection: init antenna selection structure */
static void
brcms_c_antsel_init_cfg(struct antsel_info *asi, struct brcms_antselcfg *antsel,
bool auto_sel)
{
if (asi->antsel_type == ANTSEL_2x3) {
u8 antcfg_def = ANT_SELCFG_DEF_2x3 |
((asi->antsel_avail && auto_sel) ? ANT_SELCFG_AUTO : 0);
antsel->ant_config[ANT_SELCFG_TX_DEF] = antcfg_def;
antsel->ant_config[ANT_SELCFG_TX_UNICAST] = antcfg_def;
antsel->ant_config[ANT_SELCFG_RX_DEF] = antcfg_def;
antsel->ant_config[ANT_SELCFG_RX_UNICAST] = antcfg_def;
antsel->num_antcfg = ANT_SELCFG_NUM_2x3;
} else if (asi->antsel_type == ANTSEL_2x4) {
antsel->ant_config[ANT_SELCFG_TX_DEF] = ANT_SELCFG_DEF_2x4;
antsel->ant_config[ANT_SELCFG_TX_UNICAST] = ANT_SELCFG_DEF_2x4;
antsel->ant_config[ANT_SELCFG_RX_DEF] = ANT_SELCFG_DEF_2x4;
antsel->ant_config[ANT_SELCFG_RX_UNICAST] = ANT_SELCFG_DEF_2x4;
antsel->num_antcfg = ANT_SELCFG_NUM_2x4;
} else { /* no antenna selection available */
antsel->ant_config[ANT_SELCFG_TX_DEF] = ANT_SELCFG_DEF_2x2;
antsel->ant_config[ANT_SELCFG_TX_UNICAST] = ANT_SELCFG_DEF_2x2;
antsel->ant_config[ANT_SELCFG_RX_DEF] = ANT_SELCFG_DEF_2x2;
antsel->ant_config[ANT_SELCFG_RX_UNICAST] = ANT_SELCFG_DEF_2x2;
antsel->num_antcfg = 0;
}
}
struct antsel_info *brcms_c_antsel_attach(struct brcms_c_info *wlc)
{
struct antsel_info *asi;
struct si_pub *sih = wlc->hw->sih;
asi = kzalloc(sizeof(struct antsel_info), GFP_ATOMIC);
if (!asi)
return NULL;
asi->wlc = wlc;
asi->pub = wlc->pub;
asi->antsel_type = ANTSEL_NA;
asi->antsel_avail = false;
asi->antsel_antswitch = (u8) getintvar(sih, BRCMS_SROM_ANTSWITCH);
if ((asi->pub->sromrev >= 4) && (asi->antsel_antswitch != 0)) {
switch (asi->antsel_antswitch) {
case ANTSWITCH_TYPE_1:
case ANTSWITCH_TYPE_2:
case ANTSWITCH_TYPE_3:
/* 4321/2 board with 2x3 switch logic */
asi->antsel_type = ANTSEL_2x3;
/* Antenna selection availability */
if (((u16) getintvar(sih, BRCMS_SROM_AA2G) == 7) ||
((u16) getintvar(sih, BRCMS_SROM_AA5G) == 7)) {
asi->antsel_avail = true;
} else if (
(u16) getintvar(sih, BRCMS_SROM_AA2G) == 3 ||
(u16) getintvar(sih, BRCMS_SROM_AA5G) == 3) {
asi->antsel_avail = false;
} else {
asi->antsel_avail = false;
wiphy_err(wlc->wiphy, "antsel_attach: 2o3 "
"board cfg invalid\n");
}
break;
default:
break;
}
} else if ((asi->pub->sromrev == 4) &&
((u16) getintvar(sih, BRCMS_SROM_AA2G) == 7) &&
((u16) getintvar(sih, BRCMS_SROM_AA5G) == 0)) {
/* hack to match old 4321CB2 cards with 2of3 antenna switch */
asi->antsel_type = ANTSEL_2x3;
asi->antsel_avail = true;
} else if (asi->pub->boardflags2 & BFL2_2X4_DIV) {
asi->antsel_type = ANTSEL_2x4;
asi->antsel_avail = true;
}
/* Set the antenna selection type for the low driver */
brcms_b_antsel_type_set(wlc->hw, asi->antsel_type);
/* Init (auto/manual) antenna selection */
brcms_c_antsel_init_cfg(asi, &asi->antcfg_11n, true);
brcms_c_antsel_init_cfg(asi, &asi->antcfg_cur, true);
return asi;
}
void brcms_c_antsel_detach(struct antsel_info *asi)
{
kfree(asi);
}
/*
* boardlevel antenna selection:
* convert ant_cfg to mimo_antsel (ucode interface)
*/
static u16 brcms_c_antsel_antcfg2antsel(struct antsel_info *asi, u8 ant_cfg)
{
u8 idx = BRCMS_ANTIDX_11N(BRCMS_ANTSEL_11N(ant_cfg));
u16 mimo_antsel = 0;
if (asi->antsel_type == ANTSEL_2x4) {
/* 2x4 antenna diversity board, 4 cfgs: 0-2 0-3 1-2 1-3 */
mimo_antsel = (mimo_2x4_div_antselpat_tbl[idx] & 0xf);
return mimo_antsel;
} else if (asi->antsel_type == ANTSEL_2x3) {
/* 2x3 antenna selection, 3 cfgs: 0-1 0-2 2-1 */
mimo_antsel = (mimo_2x3_div_antselpat_tbl[idx] & 0xf);
return mimo_antsel;
}
return mimo_antsel;
}
/* boardlevel antenna selection: ucode interface control */
static int brcms_c_antsel_cfgupd(struct antsel_info *asi,
struct brcms_antselcfg *antsel)
{
struct brcms_c_info *wlc = asi->wlc;
u8 ant_cfg;
u16 mimo_antsel;
/* 1) Update TX antconfig for all frames that are not unicast data
* (aka default TX)
*/
ant_cfg = antsel->ant_config[ANT_SELCFG_TX_DEF];
mimo_antsel = brcms_c_antsel_antcfg2antsel(asi, ant_cfg);
brcms_b_write_shm(wlc->hw, M_MIMO_ANTSEL_TXDFLT, mimo_antsel);
/*
* Update driver stats for currently selected
* default tx/rx antenna config
*/
asi->antcfg_cur.ant_config[ANT_SELCFG_TX_DEF] = ant_cfg;
/* 2) Update RX antconfig for all frames that are not unicast data
* (aka default RX)
*/
ant_cfg = antsel->ant_config[ANT_SELCFG_RX_DEF];
mimo_antsel = brcms_c_antsel_antcfg2antsel(asi, ant_cfg);
brcms_b_write_shm(wlc->hw, M_MIMO_ANTSEL_RXDFLT, mimo_antsel);
/*
* Update driver stats for currently selected
* default tx/rx antenna config
*/
asi->antcfg_cur.ant_config[ANT_SELCFG_RX_DEF] = ant_cfg;
return 0;
}
void brcms_c_antsel_init(struct antsel_info *asi)
{
if ((asi->antsel_type == ANTSEL_2x3) ||
(asi->antsel_type == ANTSEL_2x4))
brcms_c_antsel_cfgupd(asi, &asi->antcfg_11n);
}
/* boardlevel antenna selection: convert id to ant_cfg */
static u8 brcms_c_antsel_id2antcfg(struct antsel_info *asi, u8 id)
{
u8 antcfg = ANT_SELCFG_DEF_2x2;
if (asi->antsel_type == ANTSEL_2x4) {
/* 2x4 antenna diversity board, 4 cfgs: 0-2 0-3 1-2 1-3 */
antcfg = (((id & 0x2) << 3) | ((id & 0x1) + 2));
return antcfg;
} else if (asi->antsel_type == ANTSEL_2x3) {
/* 2x3 antenna selection, 3 cfgs: 0-1 0-2 2-1 */
antcfg = (((id & 0x02) << 4) | ((id & 0x1) + 1));
return antcfg;
}
return antcfg;
}
void
brcms_c_antsel_antcfg_get(struct antsel_info *asi, bool usedef, bool sel,
u8 antselid, u8 fbantselid, u8 *antcfg,
u8 *fbantcfg)
{
u8 ant;
/* if use default, assign it and return */
if (usedef) {
*antcfg = asi->antcfg_11n.ant_config[ANT_SELCFG_TX_DEF];
*fbantcfg = *antcfg;
return;
}
if (!sel) {
*antcfg = asi->antcfg_11n.ant_config[ANT_SELCFG_TX_UNICAST];
*fbantcfg = *antcfg;
} else {
ant = asi->antcfg_11n.ant_config[ANT_SELCFG_TX_UNICAST];
if ((ant & ANT_SELCFG_AUTO) == ANT_SELCFG_AUTO) {
*antcfg = brcms_c_antsel_id2antcfg(asi, antselid);
*fbantcfg = brcms_c_antsel_id2antcfg(asi, fbantselid);
} else {
*antcfg =
asi->antcfg_11n.ant_config[ANT_SELCFG_TX_UNICAST];
*fbantcfg = *antcfg;
}
}
return;
}
/* boardlevel antenna selection: convert mimo_antsel (ucode interface) to id */
u8 brcms_c_antsel_antsel2id(struct antsel_info *asi, u16 antsel)
{
u8 antselid = 0;
if (asi->antsel_type == ANTSEL_2x4) {
/* 2x4 antenna diversity board, 4 cfgs: 0-2 0-3 1-2 1-3 */
antselid = mimo_2x4_div_antselid_tbl[(antsel & 0xf)];
return antselid;
} else if (asi->antsel_type == ANTSEL_2x3) {
/* 2x3 antenna selection, 3 cfgs: 0-1 0-2 2-1 */
antselid = mimo_2x3_div_antselid_tbl[(antsel & 0xf)];
return antselid;
}
return antselid;
}
| gpl-2.0 |
tbalden/android_kernel_htc_m7-sense4.2 | fs/jfs/file.c | 5481 | 4460 | /*
* Copyright (C) International Business Machines Corp., 2000-2002
* Portions Copyright (C) Christoph Hellwig, 2001-2002
*
* 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/mm.h>
#include <linux/fs.h>
#include <linux/quotaops.h>
#include "jfs_incore.h"
#include "jfs_inode.h"
#include "jfs_dmap.h"
#include "jfs_txnmgr.h"
#include "jfs_xattr.h"
#include "jfs_acl.h"
#include "jfs_debug.h"
int jfs_fsync(struct file *file, loff_t start, loff_t end, int datasync)
{
struct inode *inode = file->f_mapping->host;
int rc = 0;
rc = filemap_write_and_wait_range(inode->i_mapping, start, end);
if (rc)
return rc;
mutex_lock(&inode->i_mutex);
if (!(inode->i_state & I_DIRTY) ||
(datasync && !(inode->i_state & I_DIRTY_DATASYNC))) {
/* Make sure committed changes hit the disk */
jfs_flush_journal(JFS_SBI(inode->i_sb)->log, 1);
mutex_unlock(&inode->i_mutex);
return rc;
}
rc |= jfs_commit_inode(inode, 1);
mutex_unlock(&inode->i_mutex);
return rc ? -EIO : 0;
}
static int jfs_open(struct inode *inode, struct file *file)
{
int rc;
if ((rc = dquot_file_open(inode, file)))
return rc;
/*
* We attempt to allow only one "active" file open per aggregate
* group. Otherwise, appending to files in parallel can cause
* fragmentation within the files.
*
* If the file is empty, it was probably just created and going
* to be written to. If it has a size, we'll hold off until the
* file is actually grown.
*/
if (S_ISREG(inode->i_mode) && file->f_mode & FMODE_WRITE &&
(inode->i_size == 0)) {
struct jfs_inode_info *ji = JFS_IP(inode);
spin_lock_irq(&ji->ag_lock);
if (ji->active_ag == -1) {
struct jfs_sb_info *jfs_sb = JFS_SBI(inode->i_sb);
ji->active_ag = BLKTOAG(addressPXD(&ji->ixpxd), jfs_sb);
atomic_inc( &jfs_sb->bmap->db_active[ji->active_ag]);
}
spin_unlock_irq(&ji->ag_lock);
}
return 0;
}
static int jfs_release(struct inode *inode, struct file *file)
{
struct jfs_inode_info *ji = JFS_IP(inode);
spin_lock_irq(&ji->ag_lock);
if (ji->active_ag != -1) {
struct bmap *bmap = JFS_SBI(inode->i_sb)->bmap;
atomic_dec(&bmap->db_active[ji->active_ag]);
ji->active_ag = -1;
}
spin_unlock_irq(&ji->ag_lock);
return 0;
}
int jfs_setattr(struct dentry *dentry, struct iattr *iattr)
{
struct inode *inode = dentry->d_inode;
int rc;
rc = inode_change_ok(inode, iattr);
if (rc)
return rc;
if (is_quota_modification(inode, iattr))
dquot_initialize(inode);
if ((iattr->ia_valid & ATTR_UID && iattr->ia_uid != inode->i_uid) ||
(iattr->ia_valid & ATTR_GID && iattr->ia_gid != inode->i_gid)) {
rc = dquot_transfer(inode, iattr);
if (rc)
return rc;
}
if ((iattr->ia_valid & ATTR_SIZE) &&
iattr->ia_size != i_size_read(inode)) {
inode_dio_wait(inode);
rc = vmtruncate(inode, iattr->ia_size);
if (rc)
return rc;
}
setattr_copy(inode, iattr);
mark_inode_dirty(inode);
if (iattr->ia_valid & ATTR_MODE)
rc = jfs_acl_chmod(inode);
return rc;
}
const struct inode_operations jfs_file_inode_operations = {
.truncate = jfs_truncate,
.setxattr = jfs_setxattr,
.getxattr = jfs_getxattr,
.listxattr = jfs_listxattr,
.removexattr = jfs_removexattr,
.setattr = jfs_setattr,
#ifdef CONFIG_JFS_POSIX_ACL
.get_acl = jfs_get_acl,
#endif
};
const struct file_operations jfs_file_operations = {
.open = jfs_open,
.llseek = generic_file_llseek,
.write = do_sync_write,
.read = do_sync_read,
.aio_read = generic_file_aio_read,
.aio_write = generic_file_aio_write,
.mmap = generic_file_mmap,
.splice_read = generic_file_splice_read,
.splice_write = generic_file_splice_write,
.fsync = jfs_fsync,
.release = jfs_release,
.unlocked_ioctl = jfs_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = jfs_compat_ioctl,
#endif
};
| gpl-2.0 |
crazyleen/linux-source-3.2 | arch/arm/mach-msm/last_radio_log.c | 8297 | 2130 | /* arch/arm/mach-msm/last_radio_log.c
*
* Extract the log from a modem crash though SMEM
*
* Copyright (C) 2007 Google, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/proc_fs.h>
#include <linux/uaccess.h>
#include "smd_private.h"
static void *radio_log_base;
static size_t radio_log_size;
extern void *smem_item(unsigned id, unsigned *size);
static ssize_t last_radio_log_read(struct file *file, char __user *buf,
size_t len, loff_t *offset)
{
loff_t pos = *offset;
ssize_t count;
if (pos >= radio_log_size)
return 0;
count = min(len, (size_t)(radio_log_size - pos));
if (copy_to_user(buf, radio_log_base + pos, count)) {
pr_err("%s: copy to user failed\n", __func__);
return -EFAULT;
}
*offset += count;
return count;
}
static struct file_operations last_radio_log_fops = {
.read = last_radio_log_read,
.llseek = default_llseek,
};
void msm_init_last_radio_log(struct module *owner)
{
struct proc_dir_entry *entry;
if (last_radio_log_fops.owner) {
pr_err("%s: already claimed\n", __func__);
return;
}
radio_log_base = smem_item(SMEM_CLKREGIM_BSP, &radio_log_size);
if (!radio_log_base) {
pr_err("%s: could not retrieve SMEM_CLKREGIM_BSP\n", __func__);
return;
}
entry = create_proc_entry("last_radio_log", S_IFREG | S_IRUGO, NULL);
if (!entry) {
pr_err("%s: could not create proc entry for radio log\n",
__func__);
return;
}
pr_err("%s: last radio log is %d bytes long\n", __func__,
radio_log_size);
last_radio_log_fops.owner = owner;
entry->proc_fops = &last_radio_log_fops;
entry->size = radio_log_size;
}
EXPORT_SYMBOL(msm_init_last_radio_log);
| gpl-2.0 |
xinpengliu/xinpengliu.github.io | ffmpeg+sdl-forffplayer/Androidplayer_ffplayer/SDL/test/testautomation_rwops.c | 106 | 26771 |
/**
* Automated SDL_RWops test.
*
* Original code written by Edgar Simo "bobbens"
* Ported by Markus Kauppila (markus.kauppila@gmail.com)
* Updated and extended for SDL_test by aschiffler at ferzkopp dot net
*
* Released under Public Domain.
*/
/* quiet windows compiler warnings */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
const char* RWopsReadTestFilename = "rwops_read";
const char* RWopsWriteTestFilename = "rwops_write";
const char* RWopsAlphabetFilename = "rwops_alphabet";
static const char RWopsHelloWorldTestString[] = "Hello World!";
static const char RWopsHelloWorldCompString[] = "Hello World!";
static const char RWopsAlphabetString[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/* Fixture */
void
RWopsSetUp(void *arg)
{
int fileLen;
FILE *handle;
int writtenLen;
int result;
/* Clean up from previous runs (if any); ignore errors */
remove(RWopsReadTestFilename);
remove(RWopsWriteTestFilename);
remove(RWopsAlphabetFilename);
/* Create a test file */
handle = fopen(RWopsReadTestFilename, "w");
SDLTest_AssertCheck(handle != NULL, "Verify creation of file '%s' returned non NULL handle", RWopsReadTestFilename);
if (handle == NULL) return;
/* Write some known text into it */
fileLen = SDL_strlen(RWopsHelloWorldTestString);
writtenLen = (int)fwrite(RWopsHelloWorldTestString, 1, fileLen, handle);
SDLTest_AssertCheck(fileLen == writtenLen, "Verify number of written bytes, expected %i, got %i", fileLen, writtenLen);
result = fclose(handle);
SDLTest_AssertCheck(result == 0, "Verify result from fclose, expected 0, got %i", result);
/* Create a second test file */
handle = fopen(RWopsAlphabetFilename, "w");
SDLTest_AssertCheck(handle != NULL, "Verify creation of file '%s' returned non NULL handle", RWopsAlphabetFilename);
if (handle == NULL) return;
/* Write alphabet text into it */
fileLen = SDL_strlen(RWopsAlphabetString);
writtenLen = (int)fwrite(RWopsAlphabetString, 1, fileLen, handle);
SDLTest_AssertCheck(fileLen == writtenLen, "Verify number of written bytes, expected %i, got %i", fileLen, writtenLen);
result = fclose(handle);
SDLTest_AssertCheck(result == 0, "Verify result from fclose, expected 0, got %i", result);
SDLTest_AssertPass("Creation of test file completed");
}
void
RWopsTearDown(void *arg)
{
int result;
/* Remove the created files to clean up; ignore errors for write filename */
result = remove(RWopsReadTestFilename);
SDLTest_AssertCheck(result == 0, "Verify result from remove(%s), expected 0, got %i", RWopsReadTestFilename, result);
remove(RWopsWriteTestFilename);
result = remove(RWopsAlphabetFilename);
SDLTest_AssertCheck(result == 0, "Verify result from remove(%s), expected 0, got %i", RWopsAlphabetFilename, result);
SDLTest_AssertPass("Cleanup of test files completed");
}
/**
* @brief Makes sure parameters work properly. Local helper function.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWseek
* http://wiki.libsdl.org/moin.cgi/SDL_RWread
*/
void
_testGenericRWopsValidations(SDL_RWops *rw, int write)
{
char buf[sizeof(RWopsHelloWorldTestString)];
Sint64 i;
size_t s;
int seekPos = SDLTest_RandomIntegerInRange(4, 8);
/* Clear buffer */
SDL_zero(buf);
/* Set to start. */
i = SDL_RWseek(rw, 0, RW_SEEK_SET );
SDLTest_AssertPass("Call to SDL_RWseek succeeded");
SDLTest_AssertCheck(i == (Sint64)0, "Verify seek to 0 with SDL_RWseek (RW_SEEK_SET), expected 0, got %"SDL_PRIs64, i);
/* Test write. */
s = SDL_RWwrite(rw, RWopsHelloWorldTestString, sizeof(RWopsHelloWorldTestString)-1, 1);
SDLTest_AssertPass("Call to SDL_RWwrite succeeded");
if (write) {
SDLTest_AssertCheck(s == (size_t)1, "Verify result of writing one byte with SDL_RWwrite, expected 1, got %i", s);
}
else {
SDLTest_AssertCheck(s == (size_t)0, "Verify result of writing with SDL_RWwrite, expected: 0, got %i", s);
}
/* Test seek to random position */
i = SDL_RWseek( rw, seekPos, RW_SEEK_SET );
SDLTest_AssertPass("Call to SDL_RWseek succeeded");
SDLTest_AssertCheck(i == (Sint64)seekPos, "Verify seek to %i with SDL_RWseek (RW_SEEK_SET), expected %i, got %"SDL_PRIs64, seekPos, seekPos, i);
/* Test seek back to start */
i = SDL_RWseek(rw, 0, RW_SEEK_SET );
SDLTest_AssertPass("Call to SDL_RWseek succeeded");
SDLTest_AssertCheck(i == (Sint64)0, "Verify seek to 0 with SDL_RWseek (RW_SEEK_SET), expected 0, got %"SDL_PRIs64, i);
/* Test read */
s = SDL_RWread( rw, buf, 1, sizeof(RWopsHelloWorldTestString)-1 );
SDLTest_AssertPass("Call to SDL_RWread succeeded");
SDLTest_AssertCheck(
s == (size_t)(sizeof(RWopsHelloWorldTestString)-1),
"Verify result from SDL_RWread, expected %i, got %i",
sizeof(RWopsHelloWorldTestString)-1,
s);
SDLTest_AssertCheck(
SDL_memcmp(buf, RWopsHelloWorldTestString, sizeof(RWopsHelloWorldTestString)-1 ) == 0,
"Verify read bytes match expected string, expected '%s', got '%s'", RWopsHelloWorldTestString, buf);
/* More seek tests. */
i = SDL_RWseek( rw, -4, RW_SEEK_CUR );
SDLTest_AssertPass("Call to SDL_RWseek(...,-4,RW_SEEK_CUR) succeeded");
SDLTest_AssertCheck(
i == (Sint64)(sizeof(RWopsHelloWorldTestString)-5),
"Verify seek to -4 with SDL_RWseek (RW_SEEK_CUR), expected %i, got %"SDL_PRIs64,
sizeof(RWopsHelloWorldTestString)-5,
i);
i = SDL_RWseek( rw, -1, RW_SEEK_END );
SDLTest_AssertPass("Call to SDL_RWseek(...,-1,RW_SEEK_END) succeeded");
SDLTest_AssertCheck(
i == (Sint64)(sizeof(RWopsHelloWorldTestString)-2),
"Verify seek to -1 with SDL_RWseek (RW_SEEK_END), expected %i, got %"SDL_PRIs64,
sizeof(RWopsHelloWorldTestString)-2,
i);
/* Invalid whence seek */
i = SDL_RWseek( rw, 0, 999 );
SDLTest_AssertPass("Call to SDL_RWseek(...,0,invalid_whence) succeeded");
SDLTest_AssertCheck(
i == (Sint64)(-1),
"Verify seek with SDL_RWseek (invalid_whence); expected: -1, got %"SDL_PRIs64,
i);
}
/* !
* Negative test for SDL_RWFromFile parameters
*
* \sa http://wiki.libsdl.org/moin.cgi/SDL_RWFromFile
*
*/
int
rwops_testParamNegative (void)
{
SDL_RWops *rwops;
/* These should all fail. */
rwops = SDL_RWFromFile(NULL, NULL);
SDLTest_AssertPass("Call to SDL_RWFromFile(NULL, NULL) succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromFile(NULL, NULL) returns NULL");
rwops = SDL_RWFromFile(NULL, "ab+");
SDLTest_AssertPass("Call to SDL_RWFromFile(NULL, \"ab+\") succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromFile(NULL, \"ab+\") returns NULL");
rwops = SDL_RWFromFile(NULL, "sldfkjsldkfj");
SDLTest_AssertPass("Call to SDL_RWFromFile(NULL, \"sldfkjsldkfj\") succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromFile(NULL, \"sldfkjsldkfj\") returns NULL");
rwops = SDL_RWFromFile("something", "");
SDLTest_AssertPass("Call to SDL_RWFromFile(\"something\", \"\") succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromFile(\"something\", \"\") returns NULL");
rwops = SDL_RWFromFile("something", NULL);
SDLTest_AssertPass("Call to SDL_RWFromFile(\"something\", NULL) succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromFile(\"something\", NULL) returns NULL");
rwops = SDL_RWFromMem((void *)NULL, 10);
SDLTest_AssertPass("Call to SDL_RWFromMem(NULL, 10) succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromMem(NULL, 10) returns NULL");
rwops = SDL_RWFromMem((void *)RWopsAlphabetString, 0);
SDLTest_AssertPass("Call to SDL_RWFromMem(data, 0) succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromMem(data, 0) returns NULL");
rwops = SDL_RWFromConstMem((const void *)RWopsAlphabetString, 0);
SDLTest_AssertPass("Call to SDL_RWFromConstMem(data, 0) succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromConstMem(data, 0) returns NULL");
return TEST_COMPLETED;
}
/**
* @brief Tests opening from memory.
*
* \sa http://wiki.libsdl.org/moin.cgi/SDL_RWFromMem
* \sa http://wiki.libsdl.org/moin.cgi/SDL_RWClose
*/
int
rwops_testMem (void)
{
char mem[sizeof(RWopsHelloWorldTestString)];
SDL_RWops *rw;
int result;
/* Clear buffer */
SDL_zero(mem);
/* Open */
rw = SDL_RWFromMem(mem, sizeof(RWopsHelloWorldTestString)-1);
SDLTest_AssertPass("Call to SDL_RWFromMem() succeeded");
SDLTest_AssertCheck(rw != NULL, "Verify opening memory with SDL_RWFromMem does not return NULL");
/* Bail out if NULL */
if (rw == NULL) return TEST_ABORTED;
/* Check type */
SDLTest_AssertCheck(rw->type == SDL_RWOPS_MEMORY, "Verify RWops type is SDL_RWOPS_MEMORY; expected: %d, got: %d", SDL_RWOPS_MEMORY, rw->type);
/* Run generic tests */
_testGenericRWopsValidations(rw, 1);
/* Close */
result = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Tests opening from memory.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWFromConstMem
* http://wiki.libsdl.org/moin.cgi/SDL_RWClose
*/
int
rwops_testConstMem (void)
{
SDL_RWops *rw;
int result;
/* Open handle */
rw = SDL_RWFromConstMem( RWopsHelloWorldCompString, sizeof(RWopsHelloWorldCompString)-1 );
SDLTest_AssertPass("Call to SDL_RWFromConstMem() succeeded");
SDLTest_AssertCheck(rw != NULL, "Verify opening memory with SDL_RWFromConstMem does not return NULL");
/* Bail out if NULL */
if (rw == NULL) return TEST_ABORTED;
/* Check type */
SDLTest_AssertCheck(rw->type == SDL_RWOPS_MEMORY_RO, "Verify RWops type is SDL_RWOPS_MEMORY_RO; expected: %d, got: %d", SDL_RWOPS_MEMORY_RO, rw->type);
/* Run generic tests */
_testGenericRWopsValidations( rw, 0 );
/* Close handle */
result = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Tests reading from file.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWFromFile
* http://wiki.libsdl.org/moin.cgi/SDL_RWClose
*/
int
rwops_testFileRead(void)
{
SDL_RWops *rw;
int result;
/* Read test. */
rw = SDL_RWFromFile(RWopsReadTestFilename, "r");
SDLTest_AssertPass("Call to SDL_RWFromFile(..,\"r\") succeeded");
SDLTest_AssertCheck(rw != NULL, "Verify opening file with SDL_RWFromFile in read mode does not return NULL");
/* Bail out if NULL */
if (rw == NULL) return TEST_ABORTED;
/* Check type */
#if defined(__ANDROID__)
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_STDFILE || rw->type == SDL_RWOPS_JNIFILE,
"Verify RWops type is SDL_RWOPS_STDFILE or SDL_RWOPS_JNIFILE; expected: %d|%d, got: %d", SDL_RWOPS_STDFILE, SDL_RWOPS_JNIFILE, rw->type);
#elif defined(__WIN32__)
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_WINFILE,
"Verify RWops type is SDL_RWOPS_WINFILE; expected: %d, got: %d", SDL_RWOPS_WINFILE, rw->type);
#else
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_STDFILE,
"Verify RWops type is SDL_RWOPS_STDFILE; expected: %d, got: %d", SDL_RWOPS_STDFILE, rw->type);
#endif
/* Run generic tests */
_testGenericRWopsValidations( rw, 0 );
/* Close handle */
result = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Tests writing from file.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWFromFile
* http://wiki.libsdl.org/moin.cgi/SDL_RWClose
*/
int
rwops_testFileWrite(void)
{
SDL_RWops *rw;
int result;
/* Write test. */
rw = SDL_RWFromFile(RWopsWriteTestFilename, "w+");
SDLTest_AssertPass("Call to SDL_RWFromFile(..,\"w+\") succeeded");
SDLTest_AssertCheck(rw != NULL, "Verify opening file with SDL_RWFromFile in write mode does not return NULL");
/* Bail out if NULL */
if (rw == NULL) return TEST_ABORTED;
/* Check type */
#if defined(__ANDROID__)
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_STDFILE || rw->type == SDL_RWOPS_JNIFILE,
"Verify RWops type is SDL_RWOPS_STDFILE or SDL_RWOPS_JNIFILE; expected: %d|%d, got: %d", SDL_RWOPS_STDFILE, SDL_RWOPS_JNIFILE, rw->type);
#elif defined(__WIN32__)
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_WINFILE,
"Verify RWops type is SDL_RWOPS_WINFILE; expected: %d, got: %d", SDL_RWOPS_WINFILE, rw->type);
#else
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_STDFILE,
"Verify RWops type is SDL_RWOPS_STDFILE; expected: %d, got: %d", SDL_RWOPS_STDFILE, rw->type);
#endif
/* Run generic tests */
_testGenericRWopsValidations( rw, 1 );
/* Close handle */
result = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Tests reading from file handle
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWFromFP
* http://wiki.libsdl.org/moin.cgi/SDL_RWClose
*
*/
int
rwops_testFPRead(void)
{
FILE *fp;
SDL_RWops *rw;
int result;
/* Run read tests. */
fp = fopen(RWopsReadTestFilename, "r");
SDLTest_AssertCheck(fp != NULL, "Verify handle from opening file '%s' in read mode is not NULL", RWopsReadTestFilename);
/* Bail out if NULL */
if (fp == NULL) return TEST_ABORTED;
/* Open */
rw = SDL_RWFromFP( fp, SDL_TRUE );
SDLTest_AssertPass("Call to SDL_RWFromFP() succeeded");
SDLTest_AssertCheck(rw != NULL, "Verify opening file with SDL_RWFromFP in read mode does not return NULL");
/* Bail out if NULL */
if (rw == NULL) {
fclose(fp);
return TEST_ABORTED;
}
/* Check type */
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_STDFILE,
"Verify RWops type is SDL_RWOPS_STDFILE; expected: %d, got: %d", SDL_RWOPS_STDFILE, rw->type);
/* Run generic tests */
_testGenericRWopsValidations( rw, 0 );
/* Close handle - does fclose() */
result = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Tests writing to file handle
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWFromFP
* http://wiki.libsdl.org/moin.cgi/SDL_RWClose
*
*/
int
rwops_testFPWrite(void)
{
FILE *fp;
SDL_RWops *rw;
int result;
/* Run write tests. */
fp = fopen(RWopsWriteTestFilename, "w+");
SDLTest_AssertCheck(fp != NULL, "Verify handle from opening file '%s' in write mode is not NULL", RWopsWriteTestFilename);
/* Bail out if NULL */
if (fp == NULL) return TEST_ABORTED;
/* Open */
rw = SDL_RWFromFP( fp, SDL_TRUE );
SDLTest_AssertPass("Call to SDL_RWFromFP() succeeded");
SDLTest_AssertCheck(rw != NULL, "Verify opening file with SDL_RWFromFP in write mode does not return NULL");
/* Bail out if NULL */
if (rw == NULL) {
fclose(fp);
return TEST_ABORTED;
}
/* Check type */
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_STDFILE,
"Verify RWops type is SDL_RWOPS_STDFILE; expected: %d, got: %d", SDL_RWOPS_STDFILE, rw->type);
/* Run generic tests */
_testGenericRWopsValidations( rw, 1 );
/* Close handle - does fclose() */
result = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Tests alloc and free RW context.
*
* \sa http://wiki.libsdl.org/moin.cgi/SDL_AllocRW
* \sa http://wiki.libsdl.org/moin.cgi/SDL_FreeRW
*/
int
rwops_testAllocFree (void)
{
/* Allocate context */
SDL_RWops *rw = SDL_AllocRW();
SDLTest_AssertPass("Call to SDL_AllocRW() succeeded");
SDLTest_AssertCheck(rw != NULL, "Validate result from SDL_AllocRW() is not NULL");
if (rw==NULL) return TEST_ABORTED;
/* Check type */
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_UNKNOWN,
"Verify RWops type is SDL_RWOPS_UNKNOWN; expected: %d, got: %d", SDL_RWOPS_UNKNOWN, rw->type);
/* Free context again */
SDL_FreeRW(rw);
SDLTest_AssertPass("Call to SDL_FreeRW() succeeded");
return TEST_COMPLETED;
}
/**
* @brief Compare memory and file reads
*
* \sa http://wiki.libsdl.org/moin.cgi/SDL_RWFromMem
* \sa http://wiki.libsdl.org/moin.cgi/SDL_RWFromFile
*/
int
rwops_testCompareRWFromMemWithRWFromFile(void)
{
int slen = 26;
char buffer_file[27];
char buffer_mem[27];
size_t rv_file;
size_t rv_mem;
Uint64 sv_file;
Uint64 sv_mem;
SDL_RWops* rwops_file;
SDL_RWops* rwops_mem;
int size;
int result;
for (size=5; size<10; size++)
{
/* Terminate buffer */
buffer_file[slen] = 0;
buffer_mem[slen] = 0;
/* Read/seek from memory */
rwops_mem = SDL_RWFromMem((void *)RWopsAlphabetString, slen);
SDLTest_AssertPass("Call to SDL_RWFromMem()");
rv_mem = SDL_RWread(rwops_mem, buffer_mem, size, 6);
SDLTest_AssertPass("Call to SDL_RWread(mem, size=%d)", size);
sv_mem = SDL_RWseek(rwops_mem, 0, SEEK_END);
SDLTest_AssertPass("Call to SDL_RWseek(mem,SEEK_END)");
result = SDL_RWclose(rwops_mem);
SDLTest_AssertPass("Call to SDL_RWclose(mem)");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
/* Read/see from file */
rwops_file = SDL_RWFromFile(RWopsAlphabetFilename, "r");
SDLTest_AssertPass("Call to SDL_RWFromFile()");
rv_file = SDL_RWread(rwops_file, buffer_file, size, 6);
SDLTest_AssertPass("Call to SDL_RWread(file, size=%d)", size);
sv_file = SDL_RWseek(rwops_file, 0, SEEK_END);
SDLTest_AssertPass("Call to SDL_RWseek(file,SEEK_END)");
result = SDL_RWclose(rwops_file);
SDLTest_AssertPass("Call to SDL_RWclose(file)");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
/* Compare */
SDLTest_AssertCheck(rv_mem == rv_file, "Verify returned read blocks matches for mem and file reads; got: rv_mem=%d rv_file=%d", rv_mem, rv_file);
SDLTest_AssertCheck(sv_mem == sv_file, "Verify SEEK_END position matches for mem and file seeks; got: sv_mem=%"SDL_PRIu64" sv_file=%"SDL_PRIu64, sv_mem, sv_file);
SDLTest_AssertCheck(buffer_mem[slen] == 0, "Verify mem buffer termination; expected: 0, got: %d", buffer_mem[slen]);
SDLTest_AssertCheck(buffer_file[slen] == 0, "Verify file buffer termination; expected: 0, got: %d", buffer_file[slen]);
SDLTest_AssertCheck(
SDL_strncmp(buffer_mem, RWopsAlphabetString, slen) == 0,
"Verify mem buffer contain alphabet string; expected: %s, got: %s", RWopsAlphabetString, buffer_mem);
SDLTest_AssertCheck(
SDL_strncmp(buffer_file, RWopsAlphabetString, slen) == 0,
"Verify file buffer contain alphabet string; expected: %s, got: %s", RWopsAlphabetString, buffer_file);
}
return TEST_COMPLETED;
}
/**
* @brief Tests writing and reading from file using endian aware functions.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWFromFile
* http://wiki.libsdl.org/moin.cgi/SDL_RWClose
* http://wiki.libsdl.org/moin.cgi/SDL_ReadBE16
* http://wiki.libsdl.org/moin.cgi/SDL_WriteBE16
*/
int
rwops_testFileWriteReadEndian(void)
{
SDL_RWops *rw;
Sint64 result;
int mode;
size_t objectsWritten;
Uint16 BE16value;
Uint32 BE32value;
Uint64 BE64value;
Uint16 LE16value;
Uint32 LE32value;
Uint64 LE64value;
Uint16 BE16test;
Uint32 BE32test;
Uint64 BE64test;
Uint16 LE16test;
Uint32 LE32test;
Uint64 LE64test;
int cresult;
for (mode = 0; mode < 3; mode++) {
/* Create test data */
switch (mode) {
case 0:
SDLTest_Log("All 0 values");
BE16value = 0;
BE32value = 0;
BE64value = 0;
LE16value = 0;
LE32value = 0;
LE64value = 0;
break;
case 1:
SDLTest_Log("All 1 values");
BE16value = 1;
BE32value = 1;
BE64value = 1;
LE16value = 1;
LE32value = 1;
LE64value = 1;
break;
case 2:
SDLTest_Log("Random values");
BE16value = SDLTest_RandomUint16();
BE32value = SDLTest_RandomUint32();
BE64value = SDLTest_RandomUint64();
LE16value = SDLTest_RandomUint16();
LE32value = SDLTest_RandomUint32();
LE64value = SDLTest_RandomUint64();
break;
}
/* Write test. */
rw = SDL_RWFromFile(RWopsWriteTestFilename, "w+");
SDLTest_AssertPass("Call to SDL_RWFromFile(..,\"w+\")");
SDLTest_AssertCheck(rw != NULL, "Verify opening file with SDL_RWFromFile in write mode does not return NULL");
/* Bail out if NULL */
if (rw == NULL) return TEST_ABORTED;
/* Write test data */
objectsWritten = SDL_WriteBE16(rw, BE16value);
SDLTest_AssertPass("Call to SDL_WriteBE16()");
SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", objectsWritten);
objectsWritten = SDL_WriteBE32(rw, BE32value);
SDLTest_AssertPass("Call to SDL_WriteBE32()");
SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", objectsWritten);
objectsWritten = SDL_WriteBE64(rw, BE64value);
SDLTest_AssertPass("Call to SDL_WriteBE64()");
SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", objectsWritten);
objectsWritten = SDL_WriteLE16(rw, LE16value);
SDLTest_AssertPass("Call to SDL_WriteLE16()");
SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", objectsWritten);
objectsWritten = SDL_WriteLE32(rw, LE32value);
SDLTest_AssertPass("Call to SDL_WriteLE32()");
SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", objectsWritten);
objectsWritten = SDL_WriteLE64(rw, LE64value);
SDLTest_AssertPass("Call to SDL_WriteLE64()");
SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", objectsWritten);
/* Test seek to start */
result = SDL_RWseek( rw, 0, RW_SEEK_SET );
SDLTest_AssertPass("Call to SDL_RWseek succeeded");
SDLTest_AssertCheck(result == 0, "Verify result from position 0 with SDL_RWseek, expected 0, got %"SDL_PRIs64, result);
/* Read test data */
BE16test = SDL_ReadBE16(rw);
SDLTest_AssertPass("Call to SDL_ReadBE16()");
SDLTest_AssertCheck(BE16test == BE16value, "Validate return value from SDL_ReadBE16, expected: %hu, got: %hu", BE16value, BE16test);
BE32test = SDL_ReadBE32(rw);
SDLTest_AssertPass("Call to SDL_ReadBE32()");
SDLTest_AssertCheck(BE32test == BE32value, "Validate return value from SDL_ReadBE32, expected: %u, got: %u", BE32value, BE32test);
BE64test = SDL_ReadBE64(rw);
SDLTest_AssertPass("Call to SDL_ReadBE64()");
SDLTest_AssertCheck(BE64test == BE64value, "Validate return value from SDL_ReadBE64, expected: %"SDL_PRIu64", got: %"SDL_PRIu64, BE64value, BE64test);
LE16test = SDL_ReadLE16(rw);
SDLTest_AssertPass("Call to SDL_ReadLE16()");
SDLTest_AssertCheck(LE16test == LE16value, "Validate return value from SDL_ReadLE16, expected: %hu, got: %hu", LE16value, LE16test);
LE32test = SDL_ReadLE32(rw);
SDLTest_AssertPass("Call to SDL_ReadLE32()");
SDLTest_AssertCheck(LE32test == LE32value, "Validate return value from SDL_ReadLE32, expected: %u, got: %u", LE32value, LE32test);
LE64test = SDL_ReadLE64(rw);
SDLTest_AssertPass("Call to SDL_ReadLE64()");
SDLTest_AssertCheck(LE64test == LE64value, "Validate return value from SDL_ReadLE64, expected: %"SDL_PRIu64", got: %"SDL_PRIu64, LE64value, LE64test);
/* Close handle */
cresult = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(cresult == 0, "Verify result value is 0; got: %d", cresult);
}
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* RWops test cases */
static const SDLTest_TestCaseReference rwopsTest1 =
{ (SDLTest_TestCaseFp)rwops_testParamNegative, "rwops_testParamNegative", "Negative test for SDL_RWFromFile parameters", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest2 =
{ (SDLTest_TestCaseFp)rwops_testMem, "rwops_testMem", "Tests opening from memory", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest3 =
{ (SDLTest_TestCaseFp)rwops_testConstMem, "rwops_testConstMem", "Tests opening from (const) memory", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest4 =
{ (SDLTest_TestCaseFp)rwops_testFileRead, "rwops_testFileRead", "Tests reading from a file", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest5 =
{ (SDLTest_TestCaseFp)rwops_testFileWrite, "rwops_testFileWrite", "Test writing to a file", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest6 =
{ (SDLTest_TestCaseFp)rwops_testFPRead, "rwops_testFPRead", "Test reading from file pointer", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest7 =
{ (SDLTest_TestCaseFp)rwops_testFPWrite, "rwops_testFPWrite", "Test writing to file pointer", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest8 =
{ (SDLTest_TestCaseFp)rwops_testAllocFree, "rwops_testAllocFree", "Test alloc and free of RW context", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest9 =
{ (SDLTest_TestCaseFp)rwops_testFileWriteReadEndian, "rwops_testFileWriteReadEndian", "Test writing and reading via the Endian aware functions", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest10 =
{ (SDLTest_TestCaseFp)rwops_testCompareRWFromMemWithRWFromFile, "rwops_testCompareRWFromMemWithRWFromFile", "Compare RWFromMem and RWFromFile RWops for read and seek", TEST_ENABLED };
/* Sequence of RWops test cases */
static const SDLTest_TestCaseReference *rwopsTests[] = {
&rwopsTest1, &rwopsTest2, &rwopsTest3, &rwopsTest4, &rwopsTest5, &rwopsTest6,
&rwopsTest7, &rwopsTest8, &rwopsTest9, &rwopsTest10, NULL
};
/* RWops test suite (global) */
SDLTest_TestSuiteReference rwopsTestSuite = {
"RWops",
RWopsSetUp,
rwopsTests,
RWopsTearDown
};
| gpl-2.0 |
juston-li/Grouper_3.1.10 | drivers/video/tegra/host/nvhost_channel.c | 106 | 3114 | /*
* drivers/video/tegra/host/nvhost_channel.c
*
* Tegra Graphics Host Channel
*
* Copyright (c) 2010-2012, NVIDIA Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "nvhost_channel.h"
#include "dev.h"
#include "nvhost_job.h"
#include <trace/events/nvhost.h>
#include <linux/nvhost_ioctl.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#define NVHOST_CHANNEL_LOW_PRIO_MAX_WAIT 50
int nvhost_channel_init(struct nvhost_channel *ch,
struct nvhost_master *dev, int index)
{
int err;
struct nvhost_device *ndev;
/* Link nvhost_device to nvhost_channel */
err = host_channel_op(dev).init(ch, dev, index);
if (err < 0) {
dev_err(&dev->dev->dev, "failed to init channel %d\n",
index);
return err;
}
ndev = ch->dev;
ndev->channel = ch;
return 0;
}
int nvhost_channel_submit(struct nvhost_job *job)
{
/* Low priority submits wait until sync queue is empty. Ignores result
* from nvhost_cdma_flush, as we submit either when push buffer is
* empty or when we reach the timeout. */
if (job->priority < NVHOST_PRIORITY_MEDIUM)
(void)nvhost_cdma_flush(&job->ch->cdma,
NVHOST_CHANNEL_LOW_PRIO_MAX_WAIT);
return channel_op(job->ch).submit(job);
}
struct nvhost_channel *nvhost_getchannel(struct nvhost_channel *ch)
{
int err = 0;
mutex_lock(&ch->reflock);
if (ch->refcount == 0) {
if (ch->dev->init)
ch->dev->init(ch->dev);
err = nvhost_cdma_init(&ch->cdma);
} else if (ch->dev->exclusive) {
err = -EBUSY;
}
if (!err)
ch->refcount++;
mutex_unlock(&ch->reflock);
/* Keep alive modules that needs to be when a channel is open */
if (!err && ch->dev->keepalive)
nvhost_module_busy(ch->dev);
return err ? NULL : ch;
}
void nvhost_putchannel(struct nvhost_channel *ch, struct nvhost_hwctx *ctx)
{
BUG_ON(!channel_cdma_op(ch).stop);
if (ctx) {
mutex_lock(&ch->submitlock);
if (ch->cur_ctx == ctx)
ch->cur_ctx = NULL;
mutex_unlock(&ch->submitlock);
}
/* Allow keep-alive'd module to be turned off */
if (ch->dev->keepalive)
nvhost_module_idle(ch->dev);
mutex_lock(&ch->reflock);
if (ch->refcount == 1) {
channel_cdma_op(ch).stop(&ch->cdma);
nvhost_cdma_deinit(&ch->cdma);
nvhost_module_suspend(ch->dev);
}
ch->refcount--;
mutex_unlock(&ch->reflock);
}
int nvhost_channel_suspend(struct nvhost_channel *ch)
{
int ret = 0;
mutex_lock(&ch->reflock);
BUG_ON(!channel_cdma_op(ch).stop);
if (ch->refcount) {
ret = nvhost_module_suspend(ch->dev);
if (!ret)
channel_cdma_op(ch).stop(&ch->cdma);
}
mutex_unlock(&ch->reflock);
return ret;
}
| gpl-2.0 |
shouhu1993/NX511J_kernel | drivers/staging/android/ion/msm/secure_buffer.c | 362 | 4263 | /*
* Copyright (C) 2011 Google, Inc
* Copyright (c) 2011-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/highmem.h>
#include <linux/kernel.h>
#include <linux/kref.h>
#include <linux/msm_ion.h>
#include <linux/mutex.h>
#include <linux/scatterlist.h>
#include <linux/slab.h>
#include <soc/qcom/scm.h>
DEFINE_MUTEX(secure_buffer_mutex);
struct cp2_mem_chunks {
u32 chunk_list;
u32 chunk_list_size;
u32 chunk_size;
} __attribute__ ((__packed__));
struct cp2_lock_req {
struct cp2_mem_chunks chunks;
u32 mem_usage;
u32 lock;
} __attribute__ ((__packed__));
#define MEM_PROTECT_LOCK_ID2 0x0A
#define MEM_PROTECT_LOCK_ID2_FLAT 0x11
#define V2_CHUNK_SIZE SZ_1M
#define FEATURE_ID_CP 12
static int secure_buffer_change_chunk(u32 chunks,
u32 nchunks,
u32 chunk_size,
int lock)
{
struct cp2_lock_req request;
u32 resp;
int ret;
struct scm_desc desc = {0};
desc.args[0] = request.chunks.chunk_list = chunks;
desc.args[1] = request.chunks.chunk_list_size = nchunks;
desc.args[2] = request.chunks.chunk_size = chunk_size;
/* Usage is now always 0 */
desc.args[3] = request.mem_usage = 0;
desc.args[4] = request.lock = lock;
desc.args[5] = 0;
desc.arginfo = SCM_ARGS(6, SCM_RW, SCM_VAL, SCM_VAL, SCM_VAL, SCM_VAL,
SCM_VAL);
kmap_flush_unused();
kmap_atomic_flush_unused();
if (!is_scm_armv8()) {
ret = scm_call(SCM_SVC_MP, MEM_PROTECT_LOCK_ID2,
&request, sizeof(request), &resp, sizeof(resp));
} else {
ret = scm_call2(SCM_SIP_FNID(SCM_SVC_MP,
MEM_PROTECT_LOCK_ID2_FLAT), &desc);
resp = desc.ret[0];
}
return ret;
}
static int secure_buffer_change_table(struct sg_table *table, int lock)
{
int i, j;
int ret = -EINVAL;
u32 *chunk_list;
struct scatterlist *sg;
for_each_sg(table->sgl, sg, table->nents, i) {
int nchunks;
int size = sg->length;
int chunk_list_len;
phys_addr_t chunk_list_phys;
/*
* This should theoretically be a phys_addr_t but the protocol
* indicates this should be a u32.
*/
u32 base;
u64 tmp = sg_dma_address(sg);
WARN((tmp >> 32) & 0xffffffff,
"%s: there are ones in the upper 32 bits of the sg at %p! They will be truncated! Address: 0x%llx\n",
__func__, sg, tmp);
if (unlikely(!size || (size % V2_CHUNK_SIZE))) {
WARN(1,
"%s: chunk %d has invalid size: 0x%x. Must be a multiple of 0x%x\n",
__func__, i, size, V2_CHUNK_SIZE);
return -EINVAL;
}
base = (u32)tmp;
nchunks = size / V2_CHUNK_SIZE;
chunk_list_len = sizeof(u32)*nchunks;
chunk_list = kzalloc(chunk_list_len, GFP_KERNEL);
if (!chunk_list)
return -ENOMEM;
chunk_list_phys = virt_to_phys(chunk_list);
for (j = 0; j < nchunks; j++)
chunk_list[j] = base + j * V2_CHUNK_SIZE;
/*
* Flush the chunk list before sending the memory to the
* secure environment to ensure the data is actually present
* in RAM
*/
dmac_flush_range(chunk_list, chunk_list + chunk_list_len);
ret = secure_buffer_change_chunk(virt_to_phys(chunk_list),
nchunks, V2_CHUNK_SIZE, lock);
kfree(chunk_list);
}
return ret;
}
int msm_ion_secure_table(struct sg_table *table)
{
int ret;
mutex_lock(&secure_buffer_mutex);
ret = secure_buffer_change_table(table, 1);
mutex_unlock(&secure_buffer_mutex);
return ret;
}
int msm_ion_unsecure_table(struct sg_table *table)
{
int ret;
mutex_lock(&secure_buffer_mutex);
ret = secure_buffer_change_table(table, 0);
mutex_unlock(&secure_buffer_mutex);
return ret;
}
#define MAKE_CP_VERSION(major, minor, patch) \
(((major & 0x3FF) << 22) | ((minor & 0x3FF) << 12) | (patch & 0xFFF))
bool msm_secure_v2_is_supported(void)
{
int version = scm_get_feat_version(FEATURE_ID_CP);
/*
* if the version is < 1.1.0 then dynamic buffer allocation is
* not supported
*/
return version >= MAKE_CP_VERSION(1, 1, 0);
}
| gpl-2.0 |
Orange-OpenSource/linux | drivers/net/wireless/rtlwifi/rtl8192cu/trx.c | 362 | 21465 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "../wifi.h"
#include "../usb.h"
#include "../ps.h"
#include "../base.h"
#include "reg.h"
#include "def.h"
#include "phy.h"
#include "rf.h"
#include "dm.h"
#include "mac.h"
#include "trx.h"
static int _ConfigVerTOutEP(struct ieee80211_hw *hw)
{
u8 ep_cfg, txqsele;
u8 ep_nums = 0;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb_priv *usb_priv = rtl_usbpriv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(usb_priv);
rtlusb->out_queue_sel = 0;
ep_cfg = rtl_read_byte(rtlpriv, REG_TEST_SIE_OPTIONAL);
ep_cfg = (ep_cfg & USB_TEST_EP_MASK) >> USB_TEST_EP_SHIFT;
switch (ep_cfg) {
case 0: /* 2 bulk OUT, 1 bulk IN */
case 3:
rtlusb->out_queue_sel = TX_SELE_HQ | TX_SELE_LQ;
ep_nums = 2;
break;
case 1: /* 1 bulk IN/OUT => map all endpoint to Low queue */
case 2: /* 1 bulk IN, 1 bulk OUT => map all endpoint to High queue */
txqsele = rtl_read_byte(rtlpriv, REG_TEST_USB_TXQS);
if (txqsele & 0x0F) /* /map all endpoint to High queue */
rtlusb->out_queue_sel = TX_SELE_HQ;
else if (txqsele&0xF0) /* map all endpoint to Low queue */
rtlusb->out_queue_sel = TX_SELE_LQ;
ep_nums = 1;
break;
default:
break;
}
return (rtlusb->out_ep_nums == ep_nums) ? 0 : -EINVAL;
}
static int _ConfigVerNOutEP(struct ieee80211_hw *hw)
{
u8 ep_cfg;
u8 ep_nums = 0;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb_priv *usb_priv = rtl_usbpriv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(usb_priv);
rtlusb->out_queue_sel = 0;
/* Normal and High queue */
ep_cfg = rtl_read_byte(rtlpriv, (REG_NORMAL_SIE_EP + 1));
if (ep_cfg & USB_NORMAL_SIE_EP_MASK) {
rtlusb->out_queue_sel |= TX_SELE_HQ;
ep_nums++;
}
if ((ep_cfg >> USB_NORMAL_SIE_EP_SHIFT) & USB_NORMAL_SIE_EP_MASK) {
rtlusb->out_queue_sel |= TX_SELE_NQ;
ep_nums++;
}
/* Low queue */
ep_cfg = rtl_read_byte(rtlpriv, (REG_NORMAL_SIE_EP + 2));
if (ep_cfg & USB_NORMAL_SIE_EP_MASK) {
rtlusb->out_queue_sel |= TX_SELE_LQ;
ep_nums++;
}
return (rtlusb->out_ep_nums == ep_nums) ? 0 : -EINVAL;
}
static void _TwoOutEpMapping(struct ieee80211_hw *hw, bool bIsChipB,
bool bwificfg, struct rtl_ep_map *ep_map)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
if (bwificfg) { /* for WMM */
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"USB Chip-B & WMM Setting.....\n");
ep_map->ep_mapping[RTL_TXQ_BE] = 2;
ep_map->ep_mapping[RTL_TXQ_BK] = 3;
ep_map->ep_mapping[RTL_TXQ_VI] = 3;
ep_map->ep_mapping[RTL_TXQ_VO] = 2;
ep_map->ep_mapping[RTL_TXQ_MGT] = 2;
ep_map->ep_mapping[RTL_TXQ_BCN] = 2;
ep_map->ep_mapping[RTL_TXQ_HI] = 2;
} else { /* typical setting */
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"USB typical Setting.....\n");
ep_map->ep_mapping[RTL_TXQ_BE] = 3;
ep_map->ep_mapping[RTL_TXQ_BK] = 3;
ep_map->ep_mapping[RTL_TXQ_VI] = 2;
ep_map->ep_mapping[RTL_TXQ_VO] = 2;
ep_map->ep_mapping[RTL_TXQ_MGT] = 2;
ep_map->ep_mapping[RTL_TXQ_BCN] = 2;
ep_map->ep_mapping[RTL_TXQ_HI] = 2;
}
}
static void _ThreeOutEpMapping(struct ieee80211_hw *hw, bool bwificfg,
struct rtl_ep_map *ep_map)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
if (bwificfg) { /* for WMM */
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"USB 3EP Setting for WMM.....\n");
ep_map->ep_mapping[RTL_TXQ_BE] = 5;
ep_map->ep_mapping[RTL_TXQ_BK] = 3;
ep_map->ep_mapping[RTL_TXQ_VI] = 3;
ep_map->ep_mapping[RTL_TXQ_VO] = 2;
ep_map->ep_mapping[RTL_TXQ_MGT] = 2;
ep_map->ep_mapping[RTL_TXQ_BCN] = 2;
ep_map->ep_mapping[RTL_TXQ_HI] = 2;
} else { /* typical setting */
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"USB 3EP Setting for typical.....\n");
ep_map->ep_mapping[RTL_TXQ_BE] = 5;
ep_map->ep_mapping[RTL_TXQ_BK] = 5;
ep_map->ep_mapping[RTL_TXQ_VI] = 3;
ep_map->ep_mapping[RTL_TXQ_VO] = 2;
ep_map->ep_mapping[RTL_TXQ_MGT] = 2;
ep_map->ep_mapping[RTL_TXQ_BCN] = 2;
ep_map->ep_mapping[RTL_TXQ_HI] = 2;
}
}
static void _OneOutEpMapping(struct ieee80211_hw *hw, struct rtl_ep_map *ep_map)
{
ep_map->ep_mapping[RTL_TXQ_BE] = 2;
ep_map->ep_mapping[RTL_TXQ_BK] = 2;
ep_map->ep_mapping[RTL_TXQ_VI] = 2;
ep_map->ep_mapping[RTL_TXQ_VO] = 2;
ep_map->ep_mapping[RTL_TXQ_MGT] = 2;
ep_map->ep_mapping[RTL_TXQ_BCN] = 2;
ep_map->ep_mapping[RTL_TXQ_HI] = 2;
}
static int _out_ep_mapping(struct ieee80211_hw *hw)
{
int err = 0;
bool bIsChipN, bwificfg = false;
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_usb_priv *usb_priv = rtl_usbpriv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(usb_priv);
struct rtl_ep_map *ep_map = &(rtlusb->ep_map);
bIsChipN = IS_NORMAL_CHIP(rtlhal->version);
switch (rtlusb->out_ep_nums) {
case 2:
_TwoOutEpMapping(hw, bIsChipN, bwificfg, ep_map);
break;
case 3:
/* Test chip doesn't support three out EPs. */
if (!bIsChipN) {
err = -EINVAL;
goto err_out;
}
_ThreeOutEpMapping(hw, bIsChipN, ep_map);
break;
case 1:
_OneOutEpMapping(hw, ep_map);
break;
default:
err = -EINVAL;
break;
}
err_out:
return err;
}
/* endpoint mapping */
int rtl8192cu_endpoint_mapping(struct ieee80211_hw *hw)
{
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
int error = 0;
if (likely(IS_NORMAL_CHIP(rtlhal->version)))
error = _ConfigVerNOutEP(hw);
else
error = _ConfigVerTOutEP(hw);
if (error)
goto err_out;
error = _out_ep_mapping(hw);
if (error)
goto err_out;
err_out:
return error;
}
u16 rtl8192cu_mq_to_hwq(__le16 fc, u16 mac80211_queue_index)
{
u16 hw_queue_index;
if (unlikely(ieee80211_is_beacon(fc))) {
hw_queue_index = RTL_TXQ_BCN;
goto out;
}
if (ieee80211_is_mgmt(fc)) {
hw_queue_index = RTL_TXQ_MGT;
goto out;
}
switch (mac80211_queue_index) {
case 0:
hw_queue_index = RTL_TXQ_VO;
break;
case 1:
hw_queue_index = RTL_TXQ_VI;
break;
case 2:
hw_queue_index = RTL_TXQ_BE;
break;
case 3:
hw_queue_index = RTL_TXQ_BK;
break;
default:
hw_queue_index = RTL_TXQ_BE;
RT_ASSERT(false, "QSLT_BE queue, skb_queue:%d\n",
mac80211_queue_index);
break;
}
out:
return hw_queue_index;
}
static enum rtl_desc_qsel _rtl8192cu_mq_to_descq(struct ieee80211_hw *hw,
__le16 fc, u16 mac80211_queue_index)
{
enum rtl_desc_qsel qsel;
struct rtl_priv *rtlpriv = rtl_priv(hw);
if (unlikely(ieee80211_is_beacon(fc))) {
qsel = QSLT_BEACON;
goto out;
}
if (ieee80211_is_mgmt(fc)) {
qsel = QSLT_MGNT;
goto out;
}
switch (mac80211_queue_index) {
case 0: /* VO */
qsel = QSLT_VO;
RT_TRACE(rtlpriv, COMP_USB, DBG_DMESG,
"VO queue, set qsel = 0x%x\n", QSLT_VO);
break;
case 1: /* VI */
qsel = QSLT_VI;
RT_TRACE(rtlpriv, COMP_USB, DBG_DMESG,
"VI queue, set qsel = 0x%x\n", QSLT_VI);
break;
case 3: /* BK */
qsel = QSLT_BK;
RT_TRACE(rtlpriv, COMP_USB, DBG_DMESG,
"BK queue, set qsel = 0x%x\n", QSLT_BK);
break;
case 2: /* BE */
default:
qsel = QSLT_BE;
RT_TRACE(rtlpriv, COMP_USB, DBG_DMESG,
"BE queue, set qsel = 0x%x\n", QSLT_BE);
break;
}
out:
return qsel;
}
/* =============================================================== */
/*----------------------------------------------------------------------
*
* Rx handler
*
*---------------------------------------------------------------------- */
bool rtl92cu_rx_query_desc(struct ieee80211_hw *hw,
struct rtl_stats *stats,
struct ieee80211_rx_status *rx_status,
u8 *p_desc, struct sk_buff *skb)
{
struct rx_fwinfo_92c *p_drvinfo;
struct rx_desc_92c *pdesc = (struct rx_desc_92c *)p_desc;
u32 phystatus = GET_RX_DESC_PHY_STATUS(pdesc);
stats->length = (u16) GET_RX_DESC_PKT_LEN(pdesc);
stats->rx_drvinfo_size = (u8)GET_RX_DESC_DRVINFO_SIZE(pdesc) *
RX_DRV_INFO_SIZE_UNIT;
stats->rx_bufshift = (u8) (GET_RX_DESC_SHIFT(pdesc) & 0x03);
stats->icv = (u16) GET_RX_DESC_ICV(pdesc);
stats->crc = (u16) GET_RX_DESC_CRC32(pdesc);
stats->hwerror = (stats->crc | stats->icv);
stats->decrypted = !GET_RX_DESC_SWDEC(pdesc);
stats->rate = (u8) GET_RX_DESC_RX_MCS(pdesc);
stats->shortpreamble = (u16) GET_RX_DESC_SPLCP(pdesc);
stats->isampdu = (bool) (GET_RX_DESC_PAGGR(pdesc) == 1);
stats->isampdu = (bool) ((GET_RX_DESC_PAGGR(pdesc) == 1)
&& (GET_RX_DESC_FAGGR(pdesc) == 1));
stats->timestamp_low = GET_RX_DESC_TSFL(pdesc);
stats->rx_is40Mhzpacket = (bool) GET_RX_DESC_BW(pdesc);
rx_status->freq = hw->conf.chandef.chan->center_freq;
rx_status->band = hw->conf.chandef.chan->band;
if (GET_RX_DESC_CRC32(pdesc))
rx_status->flag |= RX_FLAG_FAILED_FCS_CRC;
if (!GET_RX_DESC_SWDEC(pdesc))
rx_status->flag |= RX_FLAG_DECRYPTED;
if (GET_RX_DESC_BW(pdesc))
rx_status->flag |= RX_FLAG_40MHZ;
if (GET_RX_DESC_RX_HT(pdesc))
rx_status->flag |= RX_FLAG_HT;
rx_status->flag |= RX_FLAG_MACTIME_START;
if (stats->decrypted)
rx_status->flag |= RX_FLAG_DECRYPTED;
rx_status->rate_idx = rtlwifi_rate_mapping(hw,
(bool)GET_RX_DESC_RX_HT(pdesc),
(u8)GET_RX_DESC_RX_MCS(pdesc),
(bool)GET_RX_DESC_PAGGR(pdesc));
rx_status->mactime = GET_RX_DESC_TSFL(pdesc);
if (phystatus) {
p_drvinfo = (struct rx_fwinfo_92c *)(pdesc + RTL_RX_DESC_SIZE);
rtl92c_translate_rx_signal_stuff(hw, skb, stats, pdesc,
p_drvinfo);
}
/*rx_status->qual = stats->signal; */
rx_status->signal = stats->rssi + 10;
/*rx_status->noise = -stats->noise; */
return true;
}
#define RTL_RX_DRV_INFO_UNIT 8
static void _rtl_rx_process(struct ieee80211_hw *hw, struct sk_buff *skb)
{
struct ieee80211_rx_status *rx_status =
(struct ieee80211_rx_status *)IEEE80211_SKB_RXCB(skb);
u32 skb_len, pkt_len, drvinfo_len;
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 *rxdesc;
struct rtl_stats stats = {
.signal = 0,
.noise = -98,
.rate = 0,
};
struct rx_fwinfo_92c *p_drvinfo;
bool bv;
__le16 fc;
struct ieee80211_hdr *hdr;
memset(rx_status, 0, sizeof(*rx_status));
rxdesc = skb->data;
skb_len = skb->len;
drvinfo_len = (GET_RX_DESC_DRVINFO_SIZE(rxdesc) * RTL_RX_DRV_INFO_UNIT);
pkt_len = GET_RX_DESC_PKT_LEN(rxdesc);
/* TODO: Error recovery. drop this skb or something. */
WARN_ON(skb_len < (pkt_len + RTL_RX_DESC_SIZE + drvinfo_len));
stats.length = (u16) GET_RX_DESC_PKT_LEN(rxdesc);
stats.rx_drvinfo_size = (u8)GET_RX_DESC_DRVINFO_SIZE(rxdesc) *
RX_DRV_INFO_SIZE_UNIT;
stats.rx_bufshift = (u8) (GET_RX_DESC_SHIFT(rxdesc) & 0x03);
stats.icv = (u16) GET_RX_DESC_ICV(rxdesc);
stats.crc = (u16) GET_RX_DESC_CRC32(rxdesc);
stats.hwerror = (stats.crc | stats.icv);
stats.decrypted = !GET_RX_DESC_SWDEC(rxdesc);
stats.rate = (u8) GET_RX_DESC_RX_MCS(rxdesc);
stats.shortpreamble = (u16) GET_RX_DESC_SPLCP(rxdesc);
stats.isampdu = (bool) ((GET_RX_DESC_PAGGR(rxdesc) == 1)
&& (GET_RX_DESC_FAGGR(rxdesc) == 1));
stats.timestamp_low = GET_RX_DESC_TSFL(rxdesc);
stats.rx_is40Mhzpacket = (bool) GET_RX_DESC_BW(rxdesc);
/* TODO: is center_freq changed when doing scan? */
/* TODO: Shall we add protection or just skip those two step? */
rx_status->freq = hw->conf.chandef.chan->center_freq;
rx_status->band = hw->conf.chandef.chan->band;
if (GET_RX_DESC_CRC32(rxdesc))
rx_status->flag |= RX_FLAG_FAILED_FCS_CRC;
if (!GET_RX_DESC_SWDEC(rxdesc))
rx_status->flag |= RX_FLAG_DECRYPTED;
if (GET_RX_DESC_BW(rxdesc))
rx_status->flag |= RX_FLAG_40MHZ;
if (GET_RX_DESC_RX_HT(rxdesc))
rx_status->flag |= RX_FLAG_HT;
/* Data rate */
rx_status->rate_idx = rtlwifi_rate_mapping(hw,
(bool)GET_RX_DESC_RX_HT(rxdesc),
(u8)GET_RX_DESC_RX_MCS(rxdesc),
(bool)GET_RX_DESC_PAGGR(rxdesc));
/* There is a phy status after this rx descriptor. */
if (GET_RX_DESC_PHY_STATUS(rxdesc)) {
p_drvinfo = (struct rx_fwinfo_92c *)(rxdesc + RTL_RX_DESC_SIZE);
rtl92c_translate_rx_signal_stuff(hw, skb, &stats,
(struct rx_desc_92c *)rxdesc, p_drvinfo);
}
skb_pull(skb, (drvinfo_len + RTL_RX_DESC_SIZE));
hdr = (struct ieee80211_hdr *)(skb->data);
fc = hdr->frame_control;
bv = ieee80211_is_probe_resp(fc);
if (bv)
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"Got probe response frame\n");
if (ieee80211_is_beacon(fc))
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG, "Got beacon frame\n");
if (ieee80211_is_data(fc))
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG, "Got data frame\n");
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"Fram: fc = 0x%X addr1 = 0x%02X:0x%02X:0x%02X:0x%02X:0x%02X:0x%02X\n",
fc,
(u32)hdr->addr1[0], (u32)hdr->addr1[1],
(u32)hdr->addr1[2], (u32)hdr->addr1[3],
(u32)hdr->addr1[4], (u32)hdr->addr1[5]);
memcpy(IEEE80211_SKB_RXCB(skb), rx_status, sizeof(*rx_status));
ieee80211_rx(hw, skb);
}
void rtl8192cu_rx_hdl(struct ieee80211_hw *hw, struct sk_buff * skb)
{
_rtl_rx_process(hw, skb);
}
void rtl8192c_rx_segregate_hdl(
struct ieee80211_hw *hw,
struct sk_buff *skb,
struct sk_buff_head *skb_list)
{
}
/*----------------------------------------------------------------------
*
* Tx handler
*
*---------------------------------------------------------------------- */
void rtl8192c_tx_cleanup(struct ieee80211_hw *hw, struct sk_buff *skb)
{
}
int rtl8192c_tx_post_hdl(struct ieee80211_hw *hw, struct urb *urb,
struct sk_buff *skb)
{
return 0;
}
struct sk_buff *rtl8192c_tx_aggregate_hdl(struct ieee80211_hw *hw,
struct sk_buff_head *list)
{
return skb_dequeue(list);
}
/*======================================== trx ===============================*/
static void _rtl_fill_usb_tx_desc(u8 *txdesc)
{
SET_TX_DESC_OWN(txdesc, 1);
SET_TX_DESC_LAST_SEG(txdesc, 1);
SET_TX_DESC_FIRST_SEG(txdesc, 1);
}
/**
* For HW recovery information
*/
static void _rtl_tx_desc_checksum(u8 *txdesc)
{
u16 *ptr = (u16 *)txdesc;
u16 checksum = 0;
u32 index;
/* Clear first */
SET_TX_DESC_TX_DESC_CHECKSUM(txdesc, 0);
for (index = 0; index < 16; index++)
checksum = checksum ^ (*(ptr + index));
SET_TX_DESC_TX_DESC_CHECKSUM(txdesc, checksum);
}
void rtl92cu_tx_fill_desc(struct ieee80211_hw *hw,
struct ieee80211_hdr *hdr, u8 *pdesc_tx,
struct ieee80211_tx_info *info,
struct ieee80211_sta *sta,
struct sk_buff *skb,
u8 queue_index,
struct rtl_tcb_desc *tcb_desc)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
bool defaultadapter = true;
u8 *qc = ieee80211_get_qos_ctl(hdr);
u8 tid = qc[0] & IEEE80211_QOS_CTL_TID_MASK;
u16 seq_number;
__le16 fc = hdr->frame_control;
u8 rate_flag = info->control.rates[0].flags;
u16 pktlen = skb->len;
enum rtl_desc_qsel fw_qsel = _rtl8192cu_mq_to_descq(hw, fc,
skb_get_queue_mapping(skb));
u8 *txdesc;
seq_number = (le16_to_cpu(hdr->seq_ctrl) & IEEE80211_SCTL_SEQ) >> 4;
rtl_get_tcb_desc(hw, info, sta, skb, tcb_desc);
txdesc = (u8 *)skb_push(skb, RTL_TX_HEADER_SIZE);
memset(txdesc, 0, RTL_TX_HEADER_SIZE);
SET_TX_DESC_PKT_SIZE(txdesc, pktlen);
SET_TX_DESC_LINIP(txdesc, 0);
SET_TX_DESC_PKT_OFFSET(txdesc, RTL_DUMMY_OFFSET);
SET_TX_DESC_OFFSET(txdesc, RTL_TX_HEADER_SIZE);
SET_TX_DESC_TX_RATE(txdesc, tcb_desc->hw_rate);
if (tcb_desc->use_shortgi || tcb_desc->use_shortpreamble)
SET_TX_DESC_DATA_SHORTGI(txdesc, 1);
if (mac->tids[tid].agg.agg_state == RTL_AGG_ON &&
info->flags & IEEE80211_TX_CTL_AMPDU) {
SET_TX_DESC_AGG_ENABLE(txdesc, 1);
SET_TX_DESC_MAX_AGG_NUM(txdesc, 0x14);
} else {
SET_TX_DESC_AGG_BREAK(txdesc, 1);
}
SET_TX_DESC_SEQ(txdesc, seq_number);
SET_TX_DESC_RTS_ENABLE(txdesc, ((tcb_desc->rts_enable &&
!tcb_desc->cts_enable) ? 1 : 0));
SET_TX_DESC_HW_RTS_ENABLE(txdesc, ((tcb_desc->rts_enable ||
tcb_desc->cts_enable) ? 1 : 0));
SET_TX_DESC_CTS2SELF(txdesc, ((tcb_desc->cts_enable) ? 1 : 0));
SET_TX_DESC_RTS_STBC(txdesc, ((tcb_desc->rts_stbc) ? 1 : 0));
SET_TX_DESC_RTS_RATE(txdesc, tcb_desc->rts_rate);
SET_TX_DESC_RTS_BW(txdesc, 0);
SET_TX_DESC_RTS_SC(txdesc, tcb_desc->rts_sc);
SET_TX_DESC_RTS_SHORT(txdesc,
((tcb_desc->rts_rate <= DESC92_RATE54M) ?
(tcb_desc->rts_use_shortpreamble ? 1 : 0)
: (tcb_desc->rts_use_shortgi ? 1 : 0)));
if (mac->bw_40) {
if (rate_flag & IEEE80211_TX_RC_DUP_DATA) {
SET_TX_DESC_DATA_BW(txdesc, 1);
SET_TX_DESC_DATA_SC(txdesc, 3);
} else if(rate_flag & IEEE80211_TX_RC_40_MHZ_WIDTH){
SET_TX_DESC_DATA_BW(txdesc, 1);
SET_TX_DESC_DATA_SC(txdesc, mac->cur_40_prime_sc);
} else {
SET_TX_DESC_DATA_BW(txdesc, 0);
SET_TX_DESC_DATA_SC(txdesc, 0);
}
} else {
SET_TX_DESC_DATA_BW(txdesc, 0);
SET_TX_DESC_DATA_SC(txdesc, 0);
}
rcu_read_lock();
sta = ieee80211_find_sta(mac->vif, mac->bssid);
if (sta) {
u8 ampdu_density = sta->ht_cap.ampdu_density;
SET_TX_DESC_AMPDU_DENSITY(txdesc, ampdu_density);
}
rcu_read_unlock();
if (info->control.hw_key) {
struct ieee80211_key_conf *keyconf = info->control.hw_key;
switch (keyconf->cipher) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
case WLAN_CIPHER_SUITE_TKIP:
SET_TX_DESC_SEC_TYPE(txdesc, 0x1);
break;
case WLAN_CIPHER_SUITE_CCMP:
SET_TX_DESC_SEC_TYPE(txdesc, 0x3);
break;
default:
SET_TX_DESC_SEC_TYPE(txdesc, 0x0);
break;
}
}
SET_TX_DESC_PKT_ID(txdesc, 0);
SET_TX_DESC_QUEUE_SEL(txdesc, fw_qsel);
SET_TX_DESC_DATA_RATE_FB_LIMIT(txdesc, 0x1F);
SET_TX_DESC_RTS_RATE_FB_LIMIT(txdesc, 0xF);
SET_TX_DESC_DISABLE_FB(txdesc, 0);
SET_TX_DESC_USE_RATE(txdesc, tcb_desc->use_driver_rate ? 1 : 0);
if (ieee80211_is_data_qos(fc)) {
if (mac->rdg_en) {
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE,
"Enable RDG function\n");
SET_TX_DESC_RDG_ENABLE(txdesc, 1);
SET_TX_DESC_HTC(txdesc, 1);
}
}
if (rtlpriv->dm.useramask) {
SET_TX_DESC_RATE_ID(txdesc, tcb_desc->ratr_index);
SET_TX_DESC_MACID(txdesc, tcb_desc->mac_id);
} else {
SET_TX_DESC_RATE_ID(txdesc, 0xC + tcb_desc->ratr_index);
SET_TX_DESC_MACID(txdesc, tcb_desc->ratr_index);
}
if ((!ieee80211_is_data_qos(fc)) && ppsc->leisure_ps &&
ppsc->fwctrl_lps) {
SET_TX_DESC_HWSEQ_EN(txdesc, 1);
SET_TX_DESC_PKT_ID(txdesc, 8);
if (!defaultadapter)
SET_TX_DESC_QOS(txdesc, 1);
}
if (ieee80211_has_morefrags(fc))
SET_TX_DESC_MORE_FRAG(txdesc, 1);
if (is_multicast_ether_addr(ieee80211_get_DA(hdr)) ||
is_broadcast_ether_addr(ieee80211_get_DA(hdr)))
SET_TX_DESC_BMC(txdesc, 1);
_rtl_fill_usb_tx_desc(txdesc);
_rtl_tx_desc_checksum(txdesc);
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE, "==>\n");
}
void rtl92cu_fill_fake_txdesc(struct ieee80211_hw *hw, u8 * pDesc,
u32 buffer_len, bool bIsPsPoll)
{
/* Clear all status */
memset(pDesc, 0, RTL_TX_HEADER_SIZE);
SET_TX_DESC_FIRST_SEG(pDesc, 1); /* bFirstSeg; */
SET_TX_DESC_LAST_SEG(pDesc, 1); /* bLastSeg; */
SET_TX_DESC_OFFSET(pDesc, RTL_TX_HEADER_SIZE); /* Offset = 32 */
SET_TX_DESC_PKT_SIZE(pDesc, buffer_len); /* Buffer size + command hdr */
SET_TX_DESC_QUEUE_SEL(pDesc, QSLT_MGNT); /* Fixed queue of Mgnt queue */
/* Set NAVUSEHDR to prevent Ps-poll AId filed to be changed to error
* vlaue by Hw. */
if (bIsPsPoll) {
SET_TX_DESC_NAV_USE_HDR(pDesc, 1);
} else {
SET_TX_DESC_HWSEQ_EN(pDesc, 1); /* Hw set sequence number */
SET_TX_DESC_PKT_ID(pDesc, 0x100); /* set bit3 to 1. */
}
SET_TX_DESC_USE_RATE(pDesc, 1); /* use data rate which is set by Sw */
SET_TX_DESC_OWN(pDesc, 1);
SET_TX_DESC_TX_RATE(pDesc, DESC92_RATE1M);
_rtl_tx_desc_checksum(pDesc);
}
void rtl92cu_tx_fill_cmddesc(struct ieee80211_hw *hw,
u8 *pdesc, bool firstseg,
bool lastseg, struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 fw_queue = QSLT_BEACON;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)(skb->data);
__le16 fc = hdr->frame_control;
memset((void *)pdesc, 0, RTL_TX_HEADER_SIZE);
if (firstseg)
SET_TX_DESC_OFFSET(pdesc, RTL_TX_HEADER_SIZE);
SET_TX_DESC_TX_RATE(pdesc, DESC92_RATE1M);
SET_TX_DESC_SEQ(pdesc, 0);
SET_TX_DESC_LINIP(pdesc, 0);
SET_TX_DESC_QUEUE_SEL(pdesc, fw_queue);
SET_TX_DESC_FIRST_SEG(pdesc, 1);
SET_TX_DESC_LAST_SEG(pdesc, 1);
SET_TX_DESC_RATE_ID(pdesc, 7);
SET_TX_DESC_MACID(pdesc, 0);
SET_TX_DESC_OWN(pdesc, 1);
SET_TX_DESC_PKT_SIZE(pdesc, (u16)skb->len);
SET_TX_DESC_FIRST_SEG(pdesc, 1);
SET_TX_DESC_LAST_SEG(pdesc, 1);
SET_TX_DESC_OFFSET(pdesc, 0x20);
SET_TX_DESC_USE_RATE(pdesc, 1);
if (!ieee80211_is_data_qos(fc)) {
SET_TX_DESC_HWSEQ_EN(pdesc, 1);
SET_TX_DESC_PKT_ID(pdesc, 8);
}
RT_PRINT_DATA(rtlpriv, COMP_CMD, DBG_LOUD, "H2C Tx Cmd Content",
pdesc, RTL_TX_DESC_SIZE);
}
bool rtl92cu_cmd_send_packet(struct ieee80211_hw *hw, struct sk_buff *skb)
{
return true;
}
| gpl-2.0 |
duydb2/android_kernel_sony_msm8x60 | drivers/bluetooth/bluesleep.c | 618 | 18562 | /*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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.
Copyright (C) 2006-2007 - Motorola
Copyright (c) 2008-2010, Code Aurora Forum. All rights reserved.
Date Author Comment
----------- -------------- --------------------------------
2006-Apr-28 Motorola The kernel module for running the Bluetooth(R)
Sleep-Mode Protocol from the Host side
2006-Sep-08 Motorola Added workqueue for handling sleep work.
2007-Jan-24 Motorola Added mbm_handle_ioi() call to ISR.
*/
#include <linux/module.h> /* kernel module definitions */
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/notifier.h>
#include <linux/proc_fs.h>
#include <linux/spinlock.h>
#include <linux/timer.h>
#include <linux/uaccess.h>
#include <linux/version.h>
#include <linux/workqueue.h>
#include <linux/platform_device.h>
#include <linux/irq.h>
#include <linux/param.h>
#include <linux/bitops.h>
#include <linux/termios.h>
#include <mach/gpio.h>
#include <mach/msm_serial_hs.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h> /* event notifications */
#include "hci_uart.h"
#define BT_SLEEP_DBG
#ifndef BT_SLEEP_DBG
#define BT_DBG(fmt, arg...)
#endif
/*
* Defines
*/
#define VERSION "1.1"
#define PROC_DIR "bluetooth/sleep"
struct bluesleep_info {
unsigned host_wake;
unsigned ext_wake;
unsigned host_wake_irq;
struct uart_port *uport;
};
/* work function */
static void bluesleep_sleep_work(struct work_struct *work);
/* work queue */
DECLARE_DELAYED_WORK(sleep_workqueue, bluesleep_sleep_work);
/* Macros for handling sleep work */
#define bluesleep_rx_busy() schedule_delayed_work(&sleep_workqueue, 0)
#define bluesleep_tx_busy() schedule_delayed_work(&sleep_workqueue, 0)
#define bluesleep_rx_idle() schedule_delayed_work(&sleep_workqueue, 0)
#define bluesleep_tx_idle() schedule_delayed_work(&sleep_workqueue, 0)
/* 1 second timeout */
#define TX_TIMER_INTERVAL 1
/* state variable names and bit positions */
#define BT_PROTO 0x01
#define BT_TXDATA 0x02
#define BT_ASLEEP 0x04
/* global pointer to a single hci device. */
static struct hci_dev *bluesleep_hdev;
static struct bluesleep_info *bsi;
/* module usage */
static atomic_t open_count = ATOMIC_INIT(1);
/*
* Local function prototypes
*/
static int bluesleep_hci_event(struct notifier_block *this,
unsigned long event, void *data);
/*
* Global variables
*/
/** Global state flags */
static unsigned long flags;
/** Tasklet to respond to change in hostwake line */
static struct tasklet_struct hostwake_task;
/** Transmission timer */
static struct timer_list tx_timer;
/** Lock for state transitions */
static spinlock_t rw_lock;
/** Notifier block for HCI events */
struct notifier_block hci_event_nblock = {
.notifier_call = bluesleep_hci_event,
};
struct proc_dir_entry *bluetooth_dir, *sleep_dir;
/*
* Local functions
*/
static void hsuart_power(int on)
{
if (on) {
msm_hs_request_clock_on(bsi->uport);
msm_hs_set_mctrl(bsi->uport, TIOCM_RTS);
} else {
msm_hs_set_mctrl(bsi->uport, 0);
msm_hs_request_clock_off(bsi->uport);
}
}
/**
* @return 1 if the Host can go to sleep, 0 otherwise.
*/
static inline int bluesleep_can_sleep(void)
{
/* check if MSM_WAKE_BT_GPIO and BT_WAKE_MSM_GPIO are both deasserted */
return gpio_get_value(bsi->ext_wake) &&
gpio_get_value(bsi->host_wake) &&
(bsi->uport != NULL);
}
void bluesleep_sleep_wakeup(void)
{
if (test_bit(BT_ASLEEP, &flags)) {
BT_DBG("waking up...");
/* Start the timer */
mod_timer(&tx_timer, jiffies + (TX_TIMER_INTERVAL * HZ));
gpio_set_value(bsi->ext_wake, 0);
clear_bit(BT_ASLEEP, &flags);
/*Activating UART */
hsuart_power(1);
}
}
/**
* @brief@ main sleep work handling function which update the flags
* and activate and deactivate UART ,check FIFO.
*/
static void bluesleep_sleep_work(struct work_struct *work)
{
if (bluesleep_can_sleep()) {
/* already asleep, this is an error case */
if (test_bit(BT_ASLEEP, &flags)) {
BT_DBG("already asleep");
return;
}
if (msm_hs_tx_empty(bsi->uport)) {
BT_DBG("going to sleep...");
set_bit(BT_ASLEEP, &flags);
/*Deactivating UART */
hsuart_power(0);
} else {
mod_timer(&tx_timer, jiffies + (TX_TIMER_INTERVAL * HZ));
return;
}
} else {
bluesleep_sleep_wakeup();
}
}
/**
* A tasklet function that runs in tasklet context and reads the value
* of the HOST_WAKE GPIO pin and further defer the work.
* @param data Not used.
*/
static void bluesleep_hostwake_task(unsigned long data)
{
BT_DBG("hostwake line change");
spin_lock(&rw_lock);
if (gpio_get_value(bsi->host_wake))
bluesleep_rx_busy();
else
bluesleep_rx_idle();
spin_unlock(&rw_lock);
}
/**
* Handles proper timer action when outgoing data is delivered to the
* HCI line discipline. Sets BT_TXDATA.
*/
static void bluesleep_outgoing_data(void)
{
unsigned long irq_flags;
spin_lock_irqsave(&rw_lock, irq_flags);
/* log data passing by */
set_bit(BT_TXDATA, &flags);
/* if the tx side is sleeping... */
if (gpio_get_value(bsi->ext_wake)) {
BT_DBG("tx was sleeping");
bluesleep_sleep_wakeup();
}
spin_unlock_irqrestore(&rw_lock, irq_flags);
}
/**
* Handles HCI device events.
* @param this Not used.
* @param event The event that occurred.
* @param data The HCI device associated with the event.
* @return <code>NOTIFY_DONE</code>.
*/
static int bluesleep_hci_event(struct notifier_block *this,
unsigned long event, void *data)
{
struct hci_dev *hdev = (struct hci_dev *) data;
struct hci_uart *hu;
struct uart_state *state;
if (!hdev)
return NOTIFY_DONE;
switch (event) {
case HCI_DEV_REG:
if (!bluesleep_hdev) {
bluesleep_hdev = hdev;
hu = (struct hci_uart *) hdev->driver_data;
state = (struct uart_state *) hu->tty->driver_data;
bsi->uport = state->uart_port;
}
break;
case HCI_DEV_UNREG:
bluesleep_hdev = NULL;
bsi->uport = NULL;
break;
case HCI_DEV_WRITE:
bluesleep_outgoing_data();
break;
}
return NOTIFY_DONE;
}
/**
* Handles transmission timer expiration.
* @param data Not used.
*/
static void bluesleep_tx_timer_expire(unsigned long data)
{
unsigned long irq_flags;
spin_lock_irqsave(&rw_lock, irq_flags);
BT_DBG("Tx timer expired");
/* were we silent during the last timeout? */
if (!test_bit(BT_TXDATA, &flags)) {
BT_DBG("Tx has been idle");
gpio_set_value(bsi->ext_wake, 1);
bluesleep_tx_idle();
} else {
BT_DBG("Tx data during last period");
mod_timer(&tx_timer, jiffies + (TX_TIMER_INTERVAL*HZ));
}
/* clear the incoming data flag */
clear_bit(BT_TXDATA, &flags);
spin_unlock_irqrestore(&rw_lock, irq_flags);
}
/**
* Schedules a tasklet to run when receiving an interrupt on the
* <code>HOST_WAKE</code> GPIO pin.
* @param irq Not used.
* @param dev_id Not used.
*/
static irqreturn_t bluesleep_hostwake_isr(int irq, void *dev_id)
{
/* schedule a tasklet to handle the change in the host wake line */
tasklet_schedule(&hostwake_task);
return IRQ_HANDLED;
}
/**
* Starts the Sleep-Mode Protocol on the Host.
* @return On success, 0. On error, -1, and <code>errno</code> is set
* appropriately.
*/
static int bluesleep_start(void)
{
int retval;
unsigned long irq_flags;
spin_lock_irqsave(&rw_lock, irq_flags);
if (test_bit(BT_PROTO, &flags)) {
spin_unlock_irqrestore(&rw_lock, irq_flags);
return 0;
}
spin_unlock_irqrestore(&rw_lock, irq_flags);
if (!atomic_dec_and_test(&open_count)) {
atomic_inc(&open_count);
return -EBUSY;
}
/* start the timer */
mod_timer(&tx_timer, jiffies + (TX_TIMER_INTERVAL*HZ));
/* assert BT_WAKE */
gpio_set_value(bsi->ext_wake, 0);
retval = request_irq(bsi->host_wake_irq, bluesleep_hostwake_isr,
IRQF_DISABLED | IRQF_TRIGGER_FALLING,
"bluetooth hostwake", NULL);
if (retval < 0) {
BT_ERR("Couldn't acquire BT_HOST_WAKE IRQ");
goto fail;
}
retval = enable_irq_wake(bsi->host_wake_irq);
if (retval < 0) {
BT_ERR("Couldn't enable BT_HOST_WAKE as wakeup interrupt");
free_irq(bsi->host_wake_irq, NULL);
goto fail;
}
set_bit(BT_PROTO, &flags);
return 0;
fail:
del_timer(&tx_timer);
atomic_inc(&open_count);
return retval;
}
/**
* Stops the Sleep-Mode Protocol on the Host.
*/
static void bluesleep_stop(void)
{
unsigned long irq_flags;
spin_lock_irqsave(&rw_lock, irq_flags);
if (!test_bit(BT_PROTO, &flags)) {
spin_unlock_irqrestore(&rw_lock, irq_flags);
return;
}
/* assert BT_WAKE */
gpio_set_value(bsi->ext_wake, 0);
del_timer(&tx_timer);
clear_bit(BT_PROTO, &flags);
if (test_bit(BT_ASLEEP, &flags)) {
clear_bit(BT_ASLEEP, &flags);
hsuart_power(1);
}
atomic_inc(&open_count);
spin_unlock_irqrestore(&rw_lock, irq_flags);
if (disable_irq_wake(bsi->host_wake_irq))
BT_ERR("Couldn't disable hostwake IRQ wakeup mode\n");
free_irq(bsi->host_wake_irq, NULL);
}
/**
* Read the <code>BT_WAKE</code> GPIO pin value via the proc interface.
* When this function returns, <code>page</code> will contain a 1 if the
* pin is high, 0 otherwise.
* @param page Buffer for writing data.
* @param start Not used.
* @param offset Not used.
* @param count Not used.
* @param eof Whether or not there is more data to be read.
* @param data Not used.
* @return The number of bytes written.
*/
static int bluepower_read_proc_btwake(char *page, char **start, off_t offset,
int count, int *eof, void *data)
{
*eof = 1;
return sprintf(page, "btwake:%u\n", gpio_get_value(bsi->ext_wake));
}
/**
* Write the <code>BT_WAKE</code> GPIO pin value via the proc interface.
* @param file Not used.
* @param buffer The buffer to read from.
* @param count The number of bytes to be written.
* @param data Not used.
* @return On success, the number of bytes written. On error, -1, and
* <code>errno</code> is set appropriately.
*/
static int bluepower_write_proc_btwake(struct file *file, const char *buffer,
unsigned long count, void *data)
{
char *buf;
if (count < 1)
return -EINVAL;
buf = kmalloc(count, GFP_KERNEL);
if (!buf)
return -ENOMEM;
if (copy_from_user(buf, buffer, count)) {
kfree(buf);
return -EFAULT;
}
if (buf[0] == '0') {
gpio_set_value(bsi->ext_wake, 0);
} else if (buf[0] == '1') {
gpio_set_value(bsi->ext_wake, 1);
} else {
kfree(buf);
return -EINVAL;
}
kfree(buf);
return count;
}
/**
* Read the <code>BT_HOST_WAKE</code> GPIO pin value via the proc interface.
* When this function returns, <code>page</code> will contain a 1 if the pin
* is high, 0 otherwise.
* @param page Buffer for writing data.
* @param start Not used.
* @param offset Not used.
* @param count Not used.
* @param eof Whether or not there is more data to be read.
* @param data Not used.
* @return The number of bytes written.
*/
static int bluepower_read_proc_hostwake(char *page, char **start, off_t offset,
int count, int *eof, void *data)
{
*eof = 1;
return sprintf(page, "hostwake: %u \n", gpio_get_value(bsi->host_wake));
}
/**
* Read the low-power status of the Host via the proc interface.
* When this function returns, <code>page</code> contains a 1 if the Host
* is asleep, 0 otherwise.
* @param page Buffer for writing data.
* @param start Not used.
* @param offset Not used.
* @param count Not used.
* @param eof Whether or not there is more data to be read.
* @param data Not used.
* @return The number of bytes written.
*/
static int bluesleep_read_proc_asleep(char *page, char **start, off_t offset,
int count, int *eof, void *data)
{
unsigned int asleep;
asleep = test_bit(BT_ASLEEP, &flags) ? 1 : 0;
*eof = 1;
return sprintf(page, "asleep: %u\n", asleep);
}
/**
* Read the low-power protocol being used by the Host via the proc interface.
* When this function returns, <code>page</code> will contain a 1 if the Host
* is using the Sleep Mode Protocol, 0 otherwise.
* @param page Buffer for writing data.
* @param start Not used.
* @param offset Not used.
* @param count Not used.
* @param eof Whether or not there is more data to be read.
* @param data Not used.
* @return The number of bytes written.
*/
static int bluesleep_read_proc_proto(char *page, char **start, off_t offset,
int count, int *eof, void *data)
{
unsigned int proto;
proto = test_bit(BT_PROTO, &flags) ? 1 : 0;
*eof = 1;
return sprintf(page, "proto: %u\n", proto);
}
/**
* Modify the low-power protocol used by the Host via the proc interface.
* @param file Not used.
* @param buffer The buffer to read from.
* @param count The number of bytes to be written.
* @param data Not used.
* @return On success, the number of bytes written. On error, -1, and
* <code>errno</code> is set appropriately.
*/
static int bluesleep_write_proc_proto(struct file *file, const char *buffer,
unsigned long count, void *data)
{
char proto;
if (count < 1)
return -EINVAL;
if (copy_from_user(&proto, buffer, 1))
return -EFAULT;
if (proto == '0')
bluesleep_stop();
else
bluesleep_start();
/* claim that we wrote everything */
return count;
}
static int __init bluesleep_probe(struct platform_device *pdev)
{
int ret;
struct resource *res;
bsi = kzalloc(sizeof(struct bluesleep_info), GFP_KERNEL);
if (!bsi)
return -ENOMEM;
res = platform_get_resource_byname(pdev, IORESOURCE_IO,
"gpio_host_wake");
if (!res) {
BT_ERR("couldn't find host_wake gpio\n");
ret = -ENODEV;
goto free_bsi;
}
bsi->host_wake = res->start;
ret = gpio_request(bsi->host_wake, "bt_host_wake");
if (ret)
goto free_bsi;
ret = gpio_direction_input(bsi->host_wake);
if (ret)
goto free_bt_host_wake;
res = platform_get_resource_byname(pdev, IORESOURCE_IO,
"gpio_ext_wake");
if (!res) {
BT_ERR("couldn't find ext_wake gpio\n");
ret = -ENODEV;
goto free_bt_host_wake;
}
bsi->ext_wake = res->start;
ret = gpio_request(bsi->ext_wake, "bt_ext_wake");
if (ret)
goto free_bt_host_wake;
/* assert bt wake */
ret = gpio_direction_output(bsi->ext_wake, 0);
if (ret)
goto free_bt_ext_wake;
bsi->host_wake_irq = platform_get_irq_byname(pdev, "host_wake");
if (bsi->host_wake_irq < 0) {
BT_ERR("couldn't find host_wake irq\n");
ret = -ENODEV;
goto free_bt_ext_wake;
}
return 0;
free_bt_ext_wake:
gpio_free(bsi->ext_wake);
free_bt_host_wake:
gpio_free(bsi->host_wake);
free_bsi:
kfree(bsi);
return ret;
}
static int bluesleep_remove(struct platform_device *pdev)
{
/* assert bt wake */
gpio_set_value(bsi->ext_wake, 0);
if (test_bit(BT_PROTO, &flags)) {
if (disable_irq_wake(bsi->host_wake_irq))
BT_ERR("Couldn't disable hostwake IRQ wakeup mode \n");
free_irq(bsi->host_wake_irq, NULL);
del_timer(&tx_timer);
if (test_bit(BT_ASLEEP, &flags))
hsuart_power(1);
}
gpio_free(bsi->host_wake);
gpio_free(bsi->ext_wake);
kfree(bsi);
return 0;
}
static struct platform_driver bluesleep_driver = {
.remove = bluesleep_remove,
.driver = {
.name = "bluesleep",
.owner = THIS_MODULE,
},
};
/**
* Initializes the module.
* @return On success, 0. On error, -1, and <code>errno</code> is set
* appropriately.
*/
static int __init bluesleep_init(void)
{
int retval;
struct proc_dir_entry *ent;
BT_INFO("MSM Sleep Mode Driver Ver %s", VERSION);
retval = platform_driver_probe(&bluesleep_driver, bluesleep_probe);
if (retval)
return retval;
bluesleep_hdev = NULL;
bluetooth_dir = proc_mkdir("bluetooth", NULL);
if (bluetooth_dir == NULL) {
BT_ERR("Unable to create /proc/bluetooth directory");
return -ENOMEM;
}
sleep_dir = proc_mkdir("sleep", bluetooth_dir);
if (sleep_dir == NULL) {
BT_ERR("Unable to create /proc/%s directory", PROC_DIR);
return -ENOMEM;
}
/* Creating read/write "btwake" entry */
ent = create_proc_entry("btwake", 0, sleep_dir);
if (ent == NULL) {
BT_ERR("Unable to create /proc/%s/btwake entry", PROC_DIR);
retval = -ENOMEM;
goto fail;
}
ent->read_proc = bluepower_read_proc_btwake;
ent->write_proc = bluepower_write_proc_btwake;
/* read only proc entries */
if (create_proc_read_entry("hostwake", 0, sleep_dir,
bluepower_read_proc_hostwake, NULL) == NULL) {
BT_ERR("Unable to create /proc/%s/hostwake entry", PROC_DIR);
retval = -ENOMEM;
goto fail;
}
/* read/write proc entries */
ent = create_proc_entry("proto", 0, sleep_dir);
if (ent == NULL) {
BT_ERR("Unable to create /proc/%s/proto entry", PROC_DIR);
retval = -ENOMEM;
goto fail;
}
ent->read_proc = bluesleep_read_proc_proto;
ent->write_proc = bluesleep_write_proc_proto;
/* read only proc entries */
if (create_proc_read_entry("asleep", 0,
sleep_dir, bluesleep_read_proc_asleep, NULL) == NULL) {
BT_ERR("Unable to create /proc/%s/asleep entry", PROC_DIR);
retval = -ENOMEM;
goto fail;
}
flags = 0; /* clear all status bits */
/* Initialize spinlock. */
spin_lock_init(&rw_lock);
/* Initialize timer */
init_timer(&tx_timer);
tx_timer.function = bluesleep_tx_timer_expire;
tx_timer.data = 0;
/* initialize host wake tasklet */
tasklet_init(&hostwake_task, bluesleep_hostwake_task, 0);
hci_register_notifier(&hci_event_nblock);
return 0;
fail:
remove_proc_entry("asleep", sleep_dir);
remove_proc_entry("proto", sleep_dir);
remove_proc_entry("hostwake", sleep_dir);
remove_proc_entry("btwake", sleep_dir);
remove_proc_entry("sleep", bluetooth_dir);
remove_proc_entry("bluetooth", 0);
return retval;
}
/**
* Cleans up the module.
*/
static void __exit bluesleep_exit(void)
{
hci_unregister_notifier(&hci_event_nblock);
platform_driver_unregister(&bluesleep_driver);
remove_proc_entry("asleep", sleep_dir);
remove_proc_entry("proto", sleep_dir);
remove_proc_entry("hostwake", sleep_dir);
remove_proc_entry("btwake", sleep_dir);
remove_proc_entry("sleep", bluetooth_dir);
remove_proc_entry("bluetooth", 0);
}
module_init(bluesleep_init);
module_exit(bluesleep_exit);
MODULE_DESCRIPTION("Bluetooth Sleep Mode Driver ver %s " VERSION);
#ifdef MODULE_LICENSE
MODULE_LICENSE("GPL");
#endif
| gpl-2.0 |
EPDCenter/android_kernel_rockchip_ylp | drivers/net/e1000/e1000_main.c | 1130 | 137681 | /*******************************************************************************
Intel PRO/1000 Linux driver
Copyright(c) 1999 - 2006 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
Linux NICS <linux.nics@intel.com>
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include "e1000.h"
#include <net/ip6_checksum.h>
#include <linux/io.h>
#include <linux/prefetch.h>
/* Intel Media SOC GbE MDIO physical base address */
static unsigned long ce4100_gbe_mdio_base_phy;
/* Intel Media SOC GbE MDIO virtual base address */
void __iomem *ce4100_gbe_mdio_base_virt;
char e1000_driver_name[] = "e1000";
static char e1000_driver_string[] = "Intel(R) PRO/1000 Network Driver";
#define DRV_VERSION "7.3.21-k8-NAPI"
const char e1000_driver_version[] = DRV_VERSION;
static const char e1000_copyright[] = "Copyright (c) 1999-2006 Intel Corporation.";
/* e1000_pci_tbl - PCI Device ID Table
*
* Last entry must be all 0s
*
* Macro expands to...
* {PCI_DEVICE(PCI_VENDOR_ID_INTEL, device_id)}
*/
static DEFINE_PCI_DEVICE_TABLE(e1000_pci_tbl) = {
INTEL_E1000_ETHERNET_DEVICE(0x1000),
INTEL_E1000_ETHERNET_DEVICE(0x1001),
INTEL_E1000_ETHERNET_DEVICE(0x1004),
INTEL_E1000_ETHERNET_DEVICE(0x1008),
INTEL_E1000_ETHERNET_DEVICE(0x1009),
INTEL_E1000_ETHERNET_DEVICE(0x100C),
INTEL_E1000_ETHERNET_DEVICE(0x100D),
INTEL_E1000_ETHERNET_DEVICE(0x100E),
INTEL_E1000_ETHERNET_DEVICE(0x100F),
INTEL_E1000_ETHERNET_DEVICE(0x1010),
INTEL_E1000_ETHERNET_DEVICE(0x1011),
INTEL_E1000_ETHERNET_DEVICE(0x1012),
INTEL_E1000_ETHERNET_DEVICE(0x1013),
INTEL_E1000_ETHERNET_DEVICE(0x1014),
INTEL_E1000_ETHERNET_DEVICE(0x1015),
INTEL_E1000_ETHERNET_DEVICE(0x1016),
INTEL_E1000_ETHERNET_DEVICE(0x1017),
INTEL_E1000_ETHERNET_DEVICE(0x1018),
INTEL_E1000_ETHERNET_DEVICE(0x1019),
INTEL_E1000_ETHERNET_DEVICE(0x101A),
INTEL_E1000_ETHERNET_DEVICE(0x101D),
INTEL_E1000_ETHERNET_DEVICE(0x101E),
INTEL_E1000_ETHERNET_DEVICE(0x1026),
INTEL_E1000_ETHERNET_DEVICE(0x1027),
INTEL_E1000_ETHERNET_DEVICE(0x1028),
INTEL_E1000_ETHERNET_DEVICE(0x1075),
INTEL_E1000_ETHERNET_DEVICE(0x1076),
INTEL_E1000_ETHERNET_DEVICE(0x1077),
INTEL_E1000_ETHERNET_DEVICE(0x1078),
INTEL_E1000_ETHERNET_DEVICE(0x1079),
INTEL_E1000_ETHERNET_DEVICE(0x107A),
INTEL_E1000_ETHERNET_DEVICE(0x107B),
INTEL_E1000_ETHERNET_DEVICE(0x107C),
INTEL_E1000_ETHERNET_DEVICE(0x108A),
INTEL_E1000_ETHERNET_DEVICE(0x1099),
INTEL_E1000_ETHERNET_DEVICE(0x10B5),
INTEL_E1000_ETHERNET_DEVICE(0x2E6E),
/* required last entry */
{0,}
};
MODULE_DEVICE_TABLE(pci, e1000_pci_tbl);
int e1000_up(struct e1000_adapter *adapter);
void e1000_down(struct e1000_adapter *adapter);
void e1000_reinit_locked(struct e1000_adapter *adapter);
void e1000_reset(struct e1000_adapter *adapter);
int e1000_setup_all_tx_resources(struct e1000_adapter *adapter);
int e1000_setup_all_rx_resources(struct e1000_adapter *adapter);
void e1000_free_all_tx_resources(struct e1000_adapter *adapter);
void e1000_free_all_rx_resources(struct e1000_adapter *adapter);
static int e1000_setup_tx_resources(struct e1000_adapter *adapter,
struct e1000_tx_ring *txdr);
static int e1000_setup_rx_resources(struct e1000_adapter *adapter,
struct e1000_rx_ring *rxdr);
static void e1000_free_tx_resources(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring);
static void e1000_free_rx_resources(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring);
void e1000_update_stats(struct e1000_adapter *adapter);
static int e1000_init_module(void);
static void e1000_exit_module(void);
static int e1000_probe(struct pci_dev *pdev, const struct pci_device_id *ent);
static void __devexit e1000_remove(struct pci_dev *pdev);
static int e1000_alloc_queues(struct e1000_adapter *adapter);
static int e1000_sw_init(struct e1000_adapter *adapter);
static int e1000_open(struct net_device *netdev);
static int e1000_close(struct net_device *netdev);
static void e1000_configure_tx(struct e1000_adapter *adapter);
static void e1000_configure_rx(struct e1000_adapter *adapter);
static void e1000_setup_rctl(struct e1000_adapter *adapter);
static void e1000_clean_all_tx_rings(struct e1000_adapter *adapter);
static void e1000_clean_all_rx_rings(struct e1000_adapter *adapter);
static void e1000_clean_tx_ring(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring);
static void e1000_clean_rx_ring(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring);
static void e1000_set_rx_mode(struct net_device *netdev);
static void e1000_update_phy_info(unsigned long data);
static void e1000_update_phy_info_task(struct work_struct *work);
static void e1000_watchdog(unsigned long data);
static void e1000_82547_tx_fifo_stall(unsigned long data);
static void e1000_82547_tx_fifo_stall_task(struct work_struct *work);
static netdev_tx_t e1000_xmit_frame(struct sk_buff *skb,
struct net_device *netdev);
static struct net_device_stats * e1000_get_stats(struct net_device *netdev);
static int e1000_change_mtu(struct net_device *netdev, int new_mtu);
static int e1000_set_mac(struct net_device *netdev, void *p);
static irqreturn_t e1000_intr(int irq, void *data);
static bool e1000_clean_tx_irq(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring);
static int e1000_clean(struct napi_struct *napi, int budget);
static bool e1000_clean_rx_irq(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int *work_done, int work_to_do);
static bool e1000_clean_jumbo_rx_irq(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int *work_done, int work_to_do);
static void e1000_alloc_rx_buffers(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int cleaned_count);
static void e1000_alloc_jumbo_rx_buffers(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int cleaned_count);
static int e1000_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd);
static int e1000_mii_ioctl(struct net_device *netdev, struct ifreq *ifr,
int cmd);
static void e1000_enter_82542_rst(struct e1000_adapter *adapter);
static void e1000_leave_82542_rst(struct e1000_adapter *adapter);
static void e1000_tx_timeout(struct net_device *dev);
static void e1000_reset_task(struct work_struct *work);
static void e1000_smartspeed(struct e1000_adapter *adapter);
static int e1000_82547_fifo_workaround(struct e1000_adapter *adapter,
struct sk_buff *skb);
static void e1000_vlan_rx_register(struct net_device *netdev, struct vlan_group *grp);
static void e1000_vlan_rx_add_vid(struct net_device *netdev, u16 vid);
static void e1000_vlan_rx_kill_vid(struct net_device *netdev, u16 vid);
static void e1000_restore_vlan(struct e1000_adapter *adapter);
#ifdef CONFIG_PM
static int e1000_suspend(struct pci_dev *pdev, pm_message_t state);
static int e1000_resume(struct pci_dev *pdev);
#endif
static void e1000_shutdown(struct pci_dev *pdev);
#ifdef CONFIG_NET_POLL_CONTROLLER
/* for netdump / net console */
static void e1000_netpoll (struct net_device *netdev);
#endif
#define COPYBREAK_DEFAULT 256
static unsigned int copybreak __read_mostly = COPYBREAK_DEFAULT;
module_param(copybreak, uint, 0644);
MODULE_PARM_DESC(copybreak,
"Maximum size of packet that is copied to a new buffer on receive");
static pci_ers_result_t e1000_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state);
static pci_ers_result_t e1000_io_slot_reset(struct pci_dev *pdev);
static void e1000_io_resume(struct pci_dev *pdev);
static struct pci_error_handlers e1000_err_handler = {
.error_detected = e1000_io_error_detected,
.slot_reset = e1000_io_slot_reset,
.resume = e1000_io_resume,
};
static struct pci_driver e1000_driver = {
.name = e1000_driver_name,
.id_table = e1000_pci_tbl,
.probe = e1000_probe,
.remove = __devexit_p(e1000_remove),
#ifdef CONFIG_PM
/* Power Management Hooks */
.suspend = e1000_suspend,
.resume = e1000_resume,
#endif
.shutdown = e1000_shutdown,
.err_handler = &e1000_err_handler
};
MODULE_AUTHOR("Intel Corporation, <linux.nics@intel.com>");
MODULE_DESCRIPTION("Intel(R) PRO/1000 Network Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
static int debug = NETIF_MSG_DRV | NETIF_MSG_PROBE;
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
/**
* e1000_get_hw_dev - return device
* used by hardware layer to print debugging information
*
**/
struct net_device *e1000_get_hw_dev(struct e1000_hw *hw)
{
struct e1000_adapter *adapter = hw->back;
return adapter->netdev;
}
/**
* e1000_init_module - Driver Registration Routine
*
* e1000_init_module is the first routine called when the driver is
* loaded. All it does is register with the PCI subsystem.
**/
static int __init e1000_init_module(void)
{
int ret;
pr_info("%s - version %s\n", e1000_driver_string, e1000_driver_version);
pr_info("%s\n", e1000_copyright);
ret = pci_register_driver(&e1000_driver);
if (copybreak != COPYBREAK_DEFAULT) {
if (copybreak == 0)
pr_info("copybreak disabled\n");
else
pr_info("copybreak enabled for "
"packets <= %u bytes\n", copybreak);
}
return ret;
}
module_init(e1000_init_module);
/**
* e1000_exit_module - Driver Exit Cleanup Routine
*
* e1000_exit_module is called just before the driver is removed
* from memory.
**/
static void __exit e1000_exit_module(void)
{
pci_unregister_driver(&e1000_driver);
}
module_exit(e1000_exit_module);
static int e1000_request_irq(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
irq_handler_t handler = e1000_intr;
int irq_flags = IRQF_SHARED;
int err;
err = request_irq(adapter->pdev->irq, handler, irq_flags, netdev->name,
netdev);
if (err) {
e_err(probe, "Unable to allocate interrupt Error: %d\n", err);
}
return err;
}
static void e1000_free_irq(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
free_irq(adapter->pdev->irq, netdev);
}
/**
* e1000_irq_disable - Mask off interrupt generation on the NIC
* @adapter: board private structure
**/
static void e1000_irq_disable(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
ew32(IMC, ~0);
E1000_WRITE_FLUSH();
synchronize_irq(adapter->pdev->irq);
}
/**
* e1000_irq_enable - Enable default interrupt generation settings
* @adapter: board private structure
**/
static void e1000_irq_enable(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
ew32(IMS, IMS_ENABLE_MASK);
E1000_WRITE_FLUSH();
}
static void e1000_update_mng_vlan(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
u16 vid = hw->mng_cookie.vlan_id;
u16 old_vid = adapter->mng_vlan_id;
if (adapter->vlgrp) {
if (!vlan_group_get_device(adapter->vlgrp, vid)) {
if (hw->mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN_SUPPORT) {
e1000_vlan_rx_add_vid(netdev, vid);
adapter->mng_vlan_id = vid;
} else
adapter->mng_vlan_id = E1000_MNG_VLAN_NONE;
if ((old_vid != (u16)E1000_MNG_VLAN_NONE) &&
(vid != old_vid) &&
!vlan_group_get_device(adapter->vlgrp, old_vid))
e1000_vlan_rx_kill_vid(netdev, old_vid);
} else
adapter->mng_vlan_id = vid;
}
}
static void e1000_init_manageability(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
if (adapter->en_mng_pt) {
u32 manc = er32(MANC);
/* disable hardware interception of ARP */
manc &= ~(E1000_MANC_ARP_EN);
ew32(MANC, manc);
}
}
static void e1000_release_manageability(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
if (adapter->en_mng_pt) {
u32 manc = er32(MANC);
/* re-enable hardware interception of ARP */
manc |= E1000_MANC_ARP_EN;
ew32(MANC, manc);
}
}
/**
* e1000_configure - configure the hardware for RX and TX
* @adapter = private board structure
**/
static void e1000_configure(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int i;
e1000_set_rx_mode(netdev);
e1000_restore_vlan(adapter);
e1000_init_manageability(adapter);
e1000_configure_tx(adapter);
e1000_setup_rctl(adapter);
e1000_configure_rx(adapter);
/* call E1000_DESC_UNUSED which always leaves
* at least 1 descriptor unused to make sure
* next_to_use != next_to_clean */
for (i = 0; i < adapter->num_rx_queues; i++) {
struct e1000_rx_ring *ring = &adapter->rx_ring[i];
adapter->alloc_rx_buf(adapter, ring,
E1000_DESC_UNUSED(ring));
}
}
int e1000_up(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
/* hardware has been reset, we need to reload some things */
e1000_configure(adapter);
clear_bit(__E1000_DOWN, &adapter->flags);
napi_enable(&adapter->napi);
e1000_irq_enable(adapter);
netif_wake_queue(adapter->netdev);
/* fire a link change interrupt to start the watchdog */
ew32(ICS, E1000_ICS_LSC);
return 0;
}
/**
* e1000_power_up_phy - restore link in case the phy was powered down
* @adapter: address of board private structure
*
* The phy may be powered down to save power and turn off link when the
* driver is unloaded and wake on lan is not enabled (among others)
* *** this routine MUST be followed by a call to e1000_reset ***
*
**/
void e1000_power_up_phy(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u16 mii_reg = 0;
/* Just clear the power down bit to wake the phy back up */
if (hw->media_type == e1000_media_type_copper) {
/* according to the manual, the phy will retain its
* settings across a power-down/up cycle */
e1000_read_phy_reg(hw, PHY_CTRL, &mii_reg);
mii_reg &= ~MII_CR_POWER_DOWN;
e1000_write_phy_reg(hw, PHY_CTRL, mii_reg);
}
}
static void e1000_power_down_phy(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
/* Power down the PHY so no link is implied when interface is down *
* The PHY cannot be powered down if any of the following is true *
* (a) WoL is enabled
* (b) AMT is active
* (c) SoL/IDER session is active */
if (!adapter->wol && hw->mac_type >= e1000_82540 &&
hw->media_type == e1000_media_type_copper) {
u16 mii_reg = 0;
switch (hw->mac_type) {
case e1000_82540:
case e1000_82545:
case e1000_82545_rev_3:
case e1000_82546:
case e1000_ce4100:
case e1000_82546_rev_3:
case e1000_82541:
case e1000_82541_rev_2:
case e1000_82547:
case e1000_82547_rev_2:
if (er32(MANC) & E1000_MANC_SMBUS_EN)
goto out;
break;
default:
goto out;
}
e1000_read_phy_reg(hw, PHY_CTRL, &mii_reg);
mii_reg |= MII_CR_POWER_DOWN;
e1000_write_phy_reg(hw, PHY_CTRL, mii_reg);
mdelay(1);
}
out:
return;
}
void e1000_down(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
u32 rctl, tctl;
/* disable receives in the hardware */
rctl = er32(RCTL);
ew32(RCTL, rctl & ~E1000_RCTL_EN);
/* flush and sleep below */
netif_tx_disable(netdev);
/* disable transmits in the hardware */
tctl = er32(TCTL);
tctl &= ~E1000_TCTL_EN;
ew32(TCTL, tctl);
/* flush both disables and wait for them to finish */
E1000_WRITE_FLUSH();
msleep(10);
napi_disable(&adapter->napi);
e1000_irq_disable(adapter);
/*
* Setting DOWN must be after irq_disable to prevent
* a screaming interrupt. Setting DOWN also prevents
* timers and tasks from rescheduling.
*/
set_bit(__E1000_DOWN, &adapter->flags);
del_timer_sync(&adapter->tx_fifo_stall_timer);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_info_timer);
adapter->link_speed = 0;
adapter->link_duplex = 0;
netif_carrier_off(netdev);
e1000_reset(adapter);
e1000_clean_all_tx_rings(adapter);
e1000_clean_all_rx_rings(adapter);
}
static void e1000_reinit_safe(struct e1000_adapter *adapter)
{
while (test_and_set_bit(__E1000_RESETTING, &adapter->flags))
msleep(1);
rtnl_lock();
e1000_down(adapter);
e1000_up(adapter);
rtnl_unlock();
clear_bit(__E1000_RESETTING, &adapter->flags);
}
void e1000_reinit_locked(struct e1000_adapter *adapter)
{
/* if rtnl_lock is not held the call path is bogus */
ASSERT_RTNL();
WARN_ON(in_interrupt());
while (test_and_set_bit(__E1000_RESETTING, &adapter->flags))
msleep(1);
e1000_down(adapter);
e1000_up(adapter);
clear_bit(__E1000_RESETTING, &adapter->flags);
}
void e1000_reset(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 pba = 0, tx_space, min_tx_space, min_rx_space;
bool legacy_pba_adjust = false;
u16 hwm;
/* Repartition Pba for greater than 9k mtu
* To take effect CTRL.RST is required.
*/
switch (hw->mac_type) {
case e1000_82542_rev2_0:
case e1000_82542_rev2_1:
case e1000_82543:
case e1000_82544:
case e1000_82540:
case e1000_82541:
case e1000_82541_rev_2:
legacy_pba_adjust = true;
pba = E1000_PBA_48K;
break;
case e1000_82545:
case e1000_82545_rev_3:
case e1000_82546:
case e1000_ce4100:
case e1000_82546_rev_3:
pba = E1000_PBA_48K;
break;
case e1000_82547:
case e1000_82547_rev_2:
legacy_pba_adjust = true;
pba = E1000_PBA_30K;
break;
case e1000_undefined:
case e1000_num_macs:
break;
}
if (legacy_pba_adjust) {
if (hw->max_frame_size > E1000_RXBUFFER_8192)
pba -= 8; /* allocate more FIFO for Tx */
if (hw->mac_type == e1000_82547) {
adapter->tx_fifo_head = 0;
adapter->tx_head_addr = pba << E1000_TX_HEAD_ADDR_SHIFT;
adapter->tx_fifo_size =
(E1000_PBA_40K - pba) << E1000_PBA_BYTES_SHIFT;
atomic_set(&adapter->tx_fifo_stall, 0);
}
} else if (hw->max_frame_size > ETH_FRAME_LEN + ETH_FCS_LEN) {
/* adjust PBA for jumbo frames */
ew32(PBA, pba);
/* To maintain wire speed transmits, the Tx FIFO should be
* large enough to accommodate two full transmit packets,
* rounded up to the next 1KB and expressed in KB. Likewise,
* the Rx FIFO should be large enough to accommodate at least
* one full receive packet and is similarly rounded up and
* expressed in KB. */
pba = er32(PBA);
/* upper 16 bits has Tx packet buffer allocation size in KB */
tx_space = pba >> 16;
/* lower 16 bits has Rx packet buffer allocation size in KB */
pba &= 0xffff;
/*
* the tx fifo also stores 16 bytes of information about the tx
* but don't include ethernet FCS because hardware appends it
*/
min_tx_space = (hw->max_frame_size +
sizeof(struct e1000_tx_desc) -
ETH_FCS_LEN) * 2;
min_tx_space = ALIGN(min_tx_space, 1024);
min_tx_space >>= 10;
/* software strips receive CRC, so leave room for it */
min_rx_space = hw->max_frame_size;
min_rx_space = ALIGN(min_rx_space, 1024);
min_rx_space >>= 10;
/* If current Tx allocation is less than the min Tx FIFO size,
* and the min Tx FIFO size is less than the current Rx FIFO
* allocation, take space away from current Rx allocation */
if (tx_space < min_tx_space &&
((min_tx_space - tx_space) < pba)) {
pba = pba - (min_tx_space - tx_space);
/* PCI/PCIx hardware has PBA alignment constraints */
switch (hw->mac_type) {
case e1000_82545 ... e1000_82546_rev_3:
pba &= ~(E1000_PBA_8K - 1);
break;
default:
break;
}
/* if short on rx space, rx wins and must trump tx
* adjustment or use Early Receive if available */
if (pba < min_rx_space)
pba = min_rx_space;
}
}
ew32(PBA, pba);
/*
* flow control settings:
* The high water mark must be low enough to fit one full frame
* (or the size used for early receive) above it in the Rx FIFO.
* Set it to the lower of:
* - 90% of the Rx FIFO size, and
* - the full Rx FIFO size minus the early receive size (for parts
* with ERT support assuming ERT set to E1000_ERT_2048), or
* - the full Rx FIFO size minus one full frame
*/
hwm = min(((pba << 10) * 9 / 10),
((pba << 10) - hw->max_frame_size));
hw->fc_high_water = hwm & 0xFFF8; /* 8-byte granularity */
hw->fc_low_water = hw->fc_high_water - 8;
hw->fc_pause_time = E1000_FC_PAUSE_TIME;
hw->fc_send_xon = 1;
hw->fc = hw->original_fc;
/* Allow time for pending master requests to run */
e1000_reset_hw(hw);
if (hw->mac_type >= e1000_82544)
ew32(WUC, 0);
if (e1000_init_hw(hw))
e_dev_err("Hardware Error\n");
e1000_update_mng_vlan(adapter);
/* if (adapter->hwflags & HWFLAGS_PHY_PWR_BIT) { */
if (hw->mac_type >= e1000_82544 &&
hw->autoneg == 1 &&
hw->autoneg_advertised == ADVERTISE_1000_FULL) {
u32 ctrl = er32(CTRL);
/* clear phy power management bit if we are in gig only mode,
* which if enabled will attempt negotiation to 100Mb, which
* can cause a loss of link at power off or driver unload */
ctrl &= ~E1000_CTRL_SWDPIN3;
ew32(CTRL, ctrl);
}
/* Enable h/w to recognize an 802.1Q VLAN Ethernet packet */
ew32(VET, ETHERNET_IEEE_VLAN_TYPE);
e1000_reset_adaptive(hw);
e1000_phy_get_info(hw, &adapter->phy_info);
e1000_release_manageability(adapter);
}
/**
* Dump the eeprom for users having checksum issues
**/
static void e1000_dump_eeprom(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct ethtool_eeprom eeprom;
const struct ethtool_ops *ops = netdev->ethtool_ops;
u8 *data;
int i;
u16 csum_old, csum_new = 0;
eeprom.len = ops->get_eeprom_len(netdev);
eeprom.offset = 0;
data = kmalloc(eeprom.len, GFP_KERNEL);
if (!data) {
pr_err("Unable to allocate memory to dump EEPROM data\n");
return;
}
ops->get_eeprom(netdev, &eeprom, data);
csum_old = (data[EEPROM_CHECKSUM_REG * 2]) +
(data[EEPROM_CHECKSUM_REG * 2 + 1] << 8);
for (i = 0; i < EEPROM_CHECKSUM_REG * 2; i += 2)
csum_new += data[i] + (data[i + 1] << 8);
csum_new = EEPROM_SUM - csum_new;
pr_err("/*********************/\n");
pr_err("Current EEPROM Checksum : 0x%04x\n", csum_old);
pr_err("Calculated : 0x%04x\n", csum_new);
pr_err("Offset Values\n");
pr_err("======== ======\n");
print_hex_dump(KERN_ERR, "", DUMP_PREFIX_OFFSET, 16, 1, data, 128, 0);
pr_err("Include this output when contacting your support provider.\n");
pr_err("This is not a software error! Something bad happened to\n");
pr_err("your hardware or EEPROM image. Ignoring this problem could\n");
pr_err("result in further problems, possibly loss of data,\n");
pr_err("corruption or system hangs!\n");
pr_err("The MAC Address will be reset to 00:00:00:00:00:00,\n");
pr_err("which is invalid and requires you to set the proper MAC\n");
pr_err("address manually before continuing to enable this network\n");
pr_err("device. Please inspect the EEPROM dump and report the\n");
pr_err("issue to your hardware vendor or Intel Customer Support.\n");
pr_err("/*********************/\n");
kfree(data);
}
/**
* e1000_is_need_ioport - determine if an adapter needs ioport resources or not
* @pdev: PCI device information struct
*
* Return true if an adapter needs ioport resources
**/
static int e1000_is_need_ioport(struct pci_dev *pdev)
{
switch (pdev->device) {
case E1000_DEV_ID_82540EM:
case E1000_DEV_ID_82540EM_LOM:
case E1000_DEV_ID_82540EP:
case E1000_DEV_ID_82540EP_LOM:
case E1000_DEV_ID_82540EP_LP:
case E1000_DEV_ID_82541EI:
case E1000_DEV_ID_82541EI_MOBILE:
case E1000_DEV_ID_82541ER:
case E1000_DEV_ID_82541ER_LOM:
case E1000_DEV_ID_82541GI:
case E1000_DEV_ID_82541GI_LF:
case E1000_DEV_ID_82541GI_MOBILE:
case E1000_DEV_ID_82544EI_COPPER:
case E1000_DEV_ID_82544EI_FIBER:
case E1000_DEV_ID_82544GC_COPPER:
case E1000_DEV_ID_82544GC_LOM:
case E1000_DEV_ID_82545EM_COPPER:
case E1000_DEV_ID_82545EM_FIBER:
case E1000_DEV_ID_82546EB_COPPER:
case E1000_DEV_ID_82546EB_FIBER:
case E1000_DEV_ID_82546EB_QUAD_COPPER:
return true;
default:
return false;
}
}
static const struct net_device_ops e1000_netdev_ops = {
.ndo_open = e1000_open,
.ndo_stop = e1000_close,
.ndo_start_xmit = e1000_xmit_frame,
.ndo_get_stats = e1000_get_stats,
.ndo_set_rx_mode = e1000_set_rx_mode,
.ndo_set_mac_address = e1000_set_mac,
.ndo_tx_timeout = e1000_tx_timeout,
.ndo_change_mtu = e1000_change_mtu,
.ndo_do_ioctl = e1000_ioctl,
.ndo_validate_addr = eth_validate_addr,
.ndo_vlan_rx_register = e1000_vlan_rx_register,
.ndo_vlan_rx_add_vid = e1000_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = e1000_vlan_rx_kill_vid,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = e1000_netpoll,
#endif
};
/**
* e1000_init_hw_struct - initialize members of hw struct
* @adapter: board private struct
* @hw: structure used by e1000_hw.c
*
* Factors out initialization of the e1000_hw struct to its own function
* that can be called very early at init (just after struct allocation).
* Fields are initialized based on PCI device information and
* OS network device settings (MTU size).
* Returns negative error codes if MAC type setup fails.
*/
static int e1000_init_hw_struct(struct e1000_adapter *adapter,
struct e1000_hw *hw)
{
struct pci_dev *pdev = adapter->pdev;
/* PCI config space info */
hw->vendor_id = pdev->vendor;
hw->device_id = pdev->device;
hw->subsystem_vendor_id = pdev->subsystem_vendor;
hw->subsystem_id = pdev->subsystem_device;
hw->revision_id = pdev->revision;
pci_read_config_word(pdev, PCI_COMMAND, &hw->pci_cmd_word);
hw->max_frame_size = adapter->netdev->mtu +
ENET_HEADER_SIZE + ETHERNET_FCS_SIZE;
hw->min_frame_size = MINIMUM_ETHERNET_FRAME_SIZE;
/* identify the MAC */
if (e1000_set_mac_type(hw)) {
e_err(probe, "Unknown MAC Type\n");
return -EIO;
}
switch (hw->mac_type) {
default:
break;
case e1000_82541:
case e1000_82547:
case e1000_82541_rev_2:
case e1000_82547_rev_2:
hw->phy_init_script = 1;
break;
}
e1000_set_media_type(hw);
e1000_get_bus_info(hw);
hw->wait_autoneg_complete = false;
hw->tbi_compatibility_en = true;
hw->adaptive_ifs = true;
/* Copper options */
if (hw->media_type == e1000_media_type_copper) {
hw->mdix = AUTO_ALL_MODES;
hw->disable_polarity_correction = false;
hw->master_slave = E1000_MASTER_SLAVE;
}
return 0;
}
/**
* e1000_probe - Device Initialization Routine
* @pdev: PCI device information struct
* @ent: entry in e1000_pci_tbl
*
* Returns 0 on success, negative on failure
*
* e1000_probe initializes an adapter identified by a pci_dev structure.
* The OS initialization, configuring of the adapter private structure,
* and a hardware reset occur.
**/
static int __devinit e1000_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *netdev;
struct e1000_adapter *adapter;
struct e1000_hw *hw;
static int cards_found = 0;
static int global_quad_port_a = 0; /* global ksp3 port a indication */
int i, err, pci_using_dac;
u16 eeprom_data = 0;
u16 tmp = 0;
u16 eeprom_apme_mask = E1000_EEPROM_APME;
int bars, need_ioport;
/* do not allocate ioport bars when not needed */
need_ioport = e1000_is_need_ioport(pdev);
if (need_ioport) {
bars = pci_select_bars(pdev, IORESOURCE_MEM | IORESOURCE_IO);
err = pci_enable_device(pdev);
} else {
bars = pci_select_bars(pdev, IORESOURCE_MEM);
err = pci_enable_device_mem(pdev);
}
if (err)
return err;
err = pci_request_selected_regions(pdev, bars, e1000_driver_name);
if (err)
goto err_pci_reg;
pci_set_master(pdev);
err = pci_save_state(pdev);
if (err)
goto err_alloc_etherdev;
err = -ENOMEM;
netdev = alloc_etherdev(sizeof(struct e1000_adapter));
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->msg_enable = (1 << debug) - 1;
adapter->bars = bars;
adapter->need_ioport = need_ioport;
hw = &adapter->hw;
hw->back = adapter;
err = -EIO;
hw->hw_addr = pci_ioremap_bar(pdev, BAR_0);
if (!hw->hw_addr)
goto err_ioremap;
if (adapter->need_ioport) {
for (i = BAR_1; i <= BAR_5; i++) {
if (pci_resource_len(pdev, i) == 0)
continue;
if (pci_resource_flags(pdev, i) & IORESOURCE_IO) {
hw->io_base = pci_resource_start(pdev, i);
break;
}
}
}
/* make ready for any if (hw->...) below */
err = e1000_init_hw_struct(adapter, hw);
if (err)
goto err_sw_init;
/*
* there is a workaround being applied below that limits
* 64-bit DMA addresses to 64-bit hardware. There are some
* 32-bit adapters that Tx hang when given 64-bit DMA addresses
*/
pci_using_dac = 0;
if ((hw->bus_type == e1000_bus_type_pcix) &&
!dma_set_mask(&pdev->dev, DMA_BIT_MASK(64))) {
/*
* according to DMA-API-HOWTO, coherent calls will always
* succeed if the set call did
*/
dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(64));
pci_using_dac = 1;
} else {
err = dma_set_mask(&pdev->dev, DMA_BIT_MASK(32));
if (err) {
pr_err("No usable DMA config, aborting\n");
goto err_dma;
}
dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(32));
}
netdev->netdev_ops = &e1000_netdev_ops;
e1000_set_ethtool_ops(netdev);
netdev->watchdog_timeo = 5 * HZ;
netif_napi_add(netdev, &adapter->napi, e1000_clean, 64);
strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
adapter->bd_number = cards_found;
/* setup the private structure */
err = e1000_sw_init(adapter);
if (err)
goto err_sw_init;
err = -EIO;
if (hw->mac_type == e1000_ce4100) {
ce4100_gbe_mdio_base_phy = pci_resource_start(pdev, BAR_1);
ce4100_gbe_mdio_base_virt = ioremap(ce4100_gbe_mdio_base_phy,
pci_resource_len(pdev, BAR_1));
if (!ce4100_gbe_mdio_base_virt)
goto err_mdio_ioremap;
}
if (hw->mac_type >= e1000_82543) {
netdev->features = NETIF_F_SG |
NETIF_F_HW_CSUM |
NETIF_F_HW_VLAN_TX |
NETIF_F_HW_VLAN_RX |
NETIF_F_HW_VLAN_FILTER;
}
if ((hw->mac_type >= e1000_82544) &&
(hw->mac_type != e1000_82547))
netdev->features |= NETIF_F_TSO;
if (pci_using_dac) {
netdev->features |= NETIF_F_HIGHDMA;
netdev->vlan_features |= NETIF_F_HIGHDMA;
}
netdev->vlan_features |= NETIF_F_TSO;
netdev->vlan_features |= NETIF_F_HW_CSUM;
netdev->vlan_features |= NETIF_F_SG;
adapter->en_mng_pt = e1000_enable_mng_pass_thru(hw);
/* initialize eeprom parameters */
if (e1000_init_eeprom_params(hw)) {
e_err(probe, "EEPROM initialization failed\n");
goto err_eeprom;
}
/* before reading the EEPROM, reset the controller to
* put the device in a known good starting state */
e1000_reset_hw(hw);
/* make sure the EEPROM is good */
if (e1000_validate_eeprom_checksum(hw) < 0) {
e_err(probe, "The EEPROM Checksum Is Not Valid\n");
e1000_dump_eeprom(adapter);
/*
* set MAC address to all zeroes to invalidate and temporary
* disable this device for the user. This blocks regular
* traffic while still permitting ethtool ioctls from reaching
* the hardware as well as allowing the user to run the
* interface after manually setting a hw addr using
* `ip set address`
*/
memset(hw->mac_addr, 0, netdev->addr_len);
} else {
/* copy the MAC address out of the EEPROM */
if (e1000_read_mac_addr(hw))
e_err(probe, "EEPROM Read Error\n");
}
/* don't block initalization here due to bad MAC address */
memcpy(netdev->dev_addr, hw->mac_addr, netdev->addr_len);
memcpy(netdev->perm_addr, hw->mac_addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->perm_addr))
e_err(probe, "Invalid MAC Address\n");
init_timer(&adapter->tx_fifo_stall_timer);
adapter->tx_fifo_stall_timer.function = e1000_82547_tx_fifo_stall;
adapter->tx_fifo_stall_timer.data = (unsigned long)adapter;
init_timer(&adapter->watchdog_timer);
adapter->watchdog_timer.function = e1000_watchdog;
adapter->watchdog_timer.data = (unsigned long) adapter;
init_timer(&adapter->phy_info_timer);
adapter->phy_info_timer.function = e1000_update_phy_info;
adapter->phy_info_timer.data = (unsigned long)adapter;
INIT_WORK(&adapter->fifo_stall_task, e1000_82547_tx_fifo_stall_task);
INIT_WORK(&adapter->reset_task, e1000_reset_task);
INIT_WORK(&adapter->phy_info_task, e1000_update_phy_info_task);
e1000_check_options(adapter);
/* Initial Wake on LAN setting
* If APM wake is enabled in the EEPROM,
* enable the ACPI Magic Packet filter
*/
switch (hw->mac_type) {
case e1000_82542_rev2_0:
case e1000_82542_rev2_1:
case e1000_82543:
break;
case e1000_82544:
e1000_read_eeprom(hw,
EEPROM_INIT_CONTROL2_REG, 1, &eeprom_data);
eeprom_apme_mask = E1000_EEPROM_82544_APM;
break;
case e1000_82546:
case e1000_82546_rev_3:
if (er32(STATUS) & E1000_STATUS_FUNC_1){
e1000_read_eeprom(hw,
EEPROM_INIT_CONTROL3_PORT_B, 1, &eeprom_data);
break;
}
/* Fall Through */
default:
e1000_read_eeprom(hw,
EEPROM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
break;
}
if (eeprom_data & eeprom_apme_mask)
adapter->eeprom_wol |= E1000_WUFC_MAG;
/* now that we have the eeprom settings, apply the special cases
* where the eeprom may be wrong or the board simply won't support
* wake on lan on a particular port */
switch (pdev->device) {
case E1000_DEV_ID_82546GB_PCIE:
adapter->eeprom_wol = 0;
break;
case E1000_DEV_ID_82546EB_FIBER:
case E1000_DEV_ID_82546GB_FIBER:
/* Wake events only supported on port A for dual fiber
* regardless of eeprom setting */
if (er32(STATUS) & E1000_STATUS_FUNC_1)
adapter->eeprom_wol = 0;
break;
case E1000_DEV_ID_82546GB_QUAD_COPPER_KSP3:
/* if quad port adapter, disable WoL on all but port A */
if (global_quad_port_a != 0)
adapter->eeprom_wol = 0;
else
adapter->quad_port_a = 1;
/* Reset for multiple quad port adapters */
if (++global_quad_port_a == 4)
global_quad_port_a = 0;
break;
}
/* initialize the wol settings based on the eeprom settings */
adapter->wol = adapter->eeprom_wol;
device_set_wakeup_enable(&adapter->pdev->dev, adapter->wol);
/* Auto detect PHY address */
if (hw->mac_type == e1000_ce4100) {
for (i = 0; i < 32; i++) {
hw->phy_addr = i;
e1000_read_phy_reg(hw, PHY_ID2, &tmp);
if (tmp == 0 || tmp == 0xFF) {
if (i == 31)
goto err_eeprom;
continue;
} else
break;
}
}
/* reset the hardware with the new settings */
e1000_reset(adapter);
strcpy(netdev->name, "eth%d");
err = register_netdev(netdev);
if (err)
goto err_register;
/* print bus type/speed/width info */
e_info(probe, "(PCI%s:%dMHz:%d-bit) %pM\n",
((hw->bus_type == e1000_bus_type_pcix) ? "-X" : ""),
((hw->bus_speed == e1000_bus_speed_133) ? 133 :
(hw->bus_speed == e1000_bus_speed_120) ? 120 :
(hw->bus_speed == e1000_bus_speed_100) ? 100 :
(hw->bus_speed == e1000_bus_speed_66) ? 66 : 33),
((hw->bus_width == e1000_bus_width_64) ? 64 : 32),
netdev->dev_addr);
/* carrier off reporting is important to ethtool even BEFORE open */
netif_carrier_off(netdev);
e_info(probe, "Intel(R) PRO/1000 Network Connection\n");
cards_found++;
return 0;
err_register:
err_eeprom:
e1000_phy_hw_reset(hw);
if (hw->flash_address)
iounmap(hw->flash_address);
kfree(adapter->tx_ring);
kfree(adapter->rx_ring);
err_dma:
err_sw_init:
err_mdio_ioremap:
iounmap(ce4100_gbe_mdio_base_virt);
iounmap(hw->hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
pci_release_selected_regions(pdev, bars);
err_pci_reg:
pci_disable_device(pdev);
return err;
}
/**
* e1000_remove - Device Removal Routine
* @pdev: PCI device information struct
*
* e1000_remove is called by the PCI subsystem to alert the driver
* that it should release a PCI device. The could be caused by a
* Hot-Plug event, or because the driver is going to be removed from
* memory.
**/
static void __devexit e1000_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
set_bit(__E1000_DOWN, &adapter->flags);
del_timer_sync(&adapter->tx_fifo_stall_timer);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_info_timer);
cancel_work_sync(&adapter->reset_task);
e1000_release_manageability(adapter);
unregister_netdev(netdev);
e1000_phy_hw_reset(hw);
kfree(adapter->tx_ring);
kfree(adapter->rx_ring);
iounmap(hw->hw_addr);
if (hw->flash_address)
iounmap(hw->flash_address);
pci_release_selected_regions(pdev, adapter->bars);
free_netdev(netdev);
pci_disable_device(pdev);
}
/**
* e1000_sw_init - Initialize general software structures (struct e1000_adapter)
* @adapter: board private structure to initialize
*
* e1000_sw_init initializes the Adapter private data structure.
* e1000_init_hw_struct MUST be called before this function
**/
static int __devinit e1000_sw_init(struct e1000_adapter *adapter)
{
adapter->rx_buffer_len = MAXIMUM_ETHERNET_VLAN_SIZE;
adapter->num_tx_queues = 1;
adapter->num_rx_queues = 1;
if (e1000_alloc_queues(adapter)) {
e_err(probe, "Unable to allocate memory for queues\n");
return -ENOMEM;
}
/* Explicitly disable IRQ since the NIC can be in any state. */
e1000_irq_disable(adapter);
spin_lock_init(&adapter->stats_lock);
set_bit(__E1000_DOWN, &adapter->flags);
return 0;
}
/**
* e1000_alloc_queues - Allocate memory for all rings
* @adapter: board private structure to initialize
*
* We allocate one ring per queue at run-time since we don't know the
* number of queues at compile-time.
**/
static int __devinit e1000_alloc_queues(struct e1000_adapter *adapter)
{
adapter->tx_ring = kcalloc(adapter->num_tx_queues,
sizeof(struct e1000_tx_ring), GFP_KERNEL);
if (!adapter->tx_ring)
return -ENOMEM;
adapter->rx_ring = kcalloc(adapter->num_rx_queues,
sizeof(struct e1000_rx_ring), GFP_KERNEL);
if (!adapter->rx_ring) {
kfree(adapter->tx_ring);
return -ENOMEM;
}
return E1000_SUCCESS;
}
/**
* e1000_open - Called when a network interface is made active
* @netdev: network interface device structure
*
* Returns 0 on success, negative value on failure
*
* The open entry point is called when a network interface is made
* active by the system (IFF_UP). At this point all resources needed
* for transmit and receive operations are allocated, the interrupt
* handler is registered with the OS, the watchdog timer is started,
* and the stack is notified that the interface is ready.
**/
static int e1000_open(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
int err;
/* disallow open during test */
if (test_bit(__E1000_TESTING, &adapter->flags))
return -EBUSY;
netif_carrier_off(netdev);
/* allocate transmit descriptors */
err = e1000_setup_all_tx_resources(adapter);
if (err)
goto err_setup_tx;
/* allocate receive descriptors */
err = e1000_setup_all_rx_resources(adapter);
if (err)
goto err_setup_rx;
e1000_power_up_phy(adapter);
adapter->mng_vlan_id = E1000_MNG_VLAN_NONE;
if ((hw->mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN_SUPPORT)) {
e1000_update_mng_vlan(adapter);
}
/* before we allocate an interrupt, we must be ready to handle it.
* Setting DEBUG_SHIRQ in the kernel makes it fire an interrupt
* as soon as we call pci_request_irq, so we have to setup our
* clean_rx handler before we do so. */
e1000_configure(adapter);
err = e1000_request_irq(adapter);
if (err)
goto err_req_irq;
/* From here on the code is the same as e1000_up() */
clear_bit(__E1000_DOWN, &adapter->flags);
napi_enable(&adapter->napi);
e1000_irq_enable(adapter);
netif_start_queue(netdev);
/* fire a link status change interrupt to start the watchdog */
ew32(ICS, E1000_ICS_LSC);
return E1000_SUCCESS;
err_req_irq:
e1000_power_down_phy(adapter);
e1000_free_all_rx_resources(adapter);
err_setup_rx:
e1000_free_all_tx_resources(adapter);
err_setup_tx:
e1000_reset(adapter);
return err;
}
/**
* e1000_close - Disables a network interface
* @netdev: network interface device structure
*
* Returns 0, this is not allowed to fail
*
* The close entry point is called when an interface is de-activated
* by the OS. The hardware is still under the drivers control, but
* needs to be disabled. A global MAC reset is issued to stop the
* hardware, and all transmit and receive resources are freed.
**/
static int e1000_close(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
WARN_ON(test_bit(__E1000_RESETTING, &adapter->flags));
e1000_down(adapter);
e1000_power_down_phy(adapter);
e1000_free_irq(adapter);
e1000_free_all_tx_resources(adapter);
e1000_free_all_rx_resources(adapter);
/* kill manageability vlan ID if supported, but not if a vlan with
* the same ID is registered on the host OS (let 8021q kill it) */
if ((hw->mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN_SUPPORT) &&
!(adapter->vlgrp &&
vlan_group_get_device(adapter->vlgrp, adapter->mng_vlan_id))) {
e1000_vlan_rx_kill_vid(netdev, adapter->mng_vlan_id);
}
return 0;
}
/**
* e1000_check_64k_bound - check that memory doesn't cross 64kB boundary
* @adapter: address of board private structure
* @start: address of beginning of memory
* @len: length of memory
**/
static bool e1000_check_64k_bound(struct e1000_adapter *adapter, void *start,
unsigned long len)
{
struct e1000_hw *hw = &adapter->hw;
unsigned long begin = (unsigned long)start;
unsigned long end = begin + len;
/* First rev 82545 and 82546 need to not allow any memory
* write location to cross 64k boundary due to errata 23 */
if (hw->mac_type == e1000_82545 ||
hw->mac_type == e1000_ce4100 ||
hw->mac_type == e1000_82546) {
return ((begin ^ (end - 1)) >> 16) != 0 ? false : true;
}
return true;
}
/**
* e1000_setup_tx_resources - allocate Tx resources (Descriptors)
* @adapter: board private structure
* @txdr: tx descriptor ring (for a specific queue) to setup
*
* Return 0 on success, negative on failure
**/
static int e1000_setup_tx_resources(struct e1000_adapter *adapter,
struct e1000_tx_ring *txdr)
{
struct pci_dev *pdev = adapter->pdev;
int size;
size = sizeof(struct e1000_buffer) * txdr->count;
txdr->buffer_info = vzalloc(size);
if (!txdr->buffer_info) {
e_err(probe, "Unable to allocate memory for the Tx descriptor "
"ring\n");
return -ENOMEM;
}
/* round up to nearest 4K */
txdr->size = txdr->count * sizeof(struct e1000_tx_desc);
txdr->size = ALIGN(txdr->size, 4096);
txdr->desc = dma_alloc_coherent(&pdev->dev, txdr->size, &txdr->dma,
GFP_KERNEL);
if (!txdr->desc) {
setup_tx_desc_die:
vfree(txdr->buffer_info);
e_err(probe, "Unable to allocate memory for the Tx descriptor "
"ring\n");
return -ENOMEM;
}
/* Fix for errata 23, can't cross 64kB boundary */
if (!e1000_check_64k_bound(adapter, txdr->desc, txdr->size)) {
void *olddesc = txdr->desc;
dma_addr_t olddma = txdr->dma;
e_err(tx_err, "txdr align check failed: %u bytes at %p\n",
txdr->size, txdr->desc);
/* Try again, without freeing the previous */
txdr->desc = dma_alloc_coherent(&pdev->dev, txdr->size,
&txdr->dma, GFP_KERNEL);
/* Failed allocation, critical failure */
if (!txdr->desc) {
dma_free_coherent(&pdev->dev, txdr->size, olddesc,
olddma);
goto setup_tx_desc_die;
}
if (!e1000_check_64k_bound(adapter, txdr->desc, txdr->size)) {
/* give up */
dma_free_coherent(&pdev->dev, txdr->size, txdr->desc,
txdr->dma);
dma_free_coherent(&pdev->dev, txdr->size, olddesc,
olddma);
e_err(probe, "Unable to allocate aligned memory "
"for the transmit descriptor ring\n");
vfree(txdr->buffer_info);
return -ENOMEM;
} else {
/* Free old allocation, new allocation was successful */
dma_free_coherent(&pdev->dev, txdr->size, olddesc,
olddma);
}
}
memset(txdr->desc, 0, txdr->size);
txdr->next_to_use = 0;
txdr->next_to_clean = 0;
return 0;
}
/**
* e1000_setup_all_tx_resources - wrapper to allocate Tx resources
* (Descriptors) for all queues
* @adapter: board private structure
*
* Return 0 on success, negative on failure
**/
int e1000_setup_all_tx_resources(struct e1000_adapter *adapter)
{
int i, err = 0;
for (i = 0; i < adapter->num_tx_queues; i++) {
err = e1000_setup_tx_resources(adapter, &adapter->tx_ring[i]);
if (err) {
e_err(probe, "Allocation for Tx Queue %u failed\n", i);
for (i-- ; i >= 0; i--)
e1000_free_tx_resources(adapter,
&adapter->tx_ring[i]);
break;
}
}
return err;
}
/**
* e1000_configure_tx - Configure 8254x Transmit Unit after Reset
* @adapter: board private structure
*
* Configure the Tx unit of the MAC after a reset.
**/
static void e1000_configure_tx(struct e1000_adapter *adapter)
{
u64 tdba;
struct e1000_hw *hw = &adapter->hw;
u32 tdlen, tctl, tipg;
u32 ipgr1, ipgr2;
/* Setup the HW Tx Head and Tail descriptor pointers */
switch (adapter->num_tx_queues) {
case 1:
default:
tdba = adapter->tx_ring[0].dma;
tdlen = adapter->tx_ring[0].count *
sizeof(struct e1000_tx_desc);
ew32(TDLEN, tdlen);
ew32(TDBAH, (tdba >> 32));
ew32(TDBAL, (tdba & 0x00000000ffffffffULL));
ew32(TDT, 0);
ew32(TDH, 0);
adapter->tx_ring[0].tdh = ((hw->mac_type >= e1000_82543) ? E1000_TDH : E1000_82542_TDH);
adapter->tx_ring[0].tdt = ((hw->mac_type >= e1000_82543) ? E1000_TDT : E1000_82542_TDT);
break;
}
/* Set the default values for the Tx Inter Packet Gap timer */
if ((hw->media_type == e1000_media_type_fiber ||
hw->media_type == e1000_media_type_internal_serdes))
tipg = DEFAULT_82543_TIPG_IPGT_FIBER;
else
tipg = DEFAULT_82543_TIPG_IPGT_COPPER;
switch (hw->mac_type) {
case e1000_82542_rev2_0:
case e1000_82542_rev2_1:
tipg = DEFAULT_82542_TIPG_IPGT;
ipgr1 = DEFAULT_82542_TIPG_IPGR1;
ipgr2 = DEFAULT_82542_TIPG_IPGR2;
break;
default:
ipgr1 = DEFAULT_82543_TIPG_IPGR1;
ipgr2 = DEFAULT_82543_TIPG_IPGR2;
break;
}
tipg |= ipgr1 << E1000_TIPG_IPGR1_SHIFT;
tipg |= ipgr2 << E1000_TIPG_IPGR2_SHIFT;
ew32(TIPG, tipg);
/* Set the Tx Interrupt Delay register */
ew32(TIDV, adapter->tx_int_delay);
if (hw->mac_type >= e1000_82540)
ew32(TADV, adapter->tx_abs_int_delay);
/* Program the Transmit Control Register */
tctl = er32(TCTL);
tctl &= ~E1000_TCTL_CT;
tctl |= E1000_TCTL_PSP | E1000_TCTL_RTLC |
(E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT);
e1000_config_collision_dist(hw);
/* Setup Transmit Descriptor Settings for eop descriptor */
adapter->txd_cmd = E1000_TXD_CMD_EOP | E1000_TXD_CMD_IFCS;
/* only set IDE if we are delaying interrupts using the timers */
if (adapter->tx_int_delay)
adapter->txd_cmd |= E1000_TXD_CMD_IDE;
if (hw->mac_type < e1000_82543)
adapter->txd_cmd |= E1000_TXD_CMD_RPS;
else
adapter->txd_cmd |= E1000_TXD_CMD_RS;
/* Cache if we're 82544 running in PCI-X because we'll
* need this to apply a workaround later in the send path. */
if (hw->mac_type == e1000_82544 &&
hw->bus_type == e1000_bus_type_pcix)
adapter->pcix_82544 = 1;
ew32(TCTL, tctl);
}
/**
* e1000_setup_rx_resources - allocate Rx resources (Descriptors)
* @adapter: board private structure
* @rxdr: rx descriptor ring (for a specific queue) to setup
*
* Returns 0 on success, negative on failure
**/
static int e1000_setup_rx_resources(struct e1000_adapter *adapter,
struct e1000_rx_ring *rxdr)
{
struct pci_dev *pdev = adapter->pdev;
int size, desc_len;
size = sizeof(struct e1000_buffer) * rxdr->count;
rxdr->buffer_info = vzalloc(size);
if (!rxdr->buffer_info) {
e_err(probe, "Unable to allocate memory for the Rx descriptor "
"ring\n");
return -ENOMEM;
}
desc_len = sizeof(struct e1000_rx_desc);
/* Round up to nearest 4K */
rxdr->size = rxdr->count * desc_len;
rxdr->size = ALIGN(rxdr->size, 4096);
rxdr->desc = dma_alloc_coherent(&pdev->dev, rxdr->size, &rxdr->dma,
GFP_KERNEL);
if (!rxdr->desc) {
e_err(probe, "Unable to allocate memory for the Rx descriptor "
"ring\n");
setup_rx_desc_die:
vfree(rxdr->buffer_info);
return -ENOMEM;
}
/* Fix for errata 23, can't cross 64kB boundary */
if (!e1000_check_64k_bound(adapter, rxdr->desc, rxdr->size)) {
void *olddesc = rxdr->desc;
dma_addr_t olddma = rxdr->dma;
e_err(rx_err, "rxdr align check failed: %u bytes at %p\n",
rxdr->size, rxdr->desc);
/* Try again, without freeing the previous */
rxdr->desc = dma_alloc_coherent(&pdev->dev, rxdr->size,
&rxdr->dma, GFP_KERNEL);
/* Failed allocation, critical failure */
if (!rxdr->desc) {
dma_free_coherent(&pdev->dev, rxdr->size, olddesc,
olddma);
e_err(probe, "Unable to allocate memory for the Rx "
"descriptor ring\n");
goto setup_rx_desc_die;
}
if (!e1000_check_64k_bound(adapter, rxdr->desc, rxdr->size)) {
/* give up */
dma_free_coherent(&pdev->dev, rxdr->size, rxdr->desc,
rxdr->dma);
dma_free_coherent(&pdev->dev, rxdr->size, olddesc,
olddma);
e_err(probe, "Unable to allocate aligned memory for "
"the Rx descriptor ring\n");
goto setup_rx_desc_die;
} else {
/* Free old allocation, new allocation was successful */
dma_free_coherent(&pdev->dev, rxdr->size, olddesc,
olddma);
}
}
memset(rxdr->desc, 0, rxdr->size);
rxdr->next_to_clean = 0;
rxdr->next_to_use = 0;
rxdr->rx_skb_top = NULL;
return 0;
}
/**
* e1000_setup_all_rx_resources - wrapper to allocate Rx resources
* (Descriptors) for all queues
* @adapter: board private structure
*
* Return 0 on success, negative on failure
**/
int e1000_setup_all_rx_resources(struct e1000_adapter *adapter)
{
int i, err = 0;
for (i = 0; i < adapter->num_rx_queues; i++) {
err = e1000_setup_rx_resources(adapter, &adapter->rx_ring[i]);
if (err) {
e_err(probe, "Allocation for Rx Queue %u failed\n", i);
for (i-- ; i >= 0; i--)
e1000_free_rx_resources(adapter,
&adapter->rx_ring[i]);
break;
}
}
return err;
}
/**
* e1000_setup_rctl - configure the receive control registers
* @adapter: Board private structure
**/
static void e1000_setup_rctl(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 rctl;
rctl = er32(RCTL);
rctl &= ~(3 << E1000_RCTL_MO_SHIFT);
rctl |= E1000_RCTL_EN | E1000_RCTL_BAM |
E1000_RCTL_LBM_NO | E1000_RCTL_RDMTS_HALF |
(hw->mc_filter_type << E1000_RCTL_MO_SHIFT);
if (hw->tbi_compatibility_on == 1)
rctl |= E1000_RCTL_SBP;
else
rctl &= ~E1000_RCTL_SBP;
if (adapter->netdev->mtu <= ETH_DATA_LEN)
rctl &= ~E1000_RCTL_LPE;
else
rctl |= E1000_RCTL_LPE;
/* Setup buffer sizes */
rctl &= ~E1000_RCTL_SZ_4096;
rctl |= E1000_RCTL_BSEX;
switch (adapter->rx_buffer_len) {
case E1000_RXBUFFER_2048:
default:
rctl |= E1000_RCTL_SZ_2048;
rctl &= ~E1000_RCTL_BSEX;
break;
case E1000_RXBUFFER_4096:
rctl |= E1000_RCTL_SZ_4096;
break;
case E1000_RXBUFFER_8192:
rctl |= E1000_RCTL_SZ_8192;
break;
case E1000_RXBUFFER_16384:
rctl |= E1000_RCTL_SZ_16384;
break;
}
ew32(RCTL, rctl);
}
/**
* e1000_configure_rx - Configure 8254x Receive Unit after Reset
* @adapter: board private structure
*
* Configure the Rx unit of the MAC after a reset.
**/
static void e1000_configure_rx(struct e1000_adapter *adapter)
{
u64 rdba;
struct e1000_hw *hw = &adapter->hw;
u32 rdlen, rctl, rxcsum;
if (adapter->netdev->mtu > ETH_DATA_LEN) {
rdlen = adapter->rx_ring[0].count *
sizeof(struct e1000_rx_desc);
adapter->clean_rx = e1000_clean_jumbo_rx_irq;
adapter->alloc_rx_buf = e1000_alloc_jumbo_rx_buffers;
} else {
rdlen = adapter->rx_ring[0].count *
sizeof(struct e1000_rx_desc);
adapter->clean_rx = e1000_clean_rx_irq;
adapter->alloc_rx_buf = e1000_alloc_rx_buffers;
}
/* disable receives while setting up the descriptors */
rctl = er32(RCTL);
ew32(RCTL, rctl & ~E1000_RCTL_EN);
/* set the Receive Delay Timer Register */
ew32(RDTR, adapter->rx_int_delay);
if (hw->mac_type >= e1000_82540) {
ew32(RADV, adapter->rx_abs_int_delay);
if (adapter->itr_setting != 0)
ew32(ITR, 1000000000 / (adapter->itr * 256));
}
/* Setup the HW Rx Head and Tail Descriptor Pointers and
* the Base and Length of the Rx Descriptor Ring */
switch (adapter->num_rx_queues) {
case 1:
default:
rdba = adapter->rx_ring[0].dma;
ew32(RDLEN, rdlen);
ew32(RDBAH, (rdba >> 32));
ew32(RDBAL, (rdba & 0x00000000ffffffffULL));
ew32(RDT, 0);
ew32(RDH, 0);
adapter->rx_ring[0].rdh = ((hw->mac_type >= e1000_82543) ? E1000_RDH : E1000_82542_RDH);
adapter->rx_ring[0].rdt = ((hw->mac_type >= e1000_82543) ? E1000_RDT : E1000_82542_RDT);
break;
}
/* Enable 82543 Receive Checksum Offload for TCP and UDP */
if (hw->mac_type >= e1000_82543) {
rxcsum = er32(RXCSUM);
if (adapter->rx_csum)
rxcsum |= E1000_RXCSUM_TUOFL;
else
/* don't need to clear IPPCSE as it defaults to 0 */
rxcsum &= ~E1000_RXCSUM_TUOFL;
ew32(RXCSUM, rxcsum);
}
/* Enable Receives */
ew32(RCTL, rctl);
}
/**
* e1000_free_tx_resources - Free Tx Resources per Queue
* @adapter: board private structure
* @tx_ring: Tx descriptor ring for a specific queue
*
* Free all transmit software resources
**/
static void e1000_free_tx_resources(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring)
{
struct pci_dev *pdev = adapter->pdev;
e1000_clean_tx_ring(adapter, tx_ring);
vfree(tx_ring->buffer_info);
tx_ring->buffer_info = NULL;
dma_free_coherent(&pdev->dev, tx_ring->size, tx_ring->desc,
tx_ring->dma);
tx_ring->desc = NULL;
}
/**
* e1000_free_all_tx_resources - Free Tx Resources for All Queues
* @adapter: board private structure
*
* Free all transmit software resources
**/
void e1000_free_all_tx_resources(struct e1000_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_tx_queues; i++)
e1000_free_tx_resources(adapter, &adapter->tx_ring[i]);
}
static void e1000_unmap_and_free_tx_resource(struct e1000_adapter *adapter,
struct e1000_buffer *buffer_info)
{
if (buffer_info->dma) {
if (buffer_info->mapped_as_page)
dma_unmap_page(&adapter->pdev->dev, buffer_info->dma,
buffer_info->length, DMA_TO_DEVICE);
else
dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
buffer_info->length,
DMA_TO_DEVICE);
buffer_info->dma = 0;
}
if (buffer_info->skb) {
dev_kfree_skb_any(buffer_info->skb);
buffer_info->skb = NULL;
}
buffer_info->time_stamp = 0;
/* buffer_info must be completely set up in the transmit path */
}
/**
* e1000_clean_tx_ring - Free Tx Buffers
* @adapter: board private structure
* @tx_ring: ring to be cleaned
**/
static void e1000_clean_tx_ring(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring)
{
struct e1000_hw *hw = &adapter->hw;
struct e1000_buffer *buffer_info;
unsigned long size;
unsigned int i;
/* Free all the Tx ring sk_buffs */
for (i = 0; i < tx_ring->count; i++) {
buffer_info = &tx_ring->buffer_info[i];
e1000_unmap_and_free_tx_resource(adapter, buffer_info);
}
size = sizeof(struct e1000_buffer) * tx_ring->count;
memset(tx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(tx_ring->desc, 0, tx_ring->size);
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
tx_ring->last_tx_tso = 0;
writel(0, hw->hw_addr + tx_ring->tdh);
writel(0, hw->hw_addr + tx_ring->tdt);
}
/**
* e1000_clean_all_tx_rings - Free Tx Buffers for all queues
* @adapter: board private structure
**/
static void e1000_clean_all_tx_rings(struct e1000_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_tx_queues; i++)
e1000_clean_tx_ring(adapter, &adapter->tx_ring[i]);
}
/**
* e1000_free_rx_resources - Free Rx Resources
* @adapter: board private structure
* @rx_ring: ring to clean the resources from
*
* Free all receive software resources
**/
static void e1000_free_rx_resources(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring)
{
struct pci_dev *pdev = adapter->pdev;
e1000_clean_rx_ring(adapter, rx_ring);
vfree(rx_ring->buffer_info);
rx_ring->buffer_info = NULL;
dma_free_coherent(&pdev->dev, rx_ring->size, rx_ring->desc,
rx_ring->dma);
rx_ring->desc = NULL;
}
/**
* e1000_free_all_rx_resources - Free Rx Resources for All Queues
* @adapter: board private structure
*
* Free all receive software resources
**/
void e1000_free_all_rx_resources(struct e1000_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_rx_queues; i++)
e1000_free_rx_resources(adapter, &adapter->rx_ring[i]);
}
/**
* e1000_clean_rx_ring - Free Rx Buffers per Queue
* @adapter: board private structure
* @rx_ring: ring to free buffers from
**/
static void e1000_clean_rx_ring(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring)
{
struct e1000_hw *hw = &adapter->hw;
struct e1000_buffer *buffer_info;
struct pci_dev *pdev = adapter->pdev;
unsigned long size;
unsigned int i;
/* Free all the Rx ring sk_buffs */
for (i = 0; i < rx_ring->count; i++) {
buffer_info = &rx_ring->buffer_info[i];
if (buffer_info->dma &&
adapter->clean_rx == e1000_clean_rx_irq) {
dma_unmap_single(&pdev->dev, buffer_info->dma,
buffer_info->length,
DMA_FROM_DEVICE);
} else if (buffer_info->dma &&
adapter->clean_rx == e1000_clean_jumbo_rx_irq) {
dma_unmap_page(&pdev->dev, buffer_info->dma,
buffer_info->length,
DMA_FROM_DEVICE);
}
buffer_info->dma = 0;
if (buffer_info->page) {
put_page(buffer_info->page);
buffer_info->page = NULL;
}
if (buffer_info->skb) {
dev_kfree_skb(buffer_info->skb);
buffer_info->skb = NULL;
}
}
/* there also may be some cached data from a chained receive */
if (rx_ring->rx_skb_top) {
dev_kfree_skb(rx_ring->rx_skb_top);
rx_ring->rx_skb_top = NULL;
}
size = sizeof(struct e1000_buffer) * rx_ring->count;
memset(rx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(rx_ring->desc, 0, rx_ring->size);
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
writel(0, hw->hw_addr + rx_ring->rdh);
writel(0, hw->hw_addr + rx_ring->rdt);
}
/**
* e1000_clean_all_rx_rings - Free Rx Buffers for all queues
* @adapter: board private structure
**/
static void e1000_clean_all_rx_rings(struct e1000_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_rx_queues; i++)
e1000_clean_rx_ring(adapter, &adapter->rx_ring[i]);
}
/* The 82542 2.0 (revision 2) needs to have the receive unit in reset
* and memory write and invalidate disabled for certain operations
*/
static void e1000_enter_82542_rst(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
u32 rctl;
e1000_pci_clear_mwi(hw);
rctl = er32(RCTL);
rctl |= E1000_RCTL_RST;
ew32(RCTL, rctl);
E1000_WRITE_FLUSH();
mdelay(5);
if (netif_running(netdev))
e1000_clean_all_rx_rings(adapter);
}
static void e1000_leave_82542_rst(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
u32 rctl;
rctl = er32(RCTL);
rctl &= ~E1000_RCTL_RST;
ew32(RCTL, rctl);
E1000_WRITE_FLUSH();
mdelay(5);
if (hw->pci_cmd_word & PCI_COMMAND_INVALIDATE)
e1000_pci_set_mwi(hw);
if (netif_running(netdev)) {
/* No need to loop, because 82542 supports only 1 queue */
struct e1000_rx_ring *ring = &adapter->rx_ring[0];
e1000_configure_rx(adapter);
adapter->alloc_rx_buf(adapter, ring, E1000_DESC_UNUSED(ring));
}
}
/**
* e1000_set_mac - Change the Ethernet Address of the NIC
* @netdev: network interface device structure
* @p: pointer to an address structure
*
* Returns 0 on success, negative on failure
**/
static int e1000_set_mac(struct net_device *netdev, void *p)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
/* 82542 2.0 needs to be in reset to write receive address registers */
if (hw->mac_type == e1000_82542_rev2_0)
e1000_enter_82542_rst(adapter);
memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
memcpy(hw->mac_addr, addr->sa_data, netdev->addr_len);
e1000_rar_set(hw, hw->mac_addr, 0);
if (hw->mac_type == e1000_82542_rev2_0)
e1000_leave_82542_rst(adapter);
return 0;
}
/**
* e1000_set_rx_mode - Secondary Unicast, Multicast and Promiscuous mode set
* @netdev: network interface device structure
*
* The set_rx_mode entry point is called whenever the unicast or multicast
* address lists or the network interface flags are updated. This routine is
* responsible for configuring the hardware for proper unicast, multicast,
* promiscuous mode, and all-multi behavior.
**/
static void e1000_set_rx_mode(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct netdev_hw_addr *ha;
bool use_uc = false;
u32 rctl;
u32 hash_value;
int i, rar_entries = E1000_RAR_ENTRIES;
int mta_reg_count = E1000_NUM_MTA_REGISTERS;
u32 *mcarray = kcalloc(mta_reg_count, sizeof(u32), GFP_ATOMIC);
if (!mcarray) {
e_err(probe, "memory allocation failed\n");
return;
}
/* Check for Promiscuous and All Multicast modes */
rctl = er32(RCTL);
if (netdev->flags & IFF_PROMISC) {
rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE);
rctl &= ~E1000_RCTL_VFE;
} else {
if (netdev->flags & IFF_ALLMULTI)
rctl |= E1000_RCTL_MPE;
else
rctl &= ~E1000_RCTL_MPE;
/* Enable VLAN filter if there is a VLAN */
if (adapter->vlgrp)
rctl |= E1000_RCTL_VFE;
}
if (netdev_uc_count(netdev) > rar_entries - 1) {
rctl |= E1000_RCTL_UPE;
} else if (!(netdev->flags & IFF_PROMISC)) {
rctl &= ~E1000_RCTL_UPE;
use_uc = true;
}
ew32(RCTL, rctl);
/* 82542 2.0 needs to be in reset to write receive address registers */
if (hw->mac_type == e1000_82542_rev2_0)
e1000_enter_82542_rst(adapter);
/* load the first 14 addresses into the exact filters 1-14. Unicast
* addresses take precedence to avoid disabling unicast filtering
* when possible.
*
* RAR 0 is used for the station MAC address
* if there are not 14 addresses, go ahead and clear the filters
*/
i = 1;
if (use_uc)
netdev_for_each_uc_addr(ha, netdev) {
if (i == rar_entries)
break;
e1000_rar_set(hw, ha->addr, i++);
}
netdev_for_each_mc_addr(ha, netdev) {
if (i == rar_entries) {
/* load any remaining addresses into the hash table */
u32 hash_reg, hash_bit, mta;
hash_value = e1000_hash_mc_addr(hw, ha->addr);
hash_reg = (hash_value >> 5) & 0x7F;
hash_bit = hash_value & 0x1F;
mta = (1 << hash_bit);
mcarray[hash_reg] |= mta;
} else {
e1000_rar_set(hw, ha->addr, i++);
}
}
for (; i < rar_entries; i++) {
E1000_WRITE_REG_ARRAY(hw, RA, i << 1, 0);
E1000_WRITE_FLUSH();
E1000_WRITE_REG_ARRAY(hw, RA, (i << 1) + 1, 0);
E1000_WRITE_FLUSH();
}
/* write the hash table completely, write from bottom to avoid
* both stupid write combining chipsets, and flushing each write */
for (i = mta_reg_count - 1; i >= 0 ; i--) {
/*
* If we are on an 82544 has an errata where writing odd
* offsets overwrites the previous even offset, but writing
* backwards over the range solves the issue by always
* writing the odd offset first
*/
E1000_WRITE_REG_ARRAY(hw, MTA, i, mcarray[i]);
}
E1000_WRITE_FLUSH();
if (hw->mac_type == e1000_82542_rev2_0)
e1000_leave_82542_rst(adapter);
kfree(mcarray);
}
/* Need to wait a few seconds after link up to get diagnostic information from
* the phy */
static void e1000_update_phy_info(unsigned long data)
{
struct e1000_adapter *adapter = (struct e1000_adapter *)data;
schedule_work(&adapter->phy_info_task);
}
static void e1000_update_phy_info_task(struct work_struct *work)
{
struct e1000_adapter *adapter = container_of(work,
struct e1000_adapter,
phy_info_task);
struct e1000_hw *hw = &adapter->hw;
rtnl_lock();
e1000_phy_get_info(hw, &adapter->phy_info);
rtnl_unlock();
}
/**
* e1000_82547_tx_fifo_stall - Timer Call-back
* @data: pointer to adapter cast into an unsigned long
**/
static void e1000_82547_tx_fifo_stall(unsigned long data)
{
struct e1000_adapter *adapter = (struct e1000_adapter *)data;
schedule_work(&adapter->fifo_stall_task);
}
/**
* e1000_82547_tx_fifo_stall_task - task to complete work
* @work: work struct contained inside adapter struct
**/
static void e1000_82547_tx_fifo_stall_task(struct work_struct *work)
{
struct e1000_adapter *adapter = container_of(work,
struct e1000_adapter,
fifo_stall_task);
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
u32 tctl;
rtnl_lock();
if (atomic_read(&adapter->tx_fifo_stall)) {
if ((er32(TDT) == er32(TDH)) &&
(er32(TDFT) == er32(TDFH)) &&
(er32(TDFTS) == er32(TDFHS))) {
tctl = er32(TCTL);
ew32(TCTL, tctl & ~E1000_TCTL_EN);
ew32(TDFT, adapter->tx_head_addr);
ew32(TDFH, adapter->tx_head_addr);
ew32(TDFTS, adapter->tx_head_addr);
ew32(TDFHS, adapter->tx_head_addr);
ew32(TCTL, tctl);
E1000_WRITE_FLUSH();
adapter->tx_fifo_head = 0;
atomic_set(&adapter->tx_fifo_stall, 0);
netif_wake_queue(netdev);
} else if (!test_bit(__E1000_DOWN, &adapter->flags)) {
mod_timer(&adapter->tx_fifo_stall_timer, jiffies + 1);
}
}
rtnl_unlock();
}
bool e1000_has_link(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
bool link_active = false;
/* get_link_status is set on LSC (link status) interrupt or
* rx sequence error interrupt. get_link_status will stay
* false until the e1000_check_for_link establishes link
* for copper adapters ONLY
*/
switch (hw->media_type) {
case e1000_media_type_copper:
if (hw->get_link_status) {
e1000_check_for_link(hw);
link_active = !hw->get_link_status;
} else {
link_active = true;
}
break;
case e1000_media_type_fiber:
e1000_check_for_link(hw);
link_active = !!(er32(STATUS) & E1000_STATUS_LU);
break;
case e1000_media_type_internal_serdes:
e1000_check_for_link(hw);
link_active = hw->serdes_has_link;
break;
default:
break;
}
return link_active;
}
/**
* e1000_watchdog - Timer Call-back
* @data: pointer to adapter cast into an unsigned long
**/
static void e1000_watchdog(unsigned long data)
{
struct e1000_adapter *adapter = (struct e1000_adapter *)data;
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
struct e1000_tx_ring *txdr = adapter->tx_ring;
u32 link, tctl;
link = e1000_has_link(adapter);
if ((netif_carrier_ok(netdev)) && link)
goto link_up;
if (link) {
if (!netif_carrier_ok(netdev)) {
u32 ctrl;
bool txb2b = true;
/* update snapshot of PHY registers on LSC */
e1000_get_speed_and_duplex(hw,
&adapter->link_speed,
&adapter->link_duplex);
ctrl = er32(CTRL);
pr_info("%s NIC Link is Up %d Mbps %s, "
"Flow Control: %s\n",
netdev->name,
adapter->link_speed,
adapter->link_duplex == FULL_DUPLEX ?
"Full Duplex" : "Half Duplex",
((ctrl & E1000_CTRL_TFCE) && (ctrl &
E1000_CTRL_RFCE)) ? "RX/TX" : ((ctrl &
E1000_CTRL_RFCE) ? "RX" : ((ctrl &
E1000_CTRL_TFCE) ? "TX" : "None")));
/* adjust timeout factor according to speed/duplex */
adapter->tx_timeout_factor = 1;
switch (adapter->link_speed) {
case SPEED_10:
txb2b = false;
adapter->tx_timeout_factor = 16;
break;
case SPEED_100:
txb2b = false;
/* maybe add some timeout factor ? */
break;
}
/* enable transmits in the hardware */
tctl = er32(TCTL);
tctl |= E1000_TCTL_EN;
ew32(TCTL, tctl);
netif_carrier_on(netdev);
if (!test_bit(__E1000_DOWN, &adapter->flags))
mod_timer(&adapter->phy_info_timer,
round_jiffies(jiffies + 2 * HZ));
adapter->smartspeed = 0;
}
} else {
if (netif_carrier_ok(netdev)) {
adapter->link_speed = 0;
adapter->link_duplex = 0;
pr_info("%s NIC Link is Down\n",
netdev->name);
netif_carrier_off(netdev);
if (!test_bit(__E1000_DOWN, &adapter->flags))
mod_timer(&adapter->phy_info_timer,
round_jiffies(jiffies + 2 * HZ));
}
e1000_smartspeed(adapter);
}
link_up:
e1000_update_stats(adapter);
hw->tx_packet_delta = adapter->stats.tpt - adapter->tpt_old;
adapter->tpt_old = adapter->stats.tpt;
hw->collision_delta = adapter->stats.colc - adapter->colc_old;
adapter->colc_old = adapter->stats.colc;
adapter->gorcl = adapter->stats.gorcl - adapter->gorcl_old;
adapter->gorcl_old = adapter->stats.gorcl;
adapter->gotcl = adapter->stats.gotcl - adapter->gotcl_old;
adapter->gotcl_old = adapter->stats.gotcl;
e1000_update_adaptive(hw);
if (!netif_carrier_ok(netdev)) {
if (E1000_DESC_UNUSED(txdr) + 1 < txdr->count) {
/* We've lost link, so the controller stops DMA,
* but we've got queued Tx work that's never going
* to get done, so reset controller to flush Tx.
* (Do the reset outside of interrupt context). */
adapter->tx_timeout_count++;
schedule_work(&adapter->reset_task);
/* return immediately since reset is imminent */
return;
}
}
/* Simple mode for Interrupt Throttle Rate (ITR) */
if (hw->mac_type >= e1000_82540 && adapter->itr_setting == 4) {
/*
* Symmetric Tx/Rx gets a reduced ITR=2000;
* Total asymmetrical Tx or Rx gets ITR=8000;
* everyone else is between 2000-8000.
*/
u32 goc = (adapter->gotcl + adapter->gorcl) / 10000;
u32 dif = (adapter->gotcl > adapter->gorcl ?
adapter->gotcl - adapter->gorcl :
adapter->gorcl - adapter->gotcl) / 10000;
u32 itr = goc > 0 ? (dif * 6000 / goc + 2000) : 8000;
ew32(ITR, 1000000000 / (itr * 256));
}
/* Cause software interrupt to ensure rx ring is cleaned */
ew32(ICS, E1000_ICS_RXDMT0);
/* Force detection of hung controller every watchdog period */
adapter->detect_tx_hung = true;
/* Reset the timer */
if (!test_bit(__E1000_DOWN, &adapter->flags))
mod_timer(&adapter->watchdog_timer,
round_jiffies(jiffies + 2 * HZ));
}
enum latency_range {
lowest_latency = 0,
low_latency = 1,
bulk_latency = 2,
latency_invalid = 255
};
/**
* e1000_update_itr - update the dynamic ITR value based on statistics
* @adapter: pointer to adapter
* @itr_setting: current adapter->itr
* @packets: the number of packets during this measurement interval
* @bytes: the number of bytes during this measurement interval
*
* Stores a new ITR value based on packets and byte
* counts during the last interrupt. The advantage of per interrupt
* computation is faster updates and more accurate ITR for the current
* traffic pattern. Constants in this function were computed
* based on theoretical maximum wire speed and thresholds were set based
* on testing data as well as attempting to minimize response time
* while increasing bulk throughput.
* this functionality is controlled by the InterruptThrottleRate module
* parameter (see e1000_param.c)
**/
static unsigned int e1000_update_itr(struct e1000_adapter *adapter,
u16 itr_setting, int packets, int bytes)
{
unsigned int retval = itr_setting;
struct e1000_hw *hw = &adapter->hw;
if (unlikely(hw->mac_type < e1000_82540))
goto update_itr_done;
if (packets == 0)
goto update_itr_done;
switch (itr_setting) {
case lowest_latency:
/* jumbo frames get bulk treatment*/
if (bytes/packets > 8000)
retval = bulk_latency;
else if ((packets < 5) && (bytes > 512))
retval = low_latency;
break;
case low_latency: /* 50 usec aka 20000 ints/s */
if (bytes > 10000) {
/* jumbo frames need bulk latency setting */
if (bytes/packets > 8000)
retval = bulk_latency;
else if ((packets < 10) || ((bytes/packets) > 1200))
retval = bulk_latency;
else if ((packets > 35))
retval = lowest_latency;
} else if (bytes/packets > 2000)
retval = bulk_latency;
else if (packets <= 2 && bytes < 512)
retval = lowest_latency;
break;
case bulk_latency: /* 250 usec aka 4000 ints/s */
if (bytes > 25000) {
if (packets > 35)
retval = low_latency;
} else if (bytes < 6000) {
retval = low_latency;
}
break;
}
update_itr_done:
return retval;
}
static void e1000_set_itr(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u16 current_itr;
u32 new_itr = adapter->itr;
if (unlikely(hw->mac_type < e1000_82540))
return;
/* for non-gigabit speeds, just fix the interrupt rate at 4000 */
if (unlikely(adapter->link_speed != SPEED_1000)) {
current_itr = 0;
new_itr = 4000;
goto set_itr_now;
}
adapter->tx_itr = e1000_update_itr(adapter,
adapter->tx_itr,
adapter->total_tx_packets,
adapter->total_tx_bytes);
/* conservative mode (itr 3) eliminates the lowest_latency setting */
if (adapter->itr_setting == 3 && adapter->tx_itr == lowest_latency)
adapter->tx_itr = low_latency;
adapter->rx_itr = e1000_update_itr(adapter,
adapter->rx_itr,
adapter->total_rx_packets,
adapter->total_rx_bytes);
/* conservative mode (itr 3) eliminates the lowest_latency setting */
if (adapter->itr_setting == 3 && adapter->rx_itr == lowest_latency)
adapter->rx_itr = low_latency;
current_itr = max(adapter->rx_itr, adapter->tx_itr);
switch (current_itr) {
/* counts and packets in update_itr are dependent on these numbers */
case lowest_latency:
new_itr = 70000;
break;
case low_latency:
new_itr = 20000; /* aka hwitr = ~200 */
break;
case bulk_latency:
new_itr = 4000;
break;
default:
break;
}
set_itr_now:
if (new_itr != adapter->itr) {
/* this attempts to bias the interrupt rate towards Bulk
* by adding intermediate steps when interrupt rate is
* increasing */
new_itr = new_itr > adapter->itr ?
min(adapter->itr + (new_itr >> 2), new_itr) :
new_itr;
adapter->itr = new_itr;
ew32(ITR, 1000000000 / (new_itr * 256));
}
}
#define E1000_TX_FLAGS_CSUM 0x00000001
#define E1000_TX_FLAGS_VLAN 0x00000002
#define E1000_TX_FLAGS_TSO 0x00000004
#define E1000_TX_FLAGS_IPV4 0x00000008
#define E1000_TX_FLAGS_VLAN_MASK 0xffff0000
#define E1000_TX_FLAGS_VLAN_SHIFT 16
static int e1000_tso(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring, struct sk_buff *skb)
{
struct e1000_context_desc *context_desc;
struct e1000_buffer *buffer_info;
unsigned int i;
u32 cmd_length = 0;
u16 ipcse = 0, tucse, mss;
u8 ipcss, ipcso, tucss, tucso, hdr_len;
int err;
if (skb_is_gso(skb)) {
if (skb_header_cloned(skb)) {
err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
if (err)
return err;
}
hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb);
mss = skb_shinfo(skb)->gso_size;
if (skb->protocol == htons(ETH_P_IP)) {
struct iphdr *iph = ip_hdr(skb);
iph->tot_len = 0;
iph->check = 0;
tcp_hdr(skb)->check = ~csum_tcpudp_magic(iph->saddr,
iph->daddr, 0,
IPPROTO_TCP,
0);
cmd_length = E1000_TXD_CMD_IP;
ipcse = skb_transport_offset(skb) - 1;
} else if (skb->protocol == htons(ETH_P_IPV6)) {
ipv6_hdr(skb)->payload_len = 0;
tcp_hdr(skb)->check =
~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
0, IPPROTO_TCP, 0);
ipcse = 0;
}
ipcss = skb_network_offset(skb);
ipcso = (void *)&(ip_hdr(skb)->check) - (void *)skb->data;
tucss = skb_transport_offset(skb);
tucso = (void *)&(tcp_hdr(skb)->check) - (void *)skb->data;
tucse = 0;
cmd_length |= (E1000_TXD_CMD_DEXT | E1000_TXD_CMD_TSE |
E1000_TXD_CMD_TCP | (skb->len - (hdr_len)));
i = tx_ring->next_to_use;
context_desc = E1000_CONTEXT_DESC(*tx_ring, i);
buffer_info = &tx_ring->buffer_info[i];
context_desc->lower_setup.ip_fields.ipcss = ipcss;
context_desc->lower_setup.ip_fields.ipcso = ipcso;
context_desc->lower_setup.ip_fields.ipcse = cpu_to_le16(ipcse);
context_desc->upper_setup.tcp_fields.tucss = tucss;
context_desc->upper_setup.tcp_fields.tucso = tucso;
context_desc->upper_setup.tcp_fields.tucse = cpu_to_le16(tucse);
context_desc->tcp_seg_setup.fields.mss = cpu_to_le16(mss);
context_desc->tcp_seg_setup.fields.hdr_len = hdr_len;
context_desc->cmd_and_length = cpu_to_le32(cmd_length);
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
if (++i == tx_ring->count) i = 0;
tx_ring->next_to_use = i;
return true;
}
return false;
}
static bool e1000_tx_csum(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring, struct sk_buff *skb)
{
struct e1000_context_desc *context_desc;
struct e1000_buffer *buffer_info;
unsigned int i;
u8 css;
u32 cmd_len = E1000_TXD_CMD_DEXT;
if (skb->ip_summed != CHECKSUM_PARTIAL)
return false;
switch (skb->protocol) {
case cpu_to_be16(ETH_P_IP):
if (ip_hdr(skb)->protocol == IPPROTO_TCP)
cmd_len |= E1000_TXD_CMD_TCP;
break;
case cpu_to_be16(ETH_P_IPV6):
/* XXX not handling all IPV6 headers */
if (ipv6_hdr(skb)->nexthdr == IPPROTO_TCP)
cmd_len |= E1000_TXD_CMD_TCP;
break;
default:
if (unlikely(net_ratelimit()))
e_warn(drv, "checksum_partial proto=%x!\n",
skb->protocol);
break;
}
css = skb_checksum_start_offset(skb);
i = tx_ring->next_to_use;
buffer_info = &tx_ring->buffer_info[i];
context_desc = E1000_CONTEXT_DESC(*tx_ring, i);
context_desc->lower_setup.ip_config = 0;
context_desc->upper_setup.tcp_fields.tucss = css;
context_desc->upper_setup.tcp_fields.tucso =
css + skb->csum_offset;
context_desc->upper_setup.tcp_fields.tucse = 0;
context_desc->tcp_seg_setup.data = 0;
context_desc->cmd_and_length = cpu_to_le32(cmd_len);
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
if (unlikely(++i == tx_ring->count)) i = 0;
tx_ring->next_to_use = i;
return true;
}
#define E1000_MAX_TXD_PWR 12
#define E1000_MAX_DATA_PER_TXD (1<<E1000_MAX_TXD_PWR)
static int e1000_tx_map(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring,
struct sk_buff *skb, unsigned int first,
unsigned int max_per_txd, unsigned int nr_frags,
unsigned int mss)
{
struct e1000_hw *hw = &adapter->hw;
struct pci_dev *pdev = adapter->pdev;
struct e1000_buffer *buffer_info;
unsigned int len = skb_headlen(skb);
unsigned int offset = 0, size, count = 0, i;
unsigned int f, bytecount, segs;
i = tx_ring->next_to_use;
while (len) {
buffer_info = &tx_ring->buffer_info[i];
size = min(len, max_per_txd);
/* Workaround for Controller erratum --
* descriptor for non-tso packet in a linear SKB that follows a
* tso gets written back prematurely before the data is fully
* DMA'd to the controller */
if (!skb->data_len && tx_ring->last_tx_tso &&
!skb_is_gso(skb)) {
tx_ring->last_tx_tso = 0;
size -= 4;
}
/* Workaround for premature desc write-backs
* in TSO mode. Append 4-byte sentinel desc */
if (unlikely(mss && !nr_frags && size == len && size > 8))
size -= 4;
/* work-around for errata 10 and it applies
* to all controllers in PCI-X mode
* The fix is to make sure that the first descriptor of a
* packet is smaller than 2048 - 16 - 16 (or 2016) bytes
*/
if (unlikely((hw->bus_type == e1000_bus_type_pcix) &&
(size > 2015) && count == 0))
size = 2015;
/* Workaround for potential 82544 hang in PCI-X. Avoid
* terminating buffers within evenly-aligned dwords. */
if (unlikely(adapter->pcix_82544 &&
!((unsigned long)(skb->data + offset + size - 1) & 4) &&
size > 4))
size -= 4;
buffer_info->length = size;
/* set time_stamp *before* dma to help avoid a possible race */
buffer_info->time_stamp = jiffies;
buffer_info->mapped_as_page = false;
buffer_info->dma = dma_map_single(&pdev->dev,
skb->data + offset,
size, DMA_TO_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma))
goto dma_error;
buffer_info->next_to_watch = i;
len -= size;
offset += size;
count++;
if (len) {
i++;
if (unlikely(i == tx_ring->count))
i = 0;
}
}
for (f = 0; f < nr_frags; f++) {
struct skb_frag_struct *frag;
frag = &skb_shinfo(skb)->frags[f];
len = frag->size;
offset = frag->page_offset;
while (len) {
i++;
if (unlikely(i == tx_ring->count))
i = 0;
buffer_info = &tx_ring->buffer_info[i];
size = min(len, max_per_txd);
/* Workaround for premature desc write-backs
* in TSO mode. Append 4-byte sentinel desc */
if (unlikely(mss && f == (nr_frags-1) && size == len && size > 8))
size -= 4;
/* Workaround for potential 82544 hang in PCI-X.
* Avoid terminating buffers within evenly-aligned
* dwords. */
if (unlikely(adapter->pcix_82544 &&
!((unsigned long)(page_to_phys(frag->page) + offset
+ size - 1) & 4) &&
size > 4))
size -= 4;
buffer_info->length = size;
buffer_info->time_stamp = jiffies;
buffer_info->mapped_as_page = true;
buffer_info->dma = dma_map_page(&pdev->dev, frag->page,
offset, size,
DMA_TO_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma))
goto dma_error;
buffer_info->next_to_watch = i;
len -= size;
offset += size;
count++;
}
}
segs = skb_shinfo(skb)->gso_segs ?: 1;
/* multiply data chunks by size of headers */
bytecount = ((segs - 1) * skb_headlen(skb)) + skb->len;
tx_ring->buffer_info[i].skb = skb;
tx_ring->buffer_info[i].segs = segs;
tx_ring->buffer_info[i].bytecount = bytecount;
tx_ring->buffer_info[first].next_to_watch = i;
return count;
dma_error:
dev_err(&pdev->dev, "TX DMA map failed\n");
buffer_info->dma = 0;
if (count)
count--;
while (count--) {
if (i==0)
i += tx_ring->count;
i--;
buffer_info = &tx_ring->buffer_info[i];
e1000_unmap_and_free_tx_resource(adapter, buffer_info);
}
return 0;
}
static void e1000_tx_queue(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring, int tx_flags,
int count)
{
struct e1000_hw *hw = &adapter->hw;
struct e1000_tx_desc *tx_desc = NULL;
struct e1000_buffer *buffer_info;
u32 txd_upper = 0, txd_lower = E1000_TXD_CMD_IFCS;
unsigned int i;
if (likely(tx_flags & E1000_TX_FLAGS_TSO)) {
txd_lower |= E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D |
E1000_TXD_CMD_TSE;
txd_upper |= E1000_TXD_POPTS_TXSM << 8;
if (likely(tx_flags & E1000_TX_FLAGS_IPV4))
txd_upper |= E1000_TXD_POPTS_IXSM << 8;
}
if (likely(tx_flags & E1000_TX_FLAGS_CSUM)) {
txd_lower |= E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D;
txd_upper |= E1000_TXD_POPTS_TXSM << 8;
}
if (unlikely(tx_flags & E1000_TX_FLAGS_VLAN)) {
txd_lower |= E1000_TXD_CMD_VLE;
txd_upper |= (tx_flags & E1000_TX_FLAGS_VLAN_MASK);
}
i = tx_ring->next_to_use;
while (count--) {
buffer_info = &tx_ring->buffer_info[i];
tx_desc = E1000_TX_DESC(*tx_ring, i);
tx_desc->buffer_addr = cpu_to_le64(buffer_info->dma);
tx_desc->lower.data =
cpu_to_le32(txd_lower | buffer_info->length);
tx_desc->upper.data = cpu_to_le32(txd_upper);
if (unlikely(++i == tx_ring->count)) i = 0;
}
tx_desc->lower.data |= cpu_to_le32(adapter->txd_cmd);
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64). */
wmb();
tx_ring->next_to_use = i;
writel(i, hw->hw_addr + tx_ring->tdt);
/* we need this if more than one processor can write to our tail
* at a time, it syncronizes IO on IA64/Altix systems */
mmiowb();
}
/**
* 82547 workaround to avoid controller hang in half-duplex environment.
* The workaround is to avoid queuing a large packet that would span
* the internal Tx FIFO ring boundary by notifying the stack to resend
* the packet at a later time. This gives the Tx FIFO an opportunity to
* flush all packets. When that occurs, we reset the Tx FIFO pointers
* to the beginning of the Tx FIFO.
**/
#define E1000_FIFO_HDR 0x10
#define E1000_82547_PAD_LEN 0x3E0
static int e1000_82547_fifo_workaround(struct e1000_adapter *adapter,
struct sk_buff *skb)
{
u32 fifo_space = adapter->tx_fifo_size - adapter->tx_fifo_head;
u32 skb_fifo_len = skb->len + E1000_FIFO_HDR;
skb_fifo_len = ALIGN(skb_fifo_len, E1000_FIFO_HDR);
if (adapter->link_duplex != HALF_DUPLEX)
goto no_fifo_stall_required;
if (atomic_read(&adapter->tx_fifo_stall))
return 1;
if (skb_fifo_len >= (E1000_82547_PAD_LEN + fifo_space)) {
atomic_set(&adapter->tx_fifo_stall, 1);
return 1;
}
no_fifo_stall_required:
adapter->tx_fifo_head += skb_fifo_len;
if (adapter->tx_fifo_head >= adapter->tx_fifo_size)
adapter->tx_fifo_head -= adapter->tx_fifo_size;
return 0;
}
static int __e1000_maybe_stop_tx(struct net_device *netdev, int size)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_tx_ring *tx_ring = adapter->tx_ring;
netif_stop_queue(netdev);
/* Herbert's original patch had:
* smp_mb__after_netif_stop_queue();
* but since that doesn't exist yet, just open code it. */
smp_mb();
/* We need to check again in a case another CPU has just
* made room available. */
if (likely(E1000_DESC_UNUSED(tx_ring) < size))
return -EBUSY;
/* A reprieve! */
netif_start_queue(netdev);
++adapter->restart_queue;
return 0;
}
static int e1000_maybe_stop_tx(struct net_device *netdev,
struct e1000_tx_ring *tx_ring, int size)
{
if (likely(E1000_DESC_UNUSED(tx_ring) >= size))
return 0;
return __e1000_maybe_stop_tx(netdev, size);
}
#define TXD_USE_COUNT(S, X) (((S) >> (X)) + 1 )
static netdev_tx_t e1000_xmit_frame(struct sk_buff *skb,
struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct e1000_tx_ring *tx_ring;
unsigned int first, max_per_txd = E1000_MAX_DATA_PER_TXD;
unsigned int max_txd_pwr = E1000_MAX_TXD_PWR;
unsigned int tx_flags = 0;
unsigned int len = skb_headlen(skb);
unsigned int nr_frags;
unsigned int mss;
int count = 0;
int tso;
unsigned int f;
/* This goes back to the question of how to logically map a tx queue
* to a flow. Right now, performance is impacted slightly negatively
* if using multiple tx queues. If the stack breaks away from a
* single qdisc implementation, we can look at this again. */
tx_ring = adapter->tx_ring;
if (unlikely(skb->len <= 0)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
mss = skb_shinfo(skb)->gso_size;
/* The controller does a simple calculation to
* make sure there is enough room in the FIFO before
* initiating the DMA for each buffer. The calc is:
* 4 = ceil(buffer len/mss). To make sure we don't
* overrun the FIFO, adjust the max buffer len if mss
* drops. */
if (mss) {
u8 hdr_len;
max_per_txd = min(mss << 2, max_per_txd);
max_txd_pwr = fls(max_per_txd) - 1;
hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb);
if (skb->data_len && hdr_len == len) {
switch (hw->mac_type) {
unsigned int pull_size;
case e1000_82544:
/* Make sure we have room to chop off 4 bytes,
* and that the end alignment will work out to
* this hardware's requirements
* NOTE: this is a TSO only workaround
* if end byte alignment not correct move us
* into the next dword */
if ((unsigned long)(skb_tail_pointer(skb) - 1) & 4)
break;
/* fall through */
pull_size = min((unsigned int)4, skb->data_len);
if (!__pskb_pull_tail(skb, pull_size)) {
e_err(drv, "__pskb_pull_tail "
"failed.\n");
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
len = skb_headlen(skb);
break;
default:
/* do nothing */
break;
}
}
}
/* reserve a descriptor for the offload context */
if ((mss) || (skb->ip_summed == CHECKSUM_PARTIAL))
count++;
count++;
/* Controller Erratum workaround */
if (!skb->data_len && tx_ring->last_tx_tso && !skb_is_gso(skb))
count++;
count += TXD_USE_COUNT(len, max_txd_pwr);
if (adapter->pcix_82544)
count++;
/* work-around for errata 10 and it applies to all controllers
* in PCI-X mode, so add one more descriptor to the count
*/
if (unlikely((hw->bus_type == e1000_bus_type_pcix) &&
(len > 2015)))
count++;
nr_frags = skb_shinfo(skb)->nr_frags;
for (f = 0; f < nr_frags; f++)
count += TXD_USE_COUNT(skb_shinfo(skb)->frags[f].size,
max_txd_pwr);
if (adapter->pcix_82544)
count += nr_frags;
/* need: count + 2 desc gap to keep tail from touching
* head, otherwise try next time */
if (unlikely(e1000_maybe_stop_tx(netdev, tx_ring, count + 2)))
return NETDEV_TX_BUSY;
if (unlikely(hw->mac_type == e1000_82547)) {
if (unlikely(e1000_82547_fifo_workaround(adapter, skb))) {
netif_stop_queue(netdev);
if (!test_bit(__E1000_DOWN, &adapter->flags))
mod_timer(&adapter->tx_fifo_stall_timer,
jiffies + 1);
return NETDEV_TX_BUSY;
}
}
if (unlikely(vlan_tx_tag_present(skb))) {
tx_flags |= E1000_TX_FLAGS_VLAN;
tx_flags |= (vlan_tx_tag_get(skb) << E1000_TX_FLAGS_VLAN_SHIFT);
}
first = tx_ring->next_to_use;
tso = e1000_tso(adapter, tx_ring, skb);
if (tso < 0) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (likely(tso)) {
if (likely(hw->mac_type != e1000_82544))
tx_ring->last_tx_tso = 1;
tx_flags |= E1000_TX_FLAGS_TSO;
} else if (likely(e1000_tx_csum(adapter, tx_ring, skb)))
tx_flags |= E1000_TX_FLAGS_CSUM;
if (likely(skb->protocol == htons(ETH_P_IP)))
tx_flags |= E1000_TX_FLAGS_IPV4;
count = e1000_tx_map(adapter, tx_ring, skb, first, max_per_txd,
nr_frags, mss);
if (count) {
e1000_tx_queue(adapter, tx_ring, tx_flags, count);
/* Make sure there is space in the ring for the next send. */
e1000_maybe_stop_tx(netdev, tx_ring, MAX_SKB_FRAGS + 2);
} else {
dev_kfree_skb_any(skb);
tx_ring->buffer_info[first].time_stamp = 0;
tx_ring->next_to_use = first;
}
return NETDEV_TX_OK;
}
/**
* e1000_tx_timeout - Respond to a Tx Hang
* @netdev: network interface device structure
**/
static void e1000_tx_timeout(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
/* Do the reset outside of interrupt context */
adapter->tx_timeout_count++;
schedule_work(&adapter->reset_task);
}
static void e1000_reset_task(struct work_struct *work)
{
struct e1000_adapter *adapter =
container_of(work, struct e1000_adapter, reset_task);
e1000_reinit_safe(adapter);
}
/**
* e1000_get_stats - Get System Network Statistics
* @netdev: network interface device structure
*
* Returns the address of the device statistics structure.
* The statistics are actually updated from the timer callback.
**/
static struct net_device_stats *e1000_get_stats(struct net_device *netdev)
{
/* only return the current stats */
return &netdev->stats;
}
/**
* e1000_change_mtu - Change the Maximum Transfer Unit
* @netdev: network interface device structure
* @new_mtu: new value for maximum frame size
*
* Returns 0 on success, negative on failure
**/
static int e1000_change_mtu(struct net_device *netdev, int new_mtu)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
int max_frame = new_mtu + ENET_HEADER_SIZE + ETHERNET_FCS_SIZE;
if ((max_frame < MINIMUM_ETHERNET_FRAME_SIZE) ||
(max_frame > MAX_JUMBO_FRAME_SIZE)) {
e_err(probe, "Invalid MTU setting\n");
return -EINVAL;
}
/* Adapter-specific max frame size limits. */
switch (hw->mac_type) {
case e1000_undefined ... e1000_82542_rev2_1:
if (max_frame > (ETH_FRAME_LEN + ETH_FCS_LEN)) {
e_err(probe, "Jumbo Frames not supported.\n");
return -EINVAL;
}
break;
default:
/* Capable of supporting up to MAX_JUMBO_FRAME_SIZE limit. */
break;
}
while (test_and_set_bit(__E1000_RESETTING, &adapter->flags))
msleep(1);
/* e1000_down has a dependency on max_frame_size */
hw->max_frame_size = max_frame;
if (netif_running(netdev))
e1000_down(adapter);
/* NOTE: netdev_alloc_skb reserves 16 bytes, and typically NET_IP_ALIGN
* means we reserve 2 more, this pushes us to allocate from the next
* larger slab size.
* i.e. RXBUFFER_2048 --> size-4096 slab
* however with the new *_jumbo_rx* routines, jumbo receives will use
* fragmented skbs */
if (max_frame <= E1000_RXBUFFER_2048)
adapter->rx_buffer_len = E1000_RXBUFFER_2048;
else
#if (PAGE_SIZE >= E1000_RXBUFFER_16384)
adapter->rx_buffer_len = E1000_RXBUFFER_16384;
#elif (PAGE_SIZE >= E1000_RXBUFFER_4096)
adapter->rx_buffer_len = PAGE_SIZE;
#endif
/* adjust allocation if LPE protects us, and we aren't using SBP */
if (!hw->tbi_compatibility_on &&
((max_frame == (ETH_FRAME_LEN + ETH_FCS_LEN)) ||
(max_frame == MAXIMUM_ETHERNET_VLAN_SIZE)))
adapter->rx_buffer_len = MAXIMUM_ETHERNET_VLAN_SIZE;
pr_info("%s changing MTU from %d to %d\n",
netdev->name, netdev->mtu, new_mtu);
netdev->mtu = new_mtu;
if (netif_running(netdev))
e1000_up(adapter);
else
e1000_reset(adapter);
clear_bit(__E1000_RESETTING, &adapter->flags);
return 0;
}
/**
* e1000_update_stats - Update the board statistics counters
* @adapter: board private structure
**/
void e1000_update_stats(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct e1000_hw *hw = &adapter->hw;
struct pci_dev *pdev = adapter->pdev;
unsigned long flags;
u16 phy_tmp;
#define PHY_IDLE_ERROR_COUNT_MASK 0x00FF
/*
* Prevent stats update while adapter is being reset, or if the pci
* connection is down.
*/
if (adapter->link_speed == 0)
return;
if (pci_channel_offline(pdev))
return;
spin_lock_irqsave(&adapter->stats_lock, flags);
/* these counters are modified from e1000_tbi_adjust_stats,
* called from the interrupt context, so they must only
* be written while holding adapter->stats_lock
*/
adapter->stats.crcerrs += er32(CRCERRS);
adapter->stats.gprc += er32(GPRC);
adapter->stats.gorcl += er32(GORCL);
adapter->stats.gorch += er32(GORCH);
adapter->stats.bprc += er32(BPRC);
adapter->stats.mprc += er32(MPRC);
adapter->stats.roc += er32(ROC);
adapter->stats.prc64 += er32(PRC64);
adapter->stats.prc127 += er32(PRC127);
adapter->stats.prc255 += er32(PRC255);
adapter->stats.prc511 += er32(PRC511);
adapter->stats.prc1023 += er32(PRC1023);
adapter->stats.prc1522 += er32(PRC1522);
adapter->stats.symerrs += er32(SYMERRS);
adapter->stats.mpc += er32(MPC);
adapter->stats.scc += er32(SCC);
adapter->stats.ecol += er32(ECOL);
adapter->stats.mcc += er32(MCC);
adapter->stats.latecol += er32(LATECOL);
adapter->stats.dc += er32(DC);
adapter->stats.sec += er32(SEC);
adapter->stats.rlec += er32(RLEC);
adapter->stats.xonrxc += er32(XONRXC);
adapter->stats.xontxc += er32(XONTXC);
adapter->stats.xoffrxc += er32(XOFFRXC);
adapter->stats.xofftxc += er32(XOFFTXC);
adapter->stats.fcruc += er32(FCRUC);
adapter->stats.gptc += er32(GPTC);
adapter->stats.gotcl += er32(GOTCL);
adapter->stats.gotch += er32(GOTCH);
adapter->stats.rnbc += er32(RNBC);
adapter->stats.ruc += er32(RUC);
adapter->stats.rfc += er32(RFC);
adapter->stats.rjc += er32(RJC);
adapter->stats.torl += er32(TORL);
adapter->stats.torh += er32(TORH);
adapter->stats.totl += er32(TOTL);
adapter->stats.toth += er32(TOTH);
adapter->stats.tpr += er32(TPR);
adapter->stats.ptc64 += er32(PTC64);
adapter->stats.ptc127 += er32(PTC127);
adapter->stats.ptc255 += er32(PTC255);
adapter->stats.ptc511 += er32(PTC511);
adapter->stats.ptc1023 += er32(PTC1023);
adapter->stats.ptc1522 += er32(PTC1522);
adapter->stats.mptc += er32(MPTC);
adapter->stats.bptc += er32(BPTC);
/* used for adaptive IFS */
hw->tx_packet_delta = er32(TPT);
adapter->stats.tpt += hw->tx_packet_delta;
hw->collision_delta = er32(COLC);
adapter->stats.colc += hw->collision_delta;
if (hw->mac_type >= e1000_82543) {
adapter->stats.algnerrc += er32(ALGNERRC);
adapter->stats.rxerrc += er32(RXERRC);
adapter->stats.tncrs += er32(TNCRS);
adapter->stats.cexterr += er32(CEXTERR);
adapter->stats.tsctc += er32(TSCTC);
adapter->stats.tsctfc += er32(TSCTFC);
}
/* Fill out the OS statistics structure */
netdev->stats.multicast = adapter->stats.mprc;
netdev->stats.collisions = adapter->stats.colc;
/* Rx Errors */
/* RLEC on some newer hardware can be incorrect so build
* our own version based on RUC and ROC */
netdev->stats.rx_errors = adapter->stats.rxerrc +
adapter->stats.crcerrs + adapter->stats.algnerrc +
adapter->stats.ruc + adapter->stats.roc +
adapter->stats.cexterr;
adapter->stats.rlerrc = adapter->stats.ruc + adapter->stats.roc;
netdev->stats.rx_length_errors = adapter->stats.rlerrc;
netdev->stats.rx_crc_errors = adapter->stats.crcerrs;
netdev->stats.rx_frame_errors = adapter->stats.algnerrc;
netdev->stats.rx_missed_errors = adapter->stats.mpc;
/* Tx Errors */
adapter->stats.txerrc = adapter->stats.ecol + adapter->stats.latecol;
netdev->stats.tx_errors = adapter->stats.txerrc;
netdev->stats.tx_aborted_errors = adapter->stats.ecol;
netdev->stats.tx_window_errors = adapter->stats.latecol;
netdev->stats.tx_carrier_errors = adapter->stats.tncrs;
if (hw->bad_tx_carr_stats_fd &&
adapter->link_duplex == FULL_DUPLEX) {
netdev->stats.tx_carrier_errors = 0;
adapter->stats.tncrs = 0;
}
/* Tx Dropped needs to be maintained elsewhere */
/* Phy Stats */
if (hw->media_type == e1000_media_type_copper) {
if ((adapter->link_speed == SPEED_1000) &&
(!e1000_read_phy_reg(hw, PHY_1000T_STATUS, &phy_tmp))) {
phy_tmp &= PHY_IDLE_ERROR_COUNT_MASK;
adapter->phy_stats.idle_errors += phy_tmp;
}
if ((hw->mac_type <= e1000_82546) &&
(hw->phy_type == e1000_phy_m88) &&
!e1000_read_phy_reg(hw, M88E1000_RX_ERR_CNTR, &phy_tmp))
adapter->phy_stats.receive_errors += phy_tmp;
}
/* Management Stats */
if (hw->has_smbus) {
adapter->stats.mgptc += er32(MGTPTC);
adapter->stats.mgprc += er32(MGTPRC);
adapter->stats.mgpdc += er32(MGTPDC);
}
spin_unlock_irqrestore(&adapter->stats_lock, flags);
}
/**
* e1000_intr - Interrupt Handler
* @irq: interrupt number
* @data: pointer to a network interface device structure
**/
static irqreturn_t e1000_intr(int irq, void *data)
{
struct net_device *netdev = data;
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 icr = er32(ICR);
if (unlikely((!icr)))
return IRQ_NONE; /* Not our interrupt */
/*
* we might have caused the interrupt, but the above
* read cleared it, and just in case the driver is
* down there is nothing to do so return handled
*/
if (unlikely(test_bit(__E1000_DOWN, &adapter->flags)))
return IRQ_HANDLED;
if (unlikely(icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC))) {
hw->get_link_status = 1;
/* guard against interrupt when we're going down */
if (!test_bit(__E1000_DOWN, &adapter->flags))
mod_timer(&adapter->watchdog_timer, jiffies + 1);
}
/* disable interrupts, without the synchronize_irq bit */
ew32(IMC, ~0);
E1000_WRITE_FLUSH();
if (likely(napi_schedule_prep(&adapter->napi))) {
adapter->total_tx_bytes = 0;
adapter->total_tx_packets = 0;
adapter->total_rx_bytes = 0;
adapter->total_rx_packets = 0;
__napi_schedule(&adapter->napi);
} else {
/* this really should not happen! if it does it is basically a
* bug, but not a hard error, so enable ints and continue */
if (!test_bit(__E1000_DOWN, &adapter->flags))
e1000_irq_enable(adapter);
}
return IRQ_HANDLED;
}
/**
* e1000_clean - NAPI Rx polling callback
* @adapter: board private structure
**/
static int e1000_clean(struct napi_struct *napi, int budget)
{
struct e1000_adapter *adapter = container_of(napi, struct e1000_adapter, napi);
int tx_clean_complete = 0, work_done = 0;
tx_clean_complete = e1000_clean_tx_irq(adapter, &adapter->tx_ring[0]);
adapter->clean_rx(adapter, &adapter->rx_ring[0], &work_done, budget);
if (!tx_clean_complete)
work_done = budget;
/* If budget not fully consumed, exit the polling mode */
if (work_done < budget) {
if (likely(adapter->itr_setting & 3))
e1000_set_itr(adapter);
napi_complete(napi);
if (!test_bit(__E1000_DOWN, &adapter->flags))
e1000_irq_enable(adapter);
}
return work_done;
}
/**
* e1000_clean_tx_irq - Reclaim resources after transmit completes
* @adapter: board private structure
**/
static bool e1000_clean_tx_irq(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
struct e1000_tx_desc *tx_desc, *eop_desc;
struct e1000_buffer *buffer_info;
unsigned int i, eop;
unsigned int count = 0;
unsigned int total_tx_bytes=0, total_tx_packets=0;
i = tx_ring->next_to_clean;
eop = tx_ring->buffer_info[i].next_to_watch;
eop_desc = E1000_TX_DESC(*tx_ring, eop);
while ((eop_desc->upper.data & cpu_to_le32(E1000_TXD_STAT_DD)) &&
(count < tx_ring->count)) {
bool cleaned = false;
rmb(); /* read buffer_info after eop_desc */
for ( ; !cleaned; count++) {
tx_desc = E1000_TX_DESC(*tx_ring, i);
buffer_info = &tx_ring->buffer_info[i];
cleaned = (i == eop);
if (cleaned) {
total_tx_packets += buffer_info->segs;
total_tx_bytes += buffer_info->bytecount;
}
e1000_unmap_and_free_tx_resource(adapter, buffer_info);
tx_desc->upper.data = 0;
if (unlikely(++i == tx_ring->count)) i = 0;
}
eop = tx_ring->buffer_info[i].next_to_watch;
eop_desc = E1000_TX_DESC(*tx_ring, eop);
}
tx_ring->next_to_clean = i;
#define TX_WAKE_THRESHOLD 32
if (unlikely(count && netif_carrier_ok(netdev) &&
E1000_DESC_UNUSED(tx_ring) >= TX_WAKE_THRESHOLD)) {
/* Make sure that anybody stopping the queue after this
* sees the new next_to_clean.
*/
smp_mb();
if (netif_queue_stopped(netdev) &&
!(test_bit(__E1000_DOWN, &adapter->flags))) {
netif_wake_queue(netdev);
++adapter->restart_queue;
}
}
if (adapter->detect_tx_hung) {
/* Detect a transmit hang in hardware, this serializes the
* check with the clearing of time_stamp and movement of i */
adapter->detect_tx_hung = false;
if (tx_ring->buffer_info[eop].time_stamp &&
time_after(jiffies, tx_ring->buffer_info[eop].time_stamp +
(adapter->tx_timeout_factor * HZ)) &&
!(er32(STATUS) & E1000_STATUS_TXOFF)) {
/* detected Tx unit hang */
e_err(drv, "Detected Tx Unit Hang\n"
" Tx Queue <%lu>\n"
" TDH <%x>\n"
" TDT <%x>\n"
" next_to_use <%x>\n"
" next_to_clean <%x>\n"
"buffer_info[next_to_clean]\n"
" time_stamp <%lx>\n"
" next_to_watch <%x>\n"
" jiffies <%lx>\n"
" next_to_watch.status <%x>\n",
(unsigned long)((tx_ring - adapter->tx_ring) /
sizeof(struct e1000_tx_ring)),
readl(hw->hw_addr + tx_ring->tdh),
readl(hw->hw_addr + tx_ring->tdt),
tx_ring->next_to_use,
tx_ring->next_to_clean,
tx_ring->buffer_info[eop].time_stamp,
eop,
jiffies,
eop_desc->upper.fields.status);
netif_stop_queue(netdev);
}
}
adapter->total_tx_bytes += total_tx_bytes;
adapter->total_tx_packets += total_tx_packets;
netdev->stats.tx_bytes += total_tx_bytes;
netdev->stats.tx_packets += total_tx_packets;
return count < tx_ring->count;
}
/**
* e1000_rx_checksum - Receive Checksum Offload for 82543
* @adapter: board private structure
* @status_err: receive descriptor status and error fields
* @csum: receive descriptor csum field
* @sk_buff: socket buffer with received data
**/
static void e1000_rx_checksum(struct e1000_adapter *adapter, u32 status_err,
u32 csum, struct sk_buff *skb)
{
struct e1000_hw *hw = &adapter->hw;
u16 status = (u16)status_err;
u8 errors = (u8)(status_err >> 24);
skb_checksum_none_assert(skb);
/* 82543 or newer only */
if (unlikely(hw->mac_type < e1000_82543)) return;
/* Ignore Checksum bit is set */
if (unlikely(status & E1000_RXD_STAT_IXSM)) return;
/* TCP/UDP checksum error bit is set */
if (unlikely(errors & E1000_RXD_ERR_TCPE)) {
/* let the stack verify checksum errors */
adapter->hw_csum_err++;
return;
}
/* TCP/UDP Checksum has not been calculated */
if (!(status & E1000_RXD_STAT_TCPCS))
return;
/* It must be a TCP or UDP packet with a valid checksum */
if (likely(status & E1000_RXD_STAT_TCPCS)) {
/* TCP checksum is good */
skb->ip_summed = CHECKSUM_UNNECESSARY;
}
adapter->hw_csum_good++;
}
/**
* e1000_consume_page - helper function
**/
static void e1000_consume_page(struct e1000_buffer *bi, struct sk_buff *skb,
u16 length)
{
bi->page = NULL;
skb->len += length;
skb->data_len += length;
skb->truesize += length;
}
/**
* e1000_receive_skb - helper function to handle rx indications
* @adapter: board private structure
* @status: descriptor status field as written by hardware
* @vlan: descriptor vlan field as written by hardware (no le/be conversion)
* @skb: pointer to sk_buff to be indicated to stack
*/
static void e1000_receive_skb(struct e1000_adapter *adapter, u8 status,
__le16 vlan, struct sk_buff *skb)
{
skb->protocol = eth_type_trans(skb, adapter->netdev);
if ((unlikely(adapter->vlgrp && (status & E1000_RXD_STAT_VP))))
vlan_gro_receive(&adapter->napi, adapter->vlgrp,
le16_to_cpu(vlan) & E1000_RXD_SPC_VLAN_MASK,
skb);
else
napi_gro_receive(&adapter->napi, skb);
}
/**
* e1000_clean_jumbo_rx_irq - Send received data up the network stack; legacy
* @adapter: board private structure
* @rx_ring: ring to clean
* @work_done: amount of napi work completed this call
* @work_to_do: max amount of work allowed for this call to do
*
* the return value indicates whether actual cleaning was done, there
* is no guarantee that everything was cleaned
*/
static bool e1000_clean_jumbo_rx_irq(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int *work_done, int work_to_do)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct e1000_rx_desc *rx_desc, *next_rxd;
struct e1000_buffer *buffer_info, *next_buffer;
unsigned long irq_flags;
u32 length;
unsigned int i;
int cleaned_count = 0;
bool cleaned = false;
unsigned int total_rx_bytes=0, total_rx_packets=0;
i = rx_ring->next_to_clean;
rx_desc = E1000_RX_DESC(*rx_ring, i);
buffer_info = &rx_ring->buffer_info[i];
while (rx_desc->status & E1000_RXD_STAT_DD) {
struct sk_buff *skb;
u8 status;
if (*work_done >= work_to_do)
break;
(*work_done)++;
rmb(); /* read descriptor and rx_buffer_info after status DD */
status = rx_desc->status;
skb = buffer_info->skb;
buffer_info->skb = NULL;
if (++i == rx_ring->count) i = 0;
next_rxd = E1000_RX_DESC(*rx_ring, i);
prefetch(next_rxd);
next_buffer = &rx_ring->buffer_info[i];
cleaned = true;
cleaned_count++;
dma_unmap_page(&pdev->dev, buffer_info->dma,
buffer_info->length, DMA_FROM_DEVICE);
buffer_info->dma = 0;
length = le16_to_cpu(rx_desc->length);
/* errors is only valid for DD + EOP descriptors */
if (unlikely((status & E1000_RXD_STAT_EOP) &&
(rx_desc->errors & E1000_RXD_ERR_FRAME_ERR_MASK))) {
u8 last_byte = *(skb->data + length - 1);
if (TBI_ACCEPT(hw, status, rx_desc->errors, length,
last_byte)) {
spin_lock_irqsave(&adapter->stats_lock,
irq_flags);
e1000_tbi_adjust_stats(hw, &adapter->stats,
length, skb->data);
spin_unlock_irqrestore(&adapter->stats_lock,
irq_flags);
length--;
} else {
/* recycle both page and skb */
buffer_info->skb = skb;
/* an error means any chain goes out the window
* too */
if (rx_ring->rx_skb_top)
dev_kfree_skb(rx_ring->rx_skb_top);
rx_ring->rx_skb_top = NULL;
goto next_desc;
}
}
#define rxtop rx_ring->rx_skb_top
if (!(status & E1000_RXD_STAT_EOP)) {
/* this descriptor is only the beginning (or middle) */
if (!rxtop) {
/* this is the beginning of a chain */
rxtop = skb;
skb_fill_page_desc(rxtop, 0, buffer_info->page,
0, length);
} else {
/* this is the middle of a chain */
skb_fill_page_desc(rxtop,
skb_shinfo(rxtop)->nr_frags,
buffer_info->page, 0, length);
/* re-use the skb, only consumed the page */
buffer_info->skb = skb;
}
e1000_consume_page(buffer_info, rxtop, length);
goto next_desc;
} else {
if (rxtop) {
/* end of the chain */
skb_fill_page_desc(rxtop,
skb_shinfo(rxtop)->nr_frags,
buffer_info->page, 0, length);
/* re-use the current skb, we only consumed the
* page */
buffer_info->skb = skb;
skb = rxtop;
rxtop = NULL;
e1000_consume_page(buffer_info, skb, length);
} else {
/* no chain, got EOP, this buf is the packet
* copybreak to save the put_page/alloc_page */
if (length <= copybreak &&
skb_tailroom(skb) >= length) {
u8 *vaddr;
vaddr = kmap_atomic(buffer_info->page,
KM_SKB_DATA_SOFTIRQ);
memcpy(skb_tail_pointer(skb), vaddr, length);
kunmap_atomic(vaddr,
KM_SKB_DATA_SOFTIRQ);
/* re-use the page, so don't erase
* buffer_info->page */
skb_put(skb, length);
} else {
skb_fill_page_desc(skb, 0,
buffer_info->page, 0,
length);
e1000_consume_page(buffer_info, skb,
length);
}
}
}
/* Receive Checksum Offload XXX recompute due to CRC strip? */
e1000_rx_checksum(adapter,
(u32)(status) |
((u32)(rx_desc->errors) << 24),
le16_to_cpu(rx_desc->csum), skb);
pskb_trim(skb, skb->len - 4);
/* probably a little skewed due to removing CRC */
total_rx_bytes += skb->len;
total_rx_packets++;
/* eth type trans needs skb->data to point to something */
if (!pskb_may_pull(skb, ETH_HLEN)) {
e_err(drv, "pskb_may_pull failed.\n");
dev_kfree_skb(skb);
goto next_desc;
}
e1000_receive_skb(adapter, status, rx_desc->special, skb);
next_desc:
rx_desc->status = 0;
/* return some buffers to hardware, one at a time is too slow */
if (unlikely(cleaned_count >= E1000_RX_BUFFER_WRITE)) {
adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count);
cleaned_count = 0;
}
/* use prefetched values */
rx_desc = next_rxd;
buffer_info = next_buffer;
}
rx_ring->next_to_clean = i;
cleaned_count = E1000_DESC_UNUSED(rx_ring);
if (cleaned_count)
adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count);
adapter->total_rx_packets += total_rx_packets;
adapter->total_rx_bytes += total_rx_bytes;
netdev->stats.rx_bytes += total_rx_bytes;
netdev->stats.rx_packets += total_rx_packets;
return cleaned;
}
/*
* this should improve performance for small packets with large amounts
* of reassembly being done in the stack
*/
static void e1000_check_copybreak(struct net_device *netdev,
struct e1000_buffer *buffer_info,
u32 length, struct sk_buff **skb)
{
struct sk_buff *new_skb;
if (length > copybreak)
return;
new_skb = netdev_alloc_skb_ip_align(netdev, length);
if (!new_skb)
return;
skb_copy_to_linear_data_offset(new_skb, -NET_IP_ALIGN,
(*skb)->data - NET_IP_ALIGN,
length + NET_IP_ALIGN);
/* save the skb in buffer_info as good */
buffer_info->skb = *skb;
*skb = new_skb;
}
/**
* e1000_clean_rx_irq - Send received data up the network stack; legacy
* @adapter: board private structure
* @rx_ring: ring to clean
* @work_done: amount of napi work completed this call
* @work_to_do: max amount of work allowed for this call to do
*/
static bool e1000_clean_rx_irq(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int *work_done, int work_to_do)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct e1000_rx_desc *rx_desc, *next_rxd;
struct e1000_buffer *buffer_info, *next_buffer;
unsigned long flags;
u32 length;
unsigned int i;
int cleaned_count = 0;
bool cleaned = false;
unsigned int total_rx_bytes=0, total_rx_packets=0;
i = rx_ring->next_to_clean;
rx_desc = E1000_RX_DESC(*rx_ring, i);
buffer_info = &rx_ring->buffer_info[i];
while (rx_desc->status & E1000_RXD_STAT_DD) {
struct sk_buff *skb;
u8 status;
if (*work_done >= work_to_do)
break;
(*work_done)++;
rmb(); /* read descriptor and rx_buffer_info after status DD */
status = rx_desc->status;
skb = buffer_info->skb;
buffer_info->skb = NULL;
prefetch(skb->data - NET_IP_ALIGN);
if (++i == rx_ring->count) i = 0;
next_rxd = E1000_RX_DESC(*rx_ring, i);
prefetch(next_rxd);
next_buffer = &rx_ring->buffer_info[i];
cleaned = true;
cleaned_count++;
dma_unmap_single(&pdev->dev, buffer_info->dma,
buffer_info->length, DMA_FROM_DEVICE);
buffer_info->dma = 0;
length = le16_to_cpu(rx_desc->length);
/* !EOP means multiple descriptors were used to store a single
* packet, if thats the case we need to toss it. In fact, we
* to toss every packet with the EOP bit clear and the next
* frame that _does_ have the EOP bit set, as it is by
* definition only a frame fragment
*/
if (unlikely(!(status & E1000_RXD_STAT_EOP)))
adapter->discarding = true;
if (adapter->discarding) {
/* All receives must fit into a single buffer */
e_dbg("Receive packet consumed multiple buffers\n");
/* recycle */
buffer_info->skb = skb;
if (status & E1000_RXD_STAT_EOP)
adapter->discarding = false;
goto next_desc;
}
if (unlikely(rx_desc->errors & E1000_RXD_ERR_FRAME_ERR_MASK)) {
u8 last_byte = *(skb->data + length - 1);
if (TBI_ACCEPT(hw, status, rx_desc->errors, length,
last_byte)) {
spin_lock_irqsave(&adapter->stats_lock, flags);
e1000_tbi_adjust_stats(hw, &adapter->stats,
length, skb->data);
spin_unlock_irqrestore(&adapter->stats_lock,
flags);
length--;
} else {
/* recycle */
buffer_info->skb = skb;
goto next_desc;
}
}
/* adjust length to remove Ethernet CRC, this must be
* done after the TBI_ACCEPT workaround above */
length -= 4;
/* probably a little skewed due to removing CRC */
total_rx_bytes += length;
total_rx_packets++;
e1000_check_copybreak(netdev, buffer_info, length, &skb);
skb_put(skb, length);
/* Receive Checksum Offload */
e1000_rx_checksum(adapter,
(u32)(status) |
((u32)(rx_desc->errors) << 24),
le16_to_cpu(rx_desc->csum), skb);
e1000_receive_skb(adapter, status, rx_desc->special, skb);
next_desc:
rx_desc->status = 0;
/* return some buffers to hardware, one at a time is too slow */
if (unlikely(cleaned_count >= E1000_RX_BUFFER_WRITE)) {
adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count);
cleaned_count = 0;
}
/* use prefetched values */
rx_desc = next_rxd;
buffer_info = next_buffer;
}
rx_ring->next_to_clean = i;
cleaned_count = E1000_DESC_UNUSED(rx_ring);
if (cleaned_count)
adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count);
adapter->total_rx_packets += total_rx_packets;
adapter->total_rx_bytes += total_rx_bytes;
netdev->stats.rx_bytes += total_rx_bytes;
netdev->stats.rx_packets += total_rx_packets;
return cleaned;
}
/**
* e1000_alloc_jumbo_rx_buffers - Replace used jumbo receive buffers
* @adapter: address of board private structure
* @rx_ring: pointer to receive ring structure
* @cleaned_count: number of buffers to allocate this pass
**/
static void
e1000_alloc_jumbo_rx_buffers(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring, int cleaned_count)
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct e1000_rx_desc *rx_desc;
struct e1000_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
unsigned int bufsz = 256 - 16 /*for skb_reserve */ ;
i = rx_ring->next_to_use;
buffer_info = &rx_ring->buffer_info[i];
while (cleaned_count--) {
skb = buffer_info->skb;
if (skb) {
skb_trim(skb, 0);
goto check_page;
}
skb = netdev_alloc_skb_ip_align(netdev, bufsz);
if (unlikely(!skb)) {
/* Better luck next round */
adapter->alloc_rx_buff_failed++;
break;
}
/* Fix for errata 23, can't cross 64kB boundary */
if (!e1000_check_64k_bound(adapter, skb->data, bufsz)) {
struct sk_buff *oldskb = skb;
e_err(rx_err, "skb align check failed: %u bytes at "
"%p\n", bufsz, skb->data);
/* Try again, without freeing the previous */
skb = netdev_alloc_skb_ip_align(netdev, bufsz);
/* Failed allocation, critical failure */
if (!skb) {
dev_kfree_skb(oldskb);
adapter->alloc_rx_buff_failed++;
break;
}
if (!e1000_check_64k_bound(adapter, skb->data, bufsz)) {
/* give up */
dev_kfree_skb(skb);
dev_kfree_skb(oldskb);
break; /* while (cleaned_count--) */
}
/* Use new allocation */
dev_kfree_skb(oldskb);
}
buffer_info->skb = skb;
buffer_info->length = adapter->rx_buffer_len;
check_page:
/* allocate a new page if necessary */
if (!buffer_info->page) {
buffer_info->page = alloc_page(GFP_ATOMIC);
if (unlikely(!buffer_info->page)) {
adapter->alloc_rx_buff_failed++;
break;
}
}
if (!buffer_info->dma) {
buffer_info->dma = dma_map_page(&pdev->dev,
buffer_info->page, 0,
buffer_info->length,
DMA_FROM_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma)) {
put_page(buffer_info->page);
dev_kfree_skb(skb);
buffer_info->page = NULL;
buffer_info->skb = NULL;
buffer_info->dma = 0;
adapter->alloc_rx_buff_failed++;
break; /* while !buffer_info->skb */
}
}
rx_desc = E1000_RX_DESC(*rx_ring, i);
rx_desc->buffer_addr = cpu_to_le64(buffer_info->dma);
if (unlikely(++i == rx_ring->count))
i = 0;
buffer_info = &rx_ring->buffer_info[i];
}
if (likely(rx_ring->next_to_use != i)) {
rx_ring->next_to_use = i;
if (unlikely(i-- == 0))
i = (rx_ring->count - 1);
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64). */
wmb();
writel(i, adapter->hw.hw_addr + rx_ring->rdt);
}
}
/**
* e1000_alloc_rx_buffers - Replace used receive buffers; legacy & extended
* @adapter: address of board private structure
**/
static void e1000_alloc_rx_buffers(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int cleaned_count)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct e1000_rx_desc *rx_desc;
struct e1000_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
unsigned int bufsz = adapter->rx_buffer_len;
i = rx_ring->next_to_use;
buffer_info = &rx_ring->buffer_info[i];
while (cleaned_count--) {
skb = buffer_info->skb;
if (skb) {
skb_trim(skb, 0);
goto map_skb;
}
skb = netdev_alloc_skb_ip_align(netdev, bufsz);
if (unlikely(!skb)) {
/* Better luck next round */
adapter->alloc_rx_buff_failed++;
break;
}
/* Fix for errata 23, can't cross 64kB boundary */
if (!e1000_check_64k_bound(adapter, skb->data, bufsz)) {
struct sk_buff *oldskb = skb;
e_err(rx_err, "skb align check failed: %u bytes at "
"%p\n", bufsz, skb->data);
/* Try again, without freeing the previous */
skb = netdev_alloc_skb_ip_align(netdev, bufsz);
/* Failed allocation, critical failure */
if (!skb) {
dev_kfree_skb(oldskb);
adapter->alloc_rx_buff_failed++;
break;
}
if (!e1000_check_64k_bound(adapter, skb->data, bufsz)) {
/* give up */
dev_kfree_skb(skb);
dev_kfree_skb(oldskb);
adapter->alloc_rx_buff_failed++;
break; /* while !buffer_info->skb */
}
/* Use new allocation */
dev_kfree_skb(oldskb);
}
buffer_info->skb = skb;
buffer_info->length = adapter->rx_buffer_len;
map_skb:
buffer_info->dma = dma_map_single(&pdev->dev,
skb->data,
buffer_info->length,
DMA_FROM_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma)) {
dev_kfree_skb(skb);
buffer_info->skb = NULL;
buffer_info->dma = 0;
adapter->alloc_rx_buff_failed++;
break; /* while !buffer_info->skb */
}
/*
* XXX if it was allocated cleanly it will never map to a
* boundary crossing
*/
/* Fix for errata 23, can't cross 64kB boundary */
if (!e1000_check_64k_bound(adapter,
(void *)(unsigned long)buffer_info->dma,
adapter->rx_buffer_len)) {
e_err(rx_err, "dma align check failed: %u bytes at "
"%p\n", adapter->rx_buffer_len,
(void *)(unsigned long)buffer_info->dma);
dev_kfree_skb(skb);
buffer_info->skb = NULL;
dma_unmap_single(&pdev->dev, buffer_info->dma,
adapter->rx_buffer_len,
DMA_FROM_DEVICE);
buffer_info->dma = 0;
adapter->alloc_rx_buff_failed++;
break; /* while !buffer_info->skb */
}
rx_desc = E1000_RX_DESC(*rx_ring, i);
rx_desc->buffer_addr = cpu_to_le64(buffer_info->dma);
if (unlikely(++i == rx_ring->count))
i = 0;
buffer_info = &rx_ring->buffer_info[i];
}
if (likely(rx_ring->next_to_use != i)) {
rx_ring->next_to_use = i;
if (unlikely(i-- == 0))
i = (rx_ring->count - 1);
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64). */
wmb();
writel(i, hw->hw_addr + rx_ring->rdt);
}
}
/**
* e1000_smartspeed - Workaround for SmartSpeed on 82541 and 82547 controllers.
* @adapter:
**/
static void e1000_smartspeed(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u16 phy_status;
u16 phy_ctrl;
if ((hw->phy_type != e1000_phy_igp) || !hw->autoneg ||
!(hw->autoneg_advertised & ADVERTISE_1000_FULL))
return;
if (adapter->smartspeed == 0) {
/* If Master/Slave config fault is asserted twice,
* we assume back-to-back */
e1000_read_phy_reg(hw, PHY_1000T_STATUS, &phy_status);
if (!(phy_status & SR_1000T_MS_CONFIG_FAULT)) return;
e1000_read_phy_reg(hw, PHY_1000T_STATUS, &phy_status);
if (!(phy_status & SR_1000T_MS_CONFIG_FAULT)) return;
e1000_read_phy_reg(hw, PHY_1000T_CTRL, &phy_ctrl);
if (phy_ctrl & CR_1000T_MS_ENABLE) {
phy_ctrl &= ~CR_1000T_MS_ENABLE;
e1000_write_phy_reg(hw, PHY_1000T_CTRL,
phy_ctrl);
adapter->smartspeed++;
if (!e1000_phy_setup_autoneg(hw) &&
!e1000_read_phy_reg(hw, PHY_CTRL,
&phy_ctrl)) {
phy_ctrl |= (MII_CR_AUTO_NEG_EN |
MII_CR_RESTART_AUTO_NEG);
e1000_write_phy_reg(hw, PHY_CTRL,
phy_ctrl);
}
}
return;
} else if (adapter->smartspeed == E1000_SMARTSPEED_DOWNSHIFT) {
/* If still no link, perhaps using 2/3 pair cable */
e1000_read_phy_reg(hw, PHY_1000T_CTRL, &phy_ctrl);
phy_ctrl |= CR_1000T_MS_ENABLE;
e1000_write_phy_reg(hw, PHY_1000T_CTRL, phy_ctrl);
if (!e1000_phy_setup_autoneg(hw) &&
!e1000_read_phy_reg(hw, PHY_CTRL, &phy_ctrl)) {
phy_ctrl |= (MII_CR_AUTO_NEG_EN |
MII_CR_RESTART_AUTO_NEG);
e1000_write_phy_reg(hw, PHY_CTRL, phy_ctrl);
}
}
/* Restart process after E1000_SMARTSPEED_MAX iterations */
if (adapter->smartspeed++ == E1000_SMARTSPEED_MAX)
adapter->smartspeed = 0;
}
/**
* e1000_ioctl -
* @netdev:
* @ifreq:
* @cmd:
**/
static int e1000_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
switch (cmd) {
case SIOCGMIIPHY:
case SIOCGMIIREG:
case SIOCSMIIREG:
return e1000_mii_ioctl(netdev, ifr, cmd);
default:
return -EOPNOTSUPP;
}
}
/**
* e1000_mii_ioctl -
* @netdev:
* @ifreq:
* @cmd:
**/
static int e1000_mii_ioctl(struct net_device *netdev, struct ifreq *ifr,
int cmd)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct mii_ioctl_data *data = if_mii(ifr);
int retval;
u16 mii_reg;
unsigned long flags;
if (hw->media_type != e1000_media_type_copper)
return -EOPNOTSUPP;
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = hw->phy_addr;
break;
case SIOCGMIIREG:
spin_lock_irqsave(&adapter->stats_lock, flags);
if (e1000_read_phy_reg(hw, data->reg_num & 0x1F,
&data->val_out)) {
spin_unlock_irqrestore(&adapter->stats_lock, flags);
return -EIO;
}
spin_unlock_irqrestore(&adapter->stats_lock, flags);
break;
case SIOCSMIIREG:
if (data->reg_num & ~(0x1F))
return -EFAULT;
mii_reg = data->val_in;
spin_lock_irqsave(&adapter->stats_lock, flags);
if (e1000_write_phy_reg(hw, data->reg_num,
mii_reg)) {
spin_unlock_irqrestore(&adapter->stats_lock, flags);
return -EIO;
}
spin_unlock_irqrestore(&adapter->stats_lock, flags);
if (hw->media_type == e1000_media_type_copper) {
switch (data->reg_num) {
case PHY_CTRL:
if (mii_reg & MII_CR_POWER_DOWN)
break;
if (mii_reg & MII_CR_AUTO_NEG_EN) {
hw->autoneg = 1;
hw->autoneg_advertised = 0x2F;
} else {
u32 speed;
if (mii_reg & 0x40)
speed = SPEED_1000;
else if (mii_reg & 0x2000)
speed = SPEED_100;
else
speed = SPEED_10;
retval = e1000_set_spd_dplx(
adapter, speed,
((mii_reg & 0x100)
? DUPLEX_FULL :
DUPLEX_HALF));
if (retval)
return retval;
}
if (netif_running(adapter->netdev))
e1000_reinit_locked(adapter);
else
e1000_reset(adapter);
break;
case M88E1000_PHY_SPEC_CTRL:
case M88E1000_EXT_PHY_SPEC_CTRL:
if (e1000_phy_reset(hw))
return -EIO;
break;
}
} else {
switch (data->reg_num) {
case PHY_CTRL:
if (mii_reg & MII_CR_POWER_DOWN)
break;
if (netif_running(adapter->netdev))
e1000_reinit_locked(adapter);
else
e1000_reset(adapter);
break;
}
}
break;
default:
return -EOPNOTSUPP;
}
return E1000_SUCCESS;
}
void e1000_pci_set_mwi(struct e1000_hw *hw)
{
struct e1000_adapter *adapter = hw->back;
int ret_val = pci_set_mwi(adapter->pdev);
if (ret_val)
e_err(probe, "Error in setting MWI\n");
}
void e1000_pci_clear_mwi(struct e1000_hw *hw)
{
struct e1000_adapter *adapter = hw->back;
pci_clear_mwi(adapter->pdev);
}
int e1000_pcix_get_mmrbc(struct e1000_hw *hw)
{
struct e1000_adapter *adapter = hw->back;
return pcix_get_mmrbc(adapter->pdev);
}
void e1000_pcix_set_mmrbc(struct e1000_hw *hw, int mmrbc)
{
struct e1000_adapter *adapter = hw->back;
pcix_set_mmrbc(adapter->pdev, mmrbc);
}
void e1000_io_write(struct e1000_hw *hw, unsigned long port, u32 value)
{
outl(value, port);
}
static void e1000_vlan_rx_register(struct net_device *netdev,
struct vlan_group *grp)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 ctrl, rctl;
if (!test_bit(__E1000_DOWN, &adapter->flags))
e1000_irq_disable(adapter);
adapter->vlgrp = grp;
if (grp) {
/* enable VLAN tag insert/strip */
ctrl = er32(CTRL);
ctrl |= E1000_CTRL_VME;
ew32(CTRL, ctrl);
/* enable VLAN receive filtering */
rctl = er32(RCTL);
rctl &= ~E1000_RCTL_CFIEN;
if (!(netdev->flags & IFF_PROMISC))
rctl |= E1000_RCTL_VFE;
ew32(RCTL, rctl);
e1000_update_mng_vlan(adapter);
} else {
/* disable VLAN tag insert/strip */
ctrl = er32(CTRL);
ctrl &= ~E1000_CTRL_VME;
ew32(CTRL, ctrl);
/* disable VLAN receive filtering */
rctl = er32(RCTL);
rctl &= ~E1000_RCTL_VFE;
ew32(RCTL, rctl);
if (adapter->mng_vlan_id != (u16)E1000_MNG_VLAN_NONE) {
e1000_vlan_rx_kill_vid(netdev, adapter->mng_vlan_id);
adapter->mng_vlan_id = E1000_MNG_VLAN_NONE;
}
}
if (!test_bit(__E1000_DOWN, &adapter->flags))
e1000_irq_enable(adapter);
}
static void e1000_vlan_rx_add_vid(struct net_device *netdev, u16 vid)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 vfta, index;
if ((hw->mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN_SUPPORT) &&
(vid == adapter->mng_vlan_id))
return;
/* add VID to filter table */
index = (vid >> 5) & 0x7F;
vfta = E1000_READ_REG_ARRAY(hw, VFTA, index);
vfta |= (1 << (vid & 0x1F));
e1000_write_vfta(hw, index, vfta);
}
static void e1000_vlan_rx_kill_vid(struct net_device *netdev, u16 vid)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 vfta, index;
if (!test_bit(__E1000_DOWN, &adapter->flags))
e1000_irq_disable(adapter);
vlan_group_set_device(adapter->vlgrp, vid, NULL);
if (!test_bit(__E1000_DOWN, &adapter->flags))
e1000_irq_enable(adapter);
/* remove VID from filter table */
index = (vid >> 5) & 0x7F;
vfta = E1000_READ_REG_ARRAY(hw, VFTA, index);
vfta &= ~(1 << (vid & 0x1F));
e1000_write_vfta(hw, index, vfta);
}
static void e1000_restore_vlan(struct e1000_adapter *adapter)
{
e1000_vlan_rx_register(adapter->netdev, adapter->vlgrp);
if (adapter->vlgrp) {
u16 vid;
for (vid = 0; vid < VLAN_N_VID; vid++) {
if (!vlan_group_get_device(adapter->vlgrp, vid))
continue;
e1000_vlan_rx_add_vid(adapter->netdev, vid);
}
}
}
int e1000_set_spd_dplx(struct e1000_adapter *adapter, u32 spd, u8 dplx)
{
struct e1000_hw *hw = &adapter->hw;
hw->autoneg = 0;
/* Make sure dplx is at most 1 bit and lsb of speed is not set
* for the switch() below to work */
if ((spd & 1) || (dplx & ~1))
goto err_inval;
/* Fiber NICs only allow 1000 gbps Full duplex */
if ((hw->media_type == e1000_media_type_fiber) &&
spd != SPEED_1000 &&
dplx != DUPLEX_FULL)
goto err_inval;
switch (spd + dplx) {
case SPEED_10 + DUPLEX_HALF:
hw->forced_speed_duplex = e1000_10_half;
break;
case SPEED_10 + DUPLEX_FULL:
hw->forced_speed_duplex = e1000_10_full;
break;
case SPEED_100 + DUPLEX_HALF:
hw->forced_speed_duplex = e1000_100_half;
break;
case SPEED_100 + DUPLEX_FULL:
hw->forced_speed_duplex = e1000_100_full;
break;
case SPEED_1000 + DUPLEX_FULL:
hw->autoneg = 1;
hw->autoneg_advertised = ADVERTISE_1000_FULL;
break;
case SPEED_1000 + DUPLEX_HALF: /* not supported */
default:
goto err_inval;
}
return 0;
err_inval:
e_err(probe, "Unsupported Speed/Duplex configuration\n");
return -EINVAL;
}
static int __e1000_shutdown(struct pci_dev *pdev, bool *enable_wake)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 ctrl, ctrl_ext, rctl, status;
u32 wufc = adapter->wol;
#ifdef CONFIG_PM
int retval = 0;
#endif
netif_device_detach(netdev);
if (netif_running(netdev)) {
WARN_ON(test_bit(__E1000_RESETTING, &adapter->flags));
e1000_down(adapter);
}
#ifdef CONFIG_PM
retval = pci_save_state(pdev);
if (retval)
return retval;
#endif
status = er32(STATUS);
if (status & E1000_STATUS_LU)
wufc &= ~E1000_WUFC_LNKC;
if (wufc) {
e1000_setup_rctl(adapter);
e1000_set_rx_mode(netdev);
/* turn on all-multi mode if wake on multicast is enabled */
if (wufc & E1000_WUFC_MC) {
rctl = er32(RCTL);
rctl |= E1000_RCTL_MPE;
ew32(RCTL, rctl);
}
if (hw->mac_type >= e1000_82540) {
ctrl = er32(CTRL);
/* advertise wake from D3Cold */
#define E1000_CTRL_ADVD3WUC 0x00100000
/* phy power management enable */
#define E1000_CTRL_EN_PHY_PWR_MGMT 0x00200000
ctrl |= E1000_CTRL_ADVD3WUC |
E1000_CTRL_EN_PHY_PWR_MGMT;
ew32(CTRL, ctrl);
}
if (hw->media_type == e1000_media_type_fiber ||
hw->media_type == e1000_media_type_internal_serdes) {
/* keep the laser running in D3 */
ctrl_ext = er32(CTRL_EXT);
ctrl_ext |= E1000_CTRL_EXT_SDP7_DATA;
ew32(CTRL_EXT, ctrl_ext);
}
ew32(WUC, E1000_WUC_PME_EN);
ew32(WUFC, wufc);
} else {
ew32(WUC, 0);
ew32(WUFC, 0);
}
e1000_release_manageability(adapter);
*enable_wake = !!wufc;
/* make sure adapter isn't asleep if manageability is enabled */
if (adapter->en_mng_pt)
*enable_wake = true;
if (netif_running(netdev))
e1000_free_irq(adapter);
pci_disable_device(pdev);
return 0;
}
#ifdef CONFIG_PM
static int e1000_suspend(struct pci_dev *pdev, pm_message_t state)
{
int retval;
bool wake;
retval = __e1000_shutdown(pdev, &wake);
if (retval)
return retval;
if (wake) {
pci_prepare_to_sleep(pdev);
} else {
pci_wake_from_d3(pdev, false);
pci_set_power_state(pdev, PCI_D3hot);
}
return 0;
}
static int e1000_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 err;
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
pci_save_state(pdev);
if (adapter->need_ioport)
err = pci_enable_device(pdev);
else
err = pci_enable_device_mem(pdev);
if (err) {
pr_err("Cannot enable PCI device from suspend\n");
return err;
}
pci_set_master(pdev);
pci_enable_wake(pdev, PCI_D3hot, 0);
pci_enable_wake(pdev, PCI_D3cold, 0);
if (netif_running(netdev)) {
err = e1000_request_irq(adapter);
if (err)
return err;
}
e1000_power_up_phy(adapter);
e1000_reset(adapter);
ew32(WUS, ~0);
e1000_init_manageability(adapter);
if (netif_running(netdev))
e1000_up(adapter);
netif_device_attach(netdev);
return 0;
}
#endif
static void e1000_shutdown(struct pci_dev *pdev)
{
bool wake;
__e1000_shutdown(pdev, &wake);
if (system_state == SYSTEM_POWER_OFF) {
pci_wake_from_d3(pdev, wake);
pci_set_power_state(pdev, PCI_D3hot);
}
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* Polling 'interrupt' - used by things like netconsole to send skbs
* without having to re-enable interrupts. It's not called while
* the interrupt routine is executing.
*/
static void e1000_netpoll(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
disable_irq(adapter->pdev->irq);
e1000_intr(adapter->pdev->irq, netdev);
enable_irq(adapter->pdev->irq);
}
#endif
/**
* e1000_io_error_detected - called when PCI error is detected
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*
* This function is called after a PCI bus error affecting
* this device has been detected.
*/
static pci_ers_result_t e1000_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
netif_device_detach(netdev);
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
if (netif_running(netdev))
e1000_down(adapter);
pci_disable_device(pdev);
/* Request a slot slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
/**
* e1000_io_slot_reset - called after the pci bus has been reset.
* @pdev: Pointer to PCI device
*
* Restart the card from scratch, as if from a cold-boot. Implementation
* resembles the first-half of the e1000_resume routine.
*/
static pci_ers_result_t e1000_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
int err;
if (adapter->need_ioport)
err = pci_enable_device(pdev);
else
err = pci_enable_device_mem(pdev);
if (err) {
pr_err("Cannot re-enable PCI device after reset.\n");
return PCI_ERS_RESULT_DISCONNECT;
}
pci_set_master(pdev);
pci_enable_wake(pdev, PCI_D3hot, 0);
pci_enable_wake(pdev, PCI_D3cold, 0);
e1000_reset(adapter);
ew32(WUS, ~0);
return PCI_ERS_RESULT_RECOVERED;
}
/**
* e1000_io_resume - called when traffic can start flowing again.
* @pdev: Pointer to PCI device
*
* This callback is called when the error recovery driver tells us that
* its OK to resume normal operation. Implementation resembles the
* second-half of the e1000_resume routine.
*/
static void e1000_io_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
e1000_init_manageability(adapter);
if (netif_running(netdev)) {
if (e1000_up(adapter)) {
pr_info("can't bring device back up after reset\n");
return;
}
}
netif_device_attach(netdev);
}
/* e1000_main.c */
| gpl-2.0 |
jgcaap/boeffla | arch/arm/mach-msm/rpm_stats.c | 1386 | 10079 | /* Copyright (c) 2011-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/debugfs.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/types.h>
#include <linux/of.h>
#include <asm/uaccess.h>
#include <asm/arch_timer.h>
#include <mach/msm_iomap.h>
#include "rpm_stats.h"
enum {
ID_COUNTER,
ID_ACCUM_TIME_SCLK,
ID_MAX,
};
static char *msm_rpmstats_id_labels[ID_MAX] = {
[ID_COUNTER] = "Count",
[ID_ACCUM_TIME_SCLK] = "Total time(uSec)",
};
#define SCLK_HZ 32768
#define MSM_ARCH_TIMER_FREQ 19200000
struct msm_rpmstats_record{
char name[32];
uint32_t id;
uint32_t val;
};
struct msm_rpmstats_private_data{
void __iomem *reg_base;
u32 num_records;
u32 read_idx;
u32 len;
char buf[320];
struct msm_rpmstats_platform_data *platform_data;
};
struct msm_rpm_stats_data_v2 {
u32 stat_type;
u32 count;
u64 last_entered_at;
u64 last_exited_at;
u64 accumulated;
u32 client_votes;
u32 reserved[3];
};
static inline u64 get_time_in_sec(u64 counter)
{
do_div(counter, MSM_ARCH_TIMER_FREQ);
return counter;
}
static inline u64 get_time_in_msec(u64 counter)
{
do_div(counter, MSM_ARCH_TIMER_FREQ);
counter *= MSEC_PER_SEC;
return counter;
}
static inline int msm_rpmstats_append_data_to_buf(char *buf,
struct msm_rpm_stats_data_v2 *data, int buflength)
{
char stat_type[5];
u64 time_in_last_mode;
u64 time_since_last_mode;
u64 actual_last_sleep;
stat_type[4] = 0;
memcpy(stat_type, &data->stat_type, sizeof(u32));
time_in_last_mode = data->last_exited_at - data->last_entered_at;
time_in_last_mode = get_time_in_msec(time_in_last_mode);
time_since_last_mode = arch_counter_get_cntpct() - data->last_exited_at;
time_since_last_mode = get_time_in_sec(time_since_last_mode);
actual_last_sleep = get_time_in_msec(data->accumulated);
return snprintf(buf , buflength,
"RPM Mode:%s\n\t count:%d\ntime in last mode(msec):%llu\n"
"time since last mode(sec):%llu\nactual last sleep(msec):%llu\n"
"client votes: %#010x\n\n",
stat_type, data->count, time_in_last_mode,
time_since_last_mode, actual_last_sleep,
data->client_votes);
}
static inline u32 msm_rpmstats_read_long_register_v2(void __iomem *regbase,
int index, int offset)
{
return readl_relaxed(regbase + offset +
index * sizeof(struct msm_rpm_stats_data_v2));
}
static inline u64 msm_rpmstats_read_quad_register_v2(void __iomem *regbase,
int index, int offset)
{
u64 dst;
memcpy_fromio(&dst,
regbase + offset + index * sizeof(struct msm_rpm_stats_data_v2),
8);
return dst;
}
static inline int msm_rpmstats_copy_stats_v2(
struct msm_rpmstats_private_data *prvdata)
{
void __iomem *reg;
struct msm_rpm_stats_data_v2 data;
int i, length;
reg = prvdata->reg_base;
for (i = 0, length = 0; i < prvdata->num_records; i++) {
data.stat_type = msm_rpmstats_read_long_register_v2(reg, i,
offsetof(struct msm_rpm_stats_data_v2,
stat_type));
data.count = msm_rpmstats_read_long_register_v2(reg, i,
offsetof(struct msm_rpm_stats_data_v2, count));
data.last_entered_at = msm_rpmstats_read_quad_register_v2(reg,
i, offsetof(struct msm_rpm_stats_data_v2,
last_entered_at));
data.last_exited_at = msm_rpmstats_read_quad_register_v2(reg,
i, offsetof(struct msm_rpm_stats_data_v2,
last_exited_at));
data.accumulated = msm_rpmstats_read_quad_register_v2(reg,
i, offsetof(struct msm_rpm_stats_data_v2,
accumulated));
data.client_votes = msm_rpmstats_read_long_register_v2(reg,
i, offsetof(struct msm_rpm_stats_data_v2,
client_votes));
length += msm_rpmstats_append_data_to_buf(prvdata->buf + length,
&data, sizeof(prvdata->buf) - length);
prvdata->read_idx++;
}
return length;
}
static inline unsigned long msm_rpmstats_read_register(void __iomem *regbase,
int index, int offset)
{
return readl_relaxed(regbase + index * 12 + (offset + 1) * 4);
}
static void msm_rpmstats_strcpy(char *dest, char *src)
{
union {
char ch[4];
unsigned long word;
} string;
int index = 0;
do {
int i;
string.word = readl_relaxed(src + 4 * index);
for (i = 0; i < 4; i++) {
*dest++ = string.ch[i];
if (!string.ch[i])
break;
}
index++;
} while (*(dest-1));
}
static int msm_rpmstats_copy_stats(struct msm_rpmstats_private_data *pdata)
{
struct msm_rpmstats_record record;
unsigned long ptr;
unsigned long offset;
char *str;
uint64_t usec;
ptr = msm_rpmstats_read_register(pdata->reg_base, pdata->read_idx, 0);
offset = (ptr - (unsigned long)pdata->platform_data->phys_addr_base);
if (offset > pdata->platform_data->phys_size)
str = (char *)ioremap(ptr, SZ_256);
else
str = (char *) pdata->reg_base + offset;
msm_rpmstats_strcpy(record.name, str);
if (offset > pdata->platform_data->phys_size)
iounmap(str);
record.id = msm_rpmstats_read_register(pdata->reg_base,
pdata->read_idx, 1);
record.val = msm_rpmstats_read_register(pdata->reg_base,
pdata->read_idx, 2);
if (record.id == ID_ACCUM_TIME_SCLK) {
usec = record.val * USEC_PER_SEC;
do_div(usec, SCLK_HZ);
} else
usec = (unsigned long)record.val;
pdata->read_idx++;
return snprintf(pdata->buf, sizeof(pdata->buf),
"RPM Mode:%s\n\t%s:%llu\n",
record.name,
msm_rpmstats_id_labels[record.id],
usec);
}
static int msm_rpmstats_file_read(struct file *file, char __user *bufu,
size_t count, loff_t *ppos)
{
struct msm_rpmstats_private_data *prvdata;
prvdata = file->private_data;
if (!prvdata)
return -EINVAL;
if (!bufu || count == 0)
return -EINVAL;
if (prvdata->platform_data->version == 1) {
if (!prvdata->num_records)
prvdata->num_records = readl_relaxed(prvdata->reg_base);
}
if ((*ppos >= prvdata->len)
&& (prvdata->read_idx < prvdata->num_records)) {
if (prvdata->platform_data->version == 1)
prvdata->len = msm_rpmstats_copy_stats(prvdata);
else if (prvdata->platform_data->version == 2)
prvdata->len = msm_rpmstats_copy_stats_v2(
prvdata);
*ppos = 0;
}
return simple_read_from_buffer(bufu, count, ppos,
prvdata->buf, prvdata->len);
}
static int msm_rpmstats_file_open(struct inode *inode, struct file *file)
{
struct msm_rpmstats_private_data *prvdata;
struct msm_rpmstats_platform_data *pdata;
pdata = inode->i_private;
file->private_data =
kmalloc(sizeof(struct msm_rpmstats_private_data), GFP_KERNEL);
if (!file->private_data)
return -ENOMEM;
prvdata = file->private_data;
prvdata->reg_base = ioremap_nocache(pdata->phys_addr_base,
pdata->phys_size);
if (!prvdata->reg_base) {
kfree(file->private_data);
prvdata = NULL;
pr_err("%s: ERROR could not ioremap start=%p, len=%u\n",
__func__, (void *)pdata->phys_addr_base,
pdata->phys_size);
return -EBUSY;
}
prvdata->read_idx = prvdata->num_records = prvdata->len = 0;
prvdata->platform_data = pdata;
if (pdata->version == 2)
prvdata->num_records = 2;
return 0;
}
static int msm_rpmstats_file_close(struct inode *inode, struct file *file)
{
struct msm_rpmstats_private_data *private = file->private_data;
if (private->reg_base)
iounmap(private->reg_base);
kfree(file->private_data);
return 0;
}
static const struct file_operations msm_rpmstats_fops = {
.owner = THIS_MODULE,
.open = msm_rpmstats_file_open,
.read = msm_rpmstats_file_read,
.release = msm_rpmstats_file_close,
.llseek = no_llseek,
};
static int __devinit msm_rpmstats_probe(struct platform_device *pdev)
{
struct dentry *dent = NULL;
struct msm_rpmstats_platform_data *pdata;
struct msm_rpmstats_platform_data *pd;
struct resource *res = NULL;
struct device_node *node = NULL;
int ret = 0;
if (!pdev)
return -EINVAL;
pdata = kzalloc(sizeof(struct msm_rpmstats_platform_data), GFP_KERNEL);
if (!pdata)
return -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -EINVAL;
pdata->phys_addr_base = res->start;
pdata->phys_size = resource_size(res);
node = pdev->dev.of_node;
if (pdev->dev.platform_data) {
pd = pdev->dev.platform_data;
pdata->version = pd->version;
} else if (node)
ret = of_property_read_u32(node,
"qcom,sleep-stats-version", &pdata->version);
if (!ret) {
dent = debugfs_create_file("rpm_stats", S_IRUGO, NULL,
pdata, &msm_rpmstats_fops);
if (!dent) {
pr_err("%s: ERROR debugfs_create_file failed\n",
__func__);
kfree(pdata);
return -ENOMEM;
}
} else {
kfree(pdata);
return -EINVAL;
}
platform_set_drvdata(pdev, dent);
return 0;
}
static int __devexit msm_rpmstats_remove(struct platform_device *pdev)
{
struct dentry *dent;
dent = platform_get_drvdata(pdev);
debugfs_remove(dent);
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct of_device_id rpm_stats_table[] = {
{.compatible = "qcom,rpm-stats"},
{},
};
static struct platform_driver msm_rpmstats_driver = {
.probe = msm_rpmstats_probe,
.remove = __devexit_p(msm_rpmstats_remove),
.driver = {
.name = "msm_rpm_stat",
.owner = THIS_MODULE,
.of_match_table = rpm_stats_table,
},
};
static int __init msm_rpmstats_init(void)
{
return platform_driver_register(&msm_rpmstats_driver);
}
static void __exit msm_rpmstats_exit(void)
{
platform_driver_unregister(&msm_rpmstats_driver);
}
module_init(msm_rpmstats_init);
module_exit(msm_rpmstats_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("MSM RPM Statistics driver");
MODULE_VERSION("1.0");
MODULE_ALIAS("platform:msm_stat_log");
| gpl-2.0 |
ench0/android_kernel_samsung_hltez | drivers/coresight/coresight-replicator.c | 2154 | 5604 | /* Copyright (c) 2011-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <linux/of_coresight.h>
#include <linux/coresight.h>
#include "coresight-priv.h"
#define replicator_writel(drvdata, val, off) \
__raw_writel((val), drvdata->base + off)
#define replicator_readl(drvdata, off) \
__raw_readl(drvdata->base + off)
#define REPLICATOR_LOCK(drvdata) \
do { \
mb(); \
replicator_writel(drvdata, 0x0, CORESIGHT_LAR); \
} while (0)
#define REPLICATOR_UNLOCK(drvdata) \
do { \
replicator_writel(drvdata, CORESIGHT_UNLOCK, CORESIGHT_LAR); \
mb(); \
} while (0)
#define REPLICATOR_IDFILTER0 (0x000)
#define REPLICATOR_IDFILTER1 (0x004)
#define REPLICATOR_ITATBCTR0 (0xEFC)
#define REPLICATOR_ITATBCTR1 (0xEF8)
struct replicator_drvdata {
void __iomem *base;
struct device *dev;
struct coresight_device *csdev;
struct clk *clk;
};
static void __replicator_enable(struct replicator_drvdata *drvdata, int outport)
{
REPLICATOR_UNLOCK(drvdata);
if (outport == 0) {
replicator_writel(drvdata, 0x0, REPLICATOR_IDFILTER0);
replicator_writel(drvdata, 0xFF, REPLICATOR_IDFILTER1);
} else {
replicator_writel(drvdata, 0x0, REPLICATOR_IDFILTER1);
replicator_writel(drvdata, 0xFF, REPLICATOR_IDFILTER0);
}
REPLICATOR_LOCK(drvdata);
}
static int replicator_enable(struct coresight_device *csdev, int inport,
int outport)
{
struct replicator_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
int ret;
ret = clk_prepare_enable(drvdata->clk);
if (ret)
return ret;
__replicator_enable(drvdata, outport);
dev_info(drvdata->dev, "REPLICATOR enabled\n");
return 0;
}
static void __replicator_disable(struct replicator_drvdata *drvdata,
int outport)
{
REPLICATOR_UNLOCK(drvdata);
if (outport == 0)
replicator_writel(drvdata, 0xFF, REPLICATOR_IDFILTER0);
else
replicator_writel(drvdata, 0xFF, REPLICATOR_IDFILTER1);
REPLICATOR_LOCK(drvdata);
}
static void replicator_disable(struct coresight_device *csdev, int inport,
int outport)
{
struct replicator_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
__replicator_disable(drvdata, outport);
clk_disable_unprepare(drvdata->clk);
dev_info(drvdata->dev, "REPLICATOR disabled\n");
}
static const struct coresight_ops_link replicator_link_ops = {
.enable = replicator_enable,
.disable = replicator_disable,
};
static const struct coresight_ops replicator_cs_ops = {
.link_ops = &replicator_link_ops,
};
static int __devinit replicator_probe(struct platform_device *pdev)
{
int ret;
struct device *dev = &pdev->dev;
struct coresight_platform_data *pdata;
struct replicator_drvdata *drvdata;
struct resource *res;
struct coresight_desc *desc;
if (coresight_fuse_access_disabled())
return -EPERM;
if (pdev->dev.of_node) {
pdata = of_get_coresight_platform_data(dev, pdev->dev.of_node);
if (IS_ERR(pdata))
return PTR_ERR(pdata);
pdev->dev.platform_data = pdata;
}
drvdata = devm_kzalloc(dev, sizeof(*drvdata), GFP_KERNEL);
if (!drvdata)
return -ENOMEM;
drvdata->dev = &pdev->dev;
platform_set_drvdata(pdev, drvdata);
res = platform_get_resource_byname(pdev, IORESOURCE_MEM,
"replicator-base");
if (!res)
return -ENODEV;
drvdata->base = devm_ioremap(dev, res->start, resource_size(res));
if (!drvdata->base)
return -ENOMEM;
drvdata->clk = devm_clk_get(dev, "core_clk");
if (IS_ERR(drvdata->clk))
return PTR_ERR(drvdata->clk);
ret = clk_set_rate(drvdata->clk, CORESIGHT_CLK_RATE_TRACE);
if (ret)
return ret;
desc = devm_kzalloc(dev, sizeof(*desc), GFP_KERNEL);
if (!desc)
return -ENOMEM;
desc->type = CORESIGHT_DEV_TYPE_LINK;
desc->subtype.sink_subtype = CORESIGHT_DEV_SUBTYPE_LINK_SPLIT;
desc->ops = &replicator_cs_ops;
desc->pdata = pdev->dev.platform_data;
desc->dev = &pdev->dev;
desc->owner = THIS_MODULE;
drvdata->csdev = coresight_register(desc);
if (IS_ERR(drvdata->csdev))
return PTR_ERR(drvdata->csdev);
dev_info(dev, "REPLICATOR initialized\n");
return 0;
}
static int __devexit replicator_remove(struct platform_device *pdev)
{
struct replicator_drvdata *drvdata = platform_get_drvdata(pdev);
coresight_unregister(drvdata->csdev);
return 0;
}
static struct of_device_id replicator_match[] = {
{.compatible = "qcom,coresight-replicator"},
{}
};
static struct platform_driver replicator_driver = {
.probe = replicator_probe,
.remove = __devexit_p(replicator_remove),
.driver = {
.name = "coresight-replicator",
.owner = THIS_MODULE,
.of_match_table = replicator_match,
},
};
static int __init replicator_init(void)
{
return platform_driver_register(&replicator_driver);
}
module_init(replicator_init);
static void __exit replicator_exit(void)
{
platform_driver_unregister(&replicator_driver);
}
module_exit(replicator_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("CoreSight Replicator driver");
| gpl-2.0 |
M8s-dev/kernel_htc_msm8939 | drivers/rtc/rtc-ds1742.c | 2154 | 7219 | /*
* An rtc driver for the Dallas DS1742
*
* Copyright (C) 2006 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.
*
* Copyright (C) 2006 Torsten Ertbjerg Rasmussen <tr@newtec.dk>
* - nvram size determined from resource
* - this ds1742 driver now supports ds1743.
*/
#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/rtc.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/module.h>
#define DRV_VERSION "0.4"
#define RTC_SIZE 8
#define RTC_CONTROL 0
#define RTC_CENTURY 0
#define RTC_SECONDS 1
#define RTC_MINUTES 2
#define RTC_HOURS 3
#define RTC_DAY 4
#define RTC_DATE 5
#define RTC_MONTH 6
#define RTC_YEAR 7
#define RTC_CENTURY_MASK 0x3f
#define RTC_SECONDS_MASK 0x7f
#define RTC_DAY_MASK 0x07
/* Bits in the Control/Century register */
#define RTC_WRITE 0x80
#define RTC_READ 0x40
/* Bits in the Seconds register */
#define RTC_STOP 0x80
/* Bits in the Day register */
#define RTC_BATT_FLAG 0x80
struct rtc_plat_data {
struct rtc_device *rtc;
void __iomem *ioaddr_nvram;
void __iomem *ioaddr_rtc;
size_t size_nvram;
size_t size;
unsigned long last_jiffies;
struct bin_attribute nvram_attr;
};
static int ds1742_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_rtc;
u8 century;
century = bin2bcd((tm->tm_year + 1900) / 100);
writeb(RTC_WRITE, ioaddr + RTC_CONTROL);
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);
/* RTC_CENTURY and RTC_CONTROL share same register */
writeb(RTC_WRITE | (century & RTC_CENTURY_MASK), ioaddr + RTC_CENTURY);
writeb(century & RTC_CENTURY_MASK, ioaddr + RTC_CONTROL);
return 0;
}
static int ds1742_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_rtc;
unsigned int year, month, day, hour, minute, second, week;
unsigned int century;
/* give enough time to update RTC in case of continuous read */
if (pdata->last_jiffies == jiffies)
msleep(1);
pdata->last_jiffies = jiffies;
writeb(RTC_READ, ioaddr + RTC_CONTROL);
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) & RTC_CENTURY_MASK;
writeb(0, ioaddr + RTC_CONTROL);
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 const struct rtc_class_ops ds1742_rtc_ops = {
.read_time = ds1742_rtc_read_time,
.set_time = ds1742_rtc_set_time,
};
static ssize_t ds1742_nvram_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_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_nvram;
ssize_t count;
for (count = 0; size > 0 && pos < pdata->size_nvram; count++, size--)
*buf++ = readb(ioaddr + pos++);
return count;
}
static ssize_t ds1742_nvram_write(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_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_nvram;
ssize_t count;
for (count = 0; size > 0 && pos < pdata->size_nvram; count++, size--)
writeb(*buf++, ioaddr + pos++);
return count;
}
static int ds1742_rtc_probe(struct platform_device *pdev)
{
struct rtc_device *rtc;
struct resource *res;
unsigned int cen, sec;
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;
pdata->size = resource_size(res);
if (!devm_request_mem_region(&pdev->dev, res->start, pdata->size,
pdev->name))
return -EBUSY;
ioaddr = devm_ioremap(&pdev->dev, res->start, pdata->size);
if (!ioaddr)
return -ENOMEM;
pdata->ioaddr_nvram = ioaddr;
pdata->size_nvram = pdata->size - RTC_SIZE;
pdata->ioaddr_rtc = ioaddr + pdata->size_nvram;
sysfs_bin_attr_init(&pdata->nvram_attr);
pdata->nvram_attr.attr.name = "nvram";
pdata->nvram_attr.attr.mode = S_IRUGO | S_IWUSR;
pdata->nvram_attr.read = ds1742_nvram_read;
pdata->nvram_attr.write = ds1742_nvram_write;
pdata->nvram_attr.size = pdata->size_nvram;
/* turn RTC on if it was not on */
ioaddr = pdata->ioaddr_rtc;
sec = readb(ioaddr + RTC_SECONDS);
if (sec & RTC_STOP) {
sec &= RTC_SECONDS_MASK;
cen = readb(ioaddr + RTC_CENTURY) & RTC_CENTURY_MASK;
writeb(RTC_WRITE, ioaddr + RTC_CONTROL);
writeb(sec, ioaddr + RTC_SECONDS);
writeb(cen & RTC_CENTURY_MASK, ioaddr + RTC_CONTROL);
}
if (!(readb(ioaddr + RTC_DAY) & RTC_BATT_FLAG))
dev_warn(&pdev->dev, "voltage-low detected.\n");
pdata->last_jiffies = jiffies;
platform_set_drvdata(pdev, pdata);
rtc = devm_rtc_device_register(&pdev->dev, pdev->name,
&ds1742_rtc_ops, THIS_MODULE);
if (IS_ERR(rtc))
return PTR_ERR(rtc);
pdata->rtc = rtc;
ret = sysfs_create_bin_file(&pdev->dev.kobj, &pdata->nvram_attr);
return ret;
}
static int ds1742_rtc_remove(struct platform_device *pdev)
{
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
sysfs_remove_bin_file(&pdev->dev.kobj, &pdata->nvram_attr);
return 0;
}
static struct platform_driver ds1742_rtc_driver = {
.probe = ds1742_rtc_probe,
.remove = ds1742_rtc_remove,
.driver = {
.name = "rtc-ds1742",
.owner = THIS_MODULE,
},
};
module_platform_driver(ds1742_rtc_driver);
MODULE_AUTHOR("Atsushi Nemoto <anemo@mba.ocn.ne.jp>");
MODULE_DESCRIPTION("Dallas DS1742 RTC driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
MODULE_ALIAS("platform:rtc-ds1742");
| gpl-2.0 |
DC07/spirit_msm8226 | net/ipv6/esp6.c | 2922 | 16044 | /*
* Copyright (C)2002 USAGI/WIDE Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Authors
*
* Mitsuru KANDA @USAGI : IPv6 Support
* Kazunori MIYAZAWA @USAGI :
* Kunihiro Ishiguro <kunihiro@ipinfusion.com>
*
* This file is derived from net/ipv4/esp.c
*/
#include <crypto/aead.h>
#include <crypto/authenc.h>
#include <linux/err.h>
#include <linux/module.h>
#include <net/ip.h>
#include <net/xfrm.h>
#include <net/esp.h>
#include <linux/scatterlist.h>
#include <linux/kernel.h>
#include <linux/pfkeyv2.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <net/icmp.h>
#include <net/ipv6.h>
#include <net/protocol.h>
#include <linux/icmpv6.h>
struct esp_skb_cb {
struct xfrm_skb_cb xfrm;
void *tmp;
};
#define ESP_SKB_CB(__skb) ((struct esp_skb_cb *)&((__skb)->cb[0]))
static u32 esp6_get_mtu(struct xfrm_state *x, int mtu);
/*
* Allocate an AEAD request structure with extra space for SG and IV.
*
* For alignment considerations the upper 32 bits of the sequence number are
* placed at the front, if present. Followed by the IV, the request and finally
* the SG list.
*
* TODO: Use spare space in skb for this where possible.
*/
static void *esp_alloc_tmp(struct crypto_aead *aead, int nfrags, int seqihlen)
{
unsigned int len;
len = seqihlen;
len += crypto_aead_ivsize(aead);
if (len) {
len += crypto_aead_alignmask(aead) &
~(crypto_tfm_ctx_alignment() - 1);
len = ALIGN(len, crypto_tfm_ctx_alignment());
}
len += sizeof(struct aead_givcrypt_request) + crypto_aead_reqsize(aead);
len = ALIGN(len, __alignof__(struct scatterlist));
len += sizeof(struct scatterlist) * nfrags;
return kmalloc(len, GFP_ATOMIC);
}
static inline __be32 *esp_tmp_seqhi(void *tmp)
{
return PTR_ALIGN((__be32 *)tmp, __alignof__(__be32));
}
static inline u8 *esp_tmp_iv(struct crypto_aead *aead, void *tmp, int seqhilen)
{
return crypto_aead_ivsize(aead) ?
PTR_ALIGN((u8 *)tmp + seqhilen,
crypto_aead_alignmask(aead) + 1) : tmp + seqhilen;
}
static inline struct aead_givcrypt_request *esp_tmp_givreq(
struct crypto_aead *aead, u8 *iv)
{
struct aead_givcrypt_request *req;
req = (void *)PTR_ALIGN(iv + crypto_aead_ivsize(aead),
crypto_tfm_ctx_alignment());
aead_givcrypt_set_tfm(req, aead);
return req;
}
static inline struct aead_request *esp_tmp_req(struct crypto_aead *aead, u8 *iv)
{
struct aead_request *req;
req = (void *)PTR_ALIGN(iv + crypto_aead_ivsize(aead),
crypto_tfm_ctx_alignment());
aead_request_set_tfm(req, aead);
return req;
}
static inline struct scatterlist *esp_req_sg(struct crypto_aead *aead,
struct aead_request *req)
{
return (void *)ALIGN((unsigned long)(req + 1) +
crypto_aead_reqsize(aead),
__alignof__(struct scatterlist));
}
static inline struct scatterlist *esp_givreq_sg(
struct crypto_aead *aead, struct aead_givcrypt_request *req)
{
return (void *)ALIGN((unsigned long)(req + 1) +
crypto_aead_reqsize(aead),
__alignof__(struct scatterlist));
}
static void esp_output_done(struct crypto_async_request *base, int err)
{
struct sk_buff *skb = base->data;
kfree(ESP_SKB_CB(skb)->tmp);
xfrm_output_resume(skb, err);
}
static int esp6_output(struct xfrm_state *x, struct sk_buff *skb)
{
int err;
struct ip_esp_hdr *esph;
struct crypto_aead *aead;
struct aead_givcrypt_request *req;
struct scatterlist *sg;
struct scatterlist *asg;
struct sk_buff *trailer;
void *tmp;
int blksize;
int clen;
int alen;
int plen;
int tfclen;
int nfrags;
int assoclen;
int sglists;
int seqhilen;
u8 *iv;
u8 *tail;
__be32 *seqhi;
struct esp_data *esp = x->data;
/* skb is pure payload to encrypt */
err = -ENOMEM;
aead = esp->aead;
alen = crypto_aead_authsize(aead);
tfclen = 0;
if (x->tfcpad) {
struct xfrm_dst *dst = (struct xfrm_dst *)skb_dst(skb);
u32 padto;
padto = min(x->tfcpad, esp6_get_mtu(x, dst->child_mtu_cached));
if (skb->len < padto)
tfclen = padto - skb->len;
}
blksize = ALIGN(crypto_aead_blocksize(aead), 4);
clen = ALIGN(skb->len + 2 + tfclen, blksize);
if (esp->padlen)
clen = ALIGN(clen, esp->padlen);
plen = clen - skb->len - tfclen;
err = skb_cow_data(skb, tfclen + plen + alen, &trailer);
if (err < 0)
goto error;
nfrags = err;
assoclen = sizeof(*esph);
sglists = 1;
seqhilen = 0;
if (x->props.flags & XFRM_STATE_ESN) {
sglists += 2;
seqhilen += sizeof(__be32);
assoclen += seqhilen;
}
tmp = esp_alloc_tmp(aead, nfrags + sglists, seqhilen);
if (!tmp)
goto error;
seqhi = esp_tmp_seqhi(tmp);
iv = esp_tmp_iv(aead, tmp, seqhilen);
req = esp_tmp_givreq(aead, iv);
asg = esp_givreq_sg(aead, req);
sg = asg + sglists;
/* Fill padding... */
tail = skb_tail_pointer(trailer);
if (tfclen) {
memset(tail, 0, tfclen);
tail += tfclen;
}
do {
int i;
for (i = 0; i < plen - 2; i++)
tail[i] = i + 1;
} while (0);
tail[plen - 2] = plen - 2;
tail[plen - 1] = *skb_mac_header(skb);
pskb_put(skb, trailer, clen - skb->len + alen);
skb_push(skb, -skb_network_offset(skb));
esph = ip_esp_hdr(skb);
*skb_mac_header(skb) = IPPROTO_ESP;
esph->spi = x->id.spi;
esph->seq_no = htonl(XFRM_SKB_CB(skb)->seq.output.low);
sg_init_table(sg, nfrags);
skb_to_sgvec(skb, sg,
esph->enc_data + crypto_aead_ivsize(aead) - skb->data,
clen + alen);
if ((x->props.flags & XFRM_STATE_ESN)) {
sg_init_table(asg, 3);
sg_set_buf(asg, &esph->spi, sizeof(__be32));
*seqhi = htonl(XFRM_SKB_CB(skb)->seq.output.hi);
sg_set_buf(asg + 1, seqhi, seqhilen);
sg_set_buf(asg + 2, &esph->seq_no, sizeof(__be32));
} else
sg_init_one(asg, esph, sizeof(*esph));
aead_givcrypt_set_callback(req, 0, esp_output_done, skb);
aead_givcrypt_set_crypt(req, sg, sg, clen, iv);
aead_givcrypt_set_assoc(req, asg, assoclen);
aead_givcrypt_set_giv(req, esph->enc_data,
XFRM_SKB_CB(skb)->seq.output.low);
ESP_SKB_CB(skb)->tmp = tmp;
err = crypto_aead_givencrypt(req);
if (err == -EINPROGRESS)
goto error;
if (err == -EBUSY)
err = NET_XMIT_DROP;
kfree(tmp);
error:
return err;
}
static int esp_input_done2(struct sk_buff *skb, int err)
{
struct xfrm_state *x = xfrm_input_state(skb);
struct esp_data *esp = x->data;
struct crypto_aead *aead = esp->aead;
int alen = crypto_aead_authsize(aead);
int hlen = sizeof(struct ip_esp_hdr) + crypto_aead_ivsize(aead);
int elen = skb->len - hlen;
int hdr_len = skb_network_header_len(skb);
int padlen;
u8 nexthdr[2];
kfree(ESP_SKB_CB(skb)->tmp);
if (unlikely(err))
goto out;
if (skb_copy_bits(skb, skb->len - alen - 2, nexthdr, 2))
BUG();
err = -EINVAL;
padlen = nexthdr[0];
if (padlen + 2 + alen >= elen) {
LIMIT_NETDEBUG(KERN_WARNING "ipsec esp packet is garbage "
"padlen=%d, elen=%d\n", padlen + 2, elen - alen);
goto out;
}
/* ... check padding bits here. Silly. :-) */
pskb_trim(skb, skb->len - alen - padlen - 2);
__skb_pull(skb, hlen);
skb_set_transport_header(skb, -hdr_len);
err = nexthdr[1];
/* RFC4303: Drop dummy packets without any error */
if (err == IPPROTO_NONE)
err = -EINVAL;
out:
return err;
}
static void esp_input_done(struct crypto_async_request *base, int err)
{
struct sk_buff *skb = base->data;
xfrm_input_resume(skb, esp_input_done2(skb, err));
}
static int esp6_input(struct xfrm_state *x, struct sk_buff *skb)
{
struct ip_esp_hdr *esph;
struct esp_data *esp = x->data;
struct crypto_aead *aead = esp->aead;
struct aead_request *req;
struct sk_buff *trailer;
int elen = skb->len - sizeof(*esph) - crypto_aead_ivsize(aead);
int nfrags;
int assoclen;
int sglists;
int seqhilen;
int ret = 0;
void *tmp;
__be32 *seqhi;
u8 *iv;
struct scatterlist *sg;
struct scatterlist *asg;
if (!pskb_may_pull(skb, sizeof(*esph) + crypto_aead_ivsize(aead))) {
ret = -EINVAL;
goto out;
}
if (elen <= 0) {
ret = -EINVAL;
goto out;
}
if ((nfrags = skb_cow_data(skb, 0, &trailer)) < 0) {
ret = -EINVAL;
goto out;
}
ret = -ENOMEM;
assoclen = sizeof(*esph);
sglists = 1;
seqhilen = 0;
if (x->props.flags & XFRM_STATE_ESN) {
sglists += 2;
seqhilen += sizeof(__be32);
assoclen += seqhilen;
}
tmp = esp_alloc_tmp(aead, nfrags + sglists, seqhilen);
if (!tmp)
goto out;
ESP_SKB_CB(skb)->tmp = tmp;
seqhi = esp_tmp_seqhi(tmp);
iv = esp_tmp_iv(aead, tmp, seqhilen);
req = esp_tmp_req(aead, iv);
asg = esp_req_sg(aead, req);
sg = asg + sglists;
skb->ip_summed = CHECKSUM_NONE;
esph = (struct ip_esp_hdr *)skb->data;
/* Get ivec. This can be wrong, check against another impls. */
iv = esph->enc_data;
sg_init_table(sg, nfrags);
skb_to_sgvec(skb, sg, sizeof(*esph) + crypto_aead_ivsize(aead), elen);
if ((x->props.flags & XFRM_STATE_ESN)) {
sg_init_table(asg, 3);
sg_set_buf(asg, &esph->spi, sizeof(__be32));
*seqhi = XFRM_SKB_CB(skb)->seq.input.hi;
sg_set_buf(asg + 1, seqhi, seqhilen);
sg_set_buf(asg + 2, &esph->seq_no, sizeof(__be32));
} else
sg_init_one(asg, esph, sizeof(*esph));
aead_request_set_callback(req, 0, esp_input_done, skb);
aead_request_set_crypt(req, sg, sg, elen, iv);
aead_request_set_assoc(req, asg, assoclen);
ret = crypto_aead_decrypt(req);
if (ret == -EINPROGRESS)
goto out;
ret = esp_input_done2(skb, ret);
out:
return ret;
}
static u32 esp6_get_mtu(struct xfrm_state *x, int mtu)
{
struct esp_data *esp = x->data;
u32 blksize = ALIGN(crypto_aead_blocksize(esp->aead), 4);
u32 align = max_t(u32, blksize, esp->padlen);
unsigned int net_adj;
if (x->props.mode != XFRM_MODE_TUNNEL)
net_adj = sizeof(struct ipv6hdr);
else
net_adj = 0;
return ((mtu - x->props.header_len - crypto_aead_authsize(esp->aead) -
net_adj) & ~(align - 1)) + (net_adj - 2);
}
static void esp6_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
struct net *net = dev_net(skb->dev);
const struct ipv6hdr *iph = (const struct ipv6hdr *)skb->data;
struct ip_esp_hdr *esph = (struct ip_esp_hdr *)(skb->data + offset);
struct xfrm_state *x;
if (type != ICMPV6_DEST_UNREACH &&
type != ICMPV6_PKT_TOOBIG)
return;
x = xfrm_state_lookup(net, skb->mark, (const xfrm_address_t *)&iph->daddr,
esph->spi, IPPROTO_ESP, AF_INET6);
if (!x)
return;
printk(KERN_DEBUG "pmtu discovery on SA ESP/%08x/%pI6\n",
ntohl(esph->spi), &iph->daddr);
xfrm_state_put(x);
}
static void esp6_destroy(struct xfrm_state *x)
{
struct esp_data *esp = x->data;
if (!esp)
return;
crypto_free_aead(esp->aead);
kfree(esp);
}
static int esp_init_aead(struct xfrm_state *x)
{
struct esp_data *esp = x->data;
struct crypto_aead *aead;
int err;
aead = crypto_alloc_aead(x->aead->alg_name, 0, 0);
err = PTR_ERR(aead);
if (IS_ERR(aead))
goto error;
esp->aead = aead;
err = crypto_aead_setkey(aead, x->aead->alg_key,
(x->aead->alg_key_len + 7) / 8);
if (err)
goto error;
err = crypto_aead_setauthsize(aead, x->aead->alg_icv_len / 8);
if (err)
goto error;
error:
return err;
}
static int esp_init_authenc(struct xfrm_state *x)
{
struct esp_data *esp = x->data;
struct crypto_aead *aead;
struct crypto_authenc_key_param *param;
struct rtattr *rta;
char *key;
char *p;
char authenc_name[CRYPTO_MAX_ALG_NAME];
unsigned int keylen;
int err;
err = -EINVAL;
if (x->ealg == NULL)
goto error;
err = -ENAMETOOLONG;
if ((x->props.flags & XFRM_STATE_ESN)) {
if (snprintf(authenc_name, CRYPTO_MAX_ALG_NAME,
"authencesn(%s,%s)",
x->aalg ? x->aalg->alg_name : "digest_null",
x->ealg->alg_name) >= CRYPTO_MAX_ALG_NAME)
goto error;
} else {
if (snprintf(authenc_name, CRYPTO_MAX_ALG_NAME,
"authenc(%s,%s)",
x->aalg ? x->aalg->alg_name : "digest_null",
x->ealg->alg_name) >= CRYPTO_MAX_ALG_NAME)
goto error;
}
aead = crypto_alloc_aead(authenc_name, 0, 0);
err = PTR_ERR(aead);
if (IS_ERR(aead))
goto error;
esp->aead = aead;
keylen = (x->aalg ? (x->aalg->alg_key_len + 7) / 8 : 0) +
(x->ealg->alg_key_len + 7) / 8 + RTA_SPACE(sizeof(*param));
err = -ENOMEM;
key = kmalloc(keylen, GFP_KERNEL);
if (!key)
goto error;
p = key;
rta = (void *)p;
rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
rta->rta_len = RTA_LENGTH(sizeof(*param));
param = RTA_DATA(rta);
p += RTA_SPACE(sizeof(*param));
if (x->aalg) {
struct xfrm_algo_desc *aalg_desc;
memcpy(p, x->aalg->alg_key, (x->aalg->alg_key_len + 7) / 8);
p += (x->aalg->alg_key_len + 7) / 8;
aalg_desc = xfrm_aalg_get_byname(x->aalg->alg_name, 0);
BUG_ON(!aalg_desc);
err = -EINVAL;
if (aalg_desc->uinfo.auth.icv_fullbits/8 !=
crypto_aead_authsize(aead)) {
NETDEBUG(KERN_INFO "ESP: %s digestsize %u != %hu\n",
x->aalg->alg_name,
crypto_aead_authsize(aead),
aalg_desc->uinfo.auth.icv_fullbits/8);
goto free_key;
}
err = crypto_aead_setauthsize(
aead, x->aalg->alg_trunc_len / 8);
if (err)
goto free_key;
}
param->enckeylen = cpu_to_be32((x->ealg->alg_key_len + 7) / 8);
memcpy(p, x->ealg->alg_key, (x->ealg->alg_key_len + 7) / 8);
err = crypto_aead_setkey(aead, key, keylen);
free_key:
kfree(key);
error:
return err;
}
static int esp6_init_state(struct xfrm_state *x)
{
struct esp_data *esp;
struct crypto_aead *aead;
u32 align;
int err;
if (x->encap)
return -EINVAL;
esp = kzalloc(sizeof(*esp), GFP_KERNEL);
if (esp == NULL)
return -ENOMEM;
x->data = esp;
if (x->aead)
err = esp_init_aead(x);
else
err = esp_init_authenc(x);
if (err)
goto error;
aead = esp->aead;
esp->padlen = 0;
x->props.header_len = sizeof(struct ip_esp_hdr) +
crypto_aead_ivsize(aead);
switch (x->props.mode) {
case XFRM_MODE_BEET:
if (x->sel.family != AF_INET6)
x->props.header_len += IPV4_BEET_PHMAXLEN +
(sizeof(struct ipv6hdr) - sizeof(struct iphdr));
break;
case XFRM_MODE_TRANSPORT:
break;
case XFRM_MODE_TUNNEL:
x->props.header_len += sizeof(struct ipv6hdr);
break;
default:
goto error;
}
align = ALIGN(crypto_aead_blocksize(aead), 4);
if (esp->padlen)
align = max_t(u32, align, esp->padlen);
x->props.trailer_len = align + 1 + crypto_aead_authsize(esp->aead);
error:
return err;
}
static const struct xfrm_type esp6_type =
{
.description = "ESP6",
.owner = THIS_MODULE,
.proto = IPPROTO_ESP,
.flags = XFRM_TYPE_REPLAY_PROT,
.init_state = esp6_init_state,
.destructor = esp6_destroy,
.get_mtu = esp6_get_mtu,
.input = esp6_input,
.output = esp6_output,
.hdr_offset = xfrm6_find_1stfragopt,
};
static const struct inet6_protocol esp6_protocol = {
.handler = xfrm6_rcv,
.err_handler = esp6_err,
.flags = INET6_PROTO_NOPOLICY,
};
static int __init esp6_init(void)
{
if (xfrm_register_type(&esp6_type, AF_INET6) < 0) {
printk(KERN_INFO "ipv6 esp init: can't add xfrm type\n");
return -EAGAIN;
}
if (inet6_add_protocol(&esp6_protocol, IPPROTO_ESP) < 0) {
printk(KERN_INFO "ipv6 esp init: can't add protocol\n");
xfrm_unregister_type(&esp6_type, AF_INET6);
return -EAGAIN;
}
return 0;
}
static void __exit esp6_fini(void)
{
if (inet6_del_protocol(&esp6_protocol, IPPROTO_ESP) < 0)
printk(KERN_INFO "ipv6 esp close: can't remove protocol\n");
if (xfrm_unregister_type(&esp6_type, AF_INET6) < 0)
printk(KERN_INFO "ipv6 esp close: can't remove xfrm type\n");
}
module_init(esp6_init);
module_exit(esp6_fini);
MODULE_LICENSE("GPL");
MODULE_ALIAS_XFRM_TYPE(AF_INET6, XFRM_PROTO_ESP);
| gpl-2.0 |
brymaster5000/m7-501 | drivers/leds/leds-qci-backlight.c | 4714 | 1940 | /* Quanta I2C Backlight Driver
*
* Copyright (C) 2009 Quanta Computer Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
/*
*
* The Driver with I/O communications via the I2C Interface for ST15 platform.
* And it is only working on the nuvoTon WPCE775x Embedded Controller.
*
*/
#include <linux/module.h>
#include <linux/leds.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/wpce775x.h>
#define EC_CMD_SET_BACKLIGHT 0xB1
static void qci_backlight_store(struct led_classdev *led_cdev,
enum led_brightness val);
static struct platform_device *bl_pdev;
static struct led_classdev lcd_backlight = {
.name = "lcd-backlight",
.brightness = 147,
.brightness_set = qci_backlight_store,
};
static void qci_backlight_store(struct led_classdev *led_cdev,
enum led_brightness val)
{
u16 value = val;
wpce_smbus_write_word_data(EC_CMD_SET_BACKLIGHT, value);
msleep(10);
dev_dbg(&bl_pdev->dev, "[backlight_store] : value = %d\n", value);
}
static int __init qci_backlight_init(void)
{
int err = 0;
bl_pdev = platform_device_register_simple("backlight", 0, NULL, 0);
err = led_classdev_register(&bl_pdev->dev, &lcd_backlight);
return err;
}
static void __exit qci_backlight_exit(void)
{
led_classdev_unregister(&lcd_backlight);
platform_device_unregister(bl_pdev);
}
module_init(qci_backlight_init);
module_exit(qci_backlight_exit);
MODULE_AUTHOR("Quanta Computer Inc.");
MODULE_DESCRIPTION("Quanta Embedded Controller I2C Backlight Driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
qianxiaoxi/android_kernel_nubia_nx507j | arch/um/os-Linux/process.c | 4970 | 5333 | /*
* Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <asm/unistd.h>
#include "init.h"
#include "longjmp.h"
#include "os.h"
#include "skas_ptrace.h"
#define ARBITRARY_ADDR -1
#define FAILURE_PID -1
#define STAT_PATH_LEN sizeof("/proc/#######/stat\0")
#define COMM_SCANF "%*[^)])"
unsigned long os_process_pc(int pid)
{
char proc_stat[STAT_PATH_LEN], buf[256];
unsigned long pc = ARBITRARY_ADDR;
int fd, err;
sprintf(proc_stat, "/proc/%d/stat", pid);
fd = open(proc_stat, O_RDONLY, 0);
if (fd < 0) {
printk(UM_KERN_ERR "os_process_pc - couldn't open '%s', "
"errno = %d\n", proc_stat, errno);
goto out;
}
CATCH_EINTR(err = read(fd, buf, sizeof(buf)));
if (err < 0) {
printk(UM_KERN_ERR "os_process_pc - couldn't read '%s', "
"err = %d\n", proc_stat, errno);
goto out_close;
}
os_close_file(fd);
pc = ARBITRARY_ADDR;
if (sscanf(buf, "%*d " COMM_SCANF " %*c %*d %*d %*d %*d %*d %*d %*d "
"%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
"%*d %*d %*d %*d %*d %lu", &pc) != 1)
printk(UM_KERN_ERR "os_process_pc - couldn't find pc in '%s'\n",
buf);
out_close:
close(fd);
out:
return pc;
}
int os_process_parent(int pid)
{
char stat[STAT_PATH_LEN];
char data[256];
int parent = FAILURE_PID, n, fd;
if (pid == -1)
return parent;
snprintf(stat, sizeof(stat), "/proc/%d/stat", pid);
fd = open(stat, O_RDONLY, 0);
if (fd < 0) {
printk(UM_KERN_ERR "Couldn't open '%s', errno = %d\n", stat,
errno);
return parent;
}
CATCH_EINTR(n = read(fd, data, sizeof(data)));
close(fd);
if (n < 0) {
printk(UM_KERN_ERR "Couldn't read '%s', errno = %d\n", stat,
errno);
return parent;
}
parent = FAILURE_PID;
n = sscanf(data, "%*d " COMM_SCANF " %*c %d", &parent);
if (n != 1)
printk(UM_KERN_ERR "Failed to scan '%s'\n", data);
return parent;
}
void os_stop_process(int pid)
{
kill(pid, SIGSTOP);
}
void os_kill_process(int pid, int reap_child)
{
kill(pid, SIGKILL);
if (reap_child)
CATCH_EINTR(waitpid(pid, NULL, __WALL));
}
/* This is here uniquely to have access to the userspace errno, i.e. the one
* used by ptrace in case of error.
*/
long os_ptrace_ldt(long pid, long addr, long data)
{
int ret;
ret = ptrace(PTRACE_LDT, pid, addr, data);
if (ret < 0)
return -errno;
return ret;
}
/* Kill off a ptraced child by all means available. kill it normally first,
* then PTRACE_KILL it, then PTRACE_CONT it in case it's in a run state from
* which it can't exit directly.
*/
void os_kill_ptraced_process(int pid, int reap_child)
{
kill(pid, SIGKILL);
ptrace(PTRACE_KILL, pid);
ptrace(PTRACE_CONT, pid);
if (reap_child)
CATCH_EINTR(waitpid(pid, NULL, __WALL));
}
/* Don't use the glibc version, which caches the result in TLS. It misses some
* syscalls, and also breaks with clone(), which does not unshare the TLS.
*/
int os_getpid(void)
{
return syscall(__NR_getpid);
}
int os_getpgrp(void)
{
return getpgrp();
}
int os_map_memory(void *virt, int fd, unsigned long long off, unsigned long len,
int r, int w, int x)
{
void *loc;
int prot;
prot = (r ? PROT_READ : 0) | (w ? PROT_WRITE : 0) |
(x ? PROT_EXEC : 0);
loc = mmap64((void *) virt, len, prot, MAP_SHARED | MAP_FIXED,
fd, off);
if (loc == MAP_FAILED)
return -errno;
return 0;
}
int os_protect_memory(void *addr, unsigned long len, int r, int w, int x)
{
int prot = ((r ? PROT_READ : 0) | (w ? PROT_WRITE : 0) |
(x ? PROT_EXEC : 0));
if (mprotect(addr, len, prot) < 0)
return -errno;
return 0;
}
int os_unmap_memory(void *addr, int len)
{
int err;
err = munmap(addr, len);
if (err < 0)
return -errno;
return 0;
}
#ifndef MADV_REMOVE
#define MADV_REMOVE KERNEL_MADV_REMOVE
#endif
int os_drop_memory(void *addr, int length)
{
int err;
err = madvise(addr, length, MADV_REMOVE);
if (err < 0)
err = -errno;
return err;
}
int __init can_drop_memory(void)
{
void *addr;
int fd, ok = 0;
printk(UM_KERN_INFO "Checking host MADV_REMOVE support...");
fd = create_mem_file(UM_KERN_PAGE_SIZE);
if (fd < 0) {
printk(UM_KERN_ERR "Creating test memory file failed, "
"err = %d\n", -fd);
goto out;
}
addr = mmap64(NULL, UM_KERN_PAGE_SIZE, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
printk(UM_KERN_ERR "Mapping test memory file failed, "
"err = %d\n", -errno);
goto out_close;
}
if (madvise(addr, UM_KERN_PAGE_SIZE, MADV_REMOVE) != 0) {
printk(UM_KERN_ERR "MADV_REMOVE failed, err = %d\n", -errno);
goto out_unmap;
}
printk(UM_KERN_CONT "OK\n");
ok = 1;
out_unmap:
munmap(addr, UM_KERN_PAGE_SIZE);
out_close:
close(fd);
out:
return ok;
}
void init_new_thread_signals(void)
{
set_handler(SIGSEGV);
set_handler(SIGTRAP);
set_handler(SIGFPE);
set_handler(SIGILL);
set_handler(SIGBUS);
signal(SIGHUP, SIG_IGN);
set_handler(SIGIO);
signal(SIGWINCH, SIG_IGN);
signal(SIGTERM, SIG_DFL);
}
int run_kernel_thread(int (*fn)(void *), void *arg, jmp_buf **jmp_ptr)
{
jmp_buf buf;
int n;
*jmp_ptr = &buf;
n = UML_SETJMP(&buf);
if (n != 0)
return n;
(*fn)(arg);
return 0;
}
| gpl-2.0 |
aosp-samsung-msm7x30/android_kernel_samsung_msm7x30-common | arch/um/os-Linux/util.c | 4970 | 3308 | /*
* Copyright (C) 2000 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <termios.h>
#include <wait.h>
#include <sys/mman.h>
#include <sys/utsname.h>
#include "os.h"
void stack_protections(unsigned long address)
{
if (mprotect((void *) address, UM_THREAD_SIZE,
PROT_READ | PROT_WRITE | PROT_EXEC) < 0)
panic("protecting stack failed, errno = %d", errno);
}
int raw(int fd)
{
struct termios tt;
int err;
CATCH_EINTR(err = tcgetattr(fd, &tt));
if (err < 0)
return -errno;
cfmakeraw(&tt);
CATCH_EINTR(err = tcsetattr(fd, TCSADRAIN, &tt));
if (err < 0)
return -errno;
/*
* XXX tcsetattr could have applied only some changes
* (and cfmakeraw() is a set of changes)
*/
return 0;
}
void setup_machinename(char *machine_out)
{
struct utsname host;
uname(&host);
#ifdef UML_CONFIG_UML_X86
# ifndef UML_CONFIG_64BIT
if (!strcmp(host.machine, "x86_64")) {
strcpy(machine_out, "i686");
return;
}
# else
if (!strcmp(host.machine, "i686")) {
strcpy(machine_out, "x86_64");
return;
}
# endif
#endif
strcpy(machine_out, host.machine);
}
void setup_hostinfo(char *buf, int len)
{
struct utsname host;
uname(&host);
snprintf(buf, len, "%s %s %s %s %s", host.sysname, host.nodename,
host.release, host.version, host.machine);
}
/*
* We cannot use glibc's abort(). It makes use of tgkill() which
* has no effect within UML's kernel threads.
* After that glibc would execute an invalid instruction to kill
* the calling process and UML crashes with SIGSEGV.
*/
static inline void __attribute__ ((noreturn)) uml_abort(void)
{
sigset_t sig;
fflush(NULL);
if (!sigemptyset(&sig) && !sigaddset(&sig, SIGABRT))
sigprocmask(SIG_UNBLOCK, &sig, 0);
for (;;)
if (kill(getpid(), SIGABRT) < 0)
exit(127);
}
void os_dump_core(void)
{
int pid;
signal(SIGSEGV, SIG_DFL);
/*
* We are about to SIGTERM this entire process group to ensure that
* nothing is around to run after the kernel exits. The
* kernel wants to abort, not die through SIGTERM, so we
* ignore it here.
*/
signal(SIGTERM, SIG_IGN);
kill(0, SIGTERM);
/*
* Most of the other processes associated with this UML are
* likely sTopped, so give them a SIGCONT so they see the
* SIGTERM.
*/
kill(0, SIGCONT);
/*
* Now, having sent signals to everyone but us, make sure they
* die by ptrace. Processes can survive what's been done to
* them so far - the mechanism I understand is receiving a
* SIGSEGV and segfaulting immediately upon return. There is
* always a SIGSEGV pending, and (I'm guessing) signals are
* processed in numeric order so the SIGTERM (signal 15 vs
* SIGSEGV being signal 11) is never handled.
*
* Run a waitpid loop until we get some kind of error.
* Hopefully, it's ECHILD, but there's not a lot we can do if
* it's something else. Tell os_kill_ptraced_process not to
* wait for the child to report its death because there's
* nothing reasonable to do if that fails.
*/
while ((pid = waitpid(-1, NULL, WNOHANG | __WALL)) > 0)
os_kill_ptraced_process(pid, 0);
uml_abort();
}
void um_early_printk(const char *s, unsigned int n)
{
printf("%.*s", n, s);
}
| gpl-2.0 |
gearslam/JB_LS970ZVC | arch/um/os-Linux/process.c | 4970 | 5333 | /*
* Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <asm/unistd.h>
#include "init.h"
#include "longjmp.h"
#include "os.h"
#include "skas_ptrace.h"
#define ARBITRARY_ADDR -1
#define FAILURE_PID -1
#define STAT_PATH_LEN sizeof("/proc/#######/stat\0")
#define COMM_SCANF "%*[^)])"
unsigned long os_process_pc(int pid)
{
char proc_stat[STAT_PATH_LEN], buf[256];
unsigned long pc = ARBITRARY_ADDR;
int fd, err;
sprintf(proc_stat, "/proc/%d/stat", pid);
fd = open(proc_stat, O_RDONLY, 0);
if (fd < 0) {
printk(UM_KERN_ERR "os_process_pc - couldn't open '%s', "
"errno = %d\n", proc_stat, errno);
goto out;
}
CATCH_EINTR(err = read(fd, buf, sizeof(buf)));
if (err < 0) {
printk(UM_KERN_ERR "os_process_pc - couldn't read '%s', "
"err = %d\n", proc_stat, errno);
goto out_close;
}
os_close_file(fd);
pc = ARBITRARY_ADDR;
if (sscanf(buf, "%*d " COMM_SCANF " %*c %*d %*d %*d %*d %*d %*d %*d "
"%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
"%*d %*d %*d %*d %*d %lu", &pc) != 1)
printk(UM_KERN_ERR "os_process_pc - couldn't find pc in '%s'\n",
buf);
out_close:
close(fd);
out:
return pc;
}
int os_process_parent(int pid)
{
char stat[STAT_PATH_LEN];
char data[256];
int parent = FAILURE_PID, n, fd;
if (pid == -1)
return parent;
snprintf(stat, sizeof(stat), "/proc/%d/stat", pid);
fd = open(stat, O_RDONLY, 0);
if (fd < 0) {
printk(UM_KERN_ERR "Couldn't open '%s', errno = %d\n", stat,
errno);
return parent;
}
CATCH_EINTR(n = read(fd, data, sizeof(data)));
close(fd);
if (n < 0) {
printk(UM_KERN_ERR "Couldn't read '%s', errno = %d\n", stat,
errno);
return parent;
}
parent = FAILURE_PID;
n = sscanf(data, "%*d " COMM_SCANF " %*c %d", &parent);
if (n != 1)
printk(UM_KERN_ERR "Failed to scan '%s'\n", data);
return parent;
}
void os_stop_process(int pid)
{
kill(pid, SIGSTOP);
}
void os_kill_process(int pid, int reap_child)
{
kill(pid, SIGKILL);
if (reap_child)
CATCH_EINTR(waitpid(pid, NULL, __WALL));
}
/* This is here uniquely to have access to the userspace errno, i.e. the one
* used by ptrace in case of error.
*/
long os_ptrace_ldt(long pid, long addr, long data)
{
int ret;
ret = ptrace(PTRACE_LDT, pid, addr, data);
if (ret < 0)
return -errno;
return ret;
}
/* Kill off a ptraced child by all means available. kill it normally first,
* then PTRACE_KILL it, then PTRACE_CONT it in case it's in a run state from
* which it can't exit directly.
*/
void os_kill_ptraced_process(int pid, int reap_child)
{
kill(pid, SIGKILL);
ptrace(PTRACE_KILL, pid);
ptrace(PTRACE_CONT, pid);
if (reap_child)
CATCH_EINTR(waitpid(pid, NULL, __WALL));
}
/* Don't use the glibc version, which caches the result in TLS. It misses some
* syscalls, and also breaks with clone(), which does not unshare the TLS.
*/
int os_getpid(void)
{
return syscall(__NR_getpid);
}
int os_getpgrp(void)
{
return getpgrp();
}
int os_map_memory(void *virt, int fd, unsigned long long off, unsigned long len,
int r, int w, int x)
{
void *loc;
int prot;
prot = (r ? PROT_READ : 0) | (w ? PROT_WRITE : 0) |
(x ? PROT_EXEC : 0);
loc = mmap64((void *) virt, len, prot, MAP_SHARED | MAP_FIXED,
fd, off);
if (loc == MAP_FAILED)
return -errno;
return 0;
}
int os_protect_memory(void *addr, unsigned long len, int r, int w, int x)
{
int prot = ((r ? PROT_READ : 0) | (w ? PROT_WRITE : 0) |
(x ? PROT_EXEC : 0));
if (mprotect(addr, len, prot) < 0)
return -errno;
return 0;
}
int os_unmap_memory(void *addr, int len)
{
int err;
err = munmap(addr, len);
if (err < 0)
return -errno;
return 0;
}
#ifndef MADV_REMOVE
#define MADV_REMOVE KERNEL_MADV_REMOVE
#endif
int os_drop_memory(void *addr, int length)
{
int err;
err = madvise(addr, length, MADV_REMOVE);
if (err < 0)
err = -errno;
return err;
}
int __init can_drop_memory(void)
{
void *addr;
int fd, ok = 0;
printk(UM_KERN_INFO "Checking host MADV_REMOVE support...");
fd = create_mem_file(UM_KERN_PAGE_SIZE);
if (fd < 0) {
printk(UM_KERN_ERR "Creating test memory file failed, "
"err = %d\n", -fd);
goto out;
}
addr = mmap64(NULL, UM_KERN_PAGE_SIZE, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
printk(UM_KERN_ERR "Mapping test memory file failed, "
"err = %d\n", -errno);
goto out_close;
}
if (madvise(addr, UM_KERN_PAGE_SIZE, MADV_REMOVE) != 0) {
printk(UM_KERN_ERR "MADV_REMOVE failed, err = %d\n", -errno);
goto out_unmap;
}
printk(UM_KERN_CONT "OK\n");
ok = 1;
out_unmap:
munmap(addr, UM_KERN_PAGE_SIZE);
out_close:
close(fd);
out:
return ok;
}
void init_new_thread_signals(void)
{
set_handler(SIGSEGV);
set_handler(SIGTRAP);
set_handler(SIGFPE);
set_handler(SIGILL);
set_handler(SIGBUS);
signal(SIGHUP, SIG_IGN);
set_handler(SIGIO);
signal(SIGWINCH, SIG_IGN);
signal(SIGTERM, SIG_DFL);
}
int run_kernel_thread(int (*fn)(void *), void *arg, jmp_buf **jmp_ptr)
{
jmp_buf buf;
int n;
*jmp_ptr = &buf;
n = UML_SETJMP(&buf);
if (n != 0)
return n;
(*fn)(arg);
return 0;
}
| gpl-2.0 |
bgn9000/ShunS4 | fs/nfsd/nfscache.c | 5738 | 7795 | /*
* Request reply cache. This is currently a global cache, but this may
* change in the future and be a per-client cache.
*
* This code is heavily inspired by the 44BSD implementation, although
* it does things a bit differently.
*
* Copyright (C) 1995, 1996 Olaf Kirch <okir@monad.swb.de>
*/
#include <linux/slab.h>
#include "nfsd.h"
#include "cache.h"
/* Size of reply cache. Common values are:
* 4.3BSD: 128
* 4.4BSD: 256
* Solaris2: 1024
* DEC Unix: 512-4096
*/
#define CACHESIZE 1024
#define HASHSIZE 64
static struct hlist_head * cache_hash;
static struct list_head lru_head;
static int cache_disabled = 1;
/*
* Calculate the hash index from an XID.
*/
static inline u32 request_hash(u32 xid)
{
u32 h = xid;
h ^= (xid >> 24);
return h & (HASHSIZE-1);
}
static int nfsd_cache_append(struct svc_rqst *rqstp, struct kvec *vec);
/*
* locking for the reply cache:
* A cache entry is "single use" if c_state == RC_INPROG
* Otherwise, it when accessing _prev or _next, the lock must be held.
*/
static DEFINE_SPINLOCK(cache_lock);
int nfsd_reply_cache_init(void)
{
struct svc_cacherep *rp;
int i;
INIT_LIST_HEAD(&lru_head);
i = CACHESIZE;
while (i) {
rp = kmalloc(sizeof(*rp), GFP_KERNEL);
if (!rp)
goto out_nomem;
list_add(&rp->c_lru, &lru_head);
rp->c_state = RC_UNUSED;
rp->c_type = RC_NOCACHE;
INIT_HLIST_NODE(&rp->c_hash);
i--;
}
cache_hash = kcalloc (HASHSIZE, sizeof(struct hlist_head), GFP_KERNEL);
if (!cache_hash)
goto out_nomem;
cache_disabled = 0;
return 0;
out_nomem:
printk(KERN_ERR "nfsd: failed to allocate reply cache\n");
nfsd_reply_cache_shutdown();
return -ENOMEM;
}
void nfsd_reply_cache_shutdown(void)
{
struct svc_cacherep *rp;
while (!list_empty(&lru_head)) {
rp = list_entry(lru_head.next, struct svc_cacherep, c_lru);
if (rp->c_state == RC_DONE && rp->c_type == RC_REPLBUFF)
kfree(rp->c_replvec.iov_base);
list_del(&rp->c_lru);
kfree(rp);
}
cache_disabled = 1;
kfree (cache_hash);
cache_hash = NULL;
}
/*
* Move cache entry to end of LRU list
*/
static void
lru_put_end(struct svc_cacherep *rp)
{
list_move_tail(&rp->c_lru, &lru_head);
}
/*
* Move a cache entry from one hash list to another
*/
static void
hash_refile(struct svc_cacherep *rp)
{
hlist_del_init(&rp->c_hash);
hlist_add_head(&rp->c_hash, cache_hash + request_hash(rp->c_xid));
}
/*
* Try to find an entry matching the current call in the cache. When none
* is found, we grab the oldest unlocked entry off the LRU list.
* Note that no operation within the loop may sleep.
*/
int
nfsd_cache_lookup(struct svc_rqst *rqstp)
{
struct hlist_node *hn;
struct hlist_head *rh;
struct svc_cacherep *rp;
__be32 xid = rqstp->rq_xid;
u32 proto = rqstp->rq_prot,
vers = rqstp->rq_vers,
proc = rqstp->rq_proc;
unsigned long age;
int type = rqstp->rq_cachetype;
int rtn;
rqstp->rq_cacherep = NULL;
if (cache_disabled || type == RC_NOCACHE) {
nfsdstats.rcnocache++;
return RC_DOIT;
}
spin_lock(&cache_lock);
rtn = RC_DOIT;
rh = &cache_hash[request_hash(xid)];
hlist_for_each_entry(rp, hn, rh, c_hash) {
if (rp->c_state != RC_UNUSED &&
xid == rp->c_xid && proc == rp->c_proc &&
proto == rp->c_prot && vers == rp->c_vers &&
time_before(jiffies, rp->c_timestamp + 120*HZ) &&
memcmp((char*)&rqstp->rq_addr, (char*)&rp->c_addr, sizeof(rp->c_addr))==0) {
nfsdstats.rchits++;
goto found_entry;
}
}
nfsdstats.rcmisses++;
/* This loop shouldn't take more than a few iterations normally */
{
int safe = 0;
list_for_each_entry(rp, &lru_head, c_lru) {
if (rp->c_state != RC_INPROG)
break;
if (safe++ > CACHESIZE) {
printk("nfsd: loop in repcache LRU list\n");
cache_disabled = 1;
goto out;
}
}
}
/* All entries on the LRU are in-progress. This should not happen */
if (&rp->c_lru == &lru_head) {
static int complaints;
printk(KERN_WARNING "nfsd: all repcache entries locked!\n");
if (++complaints > 5) {
printk(KERN_WARNING "nfsd: disabling repcache.\n");
cache_disabled = 1;
}
goto out;
}
rqstp->rq_cacherep = rp;
rp->c_state = RC_INPROG;
rp->c_xid = xid;
rp->c_proc = proc;
memcpy(&rp->c_addr, svc_addr_in(rqstp), sizeof(rp->c_addr));
rp->c_prot = proto;
rp->c_vers = vers;
rp->c_timestamp = jiffies;
hash_refile(rp);
/* release any buffer */
if (rp->c_type == RC_REPLBUFF) {
kfree(rp->c_replvec.iov_base);
rp->c_replvec.iov_base = NULL;
}
rp->c_type = RC_NOCACHE;
out:
spin_unlock(&cache_lock);
return rtn;
found_entry:
/* We found a matching entry which is either in progress or done. */
age = jiffies - rp->c_timestamp;
rp->c_timestamp = jiffies;
lru_put_end(rp);
rtn = RC_DROPIT;
/* Request being processed or excessive rexmits */
if (rp->c_state == RC_INPROG || age < RC_DELAY)
goto out;
/* From the hall of fame of impractical attacks:
* Is this a user who tries to snoop on the cache? */
rtn = RC_DOIT;
if (!rqstp->rq_secure && rp->c_secure)
goto out;
/* Compose RPC reply header */
switch (rp->c_type) {
case RC_NOCACHE:
break;
case RC_REPLSTAT:
svc_putu32(&rqstp->rq_res.head[0], rp->c_replstat);
rtn = RC_REPLY;
break;
case RC_REPLBUFF:
if (!nfsd_cache_append(rqstp, &rp->c_replvec))
goto out; /* should not happen */
rtn = RC_REPLY;
break;
default:
printk(KERN_WARNING "nfsd: bad repcache type %d\n", rp->c_type);
rp->c_state = RC_UNUSED;
}
goto out;
}
/*
* Update a cache entry. This is called from nfsd_dispatch when
* the procedure has been executed and the complete reply is in
* rqstp->rq_res.
*
* We're copying around data here rather than swapping buffers because
* the toplevel loop requires max-sized buffers, which would be a waste
* of memory for a cache with a max reply size of 100 bytes (diropokres).
*
* If we should start to use different types of cache entries tailored
* specifically for attrstat and fh's, we may save even more space.
*
* Also note that a cachetype of RC_NOCACHE can legally be passed when
* nfsd failed to encode a reply that otherwise would have been cached.
* In this case, nfsd_cache_update is called with statp == NULL.
*/
void
nfsd_cache_update(struct svc_rqst *rqstp, int cachetype, __be32 *statp)
{
struct svc_cacherep *rp;
struct kvec *resv = &rqstp->rq_res.head[0], *cachv;
int len;
if (!(rp = rqstp->rq_cacherep) || cache_disabled)
return;
len = resv->iov_len - ((char*)statp - (char*)resv->iov_base);
len >>= 2;
/* Don't cache excessive amounts of data and XDR failures */
if (!statp || len > (256 >> 2)) {
rp->c_state = RC_UNUSED;
return;
}
switch (cachetype) {
case RC_REPLSTAT:
if (len != 1)
printk("nfsd: RC_REPLSTAT/reply len %d!\n",len);
rp->c_replstat = *statp;
break;
case RC_REPLBUFF:
cachv = &rp->c_replvec;
cachv->iov_base = kmalloc(len << 2, GFP_KERNEL);
if (!cachv->iov_base) {
spin_lock(&cache_lock);
rp->c_state = RC_UNUSED;
spin_unlock(&cache_lock);
return;
}
cachv->iov_len = len << 2;
memcpy(cachv->iov_base, statp, len << 2);
break;
}
spin_lock(&cache_lock);
lru_put_end(rp);
rp->c_secure = rqstp->rq_secure;
rp->c_type = cachetype;
rp->c_state = RC_DONE;
rp->c_timestamp = jiffies;
spin_unlock(&cache_lock);
return;
}
/*
* Copy cached reply to current reply buffer. Should always fit.
* FIXME as reply is in a page, we should just attach the page, and
* keep a refcount....
*/
static int
nfsd_cache_append(struct svc_rqst *rqstp, struct kvec *data)
{
struct kvec *vec = &rqstp->rq_res.head[0];
if (vec->iov_len + data->iov_len > PAGE_SIZE) {
printk(KERN_WARNING "nfsd: cached reply too large (%Zd).\n",
data->iov_len);
return 0;
}
memcpy((char*)vec->iov_base + vec->iov_len, data->iov_base, data->iov_len);
vec->iov_len += data->iov_len;
return 1;
}
| gpl-2.0 |
aopp/android_kernel_google_msm | fs/sysfs/symlink.c | 8810 | 7285 | /*
* fs/sysfs/symlink.c - sysfs symlink implementation
*
* Copyright (c) 2001-3 Patrick Mochel
* Copyright (c) 2007 SUSE Linux Products GmbH
* Copyright (c) 2007 Tejun Heo <teheo@suse.de>
*
* This file is released under the GPLv2.
*
* Please see Documentation/filesystems/sysfs.txt for more information.
*/
#include <linux/fs.h>
#include <linux/gfp.h>
#include <linux/mount.h>
#include <linux/module.h>
#include <linux/kobject.h>
#include <linux/namei.h>
#include <linux/mutex.h>
#include <linux/security.h>
#include "sysfs.h"
static int sysfs_do_create_link(struct kobject *kobj, struct kobject *target,
const char *name, int warn)
{
struct sysfs_dirent *parent_sd = NULL;
struct sysfs_dirent *target_sd = NULL;
struct sysfs_dirent *sd = NULL;
struct sysfs_addrm_cxt acxt;
enum kobj_ns_type ns_type;
int error;
BUG_ON(!name);
if (!kobj)
parent_sd = &sysfs_root;
else
parent_sd = kobj->sd;
error = -EFAULT;
if (!parent_sd)
goto out_put;
/* target->sd can go away beneath us but is protected with
* sysfs_assoc_lock. Fetch target_sd from it.
*/
spin_lock(&sysfs_assoc_lock);
if (target->sd)
target_sd = sysfs_get(target->sd);
spin_unlock(&sysfs_assoc_lock);
error = -ENOENT;
if (!target_sd)
goto out_put;
error = -ENOMEM;
sd = sysfs_new_dirent(name, S_IFLNK|S_IRWXUGO, SYSFS_KOBJ_LINK);
if (!sd)
goto out_put;
ns_type = sysfs_ns_type(parent_sd);
if (ns_type)
sd->s_ns = target->ktype->namespace(target);
sd->s_symlink.target_sd = target_sd;
target_sd = NULL; /* reference is now owned by the symlink */
sysfs_addrm_start(&acxt, parent_sd);
/* Symlinks must be between directories with the same ns_type */
if (!ns_type ||
(ns_type == sysfs_ns_type(sd->s_symlink.target_sd->s_parent))) {
if (warn)
error = sysfs_add_one(&acxt, sd);
else
error = __sysfs_add_one(&acxt, sd);
} else {
error = -EINVAL;
WARN(1, KERN_WARNING
"sysfs: symlink across ns_types %s/%s -> %s/%s\n",
parent_sd->s_name,
sd->s_name,
sd->s_symlink.target_sd->s_parent->s_name,
sd->s_symlink.target_sd->s_name);
}
sysfs_addrm_finish(&acxt);
if (error)
goto out_put;
return 0;
out_put:
sysfs_put(target_sd);
sysfs_put(sd);
return error;
}
/**
* sysfs_create_link - create symlink between two objects.
* @kobj: object whose directory we're creating the link in.
* @target: object we're pointing to.
* @name: name of the symlink.
*/
int sysfs_create_link(struct kobject *kobj, struct kobject *target,
const char *name)
{
return sysfs_do_create_link(kobj, target, name, 1);
}
/**
* sysfs_create_link_nowarn - create symlink between two objects.
* @kobj: object whose directory we're creating the link in.
* @target: object we're pointing to.
* @name: name of the symlink.
*
* This function does the same as sysf_create_link(), but it
* doesn't warn if the link already exists.
*/
int sysfs_create_link_nowarn(struct kobject *kobj, struct kobject *target,
const char *name)
{
return sysfs_do_create_link(kobj, target, name, 0);
}
/**
* sysfs_delete_link - remove symlink in object's directory.
* @kobj: object we're acting for.
* @targ: object we're pointing to.
* @name: name of the symlink to remove.
*
* Unlike sysfs_remove_link sysfs_delete_link has enough information
* to successfully delete symlinks in tagged directories.
*/
void sysfs_delete_link(struct kobject *kobj, struct kobject *targ,
const char *name)
{
const void *ns = NULL;
spin_lock(&sysfs_assoc_lock);
if (targ->sd && sysfs_ns_type(kobj->sd))
ns = targ->sd->s_ns;
spin_unlock(&sysfs_assoc_lock);
sysfs_hash_and_remove(kobj->sd, ns, name);
}
/**
* sysfs_remove_link - remove symlink in object's directory.
* @kobj: object we're acting for.
* @name: name of the symlink to remove.
*/
void sysfs_remove_link(struct kobject * kobj, const char * name)
{
struct sysfs_dirent *parent_sd = NULL;
if (!kobj)
parent_sd = &sysfs_root;
else
parent_sd = kobj->sd;
sysfs_hash_and_remove(parent_sd, NULL, name);
}
/**
* sysfs_rename_link - rename symlink in object's directory.
* @kobj: object we're acting for.
* @targ: object we're pointing to.
* @old: previous name of the symlink.
* @new: new name of the symlink.
*
* A helper function for the common rename symlink idiom.
*/
int sysfs_rename_link(struct kobject *kobj, struct kobject *targ,
const char *old, const char *new)
{
struct sysfs_dirent *parent_sd, *sd = NULL;
const void *old_ns = NULL, *new_ns = NULL;
int result;
if (!kobj)
parent_sd = &sysfs_root;
else
parent_sd = kobj->sd;
if (targ->sd)
old_ns = targ->sd->s_ns;
result = -ENOENT;
sd = sysfs_get_dirent(parent_sd, old_ns, old);
if (!sd)
goto out;
result = -EINVAL;
if (sysfs_type(sd) != SYSFS_KOBJ_LINK)
goto out;
if (sd->s_symlink.target_sd->s_dir.kobj != targ)
goto out;
if (sysfs_ns_type(parent_sd))
new_ns = targ->ktype->namespace(targ);
result = sysfs_rename(sd, parent_sd, new_ns, new);
out:
sysfs_put(sd);
return result;
}
static int sysfs_get_target_path(struct sysfs_dirent *parent_sd,
struct sysfs_dirent *target_sd, char *path)
{
struct sysfs_dirent *base, *sd;
char *s = path;
int len = 0;
/* go up to the root, stop at the base */
base = parent_sd;
while (base->s_parent) {
sd = target_sd->s_parent;
while (sd->s_parent && base != sd)
sd = sd->s_parent;
if (base == sd)
break;
strcpy(s, "../");
s += 3;
base = base->s_parent;
}
/* determine end of target string for reverse fillup */
sd = target_sd;
while (sd->s_parent && sd != base) {
len += strlen(sd->s_name) + 1;
sd = sd->s_parent;
}
/* check limits */
if (len < 2)
return -EINVAL;
len--;
if ((s - path) + len > PATH_MAX)
return -ENAMETOOLONG;
/* reverse fillup of target string from target to base */
sd = target_sd;
while (sd->s_parent && sd != base) {
int slen = strlen(sd->s_name);
len -= slen;
strncpy(s + len, sd->s_name, slen);
if (len)
s[--len] = '/';
sd = sd->s_parent;
}
return 0;
}
static int sysfs_getlink(struct dentry *dentry, char * path)
{
struct sysfs_dirent *sd = dentry->d_fsdata;
struct sysfs_dirent *parent_sd = sd->s_parent;
struct sysfs_dirent *target_sd = sd->s_symlink.target_sd;
int error;
mutex_lock(&sysfs_mutex);
error = sysfs_get_target_path(parent_sd, target_sd, path);
mutex_unlock(&sysfs_mutex);
return error;
}
static void *sysfs_follow_link(struct dentry *dentry, struct nameidata *nd)
{
int error = -ENOMEM;
unsigned long page = get_zeroed_page(GFP_KERNEL);
if (page) {
error = sysfs_getlink(dentry, (char *) page);
if (error < 0)
free_page((unsigned long)page);
}
nd_set_link(nd, error ? ERR_PTR(error) : (char *)page);
return NULL;
}
static void sysfs_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
{
char *page = nd_get_link(nd);
if (!IS_ERR(page))
free_page((unsigned long)page);
}
const struct inode_operations sysfs_symlink_inode_operations = {
.setxattr = sysfs_setxattr,
.readlink = generic_readlink,
.follow_link = sysfs_follow_link,
.put_link = sysfs_put_link,
.setattr = sysfs_setattr,
.getattr = sysfs_getattr,
.permission = sysfs_permission,
};
EXPORT_SYMBOL_GPL(sysfs_create_link);
EXPORT_SYMBOL_GPL(sysfs_remove_link);
EXPORT_SYMBOL_GPL(sysfs_rename_link);
| gpl-2.0 |
dan-sw/linux-v2.6.38.8-dan3400 | net/decnet/dn_route.c | 107 | 45700 | /*
* 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 Routing Functions (Endnode and Router)
*
* Authors: Steve Whitehouse <SteveW@ACM.org>
* Eduardo Marcelo Serrat <emserrat@geocities.com>
*
* Changes:
* Steve Whitehouse : Fixes to allow "intra-ethernet" and
* "return-to-sender" bits on outgoing
* packets.
* Steve Whitehouse : Timeouts for cached routes.
* Steve Whitehouse : Use dst cache for input routes too.
* Steve Whitehouse : Fixed error values in dn_send_skb.
* Steve Whitehouse : Rework routing functions to better fit
* DECnet routing design
* Alexey Kuznetsov : New SMP locking
* Steve Whitehouse : More SMP locking changes & dn_cache_dump()
* Steve Whitehouse : Prerouting NF hook, now really is prerouting.
* Fixed possible skb leak in rtnetlink funcs.
* Steve Whitehouse : Dave Miller's dynamic hash table sizing and
* Alexey Kuznetsov's finer grained locking
* from ipv4/route.c.
* Steve Whitehouse : Routing is now starting to look like a
* sensible set of code now, mainly due to
* my copying the IPv4 routing code. The
* hooks here are modified and will continue
* to evolve for a while.
* Steve Whitehouse : Real SMP at last :-) Also new netfilter
* stuff. Look out raw sockets your days
* are numbered!
* Steve Whitehouse : Added return-to-sender functions. Added
* backlog congestion level return codes.
* Steve Whitehouse : Fixed bug where routes were set up with
* no ref count on net devices.
* Steve Whitehouse : RCU for the route cache
* Steve Whitehouse : Preparations for the flow cache
* Steve Whitehouse : Prepare for nonlinear skbs
*/
/******************************************************************************
(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/sockios.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/inet.h>
#include <linux/route.h>
#include <linux/in_route.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <linux/mm.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/rtnetlink.h>
#include <linux/string.h>
#include <linux/netfilter_decnet.h>
#include <linux/rcupdate.h>
#include <linux/times.h>
#include <asm/errno.h>
#include <net/net_namespace.h>
#include <net/netlink.h>
#include <net/neighbour.h>
#include <net/dst.h>
#include <net/flow.h>
#include <net/fib_rules.h>
#include <net/dn.h>
#include <net/dn_dev.h>
#include <net/dn_nsp.h>
#include <net/dn_route.h>
#include <net/dn_neigh.h>
#include <net/dn_fib.h>
struct dn_rt_hash_bucket
{
struct dn_route __rcu *chain;
spinlock_t lock;
};
extern struct neigh_table dn_neigh_table;
static unsigned char dn_hiord_addr[6] = {0xAA,0x00,0x04,0x00,0x00,0x00};
static const int dn_rt_min_delay = 2 * HZ;
static const int dn_rt_max_delay = 10 * HZ;
static const int dn_rt_mtu_expires = 10 * 60 * HZ;
static unsigned long dn_rt_deadline;
static int dn_dst_gc(struct dst_ops *ops);
static struct dst_entry *dn_dst_check(struct dst_entry *, __u32);
static unsigned int dn_dst_default_advmss(const struct dst_entry *dst);
static unsigned int dn_dst_default_mtu(const struct dst_entry *dst);
static struct dst_entry *dn_dst_negative_advice(struct dst_entry *);
static void dn_dst_link_failure(struct sk_buff *);
static void dn_dst_update_pmtu(struct dst_entry *dst, u32 mtu);
static int dn_route_input(struct sk_buff *);
static void dn_run_flush(unsigned long dummy);
static struct dn_rt_hash_bucket *dn_rt_hash_table;
static unsigned dn_rt_hash_mask;
static struct timer_list dn_route_timer;
static DEFINE_TIMER(dn_rt_flush_timer, dn_run_flush, 0, 0);
int decnet_dst_gc_interval = 2;
static struct dst_ops dn_dst_ops = {
.family = PF_DECnet,
.protocol = cpu_to_be16(ETH_P_DNA_RT),
.gc_thresh = 128,
.gc = dn_dst_gc,
.check = dn_dst_check,
.default_advmss = dn_dst_default_advmss,
.default_mtu = dn_dst_default_mtu,
.negative_advice = dn_dst_negative_advice,
.link_failure = dn_dst_link_failure,
.update_pmtu = dn_dst_update_pmtu,
};
static __inline__ unsigned dn_hash(__le16 src, __le16 dst)
{
__u16 tmp = (__u16 __force)(src ^ dst);
tmp ^= (tmp >> 3);
tmp ^= (tmp >> 5);
tmp ^= (tmp >> 10);
return dn_rt_hash_mask & (unsigned)tmp;
}
static inline void dnrt_free(struct dn_route *rt)
{
call_rcu_bh(&rt->dst.rcu_head, dst_rcu_free);
}
static inline void dnrt_drop(struct dn_route *rt)
{
dst_release(&rt->dst);
call_rcu_bh(&rt->dst.rcu_head, dst_rcu_free);
}
static void dn_dst_check_expire(unsigned long dummy)
{
int i;
struct dn_route *rt;
struct dn_route __rcu **rtp;
unsigned long now = jiffies;
unsigned long expire = 120 * HZ;
for (i = 0; i <= dn_rt_hash_mask; i++) {
rtp = &dn_rt_hash_table[i].chain;
spin_lock(&dn_rt_hash_table[i].lock);
while ((rt = rcu_dereference_protected(*rtp,
lockdep_is_held(&dn_rt_hash_table[i].lock))) != NULL) {
if (atomic_read(&rt->dst.__refcnt) ||
(now - rt->dst.lastuse) < expire) {
rtp = &rt->dst.dn_next;
continue;
}
*rtp = rt->dst.dn_next;
rt->dst.dn_next = NULL;
dnrt_free(rt);
}
spin_unlock(&dn_rt_hash_table[i].lock);
if ((jiffies - now) > 0)
break;
}
mod_timer(&dn_route_timer, now + decnet_dst_gc_interval * HZ);
}
static int dn_dst_gc(struct dst_ops *ops)
{
struct dn_route *rt;
struct dn_route __rcu **rtp;
int i;
unsigned long now = jiffies;
unsigned long expire = 10 * HZ;
for (i = 0; i <= dn_rt_hash_mask; i++) {
spin_lock_bh(&dn_rt_hash_table[i].lock);
rtp = &dn_rt_hash_table[i].chain;
while ((rt = rcu_dereference_protected(*rtp,
lockdep_is_held(&dn_rt_hash_table[i].lock))) != NULL) {
if (atomic_read(&rt->dst.__refcnt) ||
(now - rt->dst.lastuse) < expire) {
rtp = &rt->dst.dn_next;
continue;
}
*rtp = rt->dst.dn_next;
rt->dst.dn_next = NULL;
dnrt_drop(rt);
break;
}
spin_unlock_bh(&dn_rt_hash_table[i].lock);
}
return 0;
}
/*
* The decnet standards don't impose a particular minimum mtu, what they
* do insist on is that the routing layer accepts a datagram of at least
* 230 bytes long. Here we have to subtract the routing header length from
* 230 to get the minimum acceptable mtu. If there is no neighbour, then we
* assume the worst and use a long header size.
*
* We update both the mtu and the advertised mss (i.e. the segment size we
* advertise to the other end).
*/
static void dn_dst_update_pmtu(struct dst_entry *dst, u32 mtu)
{
u32 min_mtu = 230;
struct dn_dev *dn = dst->neighbour ?
rcu_dereference_raw(dst->neighbour->dev->dn_ptr) : NULL;
if (dn && dn->use_long == 0)
min_mtu -= 6;
else
min_mtu -= 21;
if (dst_metric(dst, RTAX_MTU) > mtu && mtu >= min_mtu) {
if (!(dst_metric_locked(dst, RTAX_MTU))) {
dst_metric_set(dst, RTAX_MTU, mtu);
dst_set_expires(dst, dn_rt_mtu_expires);
}
if (!(dst_metric_locked(dst, RTAX_ADVMSS))) {
u32 mss = mtu - DN_MAX_NSP_DATA_HEADER;
u32 existing_mss = dst_metric_raw(dst, RTAX_ADVMSS);
if (!existing_mss || existing_mss > mss)
dst_metric_set(dst, RTAX_ADVMSS, mss);
}
}
}
/*
* When a route has been marked obsolete. (e.g. routing cache flush)
*/
static struct dst_entry *dn_dst_check(struct dst_entry *dst, __u32 cookie)
{
return NULL;
}
static struct dst_entry *dn_dst_negative_advice(struct dst_entry *dst)
{
dst_release(dst);
return NULL;
}
static void dn_dst_link_failure(struct sk_buff *skb)
{
}
static inline int compare_keys(struct flowi *fl1, struct flowi *fl2)
{
return ((fl1->fld_dst ^ fl2->fld_dst) |
(fl1->fld_src ^ fl2->fld_src) |
(fl1->mark ^ fl2->mark) |
(fl1->fld_scope ^ fl2->fld_scope) |
(fl1->oif ^ fl2->oif) |
(fl1->iif ^ fl2->iif)) == 0;
}
static int dn_insert_route(struct dn_route *rt, unsigned hash, struct dn_route **rp)
{
struct dn_route *rth;
struct dn_route __rcu **rthp;
unsigned long now = jiffies;
rthp = &dn_rt_hash_table[hash].chain;
spin_lock_bh(&dn_rt_hash_table[hash].lock);
while ((rth = rcu_dereference_protected(*rthp,
lockdep_is_held(&dn_rt_hash_table[hash].lock))) != NULL) {
if (compare_keys(&rth->fl, &rt->fl)) {
/* Put it first */
*rthp = rth->dst.dn_next;
rcu_assign_pointer(rth->dst.dn_next,
dn_rt_hash_table[hash].chain);
rcu_assign_pointer(dn_rt_hash_table[hash].chain, rth);
dst_use(&rth->dst, now);
spin_unlock_bh(&dn_rt_hash_table[hash].lock);
dnrt_drop(rt);
*rp = rth;
return 0;
}
rthp = &rth->dst.dn_next;
}
rcu_assign_pointer(rt->dst.dn_next, dn_rt_hash_table[hash].chain);
rcu_assign_pointer(dn_rt_hash_table[hash].chain, rt);
dst_use(&rt->dst, now);
spin_unlock_bh(&dn_rt_hash_table[hash].lock);
*rp = rt;
return 0;
}
static void dn_run_flush(unsigned long dummy)
{
int i;
struct dn_route *rt, *next;
for (i = 0; i < dn_rt_hash_mask; i++) {
spin_lock_bh(&dn_rt_hash_table[i].lock);
if ((rt = xchg((struct dn_route **)&dn_rt_hash_table[i].chain, NULL)) == NULL)
goto nothing_to_declare;
for(; rt; rt = next) {
next = rcu_dereference_raw(rt->dst.dn_next);
RCU_INIT_POINTER(rt->dst.dn_next, NULL);
dst_free((struct dst_entry *)rt);
}
nothing_to_declare:
spin_unlock_bh(&dn_rt_hash_table[i].lock);
}
}
static DEFINE_SPINLOCK(dn_rt_flush_lock);
void dn_rt_cache_flush(int delay)
{
unsigned long now = jiffies;
int user_mode = !in_interrupt();
if (delay < 0)
delay = dn_rt_min_delay;
spin_lock_bh(&dn_rt_flush_lock);
if (del_timer(&dn_rt_flush_timer) && delay > 0 && dn_rt_deadline) {
long tmo = (long)(dn_rt_deadline - now);
if (user_mode && tmo < dn_rt_max_delay - dn_rt_min_delay)
tmo = 0;
if (delay > tmo)
delay = tmo;
}
if (delay <= 0) {
spin_unlock_bh(&dn_rt_flush_lock);
dn_run_flush(0);
return;
}
if (dn_rt_deadline == 0)
dn_rt_deadline = now + dn_rt_max_delay;
dn_rt_flush_timer.expires = now + delay;
add_timer(&dn_rt_flush_timer);
spin_unlock_bh(&dn_rt_flush_lock);
}
/**
* dn_return_short - Return a short packet to its sender
* @skb: The packet to return
*
*/
static int dn_return_short(struct sk_buff *skb)
{
struct dn_skb_cb *cb;
unsigned char *ptr;
__le16 *src;
__le16 *dst;
/* Add back headers */
skb_push(skb, skb->data - skb_network_header(skb));
if ((skb = skb_unshare(skb, GFP_ATOMIC)) == NULL)
return NET_RX_DROP;
cb = DN_SKB_CB(skb);
/* Skip packet length and point to flags */
ptr = skb->data + 2;
*ptr++ = (cb->rt_flags & ~DN_RT_F_RQR) | DN_RT_F_RTS;
dst = (__le16 *)ptr;
ptr += 2;
src = (__le16 *)ptr;
ptr += 2;
*ptr = 0; /* Zero hop count */
swap(*src, *dst);
skb->pkt_type = PACKET_OUTGOING;
dn_rt_finish_output(skb, NULL, NULL);
return NET_RX_SUCCESS;
}
/**
* dn_return_long - Return a long packet to its sender
* @skb: The long format packet to return
*
*/
static int dn_return_long(struct sk_buff *skb)
{
struct dn_skb_cb *cb;
unsigned char *ptr;
unsigned char *src_addr, *dst_addr;
unsigned char tmp[ETH_ALEN];
/* Add back all headers */
skb_push(skb, skb->data - skb_network_header(skb));
if ((skb = skb_unshare(skb, GFP_ATOMIC)) == NULL)
return NET_RX_DROP;
cb = DN_SKB_CB(skb);
/* Ignore packet length and point to flags */
ptr = skb->data + 2;
/* Skip padding */
if (*ptr & DN_RT_F_PF) {
char padlen = (*ptr & ~DN_RT_F_PF);
ptr += padlen;
}
*ptr++ = (cb->rt_flags & ~DN_RT_F_RQR) | DN_RT_F_RTS;
ptr += 2;
dst_addr = ptr;
ptr += 8;
src_addr = ptr;
ptr += 6;
*ptr = 0; /* Zero hop count */
/* Swap source and destination */
memcpy(tmp, src_addr, ETH_ALEN);
memcpy(src_addr, dst_addr, ETH_ALEN);
memcpy(dst_addr, tmp, ETH_ALEN);
skb->pkt_type = PACKET_OUTGOING;
dn_rt_finish_output(skb, dst_addr, src_addr);
return NET_RX_SUCCESS;
}
/**
* dn_route_rx_packet - Try and find a route for an incoming packet
* @skb: The packet to find a route for
*
* Returns: result of input function if route is found, error code otherwise
*/
static int dn_route_rx_packet(struct sk_buff *skb)
{
struct dn_skb_cb *cb;
int err;
if ((err = dn_route_input(skb)) == 0)
return dst_input(skb);
cb = DN_SKB_CB(skb);
if (decnet_debug_level & 4) {
char *devname = skb->dev ? skb->dev->name : "???";
printk(KERN_DEBUG
"DECnet: dn_route_rx_packet: rt_flags=0x%02x dev=%s len=%d src=0x%04hx dst=0x%04hx err=%d type=%d\n",
(int)cb->rt_flags, devname, skb->len,
le16_to_cpu(cb->src), le16_to_cpu(cb->dst),
err, skb->pkt_type);
}
if ((skb->pkt_type == PACKET_HOST) && (cb->rt_flags & DN_RT_F_RQR)) {
switch(cb->rt_flags & DN_RT_PKT_MSK) {
case DN_RT_PKT_SHORT:
return dn_return_short(skb);
case DN_RT_PKT_LONG:
return dn_return_long(skb);
}
}
kfree_skb(skb);
return NET_RX_DROP;
}
static int dn_route_rx_long(struct sk_buff *skb)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
unsigned char *ptr = skb->data;
if (!pskb_may_pull(skb, 21)) /* 20 for long header, 1 for shortest nsp */
goto drop_it;
skb_pull(skb, 20);
skb_reset_transport_header(skb);
/* Destination info */
ptr += 2;
cb->dst = dn_eth2dn(ptr);
if (memcmp(ptr, dn_hiord_addr, 4) != 0)
goto drop_it;
ptr += 6;
/* Source info */
ptr += 2;
cb->src = dn_eth2dn(ptr);
if (memcmp(ptr, dn_hiord_addr, 4) != 0)
goto drop_it;
ptr += 6;
/* Other junk */
ptr++;
cb->hops = *ptr++; /* Visit Count */
return NF_HOOK(NFPROTO_DECNET, NF_DN_PRE_ROUTING, skb, skb->dev, NULL,
dn_route_rx_packet);
drop_it:
kfree_skb(skb);
return NET_RX_DROP;
}
static int dn_route_rx_short(struct sk_buff *skb)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
unsigned char *ptr = skb->data;
if (!pskb_may_pull(skb, 6)) /* 5 for short header + 1 for shortest nsp */
goto drop_it;
skb_pull(skb, 5);
skb_reset_transport_header(skb);
cb->dst = *(__le16 *)ptr;
ptr += 2;
cb->src = *(__le16 *)ptr;
ptr += 2;
cb->hops = *ptr & 0x3f;
return NF_HOOK(NFPROTO_DECNET, NF_DN_PRE_ROUTING, skb, skb->dev, NULL,
dn_route_rx_packet);
drop_it:
kfree_skb(skb);
return NET_RX_DROP;
}
static int dn_route_discard(struct sk_buff *skb)
{
/*
* I know we drop the packet here, but thats considered success in
* this case
*/
kfree_skb(skb);
return NET_RX_SUCCESS;
}
static int dn_route_ptp_hello(struct sk_buff *skb)
{
dn_dev_hello(skb);
dn_neigh_pointopoint_hello(skb);
return NET_RX_SUCCESS;
}
int dn_route_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev)
{
struct dn_skb_cb *cb;
unsigned char flags = 0;
__u16 len = le16_to_cpu(*(__le16 *)skb->data);
struct dn_dev *dn = rcu_dereference(dev->dn_ptr);
unsigned char padlen = 0;
if (!net_eq(dev_net(dev), &init_net))
goto dump_it;
if (dn == NULL)
goto dump_it;
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)
goto out;
if (!pskb_may_pull(skb, 3))
goto dump_it;
skb_pull(skb, 2);
if (len > skb->len)
goto dump_it;
skb_trim(skb, len);
flags = *skb->data;
cb = DN_SKB_CB(skb);
cb->stamp = jiffies;
cb->iif = dev->ifindex;
/*
* If we have padding, remove it.
*/
if (flags & DN_RT_F_PF) {
padlen = flags & ~DN_RT_F_PF;
if (!pskb_may_pull(skb, padlen + 1))
goto dump_it;
skb_pull(skb, padlen);
flags = *skb->data;
}
skb_reset_network_header(skb);
/*
* Weed out future version DECnet
*/
if (flags & DN_RT_F_VER)
goto dump_it;
cb->rt_flags = flags;
if (decnet_debug_level & 1)
printk(KERN_DEBUG
"dn_route_rcv: got 0x%02x from %s [%d %d %d]\n",
(int)flags, (dev) ? dev->name : "???", len, skb->len,
padlen);
if (flags & DN_RT_PKT_CNTL) {
if (unlikely(skb_linearize(skb)))
goto dump_it;
switch(flags & DN_RT_CNTL_MSK) {
case DN_RT_PKT_INIT:
dn_dev_init_pkt(skb);
break;
case DN_RT_PKT_VERI:
dn_dev_veri_pkt(skb);
break;
}
if (dn->parms.state != DN_DEV_S_RU)
goto dump_it;
switch(flags & DN_RT_CNTL_MSK) {
case DN_RT_PKT_HELO:
return NF_HOOK(NFPROTO_DECNET, NF_DN_HELLO,
skb, skb->dev, NULL,
dn_route_ptp_hello);
case DN_RT_PKT_L1RT:
case DN_RT_PKT_L2RT:
return NF_HOOK(NFPROTO_DECNET, NF_DN_ROUTE,
skb, skb->dev, NULL,
dn_route_discard);
case DN_RT_PKT_ERTH:
return NF_HOOK(NFPROTO_DECNET, NF_DN_HELLO,
skb, skb->dev, NULL,
dn_neigh_router_hello);
case DN_RT_PKT_EEDH:
return NF_HOOK(NFPROTO_DECNET, NF_DN_HELLO,
skb, skb->dev, NULL,
dn_neigh_endnode_hello);
}
} else {
if (dn->parms.state != DN_DEV_S_RU)
goto dump_it;
skb_pull(skb, 1); /* Pull flags */
switch(flags & DN_RT_PKT_MSK) {
case DN_RT_PKT_LONG:
return dn_route_rx_long(skb);
case DN_RT_PKT_SHORT:
return dn_route_rx_short(skb);
}
}
dump_it:
kfree_skb(skb);
out:
return NET_RX_DROP;
}
static int dn_output(struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
struct dn_route *rt = (struct dn_route *)dst;
struct net_device *dev = dst->dev;
struct dn_skb_cb *cb = DN_SKB_CB(skb);
struct neighbour *neigh;
int err = -EINVAL;
if ((neigh = dst->neighbour) == NULL)
goto error;
skb->dev = dev;
cb->src = rt->rt_saddr;
cb->dst = rt->rt_daddr;
/*
* Always set the Intra-Ethernet bit on all outgoing packets
* originated on this node. Only valid flag from upper layers
* is return-to-sender-requested. Set hop count to 0 too.
*/
cb->rt_flags &= ~DN_RT_F_RQR;
cb->rt_flags |= DN_RT_F_IE;
cb->hops = 0;
return NF_HOOK(NFPROTO_DECNET, NF_DN_LOCAL_OUT, skb, NULL, dev,
neigh->output);
error:
if (net_ratelimit())
printk(KERN_DEBUG "dn_output: This should not happen\n");
kfree_skb(skb);
return err;
}
static int dn_forward(struct sk_buff *skb)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
struct dst_entry *dst = skb_dst(skb);
struct dn_dev *dn_db = rcu_dereference(dst->dev->dn_ptr);
struct dn_route *rt;
struct neighbour *neigh = dst->neighbour;
int header_len;
#ifdef CONFIG_NETFILTER
struct net_device *dev = skb->dev;
#endif
if (skb->pkt_type != PACKET_HOST)
goto drop;
/* Ensure that we have enough space for headers */
rt = (struct dn_route *)skb_dst(skb);
header_len = dn_db->use_long ? 21 : 6;
if (skb_cow(skb, LL_RESERVED_SPACE(rt->dst.dev)+header_len))
goto drop;
/*
* Hop count exceeded.
*/
if (++cb->hops > 30)
goto drop;
skb->dev = rt->dst.dev;
/*
* If packet goes out same interface it came in on, then set
* the Intra-Ethernet bit. This has no effect for short
* packets, so we don't need to test for them here.
*/
cb->rt_flags &= ~DN_RT_F_IE;
if (rt->rt_flags & RTCF_DOREDIRECT)
cb->rt_flags |= DN_RT_F_IE;
return NF_HOOK(NFPROTO_DECNET, NF_DN_FORWARD, skb, dev, skb->dev,
neigh->output);
drop:
kfree_skb(skb);
return NET_RX_DROP;
}
/*
* Used to catch bugs. This should never normally get
* called.
*/
static int dn_rt_bug(struct sk_buff *skb)
{
if (net_ratelimit()) {
struct dn_skb_cb *cb = DN_SKB_CB(skb);
printk(KERN_DEBUG "dn_rt_bug: skb from:%04x to:%04x\n",
le16_to_cpu(cb->src), le16_to_cpu(cb->dst));
}
kfree_skb(skb);
return NET_RX_DROP;
}
static unsigned int dn_dst_default_advmss(const struct dst_entry *dst)
{
return dn_mss_from_pmtu(dst->dev, dst_mtu(dst));
}
static unsigned int dn_dst_default_mtu(const struct dst_entry *dst)
{
return dst->dev->mtu;
}
static int dn_rt_set_next_hop(struct dn_route *rt, struct dn_fib_res *res)
{
struct dn_fib_info *fi = res->fi;
struct net_device *dev = rt->dst.dev;
struct neighbour *n;
unsigned int metric;
if (fi) {
if (DN_FIB_RES_GW(*res) &&
DN_FIB_RES_NH(*res).nh_scope == RT_SCOPE_LINK)
rt->rt_gateway = DN_FIB_RES_GW(*res);
dst_import_metrics(&rt->dst, fi->fib_metrics);
}
rt->rt_type = res->type;
if (dev != NULL && rt->dst.neighbour == NULL) {
n = __neigh_lookup_errno(&dn_neigh_table, &rt->rt_gateway, dev);
if (IS_ERR(n))
return PTR_ERR(n);
rt->dst.neighbour = n;
}
if (dst_metric(&rt->dst, RTAX_MTU) > rt->dst.dev->mtu)
dst_metric_set(&rt->dst, RTAX_MTU, rt->dst.dev->mtu);
metric = dst_metric_raw(&rt->dst, RTAX_ADVMSS);
if (metric) {
unsigned int mss = dn_mss_from_pmtu(dev, dst_mtu(&rt->dst));
if (metric > mss)
dst_metric_set(&rt->dst, RTAX_ADVMSS, mss);
}
return 0;
}
static inline int dn_match_addr(__le16 addr1, __le16 addr2)
{
__u16 tmp = le16_to_cpu(addr1) ^ le16_to_cpu(addr2);
int match = 16;
while(tmp) {
tmp >>= 1;
match--;
}
return match;
}
static __le16 dnet_select_source(const struct net_device *dev, __le16 daddr, int scope)
{
__le16 saddr = 0;
struct dn_dev *dn_db;
struct dn_ifaddr *ifa;
int best_match = 0;
int ret;
rcu_read_lock();
dn_db = rcu_dereference(dev->dn_ptr);
for (ifa = rcu_dereference(dn_db->ifa_list);
ifa != NULL;
ifa = rcu_dereference(ifa->ifa_next)) {
if (ifa->ifa_scope > scope)
continue;
if (!daddr) {
saddr = ifa->ifa_local;
break;
}
ret = dn_match_addr(daddr, ifa->ifa_local);
if (ret > best_match)
saddr = ifa->ifa_local;
if (best_match == 0)
saddr = ifa->ifa_local;
}
rcu_read_unlock();
return saddr;
}
static inline __le16 __dn_fib_res_prefsrc(struct dn_fib_res *res)
{
return dnet_select_source(DN_FIB_RES_DEV(*res), DN_FIB_RES_GW(*res), res->scope);
}
static inline __le16 dn_fib_rules_map_destination(__le16 daddr, struct dn_fib_res *res)
{
__le16 mask = dnet_make_mask(res->prefixlen);
return (daddr&~mask)|res->fi->fib_nh->nh_gw;
}
static int dn_route_output_slow(struct dst_entry **pprt, const struct flowi *oldflp, int try_hard)
{
struct flowi fl = { .fld_dst = oldflp->fld_dst,
.fld_src = oldflp->fld_src,
.fld_scope = RT_SCOPE_UNIVERSE,
.mark = oldflp->mark,
.iif = init_net.loopback_dev->ifindex,
.oif = oldflp->oif };
struct dn_route *rt = NULL;
struct net_device *dev_out = NULL, *dev;
struct neighbour *neigh = NULL;
unsigned hash;
unsigned flags = 0;
struct dn_fib_res res = { .fi = NULL, .type = RTN_UNICAST };
int err;
int free_res = 0;
__le16 gateway = 0;
if (decnet_debug_level & 16)
printk(KERN_DEBUG
"dn_route_output_slow: dst=%04x src=%04x mark=%d"
" iif=%d oif=%d\n", le16_to_cpu(oldflp->fld_dst),
le16_to_cpu(oldflp->fld_src),
oldflp->mark, init_net.loopback_dev->ifindex, oldflp->oif);
/* If we have an output interface, verify its a DECnet device */
if (oldflp->oif) {
dev_out = dev_get_by_index(&init_net, oldflp->oif);
err = -ENODEV;
if (dev_out && dev_out->dn_ptr == NULL) {
dev_put(dev_out);
dev_out = NULL;
}
if (dev_out == NULL)
goto out;
}
/* If we have a source address, verify that its a local address */
if (oldflp->fld_src) {
err = -EADDRNOTAVAIL;
if (dev_out) {
if (dn_dev_islocal(dev_out, oldflp->fld_src))
goto source_ok;
dev_put(dev_out);
goto out;
}
rcu_read_lock();
for_each_netdev_rcu(&init_net, dev) {
if (!dev->dn_ptr)
continue;
if (!dn_dev_islocal(dev, oldflp->fld_src))
continue;
if ((dev->flags & IFF_LOOPBACK) &&
oldflp->fld_dst &&
!dn_dev_islocal(dev, oldflp->fld_dst))
continue;
dev_out = dev;
break;
}
rcu_read_unlock();
if (dev_out == NULL)
goto out;
dev_hold(dev_out);
source_ok:
;
}
/* No destination? Assume its local */
if (!fl.fld_dst) {
fl.fld_dst = fl.fld_src;
err = -EADDRNOTAVAIL;
if (dev_out)
dev_put(dev_out);
dev_out = init_net.loopback_dev;
dev_hold(dev_out);
if (!fl.fld_dst) {
fl.fld_dst =
fl.fld_src = dnet_select_source(dev_out, 0,
RT_SCOPE_HOST);
if (!fl.fld_dst)
goto out;
}
fl.oif = init_net.loopback_dev->ifindex;
res.type = RTN_LOCAL;
goto make_route;
}
if (decnet_debug_level & 16)
printk(KERN_DEBUG
"dn_route_output_slow: initial checks complete."
" dst=%o4x src=%04x oif=%d try_hard=%d\n",
le16_to_cpu(fl.fld_dst), le16_to_cpu(fl.fld_src),
fl.oif, try_hard);
/*
* N.B. If the kernel is compiled without router support then
* dn_fib_lookup() will evaluate to non-zero so this if () block
* will always be executed.
*/
err = -ESRCH;
if (try_hard || (err = dn_fib_lookup(&fl, &res)) != 0) {
struct dn_dev *dn_db;
if (err != -ESRCH)
goto out;
/*
* Here the fallback is basically the standard algorithm for
* routing in endnodes which is described in the DECnet routing
* docs
*
* If we are not trying hard, look in neighbour cache.
* The result is tested to ensure that if a specific output
* device/source address was requested, then we honour that
* here
*/
if (!try_hard) {
neigh = neigh_lookup_nodev(&dn_neigh_table, &init_net, &fl.fld_dst);
if (neigh) {
if ((oldflp->oif &&
(neigh->dev->ifindex != oldflp->oif)) ||
(oldflp->fld_src &&
(!dn_dev_islocal(neigh->dev,
oldflp->fld_src)))) {
neigh_release(neigh);
neigh = NULL;
} else {
if (dev_out)
dev_put(dev_out);
if (dn_dev_islocal(neigh->dev, fl.fld_dst)) {
dev_out = init_net.loopback_dev;
res.type = RTN_LOCAL;
} else {
dev_out = neigh->dev;
}
dev_hold(dev_out);
goto select_source;
}
}
}
/* Not there? Perhaps its a local address */
if (dev_out == NULL)
dev_out = dn_dev_get_default();
err = -ENODEV;
if (dev_out == NULL)
goto out;
dn_db = rcu_dereference_raw(dev_out->dn_ptr);
/* Possible improvement - check all devices for local addr */
if (dn_dev_islocal(dev_out, fl.fld_dst)) {
dev_put(dev_out);
dev_out = init_net.loopback_dev;
dev_hold(dev_out);
res.type = RTN_LOCAL;
goto select_source;
}
/* Not local either.... try sending it to the default router */
neigh = neigh_clone(dn_db->router);
BUG_ON(neigh && neigh->dev != dev_out);
/* Ok then, we assume its directly connected and move on */
select_source:
if (neigh)
gateway = ((struct dn_neigh *)neigh)->addr;
if (gateway == 0)
gateway = fl.fld_dst;
if (fl.fld_src == 0) {
fl.fld_src = dnet_select_source(dev_out, gateway,
res.type == RTN_LOCAL ?
RT_SCOPE_HOST :
RT_SCOPE_LINK);
if (fl.fld_src == 0 && res.type != RTN_LOCAL)
goto e_addr;
}
fl.oif = dev_out->ifindex;
goto make_route;
}
free_res = 1;
if (res.type == RTN_NAT)
goto e_inval;
if (res.type == RTN_LOCAL) {
if (!fl.fld_src)
fl.fld_src = fl.fld_dst;
if (dev_out)
dev_put(dev_out);
dev_out = init_net.loopback_dev;
dev_hold(dev_out);
fl.oif = dev_out->ifindex;
if (res.fi)
dn_fib_info_put(res.fi);
res.fi = NULL;
goto make_route;
}
if (res.fi->fib_nhs > 1 && fl.oif == 0)
dn_fib_select_multipath(&fl, &res);
/*
* We could add some logic to deal with default routes here and
* get rid of some of the special casing above.
*/
if (!fl.fld_src)
fl.fld_src = DN_FIB_RES_PREFSRC(res);
if (dev_out)
dev_put(dev_out);
dev_out = DN_FIB_RES_DEV(res);
dev_hold(dev_out);
fl.oif = dev_out->ifindex;
gateway = DN_FIB_RES_GW(res);
make_route:
if (dev_out->flags & IFF_LOOPBACK)
flags |= RTCF_LOCAL;
rt = dst_alloc(&dn_dst_ops);
if (rt == NULL)
goto e_nobufs;
atomic_set(&rt->dst.__refcnt, 1);
rt->dst.flags = DST_HOST;
rt->fl.fld_src = oldflp->fld_src;
rt->fl.fld_dst = oldflp->fld_dst;
rt->fl.oif = oldflp->oif;
rt->fl.iif = 0;
rt->fl.mark = oldflp->mark;
rt->rt_saddr = fl.fld_src;
rt->rt_daddr = fl.fld_dst;
rt->rt_gateway = gateway ? gateway : fl.fld_dst;
rt->rt_local_src = fl.fld_src;
rt->rt_dst_map = fl.fld_dst;
rt->rt_src_map = fl.fld_src;
rt->dst.dev = dev_out;
dev_hold(dev_out);
rt->dst.neighbour = neigh;
neigh = NULL;
rt->dst.lastuse = jiffies;
rt->dst.output = dn_output;
rt->dst.input = dn_rt_bug;
rt->rt_flags = flags;
if (flags & RTCF_LOCAL)
rt->dst.input = dn_nsp_rx;
err = dn_rt_set_next_hop(rt, &res);
if (err)
goto e_neighbour;
hash = dn_hash(rt->fl.fld_src, rt->fl.fld_dst);
dn_insert_route(rt, hash, (struct dn_route **)pprt);
done:
if (neigh)
neigh_release(neigh);
if (free_res)
dn_fib_res_put(&res);
if (dev_out)
dev_put(dev_out);
out:
return err;
e_addr:
err = -EADDRNOTAVAIL;
goto done;
e_inval:
err = -EINVAL;
goto done;
e_nobufs:
err = -ENOBUFS;
goto done;
e_neighbour:
dst_free(&rt->dst);
goto e_nobufs;
}
/*
* N.B. The flags may be moved into the flowi at some future stage.
*/
static int __dn_route_output_key(struct dst_entry **pprt, const struct flowi *flp, int flags)
{
unsigned hash = dn_hash(flp->fld_src, flp->fld_dst);
struct dn_route *rt = NULL;
if (!(flags & MSG_TRYHARD)) {
rcu_read_lock_bh();
for (rt = rcu_dereference_bh(dn_rt_hash_table[hash].chain); rt;
rt = rcu_dereference_bh(rt->dst.dn_next)) {
if ((flp->fld_dst == rt->fl.fld_dst) &&
(flp->fld_src == rt->fl.fld_src) &&
(flp->mark == rt->fl.mark) &&
dn_is_output_route(rt) &&
(rt->fl.oif == flp->oif)) {
dst_use(&rt->dst, jiffies);
rcu_read_unlock_bh();
*pprt = &rt->dst;
return 0;
}
}
rcu_read_unlock_bh();
}
return dn_route_output_slow(pprt, flp, flags);
}
static int dn_route_output_key(struct dst_entry **pprt, struct flowi *flp, int flags)
{
int err;
err = __dn_route_output_key(pprt, flp, flags);
if (err == 0 && flp->proto) {
err = xfrm_lookup(&init_net, pprt, flp, NULL, 0);
}
return err;
}
int dn_route_output_sock(struct dst_entry **pprt, struct flowi *fl, struct sock *sk, int flags)
{
int err;
err = __dn_route_output_key(pprt, fl, flags & MSG_TRYHARD);
if (err == 0 && fl->proto) {
err = xfrm_lookup(&init_net, pprt, fl, sk,
(flags & MSG_DONTWAIT) ? 0 : XFRM_LOOKUP_WAIT);
}
return err;
}
static int dn_route_input_slow(struct sk_buff *skb)
{
struct dn_route *rt = NULL;
struct dn_skb_cb *cb = DN_SKB_CB(skb);
struct net_device *in_dev = skb->dev;
struct net_device *out_dev = NULL;
struct dn_dev *dn_db;
struct neighbour *neigh = NULL;
unsigned hash;
int flags = 0;
__le16 gateway = 0;
__le16 local_src = 0;
struct flowi fl = { .fld_dst = cb->dst,
.fld_src = cb->src,
.fld_scope = RT_SCOPE_UNIVERSE,
.mark = skb->mark,
.iif = skb->dev->ifindex };
struct dn_fib_res res = { .fi = NULL, .type = RTN_UNREACHABLE };
int err = -EINVAL;
int free_res = 0;
dev_hold(in_dev);
if ((dn_db = rcu_dereference(in_dev->dn_ptr)) == NULL)
goto out;
/* Zero source addresses are not allowed */
if (fl.fld_src == 0)
goto out;
/*
* In this case we've just received a packet from a source
* outside ourselves pretending to come from us. We don't
* allow it any further to prevent routing loops, spoofing and
* other nasties. Loopback packets already have the dst attached
* so this only affects packets which have originated elsewhere.
*/
err = -ENOTUNIQ;
if (dn_dev_islocal(in_dev, cb->src))
goto out;
err = dn_fib_lookup(&fl, &res);
if (err) {
if (err != -ESRCH)
goto out;
/*
* Is the destination us ?
*/
if (!dn_dev_islocal(in_dev, cb->dst))
goto e_inval;
res.type = RTN_LOCAL;
} else {
__le16 src_map = fl.fld_src;
free_res = 1;
out_dev = DN_FIB_RES_DEV(res);
if (out_dev == NULL) {
if (net_ratelimit())
printk(KERN_CRIT "Bug in dn_route_input_slow() "
"No output device\n");
goto e_inval;
}
dev_hold(out_dev);
if (res.r)
src_map = fl.fld_src; /* no NAT support for now */
gateway = DN_FIB_RES_GW(res);
if (res.type == RTN_NAT) {
fl.fld_dst = dn_fib_rules_map_destination(fl.fld_dst, &res);
dn_fib_res_put(&res);
free_res = 0;
if (dn_fib_lookup(&fl, &res))
goto e_inval;
free_res = 1;
if (res.type != RTN_UNICAST)
goto e_inval;
flags |= RTCF_DNAT;
gateway = fl.fld_dst;
}
fl.fld_src = src_map;
}
switch(res.type) {
case RTN_UNICAST:
/*
* Forwarding check here, we only check for forwarding
* being turned off, if you want to only forward intra
* area, its up to you to set the routing tables up
* correctly.
*/
if (dn_db->parms.forwarding == 0)
goto e_inval;
if (res.fi->fib_nhs > 1 && fl.oif == 0)
dn_fib_select_multipath(&fl, &res);
/*
* Check for out_dev == in_dev. We use the RTCF_DOREDIRECT
* flag as a hint to set the intra-ethernet bit when
* forwarding. If we've got NAT in operation, we don't do
* this optimisation.
*/
if (out_dev == in_dev && !(flags & RTCF_NAT))
flags |= RTCF_DOREDIRECT;
local_src = DN_FIB_RES_PREFSRC(res);
case RTN_BLACKHOLE:
case RTN_UNREACHABLE:
break;
case RTN_LOCAL:
flags |= RTCF_LOCAL;
fl.fld_src = cb->dst;
fl.fld_dst = cb->src;
/* Routing tables gave us a gateway */
if (gateway)
goto make_route;
/* Packet was intra-ethernet, so we know its on-link */
if (cb->rt_flags & DN_RT_F_IE) {
gateway = cb->src;
flags |= RTCF_DIRECTSRC;
goto make_route;
}
/* Use the default router if there is one */
neigh = neigh_clone(dn_db->router);
if (neigh) {
gateway = ((struct dn_neigh *)neigh)->addr;
goto make_route;
}
/* Close eyes and pray */
gateway = cb->src;
flags |= RTCF_DIRECTSRC;
goto make_route;
default:
goto e_inval;
}
make_route:
rt = dst_alloc(&dn_dst_ops);
if (rt == NULL)
goto e_nobufs;
rt->rt_saddr = fl.fld_src;
rt->rt_daddr = fl.fld_dst;
rt->rt_gateway = fl.fld_dst;
if (gateway)
rt->rt_gateway = gateway;
rt->rt_local_src = local_src ? local_src : rt->rt_saddr;
rt->rt_dst_map = fl.fld_dst;
rt->rt_src_map = fl.fld_src;
rt->fl.fld_src = cb->src;
rt->fl.fld_dst = cb->dst;
rt->fl.oif = 0;
rt->fl.iif = in_dev->ifindex;
rt->fl.mark = fl.mark;
rt->dst.flags = DST_HOST;
rt->dst.neighbour = neigh;
rt->dst.dev = out_dev;
rt->dst.lastuse = jiffies;
rt->dst.output = dn_rt_bug;
switch(res.type) {
case RTN_UNICAST:
rt->dst.input = dn_forward;
break;
case RTN_LOCAL:
rt->dst.output = dn_output;
rt->dst.input = dn_nsp_rx;
rt->dst.dev = in_dev;
flags |= RTCF_LOCAL;
break;
default:
case RTN_UNREACHABLE:
case RTN_BLACKHOLE:
rt->dst.input = dst_discard;
}
rt->rt_flags = flags;
if (rt->dst.dev)
dev_hold(rt->dst.dev);
err = dn_rt_set_next_hop(rt, &res);
if (err)
goto e_neighbour;
hash = dn_hash(rt->fl.fld_src, rt->fl.fld_dst);
dn_insert_route(rt, hash, &rt);
skb_dst_set(skb, &rt->dst);
done:
if (neigh)
neigh_release(neigh);
if (free_res)
dn_fib_res_put(&res);
dev_put(in_dev);
if (out_dev)
dev_put(out_dev);
out:
return err;
e_inval:
err = -EINVAL;
goto done;
e_nobufs:
err = -ENOBUFS;
goto done;
e_neighbour:
dst_free(&rt->dst);
goto done;
}
static int dn_route_input(struct sk_buff *skb)
{
struct dn_route *rt;
struct dn_skb_cb *cb = DN_SKB_CB(skb);
unsigned hash = dn_hash(cb->src, cb->dst);
if (skb_dst(skb))
return 0;
rcu_read_lock();
for(rt = rcu_dereference(dn_rt_hash_table[hash].chain); rt != NULL;
rt = rcu_dereference(rt->dst.dn_next)) {
if ((rt->fl.fld_src == cb->src) &&
(rt->fl.fld_dst == cb->dst) &&
(rt->fl.oif == 0) &&
(rt->fl.mark == skb->mark) &&
(rt->fl.iif == cb->iif)) {
dst_use(&rt->dst, jiffies);
rcu_read_unlock();
skb_dst_set(skb, (struct dst_entry *)rt);
return 0;
}
}
rcu_read_unlock();
return dn_route_input_slow(skb);
}
static int dn_rt_fill_info(struct sk_buff *skb, u32 pid, u32 seq,
int event, int nowait, unsigned int flags)
{
struct dn_route *rt = (struct dn_route *)skb_dst(skb);
struct rtmsg *r;
struct nlmsghdr *nlh;
unsigned char *b = skb_tail_pointer(skb);
long expires;
nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*r), flags);
r = NLMSG_DATA(nlh);
r->rtm_family = AF_DECnet;
r->rtm_dst_len = 16;
r->rtm_src_len = 0;
r->rtm_tos = 0;
r->rtm_table = RT_TABLE_MAIN;
RTA_PUT_U32(skb, RTA_TABLE, RT_TABLE_MAIN);
r->rtm_type = rt->rt_type;
r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED;
r->rtm_scope = RT_SCOPE_UNIVERSE;
r->rtm_protocol = RTPROT_UNSPEC;
if (rt->rt_flags & RTCF_NOTIFY)
r->rtm_flags |= RTM_F_NOTIFY;
RTA_PUT(skb, RTA_DST, 2, &rt->rt_daddr);
if (rt->fl.fld_src) {
r->rtm_src_len = 16;
RTA_PUT(skb, RTA_SRC, 2, &rt->fl.fld_src);
}
if (rt->dst.dev)
RTA_PUT(skb, RTA_OIF, sizeof(int), &rt->dst.dev->ifindex);
/*
* Note to self - change this if input routes reverse direction when
* they deal only with inputs and not with replies like they do
* currently.
*/
RTA_PUT(skb, RTA_PREFSRC, 2, &rt->rt_local_src);
if (rt->rt_daddr != rt->rt_gateway)
RTA_PUT(skb, RTA_GATEWAY, 2, &rt->rt_gateway);
if (rtnetlink_put_metrics(skb, dst_metrics_ptr(&rt->dst)) < 0)
goto rtattr_failure;
expires = rt->dst.expires ? rt->dst.expires - jiffies : 0;
if (rtnl_put_cacheinfo(skb, &rt->dst, 0, 0, 0, expires,
rt->dst.error) < 0)
goto rtattr_failure;
if (dn_is_input_route(rt))
RTA_PUT(skb, RTA_IIF, sizeof(int), &rt->fl.iif);
nlh->nlmsg_len = skb_tail_pointer(skb) - b;
return skb->len;
nlmsg_failure:
rtattr_failure:
nlmsg_trim(skb, b);
return -1;
}
/*
* This is called by both endnodes and routers now.
*/
static int dn_cache_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh, void *arg)
{
struct net *net = sock_net(in_skb->sk);
struct rtattr **rta = arg;
struct rtmsg *rtm = NLMSG_DATA(nlh);
struct dn_route *rt = NULL;
struct dn_skb_cb *cb;
int err;
struct sk_buff *skb;
struct flowi fl;
if (!net_eq(net, &init_net))
return -EINVAL;
memset(&fl, 0, sizeof(fl));
fl.proto = DNPROTO_NSP;
skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
if (skb == NULL)
return -ENOBUFS;
skb_reset_mac_header(skb);
cb = DN_SKB_CB(skb);
if (rta[RTA_SRC-1])
memcpy(&fl.fld_src, RTA_DATA(rta[RTA_SRC-1]), 2);
if (rta[RTA_DST-1])
memcpy(&fl.fld_dst, RTA_DATA(rta[RTA_DST-1]), 2);
if (rta[RTA_IIF-1])
memcpy(&fl.iif, RTA_DATA(rta[RTA_IIF-1]), sizeof(int));
if (fl.iif) {
struct net_device *dev;
if ((dev = dev_get_by_index(&init_net, fl.iif)) == NULL) {
kfree_skb(skb);
return -ENODEV;
}
if (!dev->dn_ptr) {
dev_put(dev);
kfree_skb(skb);
return -ENODEV;
}
skb->protocol = htons(ETH_P_DNA_RT);
skb->dev = dev;
cb->src = fl.fld_src;
cb->dst = fl.fld_dst;
local_bh_disable();
err = dn_route_input(skb);
local_bh_enable();
memset(cb, 0, sizeof(struct dn_skb_cb));
rt = (struct dn_route *)skb_dst(skb);
if (!err && -rt->dst.error)
err = rt->dst.error;
} else {
int oif = 0;
if (rta[RTA_OIF - 1])
memcpy(&oif, RTA_DATA(rta[RTA_OIF - 1]), sizeof(int));
fl.oif = oif;
err = dn_route_output_key((struct dst_entry **)&rt, &fl, 0);
}
if (skb->dev)
dev_put(skb->dev);
skb->dev = NULL;
if (err)
goto out_free;
skb_dst_set(skb, &rt->dst);
if (rtm->rtm_flags & RTM_F_NOTIFY)
rt->rt_flags |= RTCF_NOTIFY;
err = dn_rt_fill_info(skb, NETLINK_CB(in_skb).pid, nlh->nlmsg_seq, RTM_NEWROUTE, 0, 0);
if (err == 0)
goto out_free;
if (err < 0) {
err = -EMSGSIZE;
goto out_free;
}
return rtnl_unicast(skb, &init_net, NETLINK_CB(in_skb).pid);
out_free:
kfree_skb(skb);
return err;
}
/*
* For routers, this is called from dn_fib_dump, but for endnodes its
* called directly from the rtnetlink dispatch table.
*/
int dn_cache_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct dn_route *rt;
int h, s_h;
int idx, s_idx;
if (!net_eq(net, &init_net))
return 0;
if (NLMSG_PAYLOAD(cb->nlh, 0) < sizeof(struct rtmsg))
return -EINVAL;
if (!(((struct rtmsg *)NLMSG_DATA(cb->nlh))->rtm_flags&RTM_F_CLONED))
return 0;
s_h = cb->args[0];
s_idx = idx = cb->args[1];
for(h = 0; h <= dn_rt_hash_mask; h++) {
if (h < s_h)
continue;
if (h > s_h)
s_idx = 0;
rcu_read_lock_bh();
for(rt = rcu_dereference_bh(dn_rt_hash_table[h].chain), idx = 0;
rt;
rt = rcu_dereference_bh(rt->dst.dn_next), idx++) {
if (idx < s_idx)
continue;
skb_dst_set(skb, dst_clone(&rt->dst));
if (dn_rt_fill_info(skb, NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, RTM_NEWROUTE,
1, NLM_F_MULTI) <= 0) {
skb_dst_drop(skb);
rcu_read_unlock_bh();
goto done;
}
skb_dst_drop(skb);
}
rcu_read_unlock_bh();
}
done:
cb->args[0] = h;
cb->args[1] = idx;
return skb->len;
}
#ifdef CONFIG_PROC_FS
struct dn_rt_cache_iter_state {
int bucket;
};
static struct dn_route *dn_rt_cache_get_first(struct seq_file *seq)
{
struct dn_route *rt = NULL;
struct dn_rt_cache_iter_state *s = seq->private;
for(s->bucket = dn_rt_hash_mask; s->bucket >= 0; --s->bucket) {
rcu_read_lock_bh();
rt = rcu_dereference_bh(dn_rt_hash_table[s->bucket].chain);
if (rt)
break;
rcu_read_unlock_bh();
}
return rt;
}
static struct dn_route *dn_rt_cache_get_next(struct seq_file *seq, struct dn_route *rt)
{
struct dn_rt_cache_iter_state *s = seq->private;
rt = rcu_dereference_bh(rt->dst.dn_next);
while (!rt) {
rcu_read_unlock_bh();
if (--s->bucket < 0)
break;
rcu_read_lock_bh();
rt = rcu_dereference_bh(dn_rt_hash_table[s->bucket].chain);
}
return rt;
}
static void *dn_rt_cache_seq_start(struct seq_file *seq, loff_t *pos)
{
struct dn_route *rt = dn_rt_cache_get_first(seq);
if (rt) {
while(*pos && (rt = dn_rt_cache_get_next(seq, rt)))
--*pos;
}
return *pos ? NULL : rt;
}
static void *dn_rt_cache_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct dn_route *rt = dn_rt_cache_get_next(seq, v);
++*pos;
return rt;
}
static void dn_rt_cache_seq_stop(struct seq_file *seq, void *v)
{
if (v)
rcu_read_unlock_bh();
}
static int dn_rt_cache_seq_show(struct seq_file *seq, void *v)
{
struct dn_route *rt = v;
char buf1[DN_ASCBUF_LEN], buf2[DN_ASCBUF_LEN];
seq_printf(seq, "%-8s %-7s %-7s %04d %04d %04d\n",
rt->dst.dev ? rt->dst.dev->name : "*",
dn_addr2asc(le16_to_cpu(rt->rt_daddr), buf1),
dn_addr2asc(le16_to_cpu(rt->rt_saddr), buf2),
atomic_read(&rt->dst.__refcnt),
rt->dst.__use,
(int) dst_metric(&rt->dst, RTAX_RTT));
return 0;
}
static const struct seq_operations dn_rt_cache_seq_ops = {
.start = dn_rt_cache_seq_start,
.next = dn_rt_cache_seq_next,
.stop = dn_rt_cache_seq_stop,
.show = dn_rt_cache_seq_show,
};
static int dn_rt_cache_seq_open(struct inode *inode, struct file *file)
{
return seq_open_private(file, &dn_rt_cache_seq_ops,
sizeof(struct dn_rt_cache_iter_state));
}
static const struct file_operations dn_rt_cache_seq_fops = {
.owner = THIS_MODULE,
.open = dn_rt_cache_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
#endif /* CONFIG_PROC_FS */
void __init dn_route_init(void)
{
int i, goal, order;
dn_dst_ops.kmem_cachep =
kmem_cache_create("dn_dst_cache", sizeof(struct dn_route), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
dst_entries_init(&dn_dst_ops);
setup_timer(&dn_route_timer, dn_dst_check_expire, 0);
dn_route_timer.expires = jiffies + decnet_dst_gc_interval * HZ;
add_timer(&dn_route_timer);
goal = totalram_pages >> (26 - PAGE_SHIFT);
for(order = 0; (1UL << order) < goal; order++)
/* NOTHING */;
/*
* Only want 1024 entries max, since the table is very, very unlikely
* to be larger than that.
*/
while(order && ((((1UL << order) * PAGE_SIZE) /
sizeof(struct dn_rt_hash_bucket)) >= 2048))
order--;
do {
dn_rt_hash_mask = (1UL << order) * PAGE_SIZE /
sizeof(struct dn_rt_hash_bucket);
while(dn_rt_hash_mask & (dn_rt_hash_mask - 1))
dn_rt_hash_mask--;
dn_rt_hash_table = (struct dn_rt_hash_bucket *)
__get_free_pages(GFP_ATOMIC, order);
} while (dn_rt_hash_table == NULL && --order > 0);
if (!dn_rt_hash_table)
panic("Failed to allocate DECnet route cache hash table\n");
printk(KERN_INFO
"DECnet: Routing cache hash table of %u buckets, %ldKbytes\n",
dn_rt_hash_mask,
(long)(dn_rt_hash_mask*sizeof(struct dn_rt_hash_bucket))/1024);
dn_rt_hash_mask--;
for(i = 0; i <= dn_rt_hash_mask; i++) {
spin_lock_init(&dn_rt_hash_table[i].lock);
dn_rt_hash_table[i].chain = NULL;
}
dn_dst_ops.gc_thresh = (dn_rt_hash_mask + 1);
proc_net_fops_create(&init_net, "decnet_cache", S_IRUGO, &dn_rt_cache_seq_fops);
#ifdef CONFIG_DECNET_ROUTER
rtnl_register(PF_DECnet, RTM_GETROUTE, dn_cache_getroute, dn_fib_dump);
#else
rtnl_register(PF_DECnet, RTM_GETROUTE, dn_cache_getroute,
dn_cache_dump);
#endif
}
void __exit dn_route_cleanup(void)
{
del_timer(&dn_route_timer);
dn_run_flush(0);
proc_net_remove(&init_net, "decnet_cache");
dst_entries_destroy(&dn_dst_ops);
}
| gpl-2.0 |
ASAZING/android_kernel_huawei_y210 | arch/x86/platform/mrst/mrst.c | 107 | 21558 | /*
* mrst.c: Intel Moorestown platform specific setup code
*
* (C) Copyright 2008 Intel Corporation
* Author: Jacob Pan (jacob.jun.pan@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.
*/
#define pr_fmt(fmt) "mrst: " fmt
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/sfi.h>
#include <linux/intel_pmic_gpio.h>
#include <linux/spi/spi.h>
#include <linux/i2c.h>
#include <linux/i2c/pca953x.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <linux/platform_device.h>
#include <linux/irq.h>
#include <linux/module.h>
#include <asm/setup.h>
#include <asm/mpspec_def.h>
#include <asm/hw_irq.h>
#include <asm/apic.h>
#include <asm/io_apic.h>
#include <asm/mrst.h>
#include <asm/io.h>
#include <asm/i8259.h>
#include <asm/intel_scu_ipc.h>
#include <asm/apb_timer.h>
#include <asm/reboot.h>
/*
* the clockevent devices on Moorestown/Medfield can be APBT or LAPIC clock,
* cmdline option x86_mrst_timer can be used to override the configuration
* to prefer one or the other.
* at runtime, there are basically three timer configurations:
* 1. per cpu apbt clock only
* 2. per cpu always-on lapic clocks only, this is Penwell/Medfield only
* 3. per cpu lapic clock (C3STOP) and one apbt clock, with broadcast.
*
* by default (without cmdline option), platform code first detects cpu type
* to see if we are on lincroft or penwell, then set up both lapic or apbt
* clocks accordingly.
* i.e. by default, medfield uses configuration #2, moorestown uses #1.
* config #3 is supported but not recommended on medfield.
*
* rating and feature summary:
* lapic (with C3STOP) --------- 100
* apbt (always-on) ------------ 110
* lapic (always-on,ARAT) ------ 150
*/
__cpuinitdata enum mrst_timer_options mrst_timer_options;
static u32 sfi_mtimer_usage[SFI_MTMR_MAX_NUM];
static struct sfi_timer_table_entry sfi_mtimer_array[SFI_MTMR_MAX_NUM];
enum mrst_cpu_type __mrst_cpu_chip;
EXPORT_SYMBOL_GPL(__mrst_cpu_chip);
int sfi_mtimer_num;
struct sfi_rtc_table_entry sfi_mrtc_array[SFI_MRTC_MAX];
EXPORT_SYMBOL_GPL(sfi_mrtc_array);
int sfi_mrtc_num;
/* parse all the mtimer info to a static mtimer array */
static int __init sfi_parse_mtmr(struct sfi_table_header *table)
{
struct sfi_table_simple *sb;
struct sfi_timer_table_entry *pentry;
struct mpc_intsrc mp_irq;
int totallen;
sb = (struct sfi_table_simple *)table;
if (!sfi_mtimer_num) {
sfi_mtimer_num = SFI_GET_NUM_ENTRIES(sb,
struct sfi_timer_table_entry);
pentry = (struct sfi_timer_table_entry *) sb->pentry;
totallen = sfi_mtimer_num * sizeof(*pentry);
memcpy(sfi_mtimer_array, pentry, totallen);
}
pr_debug("SFI MTIMER info (num = %d):\n", sfi_mtimer_num);
pentry = sfi_mtimer_array;
for (totallen = 0; totallen < sfi_mtimer_num; totallen++, pentry++) {
pr_debug("timer[%d]: paddr = 0x%08x, freq = %dHz,"
" irq = %d\n", totallen, (u32)pentry->phys_addr,
pentry->freq_hz, pentry->irq);
if (!pentry->irq)
continue;
mp_irq.type = MP_IOAPIC;
mp_irq.irqtype = mp_INT;
/* triggering mode edge bit 2-3, active high polarity bit 0-1 */
mp_irq.irqflag = 5;
mp_irq.srcbus = 0;
mp_irq.srcbusirq = pentry->irq; /* IRQ */
mp_irq.dstapic = MP_APIC_ALL;
mp_irq.dstirq = pentry->irq;
mp_save_irq(&mp_irq);
}
return 0;
}
struct sfi_timer_table_entry *sfi_get_mtmr(int hint)
{
int i;
if (hint < sfi_mtimer_num) {
if (!sfi_mtimer_usage[hint]) {
pr_debug("hint taken for timer %d irq %d\n",\
hint, sfi_mtimer_array[hint].irq);
sfi_mtimer_usage[hint] = 1;
return &sfi_mtimer_array[hint];
}
}
/* take the first timer available */
for (i = 0; i < sfi_mtimer_num;) {
if (!sfi_mtimer_usage[i]) {
sfi_mtimer_usage[i] = 1;
return &sfi_mtimer_array[i];
}
i++;
}
return NULL;
}
void sfi_free_mtmr(struct sfi_timer_table_entry *mtmr)
{
int i;
for (i = 0; i < sfi_mtimer_num;) {
if (mtmr->irq == sfi_mtimer_array[i].irq) {
sfi_mtimer_usage[i] = 0;
return;
}
i++;
}
}
/* parse all the mrtc info to a global mrtc array */
int __init sfi_parse_mrtc(struct sfi_table_header *table)
{
struct sfi_table_simple *sb;
struct sfi_rtc_table_entry *pentry;
struct mpc_intsrc mp_irq;
int totallen;
sb = (struct sfi_table_simple *)table;
if (!sfi_mrtc_num) {
sfi_mrtc_num = SFI_GET_NUM_ENTRIES(sb,
struct sfi_rtc_table_entry);
pentry = (struct sfi_rtc_table_entry *)sb->pentry;
totallen = sfi_mrtc_num * sizeof(*pentry);
memcpy(sfi_mrtc_array, pentry, totallen);
}
pr_debug("SFI RTC info (num = %d):\n", sfi_mrtc_num);
pentry = sfi_mrtc_array;
for (totallen = 0; totallen < sfi_mrtc_num; totallen++, pentry++) {
pr_debug("RTC[%d]: paddr = 0x%08x, irq = %d\n",
totallen, (u32)pentry->phys_addr, pentry->irq);
mp_irq.type = MP_IOAPIC;
mp_irq.irqtype = mp_INT;
mp_irq.irqflag = 0xf; /* level trigger and active low */
mp_irq.srcbus = 0;
mp_irq.srcbusirq = pentry->irq; /* IRQ */
mp_irq.dstapic = MP_APIC_ALL;
mp_irq.dstirq = pentry->irq;
mp_save_irq(&mp_irq);
}
return 0;
}
static unsigned long __init mrst_calibrate_tsc(void)
{
unsigned long flags, fast_calibrate;
local_irq_save(flags);
fast_calibrate = apbt_quick_calibrate();
local_irq_restore(flags);
if (fast_calibrate)
return fast_calibrate;
return 0;
}
void __init mrst_time_init(void)
{
sfi_table_parse(SFI_SIG_MTMR, NULL, NULL, sfi_parse_mtmr);
switch (mrst_timer_options) {
case MRST_TIMER_APBT_ONLY:
break;
case MRST_TIMER_LAPIC_APBT:
x86_init.timers.setup_percpu_clockev = setup_boot_APIC_clock;
x86_cpuinit.setup_percpu_clockev = setup_secondary_APIC_clock;
break;
default:
if (!boot_cpu_has(X86_FEATURE_ARAT))
break;
x86_init.timers.setup_percpu_clockev = setup_boot_APIC_clock;
x86_cpuinit.setup_percpu_clockev = setup_secondary_APIC_clock;
return;
}
/* we need at least one APB timer */
pre_init_apic_IRQ0();
apbt_time_init();
}
void __cpuinit mrst_arch_setup(void)
{
if (boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model == 0x27)
__mrst_cpu_chip = MRST_CPU_CHIP_PENWELL;
else if (boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model == 0x26)
__mrst_cpu_chip = MRST_CPU_CHIP_LINCROFT;
else {
pr_err("Unknown Moorestown CPU (%d:%d), default to Lincroft\n",
boot_cpu_data.x86, boot_cpu_data.x86_model);
__mrst_cpu_chip = MRST_CPU_CHIP_LINCROFT;
}
pr_debug("Moorestown CPU %s identified\n",
(__mrst_cpu_chip == MRST_CPU_CHIP_LINCROFT) ?
"Lincroft" : "Penwell");
}
/* MID systems don't have i8042 controller */
static int mrst_i8042_detect(void)
{
return 0;
}
/* Reboot and power off are handled by the SCU on a MID device */
static void mrst_power_off(void)
{
intel_scu_ipc_simple_command(0xf1, 1);
}
static void mrst_reboot(void)
{
intel_scu_ipc_simple_command(0xf1, 0);
}
/*
* Moorestown specific x86_init function overrides and early setup
* calls.
*/
void __init x86_mrst_early_setup(void)
{
x86_init.resources.probe_roms = x86_init_noop;
x86_init.resources.reserve_resources = x86_init_noop;
x86_init.timers.timer_init = mrst_time_init;
x86_init.timers.setup_percpu_clockev = x86_init_noop;
x86_init.irqs.pre_vector_init = x86_init_noop;
x86_init.oem.arch_setup = mrst_arch_setup;
x86_cpuinit.setup_percpu_clockev = apbt_setup_secondary_clock;
x86_platform.calibrate_tsc = mrst_calibrate_tsc;
x86_platform.i8042_detect = mrst_i8042_detect;
x86_init.pci.init = pci_mrst_init;
x86_init.pci.fixup_irqs = x86_init_noop;
legacy_pic = &null_legacy_pic;
/* Moorestown specific power_off/restart method */
pm_power_off = mrst_power_off;
machine_ops.emergency_restart = mrst_reboot;
/* Avoid searching for BIOS MP tables */
x86_init.mpparse.find_smp_config = x86_init_noop;
x86_init.mpparse.get_smp_config = x86_init_uint_noop;
}
/*
* if user does not want to use per CPU apb timer, just give it a lower rating
* than local apic timer and skip the late per cpu timer init.
*/
static inline int __init setup_x86_mrst_timer(char *arg)
{
if (!arg)
return -EINVAL;
if (strcmp("apbt_only", arg) == 0)
mrst_timer_options = MRST_TIMER_APBT_ONLY;
else if (strcmp("lapic_and_apbt", arg) == 0)
mrst_timer_options = MRST_TIMER_LAPIC_APBT;
else {
pr_warning("X86 MRST timer option %s not recognised"
" use x86_mrst_timer=apbt_only or lapic_and_apbt\n",
arg);
return -EINVAL;
}
return 0;
}
__setup("x86_mrst_timer=", setup_x86_mrst_timer);
/*
* Parsing GPIO table first, since the DEVS table will need this table
* to map the pin name to the actual pin.
*/
static struct sfi_gpio_table_entry *gpio_table;
static int gpio_num_entry;
static int __init sfi_parse_gpio(struct sfi_table_header *table)
{
struct sfi_table_simple *sb;
struct sfi_gpio_table_entry *pentry;
int num, i;
if (gpio_table)
return 0;
sb = (struct sfi_table_simple *)table;
num = SFI_GET_NUM_ENTRIES(sb, struct sfi_gpio_table_entry);
pentry = (struct sfi_gpio_table_entry *)sb->pentry;
gpio_table = (struct sfi_gpio_table_entry *)
kmalloc(num * sizeof(*pentry), GFP_KERNEL);
if (!gpio_table)
return -1;
memcpy(gpio_table, pentry, num * sizeof(*pentry));
gpio_num_entry = num;
pr_debug("GPIO pin info:\n");
for (i = 0; i < num; i++, pentry++)
pr_debug("info[%2d]: controller = %16.16s, pin_name = %16.16s,"
" pin = %d\n", i,
pentry->controller_name,
pentry->pin_name,
pentry->pin_no);
return 0;
}
static int get_gpio_by_name(const char *name)
{
struct sfi_gpio_table_entry *pentry = gpio_table;
int i;
if (!pentry)
return -1;
for (i = 0; i < gpio_num_entry; i++, pentry++) {
if (!strncmp(name, pentry->pin_name, SFI_NAME_LEN))
return pentry->pin_no;
}
return -1;
}
/*
* Here defines the array of devices platform data that IAFW would export
* through SFI "DEVS" table, we use name and type to match the device and
* its platform data.
*/
struct devs_id {
char name[SFI_NAME_LEN + 1];
u8 type;
u8 delay;
void *(*get_platform_data)(void *info);
};
/* the offset for the mapping of global gpio pin to irq */
#define MRST_IRQ_OFFSET 0x100
static void __init *pmic_gpio_platform_data(void *info)
{
static struct intel_pmic_gpio_platform_data pmic_gpio_pdata;
int gpio_base = get_gpio_by_name("pmic_gpio_base");
if (gpio_base == -1)
gpio_base = 64;
pmic_gpio_pdata.gpio_base = gpio_base;
pmic_gpio_pdata.irq_base = gpio_base + MRST_IRQ_OFFSET;
pmic_gpio_pdata.gpiointr = 0xffffeff8;
return &pmic_gpio_pdata;
}
static void __init *max3111_platform_data(void *info)
{
struct spi_board_info *spi_info = info;
int intr = get_gpio_by_name("max3111_int");
if (intr == -1)
return NULL;
spi_info->irq = intr + MRST_IRQ_OFFSET;
return NULL;
}
/* we have multiple max7315 on the board ... */
#define MAX7315_NUM 2
static void __init *max7315_platform_data(void *info)
{
static struct pca953x_platform_data max7315_pdata[MAX7315_NUM];
static int nr;
struct pca953x_platform_data *max7315 = &max7315_pdata[nr];
struct i2c_board_info *i2c_info = info;
int gpio_base, intr;
char base_pin_name[SFI_NAME_LEN + 1];
char intr_pin_name[SFI_NAME_LEN + 1];
if (nr == MAX7315_NUM) {
pr_err("too many max7315s, we only support %d\n",
MAX7315_NUM);
return NULL;
}
/* we have several max7315 on the board, we only need load several
* instances of the same pca953x driver to cover them
*/
strcpy(i2c_info->type, "max7315");
if (nr++) {
sprintf(base_pin_name, "max7315_%d_base", nr);
sprintf(intr_pin_name, "max7315_%d_int", nr);
} else {
strcpy(base_pin_name, "max7315_base");
strcpy(intr_pin_name, "max7315_int");
}
gpio_base = get_gpio_by_name(base_pin_name);
intr = get_gpio_by_name(intr_pin_name);
if (gpio_base == -1)
return NULL;
max7315->gpio_base = gpio_base;
if (intr != -1) {
i2c_info->irq = intr + MRST_IRQ_OFFSET;
max7315->irq_base = gpio_base + MRST_IRQ_OFFSET;
} else {
i2c_info->irq = -1;
max7315->irq_base = -1;
}
return max7315;
}
static void __init *emc1403_platform_data(void *info)
{
static short intr2nd_pdata;
struct i2c_board_info *i2c_info = info;
int intr = get_gpio_by_name("thermal_int");
int intr2nd = get_gpio_by_name("thermal_alert");
if (intr == -1 || intr2nd == -1)
return NULL;
i2c_info->irq = intr + MRST_IRQ_OFFSET;
intr2nd_pdata = intr2nd + MRST_IRQ_OFFSET;
return &intr2nd_pdata;
}
static void __init *lis331dl_platform_data(void *info)
{
static short intr2nd_pdata;
struct i2c_board_info *i2c_info = info;
int intr = get_gpio_by_name("accel_int");
int intr2nd = get_gpio_by_name("accel_2");
if (intr == -1 || intr2nd == -1)
return NULL;
i2c_info->irq = intr + MRST_IRQ_OFFSET;
intr2nd_pdata = intr2nd + MRST_IRQ_OFFSET;
return &intr2nd_pdata;
}
static void __init *no_platform_data(void *info)
{
return NULL;
}
static const struct devs_id __initconst device_ids[] = {
{"pmic_gpio", SFI_DEV_TYPE_SPI, 1, &pmic_gpio_platform_data},
{"spi_max3111", SFI_DEV_TYPE_SPI, 0, &max3111_platform_data},
{"i2c_max7315", SFI_DEV_TYPE_I2C, 1, &max7315_platform_data},
{"i2c_max7315_2", SFI_DEV_TYPE_I2C, 1, &max7315_platform_data},
{"emc1403", SFI_DEV_TYPE_I2C, 1, &emc1403_platform_data},
{"i2c_accel", SFI_DEV_TYPE_I2C, 0, &lis331dl_platform_data},
{"pmic_audio", SFI_DEV_TYPE_IPC, 1, &no_platform_data},
{"msic_audio", SFI_DEV_TYPE_IPC, 1, &no_platform_data},
{},
};
#define MAX_IPCDEVS 24
static struct platform_device *ipc_devs[MAX_IPCDEVS];
static int ipc_next_dev;
#define MAX_SCU_SPI 24
static struct spi_board_info *spi_devs[MAX_SCU_SPI];
static int spi_next_dev;
#define MAX_SCU_I2C 24
static struct i2c_board_info *i2c_devs[MAX_SCU_I2C];
static int i2c_bus[MAX_SCU_I2C];
static int i2c_next_dev;
static void __init intel_scu_device_register(struct platform_device *pdev)
{
if(ipc_next_dev == MAX_IPCDEVS)
pr_err("too many SCU IPC devices");
else
ipc_devs[ipc_next_dev++] = pdev;
}
static void __init intel_scu_spi_device_register(struct spi_board_info *sdev)
{
struct spi_board_info *new_dev;
if (spi_next_dev == MAX_SCU_SPI) {
pr_err("too many SCU SPI devices");
return;
}
new_dev = kzalloc(sizeof(*sdev), GFP_KERNEL);
if (!new_dev) {
pr_err("failed to alloc mem for delayed spi dev %s\n",
sdev->modalias);
return;
}
memcpy(new_dev, sdev, sizeof(*sdev));
spi_devs[spi_next_dev++] = new_dev;
}
static void __init intel_scu_i2c_device_register(int bus,
struct i2c_board_info *idev)
{
struct i2c_board_info *new_dev;
if (i2c_next_dev == MAX_SCU_I2C) {
pr_err("too many SCU I2C devices");
return;
}
new_dev = kzalloc(sizeof(*idev), GFP_KERNEL);
if (!new_dev) {
pr_err("failed to alloc mem for delayed i2c dev %s\n",
idev->type);
return;
}
memcpy(new_dev, idev, sizeof(*idev));
i2c_bus[i2c_next_dev] = bus;
i2c_devs[i2c_next_dev++] = new_dev;
}
/* Called by IPC driver */
void intel_scu_devices_create(void)
{
int i;
for (i = 0; i < ipc_next_dev; i++)
platform_device_add(ipc_devs[i]);
for (i = 0; i < spi_next_dev; i++)
spi_register_board_info(spi_devs[i], 1);
for (i = 0; i < i2c_next_dev; i++) {
struct i2c_adapter *adapter;
struct i2c_client *client;
adapter = i2c_get_adapter(i2c_bus[i]);
if (adapter) {
client = i2c_new_device(adapter, i2c_devs[i]);
if (!client)
pr_err("can't create i2c device %s\n",
i2c_devs[i]->type);
} else
i2c_register_board_info(i2c_bus[i], i2c_devs[i], 1);
}
}
EXPORT_SYMBOL_GPL(intel_scu_devices_create);
/* Called by IPC driver */
void intel_scu_devices_destroy(void)
{
int i;
for (i = 0; i < ipc_next_dev; i++)
platform_device_del(ipc_devs[i]);
}
EXPORT_SYMBOL_GPL(intel_scu_devices_destroy);
static void __init install_irq_resource(struct platform_device *pdev, int irq)
{
/* Single threaded */
static struct resource __initdata res = {
.name = "IRQ",
.flags = IORESOURCE_IRQ,
};
res.start = irq;
platform_device_add_resources(pdev, &res, 1);
}
static void __init sfi_handle_ipc_dev(struct platform_device *pdev)
{
const struct devs_id *dev = device_ids;
void *pdata = NULL;
while (dev->name[0]) {
if (dev->type == SFI_DEV_TYPE_IPC &&
!strncmp(dev->name, pdev->name, SFI_NAME_LEN)) {
pdata = dev->get_platform_data(pdev);
break;
}
dev++;
}
pdev->dev.platform_data = pdata;
intel_scu_device_register(pdev);
}
static void __init sfi_handle_spi_dev(struct spi_board_info *spi_info)
{
const struct devs_id *dev = device_ids;
void *pdata = NULL;
while (dev->name[0]) {
if (dev->type == SFI_DEV_TYPE_SPI &&
!strncmp(dev->name, spi_info->modalias, SFI_NAME_LEN)) {
pdata = dev->get_platform_data(spi_info);
break;
}
dev++;
}
spi_info->platform_data = pdata;
if (dev->delay)
intel_scu_spi_device_register(spi_info);
else
spi_register_board_info(spi_info, 1);
}
static void __init sfi_handle_i2c_dev(int bus, struct i2c_board_info *i2c_info)
{
const struct devs_id *dev = device_ids;
void *pdata = NULL;
while (dev->name[0]) {
if (dev->type == SFI_DEV_TYPE_I2C &&
!strncmp(dev->name, i2c_info->type, SFI_NAME_LEN)) {
pdata = dev->get_platform_data(i2c_info);
break;
}
dev++;
}
i2c_info->platform_data = pdata;
if (dev->delay)
intel_scu_i2c_device_register(bus, i2c_info);
else
i2c_register_board_info(bus, i2c_info, 1);
}
static int __init sfi_parse_devs(struct sfi_table_header *table)
{
struct sfi_table_simple *sb;
struct sfi_device_table_entry *pentry;
struct spi_board_info spi_info;
struct i2c_board_info i2c_info;
struct platform_device *pdev;
int num, i, bus;
int ioapic;
struct io_apic_irq_attr irq_attr;
sb = (struct sfi_table_simple *)table;
num = SFI_GET_NUM_ENTRIES(sb, struct sfi_device_table_entry);
pentry = (struct sfi_device_table_entry *)sb->pentry;
for (i = 0; i < num; i++, pentry++) {
if (pentry->irq != (u8)0xff) { /* native RTE case */
/* these SPI2 devices are not exposed to system as PCI
* devices, but they have separate RTE entry in IOAPIC
* so we have to enable them one by one here
*/
ioapic = mp_find_ioapic(pentry->irq);
irq_attr.ioapic = ioapic;
irq_attr.ioapic_pin = pentry->irq;
irq_attr.trigger = 1;
irq_attr.polarity = 1;
io_apic_set_pci_routing(NULL, pentry->irq, &irq_attr);
}
switch (pentry->type) {
case SFI_DEV_TYPE_IPC:
/* ID as IRQ is a hack that will go away */
pdev = platform_device_alloc(pentry->name, pentry->irq);
if (pdev == NULL) {
pr_err("out of memory for SFI platform device '%s'.\n",
pentry->name);
continue;
}
install_irq_resource(pdev, pentry->irq);
pr_debug("info[%2d]: IPC bus, name = %16.16s, "
"irq = 0x%2x\n", i, pentry->name, pentry->irq);
sfi_handle_ipc_dev(pdev);
break;
case SFI_DEV_TYPE_SPI:
memset(&spi_info, 0, sizeof(spi_info));
strncpy(spi_info.modalias, pentry->name, SFI_NAME_LEN);
spi_info.irq = pentry->irq;
spi_info.bus_num = pentry->host_num;
spi_info.chip_select = pentry->addr;
spi_info.max_speed_hz = pentry->max_freq;
pr_debug("info[%2d]: SPI bus = %d, name = %16.16s, "
"irq = 0x%2x, max_freq = %d, cs = %d\n", i,
spi_info.bus_num,
spi_info.modalias,
spi_info.irq,
spi_info.max_speed_hz,
spi_info.chip_select);
sfi_handle_spi_dev(&spi_info);
break;
case SFI_DEV_TYPE_I2C:
memset(&i2c_info, 0, sizeof(i2c_info));
bus = pentry->host_num;
strncpy(i2c_info.type, pentry->name, SFI_NAME_LEN);
i2c_info.irq = pentry->irq;
i2c_info.addr = pentry->addr;
pr_debug("info[%2d]: I2C bus = %d, name = %16.16s, "
"irq = 0x%2x, addr = 0x%x\n", i, bus,
i2c_info.type,
i2c_info.irq,
i2c_info.addr);
sfi_handle_i2c_dev(bus, &i2c_info);
break;
case SFI_DEV_TYPE_UART:
case SFI_DEV_TYPE_HSI:
default:
;
}
}
return 0;
}
static int __init mrst_platform_init(void)
{
sfi_table_parse(SFI_SIG_GPIO, NULL, NULL, sfi_parse_gpio);
sfi_table_parse(SFI_SIG_DEVS, NULL, NULL, sfi_parse_devs);
return 0;
}
arch_initcall(mrst_platform_init);
/*
* we will search these buttons in SFI GPIO table (by name)
* and register them dynamically. Please add all possible
* buttons here, we will shrink them if no GPIO found.
*/
static struct gpio_keys_button gpio_button[] = {
{KEY_POWER, -1, 1, "power_btn", EV_KEY, 0, 3000},
{KEY_PROG1, -1, 1, "prog_btn1", EV_KEY, 0, 20},
{KEY_PROG2, -1, 1, "prog_btn2", EV_KEY, 0, 20},
{SW_LID, -1, 1, "lid_switch", EV_SW, 0, 20},
{KEY_VOLUMEUP, -1, 1, "vol_up", EV_KEY, 0, 20},
{KEY_VOLUMEDOWN, -1, 1, "vol_down", EV_KEY, 0, 20},
{KEY_CAMERA, -1, 1, "camera_full", EV_KEY, 0, 20},
{KEY_CAMERA_FOCUS, -1, 1, "camera_half", EV_KEY, 0, 20},
{SW_KEYPAD_SLIDE, -1, 1, "MagSw1", EV_SW, 0, 20},
{SW_KEYPAD_SLIDE, -1, 1, "MagSw2", EV_SW, 0, 20},
};
static struct gpio_keys_platform_data mrst_gpio_keys = {
.buttons = gpio_button,
.rep = 1,
.nbuttons = -1, /* will fill it after search */
};
static struct platform_device pb_device = {
.name = "gpio-keys",
.id = -1,
.dev = {
.platform_data = &mrst_gpio_keys,
},
};
/*
* Shrink the non-existent buttons, register the gpio button
* device if there is some
*/
static int __init pb_keys_init(void)
{
struct gpio_keys_button *gb = gpio_button;
int i, num, good = 0;
num = sizeof(gpio_button) / sizeof(struct gpio_keys_button);
for (i = 0; i < num; i++) {
gb[i].gpio = get_gpio_by_name(gb[i].desc);
if (gb[i].gpio == -1)
continue;
if (i != good)
gb[good] = gb[i];
good++;
}
if (good) {
mrst_gpio_keys.nbuttons = good;
return platform_device_register(&pb_device);
}
return 0;
}
late_initcall(pb_keys_init);
| gpl-2.0 |
skritchz/msm_2.6.38 | sound/soc/samsung/s3c24xx-i2s.c | 107 | 13306 | /*
* s3c24xx-i2s.c -- ALSA Soc Audio Layer
*
* (c) 2006 Wolfson Microelectronics PLC.
* Graeme Gregory graeme.gregory@wolfsonmicro.com or linux@wolfsonmicro.com
*
* Copyright 2004-2005 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/jiffies.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include <mach/hardware.h>
#include <mach/regs-gpio.h>
#include <mach/regs-clock.h>
#include <asm/dma.h>
#include <mach/dma.h>
#include <plat/regs-iis.h>
#include "dma.h"
#include "s3c24xx-i2s.h"
static struct s3c2410_dma_client s3c24xx_dma_client_out = {
.name = "I2S PCM Stereo out"
};
static struct s3c2410_dma_client s3c24xx_dma_client_in = {
.name = "I2S PCM Stereo in"
};
static struct s3c_dma_params s3c24xx_i2s_pcm_stereo_out = {
.client = &s3c24xx_dma_client_out,
.channel = DMACH_I2S_OUT,
.dma_addr = S3C2410_PA_IIS + S3C2410_IISFIFO,
.dma_size = 2,
};
static struct s3c_dma_params s3c24xx_i2s_pcm_stereo_in = {
.client = &s3c24xx_dma_client_in,
.channel = DMACH_I2S_IN,
.dma_addr = S3C2410_PA_IIS + S3C2410_IISFIFO,
.dma_size = 2,
};
struct s3c24xx_i2s_info {
void __iomem *regs;
struct clk *iis_clk;
u32 iiscon;
u32 iismod;
u32 iisfcon;
u32 iispsr;
};
static struct s3c24xx_i2s_info s3c24xx_i2s;
static void s3c24xx_snd_txctrl(int on)
{
u32 iisfcon;
u32 iiscon;
u32 iismod;
pr_debug("Entered %s\n", __func__);
iisfcon = readl(s3c24xx_i2s.regs + S3C2410_IISFCON);
iiscon = readl(s3c24xx_i2s.regs + S3C2410_IISCON);
iismod = readl(s3c24xx_i2s.regs + S3C2410_IISMOD);
pr_debug("r: IISCON: %x IISMOD: %x IISFCON: %x\n", iiscon, iismod, iisfcon);
if (on) {
iisfcon |= S3C2410_IISFCON_TXDMA | S3C2410_IISFCON_TXENABLE;
iiscon |= S3C2410_IISCON_TXDMAEN | S3C2410_IISCON_IISEN;
iiscon &= ~S3C2410_IISCON_TXIDLE;
iismod |= S3C2410_IISMOD_TXMODE;
writel(iismod, s3c24xx_i2s.regs + S3C2410_IISMOD);
writel(iisfcon, s3c24xx_i2s.regs + S3C2410_IISFCON);
writel(iiscon, s3c24xx_i2s.regs + S3C2410_IISCON);
} else {
/* note, we have to disable the FIFOs otherwise bad things
* seem to happen when the DMA stops. According to the
* Samsung supplied kernel, this should allow the DMA
* engine and FIFOs to reset. If this isn't allowed, the
* DMA engine will simply freeze randomly.
*/
iisfcon &= ~S3C2410_IISFCON_TXENABLE;
iisfcon &= ~S3C2410_IISFCON_TXDMA;
iiscon |= S3C2410_IISCON_TXIDLE;
iiscon &= ~S3C2410_IISCON_TXDMAEN;
iismod &= ~S3C2410_IISMOD_TXMODE;
writel(iiscon, s3c24xx_i2s.regs + S3C2410_IISCON);
writel(iisfcon, s3c24xx_i2s.regs + S3C2410_IISFCON);
writel(iismod, s3c24xx_i2s.regs + S3C2410_IISMOD);
}
pr_debug("w: IISCON: %x IISMOD: %x IISFCON: %x\n", iiscon, iismod, iisfcon);
}
static void s3c24xx_snd_rxctrl(int on)
{
u32 iisfcon;
u32 iiscon;
u32 iismod;
pr_debug("Entered %s\n", __func__);
iisfcon = readl(s3c24xx_i2s.regs + S3C2410_IISFCON);
iiscon = readl(s3c24xx_i2s.regs + S3C2410_IISCON);
iismod = readl(s3c24xx_i2s.regs + S3C2410_IISMOD);
pr_debug("r: IISCON: %x IISMOD: %x IISFCON: %x\n", iiscon, iismod, iisfcon);
if (on) {
iisfcon |= S3C2410_IISFCON_RXDMA | S3C2410_IISFCON_RXENABLE;
iiscon |= S3C2410_IISCON_RXDMAEN | S3C2410_IISCON_IISEN;
iiscon &= ~S3C2410_IISCON_RXIDLE;
iismod |= S3C2410_IISMOD_RXMODE;
writel(iismod, s3c24xx_i2s.regs + S3C2410_IISMOD);
writel(iisfcon, s3c24xx_i2s.regs + S3C2410_IISFCON);
writel(iiscon, s3c24xx_i2s.regs + S3C2410_IISCON);
} else {
/* note, we have to disable the FIFOs otherwise bad things
* seem to happen when the DMA stops. According to the
* Samsung supplied kernel, this should allow the DMA
* engine and FIFOs to reset. If this isn't allowed, the
* DMA engine will simply freeze randomly.
*/
iisfcon &= ~S3C2410_IISFCON_RXENABLE;
iisfcon &= ~S3C2410_IISFCON_RXDMA;
iiscon |= S3C2410_IISCON_RXIDLE;
iiscon &= ~S3C2410_IISCON_RXDMAEN;
iismod &= ~S3C2410_IISMOD_RXMODE;
writel(iisfcon, s3c24xx_i2s.regs + S3C2410_IISFCON);
writel(iiscon, s3c24xx_i2s.regs + S3C2410_IISCON);
writel(iismod, s3c24xx_i2s.regs + S3C2410_IISMOD);
}
pr_debug("w: IISCON: %x IISMOD: %x IISFCON: %x\n", iiscon, iismod, iisfcon);
}
/*
* Wait for the LR signal to allow synchronisation to the L/R clock
* from the codec. May only be needed for slave mode.
*/
static int s3c24xx_snd_lrsync(void)
{
u32 iiscon;
int timeout = 50; /* 5ms */
pr_debug("Entered %s\n", __func__);
while (1) {
iiscon = readl(s3c24xx_i2s.regs + S3C2410_IISCON);
if (iiscon & S3C2410_IISCON_LRINDEX)
break;
if (!timeout--)
return -ETIMEDOUT;
udelay(100);
}
return 0;
}
/*
* Check whether CPU is the master or slave
*/
static inline int s3c24xx_snd_is_clkmaster(void)
{
pr_debug("Entered %s\n", __func__);
return (readl(s3c24xx_i2s.regs + S3C2410_IISMOD) & S3C2410_IISMOD_SLAVE) ? 0:1;
}
/*
* Set S3C24xx I2S DAI format
*/
static int s3c24xx_i2s_set_fmt(struct snd_soc_dai *cpu_dai,
unsigned int fmt)
{
u32 iismod;
pr_debug("Entered %s\n", __func__);
iismod = readl(s3c24xx_i2s.regs + S3C2410_IISMOD);
pr_debug("hw_params r: IISMOD: %x \n", iismod);
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
iismod |= S3C2410_IISMOD_SLAVE;
break;
case SND_SOC_DAIFMT_CBS_CFS:
iismod &= ~S3C2410_IISMOD_SLAVE;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_LEFT_J:
iismod |= S3C2410_IISMOD_MSB;
break;
case SND_SOC_DAIFMT_I2S:
iismod &= ~S3C2410_IISMOD_MSB;
break;
default:
return -EINVAL;
}
writel(iismod, s3c24xx_i2s.regs + S3C2410_IISMOD);
pr_debug("hw_params w: IISMOD: %x \n", iismod);
return 0;
}
static int s3c24xx_i2s_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct s3c_dma_params *dma_data;
u32 iismod;
pr_debug("Entered %s\n", __func__);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
dma_data = &s3c24xx_i2s_pcm_stereo_out;
else
dma_data = &s3c24xx_i2s_pcm_stereo_in;
snd_soc_dai_set_dma_data(rtd->cpu_dai, substream, dma_data);
/* Working copies of register */
iismod = readl(s3c24xx_i2s.regs + S3C2410_IISMOD);
pr_debug("hw_params r: IISMOD: %x\n", iismod);
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S8:
iismod &= ~S3C2410_IISMOD_16BIT;
dma_data->dma_size = 1;
break;
case SNDRV_PCM_FORMAT_S16_LE:
iismod |= S3C2410_IISMOD_16BIT;
dma_data->dma_size = 2;
break;
default:
return -EINVAL;
}
writel(iismod, s3c24xx_i2s.regs + S3C2410_IISMOD);
pr_debug("hw_params w: IISMOD: %x\n", iismod);
return 0;
}
static int s3c24xx_i2s_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
int ret = 0;
struct s3c_dma_params *dma_data =
snd_soc_dai_get_dma_data(dai, substream);
pr_debug("Entered %s\n", __func__);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
if (!s3c24xx_snd_is_clkmaster()) {
ret = s3c24xx_snd_lrsync();
if (ret)
goto exit_err;
}
if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
s3c24xx_snd_rxctrl(1);
else
s3c24xx_snd_txctrl(1);
s3c2410_dma_ctrl(dma_data->channel, S3C2410_DMAOP_STARTED);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
s3c24xx_snd_rxctrl(0);
else
s3c24xx_snd_txctrl(0);
break;
default:
ret = -EINVAL;
break;
}
exit_err:
return ret;
}
/*
* Set S3C24xx Clock source
*/
static int s3c24xx_i2s_set_sysclk(struct snd_soc_dai *cpu_dai,
int clk_id, unsigned int freq, int dir)
{
u32 iismod = readl(s3c24xx_i2s.regs + S3C2410_IISMOD);
pr_debug("Entered %s\n", __func__);
iismod &= ~S3C2440_IISMOD_MPLL;
switch (clk_id) {
case S3C24XX_CLKSRC_PCLK:
break;
case S3C24XX_CLKSRC_MPLL:
iismod |= S3C2440_IISMOD_MPLL;
break;
default:
return -EINVAL;
}
writel(iismod, s3c24xx_i2s.regs + S3C2410_IISMOD);
return 0;
}
/*
* Set S3C24xx Clock dividers
*/
static int s3c24xx_i2s_set_clkdiv(struct snd_soc_dai *cpu_dai,
int div_id, int div)
{
u32 reg;
pr_debug("Entered %s\n", __func__);
switch (div_id) {
case S3C24XX_DIV_BCLK:
reg = readl(s3c24xx_i2s.regs + S3C2410_IISMOD) & ~S3C2410_IISMOD_FS_MASK;
writel(reg | div, s3c24xx_i2s.regs + S3C2410_IISMOD);
break;
case S3C24XX_DIV_MCLK:
reg = readl(s3c24xx_i2s.regs + S3C2410_IISMOD) & ~(S3C2410_IISMOD_384FS);
writel(reg | div, s3c24xx_i2s.regs + S3C2410_IISMOD);
break;
case S3C24XX_DIV_PRESCALER:
writel(div, s3c24xx_i2s.regs + S3C2410_IISPSR);
reg = readl(s3c24xx_i2s.regs + S3C2410_IISCON);
writel(reg | S3C2410_IISCON_PSCEN, s3c24xx_i2s.regs + S3C2410_IISCON);
break;
default:
return -EINVAL;
}
return 0;
}
/*
* To avoid duplicating clock code, allow machine driver to
* get the clockrate from here.
*/
u32 s3c24xx_i2s_get_clockrate(void)
{
return clk_get_rate(s3c24xx_i2s.iis_clk);
}
EXPORT_SYMBOL_GPL(s3c24xx_i2s_get_clockrate);
static int s3c24xx_i2s_probe(struct snd_soc_dai *dai)
{
pr_debug("Entered %s\n", __func__);
s3c24xx_i2s.regs = ioremap(S3C2410_PA_IIS, 0x100);
if (s3c24xx_i2s.regs == NULL)
return -ENXIO;
s3c24xx_i2s.iis_clk = clk_get(dai->dev, "iis");
if (s3c24xx_i2s.iis_clk == NULL) {
pr_err("failed to get iis_clock\n");
iounmap(s3c24xx_i2s.regs);
return -ENODEV;
}
clk_enable(s3c24xx_i2s.iis_clk);
/* Configure the I2S pins in correct mode */
s3c2410_gpio_cfgpin(S3C2410_GPE0, S3C2410_GPE0_I2SLRCK);
s3c2410_gpio_cfgpin(S3C2410_GPE1, S3C2410_GPE1_I2SSCLK);
s3c2410_gpio_cfgpin(S3C2410_GPE2, S3C2410_GPE2_CDCLK);
s3c2410_gpio_cfgpin(S3C2410_GPE3, S3C2410_GPE3_I2SSDI);
s3c2410_gpio_cfgpin(S3C2410_GPE4, S3C2410_GPE4_I2SSDO);
writel(S3C2410_IISCON_IISEN, s3c24xx_i2s.regs + S3C2410_IISCON);
s3c24xx_snd_txctrl(0);
s3c24xx_snd_rxctrl(0);
return 0;
}
#ifdef CONFIG_PM
static int s3c24xx_i2s_suspend(struct snd_soc_dai *cpu_dai)
{
pr_debug("Entered %s\n", __func__);
s3c24xx_i2s.iiscon = readl(s3c24xx_i2s.regs + S3C2410_IISCON);
s3c24xx_i2s.iismod = readl(s3c24xx_i2s.regs + S3C2410_IISMOD);
s3c24xx_i2s.iisfcon = readl(s3c24xx_i2s.regs + S3C2410_IISFCON);
s3c24xx_i2s.iispsr = readl(s3c24xx_i2s.regs + S3C2410_IISPSR);
clk_disable(s3c24xx_i2s.iis_clk);
return 0;
}
static int s3c24xx_i2s_resume(struct snd_soc_dai *cpu_dai)
{
pr_debug("Entered %s\n", __func__);
clk_enable(s3c24xx_i2s.iis_clk);
writel(s3c24xx_i2s.iiscon, s3c24xx_i2s.regs + S3C2410_IISCON);
writel(s3c24xx_i2s.iismod, s3c24xx_i2s.regs + S3C2410_IISMOD);
writel(s3c24xx_i2s.iisfcon, s3c24xx_i2s.regs + S3C2410_IISFCON);
writel(s3c24xx_i2s.iispsr, s3c24xx_i2s.regs + S3C2410_IISPSR);
return 0;
}
#else
#define s3c24xx_i2s_suspend NULL
#define s3c24xx_i2s_resume NULL
#endif
#define S3C24XX_I2S_RATES \
(SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 | SNDRV_PCM_RATE_16000 | \
SNDRV_PCM_RATE_22050 | SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 | \
SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_88200 | SNDRV_PCM_RATE_96000)
static struct snd_soc_dai_ops s3c24xx_i2s_dai_ops = {
.trigger = s3c24xx_i2s_trigger,
.hw_params = s3c24xx_i2s_hw_params,
.set_fmt = s3c24xx_i2s_set_fmt,
.set_clkdiv = s3c24xx_i2s_set_clkdiv,
.set_sysclk = s3c24xx_i2s_set_sysclk,
};
static struct snd_soc_dai_driver s3c24xx_i2s_dai = {
.probe = s3c24xx_i2s_probe,
.suspend = s3c24xx_i2s_suspend,
.resume = s3c24xx_i2s_resume,
.playback = {
.channels_min = 2,
.channels_max = 2,
.rates = S3C24XX_I2S_RATES,
.formats = SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_S16_LE,},
.capture = {
.channels_min = 2,
.channels_max = 2,
.rates = S3C24XX_I2S_RATES,
.formats = SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_S16_LE,},
.ops = &s3c24xx_i2s_dai_ops,
};
static __devinit int s3c24xx_iis_dev_probe(struct platform_device *pdev)
{
return snd_soc_register_dai(&pdev->dev, &s3c24xx_i2s_dai);
}
static __devexit int s3c24xx_iis_dev_remove(struct platform_device *pdev)
{
snd_soc_unregister_dai(&pdev->dev);
return 0;
}
static struct platform_driver s3c24xx_iis_driver = {
.probe = s3c24xx_iis_dev_probe,
.remove = s3c24xx_iis_dev_remove,
.driver = {
.name = "s3c24xx-iis",
.owner = THIS_MODULE,
},
};
static int __init s3c24xx_i2s_init(void)
{
return platform_driver_register(&s3c24xx_iis_driver);
}
module_init(s3c24xx_i2s_init);
static void __exit s3c24xx_i2s_exit(void)
{
platform_driver_unregister(&s3c24xx_iis_driver);
}
module_exit(s3c24xx_i2s_exit);
/* Module information */
MODULE_AUTHOR("Ben Dooks, <ben@simtec.co.uk>");
MODULE_DESCRIPTION("s3c24xx I2S SoC Interface");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:s3c24xx-iis");
| gpl-2.0 |
rubiojr/surface3-kernel | drivers/video/grvga.c | 363 | 14329 | /*
* Driver for Aeroflex Gaisler SVGACTRL framebuffer device.
*
* 2011 (c) Aeroflex Gaisler AB
*
* Full documentation of the core can be found here:
* http://www.gaisler.com/products/grlib/grip.pdf
*
* 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.
*
* Contributors: Kristoffer Glembo <kristoffer@gaisler.com>
*
*/
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/of_platform.h>
#include <linux/of_device.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/mm.h>
#include <linux/fb.h>
#include <linux/io.h>
struct grvga_regs {
u32 status; /* 0x00 */
u32 video_length; /* 0x04 */
u32 front_porch; /* 0x08 */
u32 sync_length; /* 0x0C */
u32 line_length; /* 0x10 */
u32 fb_pos; /* 0x14 */
u32 clk_vector[4]; /* 0x18 */
u32 clut; /* 0x20 */
};
struct grvga_par {
struct grvga_regs *regs;
u32 color_palette[16]; /* 16 entry pseudo palette used by fbcon in true color mode */
int clk_sel;
int fb_alloced; /* = 1 if framebuffer is allocated in main memory */
};
static const struct fb_videomode grvga_modedb[] = {
{
/* 640x480 @ 60 Hz */
NULL, 60, 640, 480, 40000, 48, 16, 39, 11, 96, 2,
0, FB_VMODE_NONINTERLACED
}, {
/* 800x600 @ 60 Hz */
NULL, 60, 800, 600, 25000, 88, 40, 23, 1, 128, 4,
0, FB_VMODE_NONINTERLACED
}, {
/* 800x600 @ 72 Hz */
NULL, 72, 800, 600, 20000, 64, 56, 23, 37, 120, 6,
0, FB_VMODE_NONINTERLACED
}, {
/* 1024x768 @ 60 Hz */
NULL, 60, 1024, 768, 15385, 160, 24, 29, 3, 136, 6,
0, FB_VMODE_NONINTERLACED
}
};
static struct fb_fix_screeninfo grvga_fix = {
.id = "AG SVGACTRL",
.type = FB_TYPE_PACKED_PIXELS,
.visual = FB_VISUAL_PSEUDOCOLOR,
.xpanstep = 0,
.ypanstep = 1,
.ywrapstep = 0,
.accel = FB_ACCEL_NONE,
};
static int grvga_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct grvga_par *par = info->par;
int i;
if (!var->xres)
var->xres = 1;
if (!var->yres)
var->yres = 1;
if (var->bits_per_pixel <= 8)
var->bits_per_pixel = 8;
else if (var->bits_per_pixel <= 16)
var->bits_per_pixel = 16;
else if (var->bits_per_pixel <= 24)
var->bits_per_pixel = 24;
else if (var->bits_per_pixel <= 32)
var->bits_per_pixel = 32;
else
return -EINVAL;
var->xres_virtual = var->xres;
var->yres_virtual = 2*var->yres;
if (info->fix.smem_len) {
if ((var->yres_virtual*var->xres_virtual*var->bits_per_pixel/8) > info->fix.smem_len)
return -ENOMEM;
}
/* Which clocks that are available can be read out in these registers */
for (i = 0; i <= 3 ; i++) {
if (var->pixclock == par->regs->clk_vector[i])
break;
}
if (i <= 3)
par->clk_sel = i;
else
return -EINVAL;
switch (info->var.bits_per_pixel) {
case 8:
var->red = (struct fb_bitfield) {0, 8, 0}; /* offset, length, msb-right */
var->green = (struct fb_bitfield) {0, 8, 0};
var->blue = (struct fb_bitfield) {0, 8, 0};
var->transp = (struct fb_bitfield) {0, 0, 0};
break;
case 16:
var->red = (struct fb_bitfield) {11, 5, 0};
var->green = (struct fb_bitfield) {5, 6, 0};
var->blue = (struct fb_bitfield) {0, 5, 0};
var->transp = (struct fb_bitfield) {0, 0, 0};
break;
case 24:
case 32:
var->red = (struct fb_bitfield) {16, 8, 0};
var->green = (struct fb_bitfield) {8, 8, 0};
var->blue = (struct fb_bitfield) {0, 8, 0};
var->transp = (struct fb_bitfield) {24, 8, 0};
break;
default:
return -EINVAL;
}
return 0;
}
static int grvga_set_par(struct fb_info *info)
{
u32 func = 0;
struct grvga_par *par = info->par;
__raw_writel(((info->var.yres - 1) << 16) | (info->var.xres - 1),
&par->regs->video_length);
__raw_writel((info->var.lower_margin << 16) | (info->var.right_margin),
&par->regs->front_porch);
__raw_writel((info->var.vsync_len << 16) | (info->var.hsync_len),
&par->regs->sync_length);
__raw_writel(((info->var.yres + info->var.lower_margin + info->var.upper_margin + info->var.vsync_len - 1) << 16) |
(info->var.xres + info->var.right_margin + info->var.left_margin + info->var.hsync_len - 1),
&par->regs->line_length);
switch (info->var.bits_per_pixel) {
case 8:
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
func = 1;
break;
case 16:
info->fix.visual = FB_VISUAL_TRUECOLOR;
func = 2;
break;
case 24:
case 32:
info->fix.visual = FB_VISUAL_TRUECOLOR;
func = 3;
break;
default:
return -EINVAL;
}
__raw_writel((par->clk_sel << 6) | (func << 4) | 1,
&par->regs->status);
info->fix.line_length = (info->var.xres_virtual*info->var.bits_per_pixel)/8;
return 0;
}
static int grvga_setcolreg(unsigned regno, unsigned red, unsigned green, unsigned blue, unsigned transp, struct fb_info *info)
{
struct grvga_par *par;
par = info->par;
if (regno >= 256) /* Size of CLUT */
return -EINVAL;
if (info->var.grayscale) {
/* grayscale = 0.30*R + 0.59*G + 0.11*B */
red = green = blue = (red * 77 + green * 151 + blue * 28) >> 8;
}
#define CNVT_TOHW(val, width) ((((val)<<(width))+0x7FFF-(val))>>16)
red = CNVT_TOHW(red, info->var.red.length);
green = CNVT_TOHW(green, info->var.green.length);
blue = CNVT_TOHW(blue, info->var.blue.length);
transp = CNVT_TOHW(transp, info->var.transp.length);
#undef CNVT_TOHW
/* In PSEUDOCOLOR we use the hardware CLUT */
if (info->fix.visual == FB_VISUAL_PSEUDOCOLOR)
__raw_writel((regno << 24) | (red << 16) | (green << 8) | blue,
&par->regs->clut);
/* Truecolor uses the pseudo palette */
else if (info->fix.visual == FB_VISUAL_TRUECOLOR) {
u32 v;
if (regno >= 16)
return -EINVAL;
v = (red << info->var.red.offset) |
(green << info->var.green.offset) |
(blue << info->var.blue.offset) |
(transp << info->var.transp.offset);
((u32 *) (info->pseudo_palette))[regno] = v;
}
return 0;
}
static int grvga_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct grvga_par *par = info->par;
struct fb_fix_screeninfo *fix = &info->fix;
u32 base_addr;
if (var->xoffset != 0)
return -EINVAL;
base_addr = fix->smem_start + (var->yoffset * fix->line_length);
base_addr &= ~3UL;
/* Set framebuffer base address */
__raw_writel(base_addr,
&par->regs->fb_pos);
return 0;
}
static struct fb_ops grvga_ops = {
.owner = THIS_MODULE,
.fb_check_var = grvga_check_var,
.fb_set_par = grvga_set_par,
.fb_setcolreg = grvga_setcolreg,
.fb_pan_display = grvga_pan_display,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit
};
static int grvga_parse_custom(char *options,
struct fb_var_screeninfo *screendata)
{
char *this_opt;
int count = 0;
if (!options || !*options)
return -1;
while ((this_opt = strsep(&options, " ")) != NULL) {
if (!*this_opt)
continue;
switch (count) {
case 0:
screendata->pixclock = simple_strtoul(this_opt, NULL, 0);
count++;
break;
case 1:
screendata->xres = screendata->xres_virtual = simple_strtoul(this_opt, NULL, 0);
count++;
break;
case 2:
screendata->right_margin = simple_strtoul(this_opt, NULL, 0);
count++;
break;
case 3:
screendata->hsync_len = simple_strtoul(this_opt, NULL, 0);
count++;
break;
case 4:
screendata->left_margin = simple_strtoul(this_opt, NULL, 0);
count++;
break;
case 5:
screendata->yres = screendata->yres_virtual = simple_strtoul(this_opt, NULL, 0);
count++;
break;
case 6:
screendata->lower_margin = simple_strtoul(this_opt, NULL, 0);
count++;
break;
case 7:
screendata->vsync_len = simple_strtoul(this_opt, NULL, 0);
count++;
break;
case 8:
screendata->upper_margin = simple_strtoul(this_opt, NULL, 0);
count++;
break;
case 9:
screendata->bits_per_pixel = simple_strtoul(this_opt, NULL, 0);
count++;
break;
default:
return -1;
}
}
screendata->activate = FB_ACTIVATE_NOW;
screendata->vmode = FB_VMODE_NONINTERLACED;
return 0;
}
static int grvga_probe(struct platform_device *dev)
{
struct fb_info *info;
int retval = -ENOMEM;
unsigned long virtual_start;
unsigned long grvga_fix_addr = 0;
unsigned long physical_start = 0;
unsigned long grvga_mem_size = 0;
struct grvga_par *par = NULL;
char *options = NULL, *mode_opt = NULL;
info = framebuffer_alloc(sizeof(struct grvga_par), &dev->dev);
if (!info) {
dev_err(&dev->dev, "framebuffer_alloc failed\n");
return -ENOMEM;
}
/* Expecting: "grvga: modestring, [addr:<framebuffer physical address>], [size:<framebuffer size>]
*
* If modestring is custom:<custom mode string> we parse the string which then contains all videoparameters
* If address is left out, we allocate memory,
* if size is left out we only allocate enough to support the given mode.
*/
if (fb_get_options("grvga", &options)) {
retval = -ENODEV;
goto free_fb;
}
if (!options || !*options)
options = "640x480-8@60";
while (1) {
char *this_opt = strsep(&options, ",");
if (!this_opt)
break;
if (!strncmp(this_opt, "custom", 6)) {
if (grvga_parse_custom(this_opt, &info->var) < 0) {
dev_err(&dev->dev, "Failed to parse custom mode (%s).\n", this_opt);
retval = -EINVAL;
goto free_fb;
}
} else if (!strncmp(this_opt, "addr", 4))
grvga_fix_addr = simple_strtoul(this_opt + 5, NULL, 16);
else if (!strncmp(this_opt, "size", 4))
grvga_mem_size = simple_strtoul(this_opt + 5, NULL, 0);
else
mode_opt = this_opt;
}
par = info->par;
info->fbops = &grvga_ops;
info->fix = grvga_fix;
info->pseudo_palette = par->color_palette;
info->flags = FBINFO_DEFAULT | FBINFO_PARTIAL_PAN_OK | FBINFO_HWACCEL_YPAN;
info->fix.smem_len = grvga_mem_size;
if (!devm_request_mem_region(&dev->dev, dev->resource[0].start,
resource_size(&dev->resource[0]), "grlib-svgactrl regs")) {
dev_err(&dev->dev, "registers already mapped\n");
retval = -EBUSY;
goto free_fb;
}
par->regs = of_ioremap(&dev->resource[0], 0,
resource_size(&dev->resource[0]),
"grlib-svgactrl regs");
if (!par->regs) {
dev_err(&dev->dev, "failed to map registers\n");
retval = -ENOMEM;
goto free_fb;
}
retval = fb_alloc_cmap(&info->cmap, 256, 0);
if (retval < 0) {
dev_err(&dev->dev, "failed to allocate mem with fb_alloc_cmap\n");
retval = -ENOMEM;
goto unmap_regs;
}
if (mode_opt) {
retval = fb_find_mode(&info->var, info, mode_opt,
grvga_modedb, sizeof(grvga_modedb), &grvga_modedb[0], 8);
if (!retval || retval == 4) {
retval = -EINVAL;
goto dealloc_cmap;
}
}
if (!grvga_mem_size)
grvga_mem_size = info->var.xres_virtual * info->var.yres_virtual * info->var.bits_per_pixel/8;
if (grvga_fix_addr) {
/* Got framebuffer base address from argument list */
physical_start = grvga_fix_addr;
if (!devm_request_mem_region(&dev->dev, physical_start,
grvga_mem_size, dev->name)) {
dev_err(&dev->dev, "failed to request memory region\n");
retval = -ENOMEM;
goto dealloc_cmap;
}
virtual_start = (unsigned long) ioremap(physical_start, grvga_mem_size);
if (!virtual_start) {
dev_err(&dev->dev, "error mapping framebuffer memory\n");
retval = -ENOMEM;
goto dealloc_cmap;
}
} else { /* Allocate frambuffer memory */
unsigned long page;
virtual_start = (unsigned long) __get_free_pages(GFP_DMA,
get_order(grvga_mem_size));
if (!virtual_start) {
dev_err(&dev->dev,
"unable to allocate framebuffer memory (%lu bytes)\n",
grvga_mem_size);
retval = -ENOMEM;
goto dealloc_cmap;
}
physical_start = dma_map_single(&dev->dev, (void *)virtual_start, grvga_mem_size, DMA_TO_DEVICE);
/* Set page reserved so that mmap will work. This is necessary
* since we'll be remapping normal memory.
*/
for (page = virtual_start;
page < PAGE_ALIGN(virtual_start + grvga_mem_size);
page += PAGE_SIZE) {
SetPageReserved(virt_to_page(page));
}
par->fb_alloced = 1;
}
memset((unsigned long *) virtual_start, 0, grvga_mem_size);
info->screen_base = (char __iomem *) virtual_start;
info->fix.smem_start = physical_start;
info->fix.smem_len = grvga_mem_size;
dev_set_drvdata(&dev->dev, info);
dev_info(&dev->dev,
"Aeroflex Gaisler framebuffer device (fb%d), %dx%d-%d, using %luK of video memory @ %p\n",
info->node, info->var.xres, info->var.yres, info->var.bits_per_pixel,
grvga_mem_size >> 10, info->screen_base);
retval = register_framebuffer(info);
if (retval < 0) {
dev_err(&dev->dev, "failed to register framebuffer\n");
goto free_mem;
}
__raw_writel(physical_start, &par->regs->fb_pos);
__raw_writel(__raw_readl(&par->regs->status) | 1, /* Enable framebuffer */
&par->regs->status);
return 0;
free_mem:
if (grvga_fix_addr)
iounmap((void *)virtual_start);
else
kfree((void *)virtual_start);
dealloc_cmap:
fb_dealloc_cmap(&info->cmap);
unmap_regs:
of_iounmap(&dev->resource[0], par->regs,
resource_size(&dev->resource[0]));
free_fb:
framebuffer_release(info);
return retval;
}
static int grvga_remove(struct platform_device *device)
{
struct fb_info *info = dev_get_drvdata(&device->dev);
struct grvga_par *par = info->par;
if (info) {
unregister_framebuffer(info);
fb_dealloc_cmap(&info->cmap);
of_iounmap(&device->resource[0], par->regs,
resource_size(&device->resource[0]));
if (!par->fb_alloced)
iounmap(info->screen_base);
else
kfree((void *)info->screen_base);
framebuffer_release(info);
}
return 0;
}
static struct of_device_id svgactrl_of_match[] = {
{
.name = "GAISLER_SVGACTRL",
},
{
.name = "01_063",
},
{},
};
MODULE_DEVICE_TABLE(of, svgactrl_of_match);
static struct platform_driver grvga_driver = {
.driver = {
.name = "grlib-svgactrl",
.owner = THIS_MODULE,
.of_match_table = svgactrl_of_match,
},
.probe = grvga_probe,
.remove = grvga_remove,
};
module_platform_driver(grvga_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Aeroflex Gaisler");
MODULE_DESCRIPTION("Aeroflex Gaisler framebuffer device driver");
| gpl-2.0 |
pengdonglin137/linux-4.4_tiny4412 | drivers/gpu/drm/exynos/exynos_drm_dpi.c | 363 | 8067 | /*
* Exynos DRM Parallel output support.
*
* Copyright (c) 2014 Samsung Electronics Co., Ltd
*
* Contacts: Andrzej Hajda <a.hajda@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <drm/drmP.h>
#include <drm/drm_crtc_helper.h>
#include <drm/drm_panel.h>
#include <drm/drm_atomic_helper.h>
#include <linux/regulator/consumer.h>
#include <video/of_videomode.h>
#include <video/videomode.h>
#include "exynos_drm_crtc.h"
struct exynos_dpi {
struct drm_encoder encoder;
struct device *dev;
struct device_node *panel_node;
struct drm_panel *panel;
struct drm_connector connector;
struct videomode *vm;
};
#define connector_to_dpi(c) container_of(c, struct exynos_dpi, connector)
static inline struct exynos_dpi *encoder_to_dpi(struct drm_encoder *e)
{
return container_of(e, struct exynos_dpi, encoder);
}
static enum drm_connector_status
exynos_dpi_detect(struct drm_connector *connector, bool force)
{
struct exynos_dpi *ctx = connector_to_dpi(connector);
if (ctx->panel && !ctx->panel->connector)
drm_panel_attach(ctx->panel, &ctx->connector);
return connector_status_connected;
}
static void exynos_dpi_connector_destroy(struct drm_connector *connector)
{
drm_connector_unregister(connector);
drm_connector_cleanup(connector);
}
static struct drm_connector_funcs exynos_dpi_connector_funcs = {
.dpms = drm_atomic_helper_connector_dpms,
.detect = exynos_dpi_detect,
.fill_modes = drm_helper_probe_single_connector_modes,
.destroy = exynos_dpi_connector_destroy,
.reset = drm_atomic_helper_connector_reset,
.atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state,
.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
};
static int exynos_dpi_get_modes(struct drm_connector *connector)
{
struct exynos_dpi *ctx = connector_to_dpi(connector);
/* fimd timings gets precedence over panel modes */
if (ctx->vm) {
struct drm_display_mode *mode;
mode = drm_mode_create(connector->dev);
if (!mode) {
DRM_ERROR("failed to create a new display mode\n");
return 0;
}
drm_display_mode_from_videomode(ctx->vm, mode);
mode->type = DRM_MODE_TYPE_DRIVER | DRM_MODE_TYPE_PREFERRED;
drm_mode_probed_add(connector, mode);
return 1;
}
if (ctx->panel)
return ctx->panel->funcs->get_modes(ctx->panel);
return 0;
}
static struct drm_encoder *
exynos_dpi_best_encoder(struct drm_connector *connector)
{
struct exynos_dpi *ctx = connector_to_dpi(connector);
return &ctx->encoder;
}
static struct drm_connector_helper_funcs exynos_dpi_connector_helper_funcs = {
.get_modes = exynos_dpi_get_modes,
.best_encoder = exynos_dpi_best_encoder,
};
static int exynos_dpi_create_connector(struct drm_encoder *encoder)
{
struct exynos_dpi *ctx = encoder_to_dpi(encoder);
struct drm_connector *connector = &ctx->connector;
int ret;
connector->polled = DRM_CONNECTOR_POLL_HPD;
ret = drm_connector_init(encoder->dev, connector,
&exynos_dpi_connector_funcs,
DRM_MODE_CONNECTOR_VGA);
if (ret) {
DRM_ERROR("failed to initialize connector with drm\n");
return ret;
}
drm_connector_helper_add(connector, &exynos_dpi_connector_helper_funcs);
drm_connector_register(connector);
drm_mode_connector_attach_encoder(connector, encoder);
return 0;
}
static bool exynos_dpi_mode_fixup(struct drm_encoder *encoder,
const struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
return true;
}
static void exynos_dpi_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
}
static void exynos_dpi_enable(struct drm_encoder *encoder)
{
struct exynos_dpi *ctx = encoder_to_dpi(encoder);
if (ctx->panel) {
drm_panel_prepare(ctx->panel);
drm_panel_enable(ctx->panel);
}
}
static void exynos_dpi_disable(struct drm_encoder *encoder)
{
struct exynos_dpi *ctx = encoder_to_dpi(encoder);
if (ctx->panel) {
drm_panel_disable(ctx->panel);
drm_panel_unprepare(ctx->panel);
}
}
static struct drm_encoder_helper_funcs exynos_dpi_encoder_helper_funcs = {
.mode_fixup = exynos_dpi_mode_fixup,
.mode_set = exynos_dpi_mode_set,
.enable = exynos_dpi_enable,
.disable = exynos_dpi_disable,
};
static struct drm_encoder_funcs exynos_dpi_encoder_funcs = {
.destroy = drm_encoder_cleanup,
};
/* of_* functions will be removed after merge of of_graph patches */
static struct device_node *
of_get_child_by_name_reg(struct device_node *parent, const char *name, u32 reg)
{
struct device_node *np;
for_each_child_of_node(parent, np) {
u32 r;
if (!np->name || of_node_cmp(np->name, name))
continue;
if (of_property_read_u32(np, "reg", &r) < 0)
r = 0;
if (reg == r)
break;
}
return np;
}
static struct device_node *of_graph_get_port_by_reg(struct device_node *parent,
u32 reg)
{
struct device_node *ports, *port;
ports = of_get_child_by_name(parent, "ports");
if (ports)
parent = ports;
port = of_get_child_by_name_reg(parent, "port", reg);
of_node_put(ports);
return port;
}
static struct device_node *
of_graph_get_endpoint_by_reg(struct device_node *port, u32 reg)
{
return of_get_child_by_name_reg(port, "endpoint", reg);
}
static struct device_node *
of_graph_get_remote_port_parent(const struct device_node *node)
{
struct device_node *np;
unsigned int depth;
np = of_parse_phandle(node, "remote-endpoint", 0);
/* Walk 3 levels up only if there is 'ports' node. */
for (depth = 3; depth && np; depth--) {
np = of_get_next_parent(np);
if (depth == 2 && of_node_cmp(np->name, "ports"))
break;
}
return np;
}
enum {
FIMD_PORT_IN0,
FIMD_PORT_IN1,
FIMD_PORT_IN2,
FIMD_PORT_RGB,
FIMD_PORT_WRB,
};
static struct device_node *exynos_dpi_of_find_panel_node(struct device *dev)
{
struct device_node *np, *ep;
np = of_graph_get_port_by_reg(dev->of_node, FIMD_PORT_RGB);
if (!np)
return NULL;
ep = of_graph_get_endpoint_by_reg(np, 0);
of_node_put(np);
if (!ep)
return NULL;
np = of_graph_get_remote_port_parent(ep);
of_node_put(ep);
return np;
}
static int exynos_dpi_parse_dt(struct exynos_dpi *ctx)
{
struct device *dev = ctx->dev;
struct device_node *dn = dev->of_node;
struct device_node *np;
ctx->panel_node = exynos_dpi_of_find_panel_node(dev);
np = of_get_child_by_name(dn, "display-timings");
if (np) {
struct videomode *vm;
int ret;
of_node_put(np);
vm = devm_kzalloc(dev, sizeof(*ctx->vm), GFP_KERNEL);
if (!vm)
return -ENOMEM;
ret = of_get_videomode(dn, vm, 0);
if (ret < 0) {
devm_kfree(dev, vm);
return ret;
}
ctx->vm = vm;
return 0;
}
if (!ctx->panel_node)
return -EINVAL;
return 0;
}
int exynos_dpi_bind(struct drm_device *dev, struct drm_encoder *encoder)
{
int ret;
ret = exynos_drm_crtc_get_pipe_from_type(dev, EXYNOS_DISPLAY_TYPE_LCD);
if (ret < 0)
return ret;
encoder->possible_crtcs = 1 << ret;
DRM_DEBUG_KMS("possible_crtcs = 0x%x\n", encoder->possible_crtcs);
drm_encoder_init(dev, encoder, &exynos_dpi_encoder_funcs,
DRM_MODE_ENCODER_TMDS);
drm_encoder_helper_add(encoder, &exynos_dpi_encoder_helper_funcs);
ret = exynos_dpi_create_connector(encoder);
if (ret) {
DRM_ERROR("failed to create connector ret = %d\n", ret);
drm_encoder_cleanup(encoder);
return ret;
}
return 0;
}
struct drm_encoder *exynos_dpi_probe(struct device *dev)
{
struct exynos_dpi *ctx;
int ret;
ctx = devm_kzalloc(dev, sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return ERR_PTR(-ENOMEM);
ctx->dev = dev;
ret = exynos_dpi_parse_dt(ctx);
if (ret < 0) {
devm_kfree(dev, ctx);
return NULL;
}
if (ctx->panel_node) {
ctx->panel = of_drm_find_panel(ctx->panel_node);
if (!ctx->panel)
return ERR_PTR(-EPROBE_DEFER);
}
return &ctx->encoder;
}
int exynos_dpi_remove(struct drm_encoder *encoder)
{
struct exynos_dpi *ctx = encoder_to_dpi(encoder);
exynos_dpi_disable(&ctx->encoder);
if (ctx->panel)
drm_panel_detach(ctx->panel);
return 0;
}
| gpl-2.0 |
FiveNinjas/linux | sound/soc/codecs/wm_hubs.c | 363 | 41999 | /*
* wm_hubs.c -- WM8993/4 common code
*
* Copyright 2009-12 Wolfson Microelectronics plc
*
* Author: Mark Brown <broonie@opensource.wolfsonmicro.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/moduleparam.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <linux/mfd/wm8994/registers.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>
#include "wm8993.h"
#include "wm_hubs.h"
const DECLARE_TLV_DB_SCALE(wm_hubs_spkmix_tlv, -300, 300, 0);
EXPORT_SYMBOL_GPL(wm_hubs_spkmix_tlv);
static const DECLARE_TLV_DB_SCALE(inpga_tlv, -1650, 150, 0);
static const DECLARE_TLV_DB_SCALE(inmix_sw_tlv, 0, 3000, 0);
static const DECLARE_TLV_DB_SCALE(inmix_tlv, -1500, 300, 1);
static const DECLARE_TLV_DB_SCALE(earpiece_tlv, -600, 600, 0);
static const DECLARE_TLV_DB_SCALE(outmix_tlv, -2100, 300, 0);
static const DECLARE_TLV_DB_SCALE(spkmixout_tlv, -1800, 600, 1);
static const DECLARE_TLV_DB_SCALE(outpga_tlv, -5700, 100, 0);
static const unsigned int spkboost_tlv[] = {
TLV_DB_RANGE_HEAD(2),
0, 6, TLV_DB_SCALE_ITEM(0, 150, 0),
7, 7, TLV_DB_SCALE_ITEM(1200, 0, 0),
};
static const DECLARE_TLV_DB_SCALE(line_tlv, -600, 600, 0);
static const char *speaker_ref_text[] = {
"SPKVDD/2",
"VMID",
};
static SOC_ENUM_SINGLE_DECL(speaker_ref,
WM8993_SPEAKER_MIXER, 8, speaker_ref_text);
static const char *speaker_mode_text[] = {
"Class D",
"Class AB",
};
static SOC_ENUM_SINGLE_DECL(speaker_mode,
WM8993_SPKMIXR_ATTENUATION, 8, speaker_mode_text);
static void wait_for_dc_servo(struct snd_soc_codec *codec, unsigned int op)
{
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
unsigned int reg;
int count = 0;
int timeout;
unsigned int val;
val = op | WM8993_DCS_ENA_CHAN_0 | WM8993_DCS_ENA_CHAN_1;
/* Trigger the command */
snd_soc_write(codec, WM8993_DC_SERVO_0, val);
dev_dbg(codec->dev, "Waiting for DC servo...\n");
if (hubs->dcs_done_irq)
timeout = 4;
else
timeout = 400;
do {
count++;
if (hubs->dcs_done_irq)
wait_for_completion_timeout(&hubs->dcs_done,
msecs_to_jiffies(250));
else
msleep(1);
reg = snd_soc_read(codec, WM8993_DC_SERVO_0);
dev_dbg(codec->dev, "DC servo: %x\n", reg);
} while (reg & op && count < timeout);
if (reg & op)
dev_err(codec->dev, "Timed out waiting for DC Servo %x\n",
op);
}
irqreturn_t wm_hubs_dcs_done(int irq, void *data)
{
struct wm_hubs_data *hubs = data;
complete(&hubs->dcs_done);
return IRQ_HANDLED;
}
EXPORT_SYMBOL_GPL(wm_hubs_dcs_done);
static bool wm_hubs_dac_hp_direct(struct snd_soc_codec *codec)
{
int reg;
/* If we're going via the mixer we'll need to do additional checks */
reg = snd_soc_read(codec, WM8993_OUTPUT_MIXER1);
if (!(reg & WM8993_DACL_TO_HPOUT1L)) {
if (reg & ~WM8993_DACL_TO_MIXOUTL) {
dev_vdbg(codec->dev, "Analogue paths connected: %x\n",
reg & ~WM8993_DACL_TO_HPOUT1L);
return false;
} else {
dev_vdbg(codec->dev, "HPL connected to mixer\n");
}
} else {
dev_vdbg(codec->dev, "HPL connected to DAC\n");
}
reg = snd_soc_read(codec, WM8993_OUTPUT_MIXER2);
if (!(reg & WM8993_DACR_TO_HPOUT1R)) {
if (reg & ~WM8993_DACR_TO_MIXOUTR) {
dev_vdbg(codec->dev, "Analogue paths connected: %x\n",
reg & ~WM8993_DACR_TO_HPOUT1R);
return false;
} else {
dev_vdbg(codec->dev, "HPR connected to mixer\n");
}
} else {
dev_vdbg(codec->dev, "HPR connected to DAC\n");
}
return true;
}
struct wm_hubs_dcs_cache {
struct list_head list;
unsigned int left;
unsigned int right;
u16 dcs_cfg;
};
static bool wm_hubs_dcs_cache_get(struct snd_soc_codec *codec,
struct wm_hubs_dcs_cache **entry)
{
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
struct wm_hubs_dcs_cache *cache;
unsigned int left, right;
left = snd_soc_read(codec, WM8993_LEFT_OUTPUT_VOLUME);
left &= WM8993_HPOUT1L_VOL_MASK;
right = snd_soc_read(codec, WM8993_RIGHT_OUTPUT_VOLUME);
right &= WM8993_HPOUT1R_VOL_MASK;
list_for_each_entry(cache, &hubs->dcs_cache, list) {
if (cache->left != left || cache->right != right)
continue;
*entry = cache;
return true;
}
return false;
}
static void wm_hubs_dcs_cache_set(struct snd_soc_codec *codec, u16 dcs_cfg)
{
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
struct wm_hubs_dcs_cache *cache;
if (hubs->no_cache_dac_hp_direct)
return;
cache = devm_kzalloc(codec->dev, sizeof(*cache), GFP_KERNEL);
if (!cache)
return;
cache->left = snd_soc_read(codec, WM8993_LEFT_OUTPUT_VOLUME);
cache->left &= WM8993_HPOUT1L_VOL_MASK;
cache->right = snd_soc_read(codec, WM8993_RIGHT_OUTPUT_VOLUME);
cache->right &= WM8993_HPOUT1R_VOL_MASK;
cache->dcs_cfg = dcs_cfg;
list_add_tail(&cache->list, &hubs->dcs_cache);
}
static int wm_hubs_read_dc_servo(struct snd_soc_codec *codec,
u16 *reg_l, u16 *reg_r)
{
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
u16 dcs_reg, reg;
int ret = 0;
switch (hubs->dcs_readback_mode) {
case 2:
dcs_reg = WM8994_DC_SERVO_4E;
break;
case 1:
dcs_reg = WM8994_DC_SERVO_READBACK;
break;
default:
dcs_reg = WM8993_DC_SERVO_3;
break;
}
/* Different chips in the family support different readback
* methods.
*/
switch (hubs->dcs_readback_mode) {
case 0:
*reg_l = snd_soc_read(codec, WM8993_DC_SERVO_READBACK_1)
& WM8993_DCS_INTEG_CHAN_0_MASK;
*reg_r = snd_soc_read(codec, WM8993_DC_SERVO_READBACK_2)
& WM8993_DCS_INTEG_CHAN_1_MASK;
break;
case 2:
case 1:
reg = snd_soc_read(codec, dcs_reg);
*reg_r = (reg & WM8993_DCS_DAC_WR_VAL_1_MASK)
>> WM8993_DCS_DAC_WR_VAL_1_SHIFT;
*reg_l = reg & WM8993_DCS_DAC_WR_VAL_0_MASK;
break;
default:
WARN(1, "Unknown DCS readback method\n");
ret = -1;
}
return ret;
}
/*
* Startup calibration of the DC servo
*/
static void enable_dc_servo(struct snd_soc_codec *codec)
{
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
struct wm_hubs_dcs_cache *cache;
s8 offset;
u16 reg_l, reg_r, dcs_cfg, dcs_reg;
switch (hubs->dcs_readback_mode) {
case 2:
dcs_reg = WM8994_DC_SERVO_4E;
break;
default:
dcs_reg = WM8993_DC_SERVO_3;
break;
}
/* If we're using a digital only path and have a previously
* callibrated DC servo offset stored then use that. */
if (wm_hubs_dac_hp_direct(codec) &&
wm_hubs_dcs_cache_get(codec, &cache)) {
dev_dbg(codec->dev, "Using cached DCS offset %x for %d,%d\n",
cache->dcs_cfg, cache->left, cache->right);
snd_soc_write(codec, dcs_reg, cache->dcs_cfg);
wait_for_dc_servo(codec,
WM8993_DCS_TRIG_DAC_WR_0 |
WM8993_DCS_TRIG_DAC_WR_1);
return;
}
if (hubs->series_startup) {
/* Set for 32 series updates */
snd_soc_update_bits(codec, WM8993_DC_SERVO_1,
WM8993_DCS_SERIES_NO_01_MASK,
32 << WM8993_DCS_SERIES_NO_01_SHIFT);
wait_for_dc_servo(codec,
WM8993_DCS_TRIG_SERIES_0 |
WM8993_DCS_TRIG_SERIES_1);
} else {
wait_for_dc_servo(codec,
WM8993_DCS_TRIG_STARTUP_0 |
WM8993_DCS_TRIG_STARTUP_1);
}
if (wm_hubs_read_dc_servo(codec, ®_l, ®_r) < 0)
return;
dev_dbg(codec->dev, "DCS input: %x %x\n", reg_l, reg_r);
/* Apply correction to DC servo result */
if (hubs->dcs_codes_l || hubs->dcs_codes_r) {
dev_dbg(codec->dev,
"Applying %d/%d code DC servo correction\n",
hubs->dcs_codes_l, hubs->dcs_codes_r);
/* HPOUT1R */
offset = (s8)reg_r;
dev_dbg(codec->dev, "DCS right %d->%d\n", offset,
offset + hubs->dcs_codes_r);
offset += hubs->dcs_codes_r;
dcs_cfg = (u8)offset << WM8993_DCS_DAC_WR_VAL_1_SHIFT;
/* HPOUT1L */
offset = (s8)reg_l;
dev_dbg(codec->dev, "DCS left %d->%d\n", offset,
offset + hubs->dcs_codes_l);
offset += hubs->dcs_codes_l;
dcs_cfg |= (u8)offset;
dev_dbg(codec->dev, "DCS result: %x\n", dcs_cfg);
/* Do it */
snd_soc_write(codec, dcs_reg, dcs_cfg);
wait_for_dc_servo(codec,
WM8993_DCS_TRIG_DAC_WR_0 |
WM8993_DCS_TRIG_DAC_WR_1);
} else {
dcs_cfg = reg_r << WM8993_DCS_DAC_WR_VAL_1_SHIFT;
dcs_cfg |= reg_l;
}
/* Save the callibrated offset if we're in class W mode and
* therefore don't have any analogue signal mixed in. */
if (wm_hubs_dac_hp_direct(codec))
wm_hubs_dcs_cache_set(codec, dcs_cfg);
}
/*
* Update the DC servo calibration on gain changes
*/
static int wm8993_put_dc_servo(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol);
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
int ret;
ret = snd_soc_put_volsw(kcontrol, ucontrol);
/* If we're applying an offset correction then updating the
* callibration would be likely to introduce further offsets. */
if (hubs->dcs_codes_l || hubs->dcs_codes_r || hubs->no_series_update)
return ret;
/* Only need to do this if the outputs are active */
if (snd_soc_read(codec, WM8993_POWER_MANAGEMENT_1)
& (WM8993_HPOUT1L_ENA | WM8993_HPOUT1R_ENA))
snd_soc_update_bits(codec,
WM8993_DC_SERVO_0,
WM8993_DCS_TRIG_SINGLE_0 |
WM8993_DCS_TRIG_SINGLE_1,
WM8993_DCS_TRIG_SINGLE_0 |
WM8993_DCS_TRIG_SINGLE_1);
return ret;
}
static const struct snd_kcontrol_new analogue_snd_controls[] = {
SOC_SINGLE_TLV("IN1L Volume", WM8993_LEFT_LINE_INPUT_1_2_VOLUME, 0, 31, 0,
inpga_tlv),
SOC_SINGLE("IN1L Switch", WM8993_LEFT_LINE_INPUT_1_2_VOLUME, 7, 1, 1),
SOC_SINGLE("IN1L ZC Switch", WM8993_LEFT_LINE_INPUT_1_2_VOLUME, 6, 1, 0),
SOC_SINGLE_TLV("IN1R Volume", WM8993_RIGHT_LINE_INPUT_1_2_VOLUME, 0, 31, 0,
inpga_tlv),
SOC_SINGLE("IN1R Switch", WM8993_RIGHT_LINE_INPUT_1_2_VOLUME, 7, 1, 1),
SOC_SINGLE("IN1R ZC Switch", WM8993_RIGHT_LINE_INPUT_1_2_VOLUME, 6, 1, 0),
SOC_SINGLE_TLV("IN2L Volume", WM8993_LEFT_LINE_INPUT_3_4_VOLUME, 0, 31, 0,
inpga_tlv),
SOC_SINGLE("IN2L Switch", WM8993_LEFT_LINE_INPUT_3_4_VOLUME, 7, 1, 1),
SOC_SINGLE("IN2L ZC Switch", WM8993_LEFT_LINE_INPUT_3_4_VOLUME, 6, 1, 0),
SOC_SINGLE_TLV("IN2R Volume", WM8993_RIGHT_LINE_INPUT_3_4_VOLUME, 0, 31, 0,
inpga_tlv),
SOC_SINGLE("IN2R Switch", WM8993_RIGHT_LINE_INPUT_3_4_VOLUME, 7, 1, 1),
SOC_SINGLE("IN2R ZC Switch", WM8993_RIGHT_LINE_INPUT_3_4_VOLUME, 6, 1, 0),
SOC_SINGLE_TLV("MIXINL IN2L Volume", WM8993_INPUT_MIXER3, 7, 1, 0,
inmix_sw_tlv),
SOC_SINGLE_TLV("MIXINL IN1L Volume", WM8993_INPUT_MIXER3, 4, 1, 0,
inmix_sw_tlv),
SOC_SINGLE_TLV("MIXINL Output Record Volume", WM8993_INPUT_MIXER3, 0, 7, 0,
inmix_tlv),
SOC_SINGLE_TLV("MIXINL IN1LP Volume", WM8993_INPUT_MIXER5, 6, 7, 0, inmix_tlv),
SOC_SINGLE_TLV("MIXINL Direct Voice Volume", WM8993_INPUT_MIXER5, 0, 6, 0,
inmix_tlv),
SOC_SINGLE_TLV("MIXINR IN2R Volume", WM8993_INPUT_MIXER4, 7, 1, 0,
inmix_sw_tlv),
SOC_SINGLE_TLV("MIXINR IN1R Volume", WM8993_INPUT_MIXER4, 4, 1, 0,
inmix_sw_tlv),
SOC_SINGLE_TLV("MIXINR Output Record Volume", WM8993_INPUT_MIXER4, 0, 7, 0,
inmix_tlv),
SOC_SINGLE_TLV("MIXINR IN1RP Volume", WM8993_INPUT_MIXER6, 6, 7, 0, inmix_tlv),
SOC_SINGLE_TLV("MIXINR Direct Voice Volume", WM8993_INPUT_MIXER6, 0, 6, 0,
inmix_tlv),
SOC_SINGLE_TLV("Left Output Mixer IN2RN Volume", WM8993_OUTPUT_MIXER5, 6, 7, 1,
outmix_tlv),
SOC_SINGLE_TLV("Left Output Mixer IN2LN Volume", WM8993_OUTPUT_MIXER3, 6, 7, 1,
outmix_tlv),
SOC_SINGLE_TLV("Left Output Mixer IN2LP Volume", WM8993_OUTPUT_MIXER3, 9, 7, 1,
outmix_tlv),
SOC_SINGLE_TLV("Left Output Mixer IN1L Volume", WM8993_OUTPUT_MIXER3, 0, 7, 1,
outmix_tlv),
SOC_SINGLE_TLV("Left Output Mixer IN1R Volume", WM8993_OUTPUT_MIXER3, 3, 7, 1,
outmix_tlv),
SOC_SINGLE_TLV("Left Output Mixer Right Input Volume",
WM8993_OUTPUT_MIXER5, 3, 7, 1, outmix_tlv),
SOC_SINGLE_TLV("Left Output Mixer Left Input Volume",
WM8993_OUTPUT_MIXER5, 0, 7, 1, outmix_tlv),
SOC_SINGLE_TLV("Left Output Mixer DAC Volume", WM8993_OUTPUT_MIXER5, 9, 7, 1,
outmix_tlv),
SOC_SINGLE_TLV("Right Output Mixer IN2LN Volume",
WM8993_OUTPUT_MIXER6, 6, 7, 1, outmix_tlv),
SOC_SINGLE_TLV("Right Output Mixer IN2RN Volume",
WM8993_OUTPUT_MIXER4, 6, 7, 1, outmix_tlv),
SOC_SINGLE_TLV("Right Output Mixer IN1L Volume",
WM8993_OUTPUT_MIXER4, 3, 7, 1, outmix_tlv),
SOC_SINGLE_TLV("Right Output Mixer IN1R Volume",
WM8993_OUTPUT_MIXER4, 0, 7, 1, outmix_tlv),
SOC_SINGLE_TLV("Right Output Mixer IN2RP Volume",
WM8993_OUTPUT_MIXER4, 9, 7, 1, outmix_tlv),
SOC_SINGLE_TLV("Right Output Mixer Left Input Volume",
WM8993_OUTPUT_MIXER6, 3, 7, 1, outmix_tlv),
SOC_SINGLE_TLV("Right Output Mixer Right Input Volume",
WM8993_OUTPUT_MIXER6, 6, 7, 1, outmix_tlv),
SOC_SINGLE_TLV("Right Output Mixer DAC Volume",
WM8993_OUTPUT_MIXER6, 9, 7, 1, outmix_tlv),
SOC_DOUBLE_R_TLV("Output Volume", WM8993_LEFT_OPGA_VOLUME,
WM8993_RIGHT_OPGA_VOLUME, 0, 63, 0, outpga_tlv),
SOC_DOUBLE_R("Output Switch", WM8993_LEFT_OPGA_VOLUME,
WM8993_RIGHT_OPGA_VOLUME, 6, 1, 0),
SOC_DOUBLE_R("Output ZC Switch", WM8993_LEFT_OPGA_VOLUME,
WM8993_RIGHT_OPGA_VOLUME, 7, 1, 0),
SOC_SINGLE("Earpiece Switch", WM8993_HPOUT2_VOLUME, 5, 1, 1),
SOC_SINGLE_TLV("Earpiece Volume", WM8993_HPOUT2_VOLUME, 4, 1, 1, earpiece_tlv),
SOC_SINGLE_TLV("SPKL Input Volume", WM8993_SPKMIXL_ATTENUATION,
5, 1, 1, wm_hubs_spkmix_tlv),
SOC_SINGLE_TLV("SPKL IN1LP Volume", WM8993_SPKMIXL_ATTENUATION,
4, 1, 1, wm_hubs_spkmix_tlv),
SOC_SINGLE_TLV("SPKL Output Volume", WM8993_SPKMIXL_ATTENUATION,
3, 1, 1, wm_hubs_spkmix_tlv),
SOC_SINGLE_TLV("SPKR Input Volume", WM8993_SPKMIXR_ATTENUATION,
5, 1, 1, wm_hubs_spkmix_tlv),
SOC_SINGLE_TLV("SPKR IN1RP Volume", WM8993_SPKMIXR_ATTENUATION,
4, 1, 1, wm_hubs_spkmix_tlv),
SOC_SINGLE_TLV("SPKR Output Volume", WM8993_SPKMIXR_ATTENUATION,
3, 1, 1, wm_hubs_spkmix_tlv),
SOC_DOUBLE_R_TLV("Speaker Mixer Volume",
WM8993_SPKMIXL_ATTENUATION, WM8993_SPKMIXR_ATTENUATION,
0, 3, 1, spkmixout_tlv),
SOC_DOUBLE_R_TLV("Speaker Volume",
WM8993_SPEAKER_VOLUME_LEFT, WM8993_SPEAKER_VOLUME_RIGHT,
0, 63, 0, outpga_tlv),
SOC_DOUBLE_R("Speaker Switch",
WM8993_SPEAKER_VOLUME_LEFT, WM8993_SPEAKER_VOLUME_RIGHT,
6, 1, 0),
SOC_DOUBLE_R("Speaker ZC Switch",
WM8993_SPEAKER_VOLUME_LEFT, WM8993_SPEAKER_VOLUME_RIGHT,
7, 1, 0),
SOC_DOUBLE_TLV("Speaker Boost Volume", WM8993_SPKOUT_BOOST, 3, 0, 7, 0,
spkboost_tlv),
SOC_ENUM("Speaker Reference", speaker_ref),
SOC_ENUM("Speaker Mode", speaker_mode),
SOC_DOUBLE_R_EXT_TLV("Headphone Volume",
WM8993_LEFT_OUTPUT_VOLUME, WM8993_RIGHT_OUTPUT_VOLUME,
0, 63, 0, snd_soc_get_volsw, wm8993_put_dc_servo,
outpga_tlv),
SOC_DOUBLE_R("Headphone Switch", WM8993_LEFT_OUTPUT_VOLUME,
WM8993_RIGHT_OUTPUT_VOLUME, 6, 1, 0),
SOC_DOUBLE_R("Headphone ZC Switch", WM8993_LEFT_OUTPUT_VOLUME,
WM8993_RIGHT_OUTPUT_VOLUME, 7, 1, 0),
SOC_SINGLE("LINEOUT1N Switch", WM8993_LINE_OUTPUTS_VOLUME, 6, 1, 1),
SOC_SINGLE("LINEOUT1P Switch", WM8993_LINE_OUTPUTS_VOLUME, 5, 1, 1),
SOC_SINGLE_TLV("LINEOUT1 Volume", WM8993_LINE_OUTPUTS_VOLUME, 4, 1, 1,
line_tlv),
SOC_SINGLE("LINEOUT2N Switch", WM8993_LINE_OUTPUTS_VOLUME, 2, 1, 1),
SOC_SINGLE("LINEOUT2P Switch", WM8993_LINE_OUTPUTS_VOLUME, 1, 1, 1),
SOC_SINGLE_TLV("LINEOUT2 Volume", WM8993_LINE_OUTPUTS_VOLUME, 0, 1, 1,
line_tlv),
};
static int hp_supply_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = snd_soc_dapm_to_codec(w->dapm);
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
switch (hubs->hp_startup_mode) {
case 0:
break;
case 1:
/* Enable the headphone amp */
snd_soc_update_bits(codec, WM8993_POWER_MANAGEMENT_1,
WM8993_HPOUT1L_ENA |
WM8993_HPOUT1R_ENA,
WM8993_HPOUT1L_ENA |
WM8993_HPOUT1R_ENA);
/* Enable the second stage */
snd_soc_update_bits(codec, WM8993_ANALOGUE_HP_0,
WM8993_HPOUT1L_DLY |
WM8993_HPOUT1R_DLY,
WM8993_HPOUT1L_DLY |
WM8993_HPOUT1R_DLY);
break;
default:
dev_err(codec->dev, "Unknown HP startup mode %d\n",
hubs->hp_startup_mode);
break;
}
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, WM8993_CHARGE_PUMP_1,
WM8993_CP_ENA, 0);
break;
}
return 0;
}
static int hp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = snd_soc_dapm_to_codec(w->dapm);
unsigned int reg = snd_soc_read(codec, WM8993_ANALOGUE_HP_0);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
snd_soc_update_bits(codec, WM8993_CHARGE_PUMP_1,
WM8993_CP_ENA, WM8993_CP_ENA);
msleep(5);
snd_soc_update_bits(codec, WM8993_POWER_MANAGEMENT_1,
WM8993_HPOUT1L_ENA | WM8993_HPOUT1R_ENA,
WM8993_HPOUT1L_ENA | WM8993_HPOUT1R_ENA);
reg |= WM8993_HPOUT1L_DLY | WM8993_HPOUT1R_DLY;
snd_soc_write(codec, WM8993_ANALOGUE_HP_0, reg);
snd_soc_update_bits(codec, WM8993_DC_SERVO_1,
WM8993_DCS_TIMER_PERIOD_01_MASK, 0);
enable_dc_servo(codec);
reg |= WM8993_HPOUT1R_OUTP | WM8993_HPOUT1R_RMV_SHORT |
WM8993_HPOUT1L_OUTP | WM8993_HPOUT1L_RMV_SHORT;
snd_soc_write(codec, WM8993_ANALOGUE_HP_0, reg);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, WM8993_ANALOGUE_HP_0,
WM8993_HPOUT1L_OUTP |
WM8993_HPOUT1R_OUTP |
WM8993_HPOUT1L_RMV_SHORT |
WM8993_HPOUT1R_RMV_SHORT, 0);
snd_soc_update_bits(codec, WM8993_ANALOGUE_HP_0,
WM8993_HPOUT1L_DLY |
WM8993_HPOUT1R_DLY, 0);
snd_soc_write(codec, WM8993_DC_SERVO_0, 0);
snd_soc_update_bits(codec, WM8993_POWER_MANAGEMENT_1,
WM8993_HPOUT1L_ENA | WM8993_HPOUT1R_ENA,
0);
break;
}
return 0;
}
static int earpiece_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *control, int event)
{
struct snd_soc_codec *codec = snd_soc_dapm_to_codec(w->dapm);
u16 reg = snd_soc_read(codec, WM8993_ANTIPOP1) & ~WM8993_HPOUT2_IN_ENA;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
reg |= WM8993_HPOUT2_IN_ENA;
snd_soc_write(codec, WM8993_ANTIPOP1, reg);
udelay(50);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_write(codec, WM8993_ANTIPOP1, reg);
break;
default:
WARN(1, "Invalid event %d\n", event);
break;
}
return 0;
}
static int lineout_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *control, int event)
{
struct snd_soc_codec *codec = snd_soc_dapm_to_codec(w->dapm);
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
bool *flag;
switch (w->shift) {
case WM8993_LINEOUT1N_ENA_SHIFT:
flag = &hubs->lineout1n_ena;
break;
case WM8993_LINEOUT1P_ENA_SHIFT:
flag = &hubs->lineout1p_ena;
break;
case WM8993_LINEOUT2N_ENA_SHIFT:
flag = &hubs->lineout2n_ena;
break;
case WM8993_LINEOUT2P_ENA_SHIFT:
flag = &hubs->lineout2p_ena;
break;
default:
WARN(1, "Unknown line output");
return -EINVAL;
}
*flag = SND_SOC_DAPM_EVENT_ON(event);
return 0;
}
static int micbias_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = snd_soc_dapm_to_codec(w->dapm);
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
switch (w->shift) {
case WM8993_MICB1_ENA_SHIFT:
if (hubs->micb1_delay)
msleep(hubs->micb1_delay);
break;
case WM8993_MICB2_ENA_SHIFT:
if (hubs->micb2_delay)
msleep(hubs->micb2_delay);
break;
default:
return -EINVAL;
}
return 0;
}
void wm_hubs_update_class_w(struct snd_soc_codec *codec)
{
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
int enable = WM8993_CP_DYN_V | WM8993_CP_DYN_FREQ;
if (!wm_hubs_dac_hp_direct(codec))
enable = false;
if (hubs->check_class_w_digital && !hubs->check_class_w_digital(codec))
enable = false;
dev_vdbg(codec->dev, "Class W %s\n", enable ? "enabled" : "disabled");
snd_soc_update_bits(codec, WM8993_CLASS_W_0,
WM8993_CP_DYN_V | WM8993_CP_DYN_FREQ, enable);
snd_soc_write(codec, WM8993_LEFT_OUTPUT_VOLUME,
snd_soc_read(codec, WM8993_LEFT_OUTPUT_VOLUME));
snd_soc_write(codec, WM8993_RIGHT_OUTPUT_VOLUME,
snd_soc_read(codec, WM8993_RIGHT_OUTPUT_VOLUME));
}
EXPORT_SYMBOL_GPL(wm_hubs_update_class_w);
#define WM_HUBS_SINGLE_W(xname, reg, shift, max, invert) \
SOC_SINGLE_EXT(xname, reg, shift, max, invert, \
snd_soc_dapm_get_volsw, class_w_put_volsw)
static int class_w_put_volsw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_soc_dapm_kcontrol_codec(kcontrol);
int ret;
ret = snd_soc_dapm_put_volsw(kcontrol, ucontrol);
wm_hubs_update_class_w(codec);
return ret;
}
#define WM_HUBS_ENUM_W(xname, xenum) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_soc_info_enum_double, \
.get = snd_soc_dapm_get_enum_double, \
.put = class_w_put_double, \
.private_value = (unsigned long)&xenum }
static int class_w_put_double(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_soc_dapm_kcontrol_codec(kcontrol);
int ret;
ret = snd_soc_dapm_put_enum_double(kcontrol, ucontrol);
wm_hubs_update_class_w(codec);
return ret;
}
static const char *hp_mux_text[] = {
"Mixer",
"DAC",
};
static SOC_ENUM_SINGLE_DECL(hpl_enum,
WM8993_OUTPUT_MIXER1, 8, hp_mux_text);
const struct snd_kcontrol_new wm_hubs_hpl_mux =
WM_HUBS_ENUM_W("Left Headphone Mux", hpl_enum);
EXPORT_SYMBOL_GPL(wm_hubs_hpl_mux);
static SOC_ENUM_SINGLE_DECL(hpr_enum,
WM8993_OUTPUT_MIXER2, 8, hp_mux_text);
const struct snd_kcontrol_new wm_hubs_hpr_mux =
WM_HUBS_ENUM_W("Right Headphone Mux", hpr_enum);
EXPORT_SYMBOL_GPL(wm_hubs_hpr_mux);
static const struct snd_kcontrol_new in1l_pga[] = {
SOC_DAPM_SINGLE("IN1LP Switch", WM8993_INPUT_MIXER2, 5, 1, 0),
SOC_DAPM_SINGLE("IN1LN Switch", WM8993_INPUT_MIXER2, 4, 1, 0),
};
static const struct snd_kcontrol_new in1r_pga[] = {
SOC_DAPM_SINGLE("IN1RP Switch", WM8993_INPUT_MIXER2, 1, 1, 0),
SOC_DAPM_SINGLE("IN1RN Switch", WM8993_INPUT_MIXER2, 0, 1, 0),
};
static const struct snd_kcontrol_new in2l_pga[] = {
SOC_DAPM_SINGLE("IN2LP Switch", WM8993_INPUT_MIXER2, 7, 1, 0),
SOC_DAPM_SINGLE("IN2LN Switch", WM8993_INPUT_MIXER2, 6, 1, 0),
};
static const struct snd_kcontrol_new in2r_pga[] = {
SOC_DAPM_SINGLE("IN2RP Switch", WM8993_INPUT_MIXER2, 3, 1, 0),
SOC_DAPM_SINGLE("IN2RN Switch", WM8993_INPUT_MIXER2, 2, 1, 0),
};
static const struct snd_kcontrol_new mixinl[] = {
SOC_DAPM_SINGLE("IN2L Switch", WM8993_INPUT_MIXER3, 8, 1, 0),
SOC_DAPM_SINGLE("IN1L Switch", WM8993_INPUT_MIXER3, 5, 1, 0),
};
static const struct snd_kcontrol_new mixinr[] = {
SOC_DAPM_SINGLE("IN2R Switch", WM8993_INPUT_MIXER4, 8, 1, 0),
SOC_DAPM_SINGLE("IN1R Switch", WM8993_INPUT_MIXER4, 5, 1, 0),
};
static const struct snd_kcontrol_new left_output_mixer[] = {
WM_HUBS_SINGLE_W("Right Input Switch", WM8993_OUTPUT_MIXER1, 7, 1, 0),
WM_HUBS_SINGLE_W("Left Input Switch", WM8993_OUTPUT_MIXER1, 6, 1, 0),
WM_HUBS_SINGLE_W("IN2RN Switch", WM8993_OUTPUT_MIXER1, 5, 1, 0),
WM_HUBS_SINGLE_W("IN2LN Switch", WM8993_OUTPUT_MIXER1, 4, 1, 0),
WM_HUBS_SINGLE_W("IN2LP Switch", WM8993_OUTPUT_MIXER1, 1, 1, 0),
WM_HUBS_SINGLE_W("IN1R Switch", WM8993_OUTPUT_MIXER1, 3, 1, 0),
WM_HUBS_SINGLE_W("IN1L Switch", WM8993_OUTPUT_MIXER1, 2, 1, 0),
WM_HUBS_SINGLE_W("DAC Switch", WM8993_OUTPUT_MIXER1, 0, 1, 0),
};
static const struct snd_kcontrol_new right_output_mixer[] = {
WM_HUBS_SINGLE_W("Left Input Switch", WM8993_OUTPUT_MIXER2, 7, 1, 0),
WM_HUBS_SINGLE_W("Right Input Switch", WM8993_OUTPUT_MIXER2, 6, 1, 0),
WM_HUBS_SINGLE_W("IN2LN Switch", WM8993_OUTPUT_MIXER2, 5, 1, 0),
WM_HUBS_SINGLE_W("IN2RN Switch", WM8993_OUTPUT_MIXER2, 4, 1, 0),
WM_HUBS_SINGLE_W("IN1L Switch", WM8993_OUTPUT_MIXER2, 3, 1, 0),
WM_HUBS_SINGLE_W("IN1R Switch", WM8993_OUTPUT_MIXER2, 2, 1, 0),
WM_HUBS_SINGLE_W("IN2RP Switch", WM8993_OUTPUT_MIXER2, 1, 1, 0),
WM_HUBS_SINGLE_W("DAC Switch", WM8993_OUTPUT_MIXER2, 0, 1, 0),
};
static const struct snd_kcontrol_new earpiece_mixer[] = {
SOC_DAPM_SINGLE("Direct Voice Switch", WM8993_HPOUT2_MIXER, 5, 1, 0),
SOC_DAPM_SINGLE("Left Output Switch", WM8993_HPOUT2_MIXER, 4, 1, 0),
SOC_DAPM_SINGLE("Right Output Switch", WM8993_HPOUT2_MIXER, 3, 1, 0),
};
static const struct snd_kcontrol_new left_speaker_boost[] = {
SOC_DAPM_SINGLE("Direct Voice Switch", WM8993_SPKOUT_MIXERS, 5, 1, 0),
SOC_DAPM_SINGLE("SPKL Switch", WM8993_SPKOUT_MIXERS, 4, 1, 0),
SOC_DAPM_SINGLE("SPKR Switch", WM8993_SPKOUT_MIXERS, 3, 1, 0),
};
static const struct snd_kcontrol_new right_speaker_boost[] = {
SOC_DAPM_SINGLE("Direct Voice Switch", WM8993_SPKOUT_MIXERS, 2, 1, 0),
SOC_DAPM_SINGLE("SPKL Switch", WM8993_SPKOUT_MIXERS, 1, 1, 0),
SOC_DAPM_SINGLE("SPKR Switch", WM8993_SPKOUT_MIXERS, 0, 1, 0),
};
static const struct snd_kcontrol_new line1_mix[] = {
SOC_DAPM_SINGLE("IN1R Switch", WM8993_LINE_MIXER1, 2, 1, 0),
SOC_DAPM_SINGLE("IN1L Switch", WM8993_LINE_MIXER1, 1, 1, 0),
SOC_DAPM_SINGLE("Output Switch", WM8993_LINE_MIXER1, 0, 1, 0),
};
static const struct snd_kcontrol_new line1n_mix[] = {
SOC_DAPM_SINGLE("Left Output Switch", WM8993_LINE_MIXER1, 6, 1, 0),
SOC_DAPM_SINGLE("Right Output Switch", WM8993_LINE_MIXER1, 5, 1, 0),
};
static const struct snd_kcontrol_new line1p_mix[] = {
SOC_DAPM_SINGLE("Left Output Switch", WM8993_LINE_MIXER1, 0, 1, 0),
};
static const struct snd_kcontrol_new line2_mix[] = {
SOC_DAPM_SINGLE("IN1L Switch", WM8993_LINE_MIXER2, 2, 1, 0),
SOC_DAPM_SINGLE("IN1R Switch", WM8993_LINE_MIXER2, 1, 1, 0),
SOC_DAPM_SINGLE("Output Switch", WM8993_LINE_MIXER2, 0, 1, 0),
};
static const struct snd_kcontrol_new line2n_mix[] = {
SOC_DAPM_SINGLE("Left Output Switch", WM8993_LINE_MIXER2, 5, 1, 0),
SOC_DAPM_SINGLE("Right Output Switch", WM8993_LINE_MIXER2, 6, 1, 0),
};
static const struct snd_kcontrol_new line2p_mix[] = {
SOC_DAPM_SINGLE("Right Output Switch", WM8993_LINE_MIXER2, 0, 1, 0),
};
static const struct snd_soc_dapm_widget analogue_dapm_widgets[] = {
SND_SOC_DAPM_INPUT("IN1LN"),
SND_SOC_DAPM_INPUT("IN1LP"),
SND_SOC_DAPM_INPUT("IN2LN"),
SND_SOC_DAPM_INPUT("IN2LP:VXRN"),
SND_SOC_DAPM_INPUT("IN1RN"),
SND_SOC_DAPM_INPUT("IN1RP"),
SND_SOC_DAPM_INPUT("IN2RN"),
SND_SOC_DAPM_INPUT("IN2RP:VXRP"),
SND_SOC_DAPM_SUPPLY("MICBIAS2", WM8993_POWER_MANAGEMENT_1, 5, 0,
micbias_event, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_SUPPLY("MICBIAS1", WM8993_POWER_MANAGEMENT_1, 4, 0,
micbias_event, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER("IN1L PGA", WM8993_POWER_MANAGEMENT_2, 6, 0,
in1l_pga, ARRAY_SIZE(in1l_pga)),
SND_SOC_DAPM_MIXER("IN1R PGA", WM8993_POWER_MANAGEMENT_2, 4, 0,
in1r_pga, ARRAY_SIZE(in1r_pga)),
SND_SOC_DAPM_MIXER("IN2L PGA", WM8993_POWER_MANAGEMENT_2, 7, 0,
in2l_pga, ARRAY_SIZE(in2l_pga)),
SND_SOC_DAPM_MIXER("IN2R PGA", WM8993_POWER_MANAGEMENT_2, 5, 0,
in2r_pga, ARRAY_SIZE(in2r_pga)),
SND_SOC_DAPM_MIXER("MIXINL", WM8993_POWER_MANAGEMENT_2, 9, 0,
mixinl, ARRAY_SIZE(mixinl)),
SND_SOC_DAPM_MIXER("MIXINR", WM8993_POWER_MANAGEMENT_2, 8, 0,
mixinr, ARRAY_SIZE(mixinr)),
SND_SOC_DAPM_MIXER("Left Output Mixer", WM8993_POWER_MANAGEMENT_3, 5, 0,
left_output_mixer, ARRAY_SIZE(left_output_mixer)),
SND_SOC_DAPM_MIXER("Right Output Mixer", WM8993_POWER_MANAGEMENT_3, 4, 0,
right_output_mixer, ARRAY_SIZE(right_output_mixer)),
SND_SOC_DAPM_PGA("Left Output PGA", WM8993_POWER_MANAGEMENT_3, 7, 0, NULL, 0),
SND_SOC_DAPM_PGA("Right Output PGA", WM8993_POWER_MANAGEMENT_3, 6, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("Headphone Supply", SND_SOC_NOPM, 0, 0, hp_supply_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_OUT_DRV_E("Headphone PGA", SND_SOC_NOPM, 0, 0, NULL, 0,
hp_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_MIXER("Earpiece Mixer", SND_SOC_NOPM, 0, 0,
earpiece_mixer, ARRAY_SIZE(earpiece_mixer)),
SND_SOC_DAPM_PGA_E("Earpiece Driver", WM8993_POWER_MANAGEMENT_1, 11, 0,
NULL, 0, earpiece_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MIXER("SPKL Boost", SND_SOC_NOPM, 0, 0,
left_speaker_boost, ARRAY_SIZE(left_speaker_boost)),
SND_SOC_DAPM_MIXER("SPKR Boost", SND_SOC_NOPM, 0, 0,
right_speaker_boost, ARRAY_SIZE(right_speaker_boost)),
SND_SOC_DAPM_SUPPLY("TSHUT", WM8993_POWER_MANAGEMENT_2, 14, 0, NULL, 0),
SND_SOC_DAPM_OUT_DRV("SPKL Driver", WM8993_POWER_MANAGEMENT_1, 12, 0,
NULL, 0),
SND_SOC_DAPM_OUT_DRV("SPKR Driver", WM8993_POWER_MANAGEMENT_1, 13, 0,
NULL, 0),
SND_SOC_DAPM_MIXER("LINEOUT1 Mixer", SND_SOC_NOPM, 0, 0,
line1_mix, ARRAY_SIZE(line1_mix)),
SND_SOC_DAPM_MIXER("LINEOUT2 Mixer", SND_SOC_NOPM, 0, 0,
line2_mix, ARRAY_SIZE(line2_mix)),
SND_SOC_DAPM_MIXER("LINEOUT1N Mixer", SND_SOC_NOPM, 0, 0,
line1n_mix, ARRAY_SIZE(line1n_mix)),
SND_SOC_DAPM_MIXER("LINEOUT1P Mixer", SND_SOC_NOPM, 0, 0,
line1p_mix, ARRAY_SIZE(line1p_mix)),
SND_SOC_DAPM_MIXER("LINEOUT2N Mixer", SND_SOC_NOPM, 0, 0,
line2n_mix, ARRAY_SIZE(line2n_mix)),
SND_SOC_DAPM_MIXER("LINEOUT2P Mixer", SND_SOC_NOPM, 0, 0,
line2p_mix, ARRAY_SIZE(line2p_mix)),
SND_SOC_DAPM_OUT_DRV_E("LINEOUT1N Driver", WM8993_POWER_MANAGEMENT_3, 13, 0,
NULL, 0, lineout_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_OUT_DRV_E("LINEOUT1P Driver", WM8993_POWER_MANAGEMENT_3, 12, 0,
NULL, 0, lineout_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_OUT_DRV_E("LINEOUT2N Driver", WM8993_POWER_MANAGEMENT_3, 11, 0,
NULL, 0, lineout_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_OUT_DRV_E("LINEOUT2P Driver", WM8993_POWER_MANAGEMENT_3, 10, 0,
NULL, 0, lineout_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_OUTPUT("SPKOUTLP"),
SND_SOC_DAPM_OUTPUT("SPKOUTLN"),
SND_SOC_DAPM_OUTPUT("SPKOUTRP"),
SND_SOC_DAPM_OUTPUT("SPKOUTRN"),
SND_SOC_DAPM_OUTPUT("HPOUT1L"),
SND_SOC_DAPM_OUTPUT("HPOUT1R"),
SND_SOC_DAPM_OUTPUT("HPOUT2P"),
SND_SOC_DAPM_OUTPUT("HPOUT2N"),
SND_SOC_DAPM_OUTPUT("LINEOUT1P"),
SND_SOC_DAPM_OUTPUT("LINEOUT1N"),
SND_SOC_DAPM_OUTPUT("LINEOUT2P"),
SND_SOC_DAPM_OUTPUT("LINEOUT2N"),
};
static const struct snd_soc_dapm_route analogue_routes[] = {
{ "MICBIAS1", NULL, "CLK_SYS" },
{ "MICBIAS2", NULL, "CLK_SYS" },
{ "IN1L PGA", "IN1LP Switch", "IN1LP" },
{ "IN1L PGA", "IN1LN Switch", "IN1LN" },
{ "IN1L PGA", NULL, "VMID" },
{ "IN1R PGA", NULL, "VMID" },
{ "IN2L PGA", NULL, "VMID" },
{ "IN2R PGA", NULL, "VMID" },
{ "IN1R PGA", "IN1RP Switch", "IN1RP" },
{ "IN1R PGA", "IN1RN Switch", "IN1RN" },
{ "IN2L PGA", "IN2LP Switch", "IN2LP:VXRN" },
{ "IN2L PGA", "IN2LN Switch", "IN2LN" },
{ "IN2R PGA", "IN2RP Switch", "IN2RP:VXRP" },
{ "IN2R PGA", "IN2RN Switch", "IN2RN" },
{ "Direct Voice", NULL, "IN2LP:VXRN" },
{ "Direct Voice", NULL, "IN2RP:VXRP" },
{ "MIXINL", "IN1L Switch", "IN1L PGA" },
{ "MIXINL", "IN2L Switch", "IN2L PGA" },
{ "MIXINL", NULL, "Direct Voice" },
{ "MIXINL", NULL, "IN1LP" },
{ "MIXINL", NULL, "Left Output Mixer" },
{ "MIXINL", NULL, "VMID" },
{ "MIXINR", "IN1R Switch", "IN1R PGA" },
{ "MIXINR", "IN2R Switch", "IN2R PGA" },
{ "MIXINR", NULL, "Direct Voice" },
{ "MIXINR", NULL, "IN1RP" },
{ "MIXINR", NULL, "Right Output Mixer" },
{ "MIXINR", NULL, "VMID" },
{ "ADCL", NULL, "MIXINL" },
{ "ADCR", NULL, "MIXINR" },
{ "Left Output Mixer", "Left Input Switch", "MIXINL" },
{ "Left Output Mixer", "Right Input Switch", "MIXINR" },
{ "Left Output Mixer", "IN2RN Switch", "IN2RN" },
{ "Left Output Mixer", "IN2LN Switch", "IN2LN" },
{ "Left Output Mixer", "IN2LP Switch", "IN2LP:VXRN" },
{ "Left Output Mixer", "IN1L Switch", "IN1L PGA" },
{ "Left Output Mixer", "IN1R Switch", "IN1R PGA" },
{ "Right Output Mixer", "Left Input Switch", "MIXINL" },
{ "Right Output Mixer", "Right Input Switch", "MIXINR" },
{ "Right Output Mixer", "IN2LN Switch", "IN2LN" },
{ "Right Output Mixer", "IN2RN Switch", "IN2RN" },
{ "Right Output Mixer", "IN2RP Switch", "IN2RP:VXRP" },
{ "Right Output Mixer", "IN1L Switch", "IN1L PGA" },
{ "Right Output Mixer", "IN1R Switch", "IN1R PGA" },
{ "Left Output PGA", NULL, "Left Output Mixer" },
{ "Left Output PGA", NULL, "TOCLK" },
{ "Right Output PGA", NULL, "Right Output Mixer" },
{ "Right Output PGA", NULL, "TOCLK" },
{ "Earpiece Mixer", "Direct Voice Switch", "Direct Voice" },
{ "Earpiece Mixer", "Left Output Switch", "Left Output PGA" },
{ "Earpiece Mixer", "Right Output Switch", "Right Output PGA" },
{ "Earpiece Driver", NULL, "VMID" },
{ "Earpiece Driver", NULL, "Earpiece Mixer" },
{ "HPOUT2N", NULL, "Earpiece Driver" },
{ "HPOUT2P", NULL, "Earpiece Driver" },
{ "SPKL", "Input Switch", "MIXINL" },
{ "SPKL", "IN1LP Switch", "IN1LP" },
{ "SPKL", "Output Switch", "Left Output PGA" },
{ "SPKL", NULL, "TOCLK" },
{ "SPKR", "Input Switch", "MIXINR" },
{ "SPKR", "IN1RP Switch", "IN1RP" },
{ "SPKR", "Output Switch", "Right Output PGA" },
{ "SPKR", NULL, "TOCLK" },
{ "SPKL Boost", "Direct Voice Switch", "Direct Voice" },
{ "SPKL Boost", "SPKL Switch", "SPKL" },
{ "SPKL Boost", "SPKR Switch", "SPKR" },
{ "SPKR Boost", "Direct Voice Switch", "Direct Voice" },
{ "SPKR Boost", "SPKR Switch", "SPKR" },
{ "SPKR Boost", "SPKL Switch", "SPKL" },
{ "SPKL Driver", NULL, "VMID" },
{ "SPKL Driver", NULL, "SPKL Boost" },
{ "SPKL Driver", NULL, "CLK_SYS" },
{ "SPKL Driver", NULL, "TSHUT" },
{ "SPKR Driver", NULL, "VMID" },
{ "SPKR Driver", NULL, "SPKR Boost" },
{ "SPKR Driver", NULL, "CLK_SYS" },
{ "SPKR Driver", NULL, "TSHUT" },
{ "SPKOUTLP", NULL, "SPKL Driver" },
{ "SPKOUTLN", NULL, "SPKL Driver" },
{ "SPKOUTRP", NULL, "SPKR Driver" },
{ "SPKOUTRN", NULL, "SPKR Driver" },
{ "Left Headphone Mux", "Mixer", "Left Output PGA" },
{ "Right Headphone Mux", "Mixer", "Right Output PGA" },
{ "Headphone PGA", NULL, "Left Headphone Mux" },
{ "Headphone PGA", NULL, "Right Headphone Mux" },
{ "Headphone PGA", NULL, "VMID" },
{ "Headphone PGA", NULL, "CLK_SYS" },
{ "Headphone PGA", NULL, "Headphone Supply" },
{ "HPOUT1L", NULL, "Headphone PGA" },
{ "HPOUT1R", NULL, "Headphone PGA" },
{ "LINEOUT1N Driver", NULL, "VMID" },
{ "LINEOUT1P Driver", NULL, "VMID" },
{ "LINEOUT2N Driver", NULL, "VMID" },
{ "LINEOUT2P Driver", NULL, "VMID" },
{ "LINEOUT1N", NULL, "LINEOUT1N Driver" },
{ "LINEOUT1P", NULL, "LINEOUT1P Driver" },
{ "LINEOUT2N", NULL, "LINEOUT2N Driver" },
{ "LINEOUT2P", NULL, "LINEOUT2P Driver" },
};
static const struct snd_soc_dapm_route lineout1_diff_routes[] = {
{ "LINEOUT1 Mixer", "IN1L Switch", "IN1L PGA" },
{ "LINEOUT1 Mixer", "IN1R Switch", "IN1R PGA" },
{ "LINEOUT1 Mixer", "Output Switch", "Left Output PGA" },
{ "LINEOUT1N Driver", NULL, "LINEOUT1 Mixer" },
{ "LINEOUT1P Driver", NULL, "LINEOUT1 Mixer" },
};
static const struct snd_soc_dapm_route lineout1_se_routes[] = {
{ "LINEOUT1N Mixer", "Left Output Switch", "Left Output PGA" },
{ "LINEOUT1N Mixer", "Right Output Switch", "Right Output PGA" },
{ "LINEOUT1P Mixer", "Left Output Switch", "Left Output PGA" },
{ "LINEOUT1N Driver", NULL, "LINEOUT1N Mixer" },
{ "LINEOUT1P Driver", NULL, "LINEOUT1P Mixer" },
};
static const struct snd_soc_dapm_route lineout2_diff_routes[] = {
{ "LINEOUT2 Mixer", "IN1L Switch", "IN1L PGA" },
{ "LINEOUT2 Mixer", "IN1R Switch", "IN1R PGA" },
{ "LINEOUT2 Mixer", "Output Switch", "Right Output PGA" },
{ "LINEOUT2N Driver", NULL, "LINEOUT2 Mixer" },
{ "LINEOUT2P Driver", NULL, "LINEOUT2 Mixer" },
};
static const struct snd_soc_dapm_route lineout2_se_routes[] = {
{ "LINEOUT2N Mixer", "Left Output Switch", "Left Output PGA" },
{ "LINEOUT2N Mixer", "Right Output Switch", "Right Output PGA" },
{ "LINEOUT2P Mixer", "Right Output Switch", "Right Output PGA" },
{ "LINEOUT2N Driver", NULL, "LINEOUT2N Mixer" },
{ "LINEOUT2P Driver", NULL, "LINEOUT2P Mixer" },
};
int wm_hubs_add_analogue_controls(struct snd_soc_codec *codec)
{
struct snd_soc_dapm_context *dapm = &codec->dapm;
/* Latch volume update bits & default ZC on */
snd_soc_update_bits(codec, WM8993_LEFT_LINE_INPUT_1_2_VOLUME,
WM8993_IN1_VU, WM8993_IN1_VU);
snd_soc_update_bits(codec, WM8993_RIGHT_LINE_INPUT_1_2_VOLUME,
WM8993_IN1_VU, WM8993_IN1_VU);
snd_soc_update_bits(codec, WM8993_LEFT_LINE_INPUT_3_4_VOLUME,
WM8993_IN2_VU, WM8993_IN2_VU);
snd_soc_update_bits(codec, WM8993_RIGHT_LINE_INPUT_3_4_VOLUME,
WM8993_IN2_VU, WM8993_IN2_VU);
snd_soc_update_bits(codec, WM8993_SPEAKER_VOLUME_LEFT,
WM8993_SPKOUT_VU, WM8993_SPKOUT_VU);
snd_soc_update_bits(codec, WM8993_SPEAKER_VOLUME_RIGHT,
WM8993_SPKOUT_VU, WM8993_SPKOUT_VU);
snd_soc_update_bits(codec, WM8993_LEFT_OUTPUT_VOLUME,
WM8993_HPOUT1_VU | WM8993_HPOUT1L_ZC,
WM8993_HPOUT1_VU | WM8993_HPOUT1L_ZC);
snd_soc_update_bits(codec, WM8993_RIGHT_OUTPUT_VOLUME,
WM8993_HPOUT1_VU | WM8993_HPOUT1R_ZC,
WM8993_HPOUT1_VU | WM8993_HPOUT1R_ZC);
snd_soc_update_bits(codec, WM8993_LEFT_OPGA_VOLUME,
WM8993_MIXOUTL_ZC | WM8993_MIXOUT_VU,
WM8993_MIXOUTL_ZC | WM8993_MIXOUT_VU);
snd_soc_update_bits(codec, WM8993_RIGHT_OPGA_VOLUME,
WM8993_MIXOUTR_ZC | WM8993_MIXOUT_VU,
WM8993_MIXOUTR_ZC | WM8993_MIXOUT_VU);
snd_soc_add_codec_controls(codec, analogue_snd_controls,
ARRAY_SIZE(analogue_snd_controls));
snd_soc_dapm_new_controls(dapm, analogue_dapm_widgets,
ARRAY_SIZE(analogue_dapm_widgets));
return 0;
}
EXPORT_SYMBOL_GPL(wm_hubs_add_analogue_controls);
int wm_hubs_add_analogue_routes(struct snd_soc_codec *codec,
int lineout1_diff, int lineout2_diff)
{
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
struct snd_soc_dapm_context *dapm = &codec->dapm;
hubs->codec = codec;
INIT_LIST_HEAD(&hubs->dcs_cache);
init_completion(&hubs->dcs_done);
snd_soc_dapm_add_routes(dapm, analogue_routes,
ARRAY_SIZE(analogue_routes));
if (lineout1_diff)
snd_soc_dapm_add_routes(dapm,
lineout1_diff_routes,
ARRAY_SIZE(lineout1_diff_routes));
else
snd_soc_dapm_add_routes(dapm,
lineout1_se_routes,
ARRAY_SIZE(lineout1_se_routes));
if (lineout2_diff)
snd_soc_dapm_add_routes(dapm,
lineout2_diff_routes,
ARRAY_SIZE(lineout2_diff_routes));
else
snd_soc_dapm_add_routes(dapm,
lineout2_se_routes,
ARRAY_SIZE(lineout2_se_routes));
return 0;
}
EXPORT_SYMBOL_GPL(wm_hubs_add_analogue_routes);
int wm_hubs_handle_analogue_pdata(struct snd_soc_codec *codec,
int lineout1_diff, int lineout2_diff,
int lineout1fb, int lineout2fb,
int jd_scthr, int jd_thr,
int micbias1_delay, int micbias2_delay,
int micbias1_lvl, int micbias2_lvl)
{
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
hubs->lineout1_se = !lineout1_diff;
hubs->lineout2_se = !lineout2_diff;
hubs->micb1_delay = micbias1_delay;
hubs->micb2_delay = micbias2_delay;
if (!lineout1_diff)
snd_soc_update_bits(codec, WM8993_LINE_MIXER1,
WM8993_LINEOUT1_MODE,
WM8993_LINEOUT1_MODE);
if (!lineout2_diff)
snd_soc_update_bits(codec, WM8993_LINE_MIXER2,
WM8993_LINEOUT2_MODE,
WM8993_LINEOUT2_MODE);
if (!lineout1_diff && !lineout2_diff)
snd_soc_update_bits(codec, WM8993_ANTIPOP1,
WM8993_LINEOUT_VMID_BUF_ENA,
WM8993_LINEOUT_VMID_BUF_ENA);
if (lineout1fb)
snd_soc_update_bits(codec, WM8993_ADDITIONAL_CONTROL,
WM8993_LINEOUT1_FB, WM8993_LINEOUT1_FB);
if (lineout2fb)
snd_soc_update_bits(codec, WM8993_ADDITIONAL_CONTROL,
WM8993_LINEOUT2_FB, WM8993_LINEOUT2_FB);
snd_soc_update_bits(codec, WM8993_MICBIAS,
WM8993_JD_SCTHR_MASK | WM8993_JD_THR_MASK |
WM8993_MICB1_LVL | WM8993_MICB2_LVL,
jd_scthr << WM8993_JD_SCTHR_SHIFT |
jd_thr << WM8993_JD_THR_SHIFT |
micbias1_lvl |
micbias2_lvl << WM8993_MICB2_LVL_SHIFT);
return 0;
}
EXPORT_SYMBOL_GPL(wm_hubs_handle_analogue_pdata);
void wm_hubs_vmid_ena(struct snd_soc_codec *codec)
{
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
int val = 0;
if (hubs->lineout1_se)
val |= WM8993_LINEOUT1N_ENA | WM8993_LINEOUT1P_ENA;
if (hubs->lineout2_se)
val |= WM8993_LINEOUT2N_ENA | WM8993_LINEOUT2P_ENA;
/* Enable the line outputs while we power up */
snd_soc_update_bits(codec, WM8993_POWER_MANAGEMENT_3, val, val);
}
EXPORT_SYMBOL_GPL(wm_hubs_vmid_ena);
void wm_hubs_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
struct wm_hubs_data *hubs = snd_soc_codec_get_drvdata(codec);
int mask, val;
switch (level) {
case SND_SOC_BIAS_STANDBY:
/* Clamp the inputs to VMID while we ramp to charge caps */
snd_soc_update_bits(codec, WM8993_INPUTS_CLAMP_REG,
WM8993_INPUTS_CLAMP, WM8993_INPUTS_CLAMP);
break;
case SND_SOC_BIAS_ON:
/* Turn off any unneded single ended outputs */
val = 0;
mask = 0;
if (hubs->lineout1_se)
mask |= WM8993_LINEOUT1N_ENA | WM8993_LINEOUT1P_ENA;
if (hubs->lineout2_se)
mask |= WM8993_LINEOUT2N_ENA | WM8993_LINEOUT2P_ENA;
if (hubs->lineout1_se && hubs->lineout1n_ena)
val |= WM8993_LINEOUT1N_ENA;
if (hubs->lineout1_se && hubs->lineout1p_ena)
val |= WM8993_LINEOUT1P_ENA;
if (hubs->lineout2_se && hubs->lineout2n_ena)
val |= WM8993_LINEOUT2N_ENA;
if (hubs->lineout2_se && hubs->lineout2p_ena)
val |= WM8993_LINEOUT2P_ENA;
snd_soc_update_bits(codec, WM8993_POWER_MANAGEMENT_3,
mask, val);
/* Remove the input clamps */
snd_soc_update_bits(codec, WM8993_INPUTS_CLAMP_REG,
WM8993_INPUTS_CLAMP, 0);
break;
default:
break;
}
}
EXPORT_SYMBOL_GPL(wm_hubs_set_bias_level);
MODULE_DESCRIPTION("Shared support for Wolfson hubs products");
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
jayk/linux | drivers/media/pci/cx88/cx88-blackbird.c | 619 | 34645 | /*
*
* Support for a cx23416 mpeg encoder via cx2388x host port.
* "blackbird" reference design.
*
* (c) 2004 Jelle Foks <jelle@foks.us>
* (c) 2004 Gerd Knorr <kraxel@bytesex.org>
*
* (c) 2005-2006 Mauro Carvalho Chehab <mchehab@infradead.org>
* - video_ioctl2 conversion
*
* Includes parts from the ivtv driver <http://sourceforge.net/projects/ivtv/>
*
* 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/fs.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/firmware.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-event.h>
#include <media/cx2341x.h>
#include "cx88.h"
MODULE_DESCRIPTION("driver for cx2388x/cx23416 based mpeg encoder cards");
MODULE_AUTHOR("Jelle Foks <jelle@foks.us>, Gerd Knorr <kraxel@bytesex.org> [SuSE Labs]");
MODULE_LICENSE("GPL");
MODULE_VERSION(CX88_VERSION);
static unsigned int debug;
module_param(debug,int,0644);
MODULE_PARM_DESC(debug,"enable debug messages [blackbird]");
#define dprintk(level, fmt, arg...) do { \
if (debug + 1 > level) \
printk(KERN_DEBUG "%s/2-bb: " fmt, dev->core->name , ## arg); \
} while(0)
/* ------------------------------------------------------------------ */
#define BLACKBIRD_FIRM_IMAGE_SIZE 376836
/* defines below are from ivtv-driver.h */
#define IVTV_CMD_HW_BLOCKS_RST 0xFFFFFFFF
/* Firmware API commands */
#define IVTV_API_STD_TIMEOUT 500
enum blackbird_capture_type {
BLACKBIRD_MPEG_CAPTURE,
BLACKBIRD_RAW_CAPTURE,
BLACKBIRD_RAW_PASSTHRU_CAPTURE
};
enum blackbird_capture_bits {
BLACKBIRD_RAW_BITS_NONE = 0x00,
BLACKBIRD_RAW_BITS_YUV_CAPTURE = 0x01,
BLACKBIRD_RAW_BITS_PCM_CAPTURE = 0x02,
BLACKBIRD_RAW_BITS_VBI_CAPTURE = 0x04,
BLACKBIRD_RAW_BITS_PASSTHRU_CAPTURE = 0x08,
BLACKBIRD_RAW_BITS_TO_HOST_CAPTURE = 0x10
};
enum blackbird_capture_end {
BLACKBIRD_END_AT_GOP, /* stop at the end of gop, generate irq */
BLACKBIRD_END_NOW, /* stop immediately, no irq */
};
enum blackbird_framerate {
BLACKBIRD_FRAMERATE_NTSC_30, /* NTSC: 30fps */
BLACKBIRD_FRAMERATE_PAL_25 /* PAL: 25fps */
};
enum blackbird_stream_port {
BLACKBIRD_OUTPUT_PORT_MEMORY,
BLACKBIRD_OUTPUT_PORT_STREAMING,
BLACKBIRD_OUTPUT_PORT_SERIAL
};
enum blackbird_data_xfer_status {
BLACKBIRD_MORE_BUFFERS_FOLLOW,
BLACKBIRD_LAST_BUFFER,
};
enum blackbird_picture_mask {
BLACKBIRD_PICTURE_MASK_NONE,
BLACKBIRD_PICTURE_MASK_I_FRAMES,
BLACKBIRD_PICTURE_MASK_I_P_FRAMES = 0x3,
BLACKBIRD_PICTURE_MASK_ALL_FRAMES = 0x7,
};
enum blackbird_vbi_mode_bits {
BLACKBIRD_VBI_BITS_SLICED,
BLACKBIRD_VBI_BITS_RAW,
};
enum blackbird_vbi_insertion_bits {
BLACKBIRD_VBI_BITS_INSERT_IN_XTENSION_USR_DATA,
BLACKBIRD_VBI_BITS_INSERT_IN_PRIVATE_PACKETS = 0x1 << 1,
BLACKBIRD_VBI_BITS_SEPARATE_STREAM = 0x2 << 1,
BLACKBIRD_VBI_BITS_SEPARATE_STREAM_USR_DATA = 0x4 << 1,
BLACKBIRD_VBI_BITS_SEPARATE_STREAM_PRV_DATA = 0x5 << 1,
};
enum blackbird_dma_unit {
BLACKBIRD_DMA_BYTES,
BLACKBIRD_DMA_FRAMES,
};
enum blackbird_dma_transfer_status_bits {
BLACKBIRD_DMA_TRANSFER_BITS_DONE = 0x01,
BLACKBIRD_DMA_TRANSFER_BITS_ERROR = 0x04,
BLACKBIRD_DMA_TRANSFER_BITS_LL_ERROR = 0x10,
};
enum blackbird_pause {
BLACKBIRD_PAUSE_ENCODING,
BLACKBIRD_RESUME_ENCODING,
};
enum blackbird_copyright {
BLACKBIRD_COPYRIGHT_OFF,
BLACKBIRD_COPYRIGHT_ON,
};
enum blackbird_notification_type {
BLACKBIRD_NOTIFICATION_REFRESH,
};
enum blackbird_notification_status {
BLACKBIRD_NOTIFICATION_OFF,
BLACKBIRD_NOTIFICATION_ON,
};
enum blackbird_notification_mailbox {
BLACKBIRD_NOTIFICATION_NO_MAILBOX = -1,
};
enum blackbird_field1_lines {
BLACKBIRD_FIELD1_SAA7114 = 0x00EF, /* 239 */
BLACKBIRD_FIELD1_SAA7115 = 0x00F0, /* 240 */
BLACKBIRD_FIELD1_MICRONAS = 0x0105, /* 261 */
};
enum blackbird_field2_lines {
BLACKBIRD_FIELD2_SAA7114 = 0x00EF, /* 239 */
BLACKBIRD_FIELD2_SAA7115 = 0x00F0, /* 240 */
BLACKBIRD_FIELD2_MICRONAS = 0x0106, /* 262 */
};
enum blackbird_custom_data_type {
BLACKBIRD_CUSTOM_EXTENSION_USR_DATA,
BLACKBIRD_CUSTOM_PRIVATE_PACKET,
};
enum blackbird_mute {
BLACKBIRD_UNMUTE,
BLACKBIRD_MUTE,
};
enum blackbird_mute_video_mask {
BLACKBIRD_MUTE_VIDEO_V_MASK = 0x0000FF00,
BLACKBIRD_MUTE_VIDEO_U_MASK = 0x00FF0000,
BLACKBIRD_MUTE_VIDEO_Y_MASK = 0xFF000000,
};
enum blackbird_mute_video_shift {
BLACKBIRD_MUTE_VIDEO_V_SHIFT = 8,
BLACKBIRD_MUTE_VIDEO_U_SHIFT = 16,
BLACKBIRD_MUTE_VIDEO_Y_SHIFT = 24,
};
/* Registers */
#define IVTV_REG_ENC_SDRAM_REFRESH (0x07F8 /*| IVTV_REG_OFFSET*/)
#define IVTV_REG_ENC_SDRAM_PRECHARGE (0x07FC /*| IVTV_REG_OFFSET*/)
#define IVTV_REG_SPU (0x9050 /*| IVTV_REG_OFFSET*/)
#define IVTV_REG_HW_BLOCKS (0x9054 /*| IVTV_REG_OFFSET*/)
#define IVTV_REG_VPU (0x9058 /*| IVTV_REG_OFFSET*/)
#define IVTV_REG_APU (0xA064 /*| IVTV_REG_OFFSET*/)
/* ------------------------------------------------------------------ */
static void host_setup(struct cx88_core *core)
{
/* toggle reset of the host */
cx_write(MO_GPHST_SOFT_RST, 1);
udelay(100);
cx_write(MO_GPHST_SOFT_RST, 0);
udelay(100);
/* host port setup */
cx_write(MO_GPHST_WSC, 0x44444444U);
cx_write(MO_GPHST_XFR, 0);
cx_write(MO_GPHST_WDTH, 15);
cx_write(MO_GPHST_HDSHK, 0);
cx_write(MO_GPHST_MUX16, 0x44448888U);
cx_write(MO_GPHST_MODE, 0);
}
/* ------------------------------------------------------------------ */
#define P1_MDATA0 0x390000
#define P1_MDATA1 0x390001
#define P1_MDATA2 0x390002
#define P1_MDATA3 0x390003
#define P1_MADDR2 0x390004
#define P1_MADDR1 0x390005
#define P1_MADDR0 0x390006
#define P1_RDATA0 0x390008
#define P1_RDATA1 0x390009
#define P1_RDATA2 0x39000A
#define P1_RDATA3 0x39000B
#define P1_RADDR0 0x39000C
#define P1_RADDR1 0x39000D
#define P1_RRDWR 0x39000E
static int wait_ready_gpio0_bit1(struct cx88_core *core, u32 state)
{
unsigned long timeout = jiffies + msecs_to_jiffies(1);
u32 gpio0,need;
need = state ? 2 : 0;
for (;;) {
gpio0 = cx_read(MO_GP0_IO) & 2;
if (need == gpio0)
return 0;
if (time_after(jiffies,timeout))
return -1;
udelay(1);
}
}
static int memory_write(struct cx88_core *core, u32 address, u32 value)
{
/* Warning: address is dword address (4 bytes) */
cx_writeb(P1_MDATA0, (unsigned int)value);
cx_writeb(P1_MDATA1, (unsigned int)(value >> 8));
cx_writeb(P1_MDATA2, (unsigned int)(value >> 16));
cx_writeb(P1_MDATA3, (unsigned int)(value >> 24));
cx_writeb(P1_MADDR2, (unsigned int)(address >> 16) | 0x40);
cx_writeb(P1_MADDR1, (unsigned int)(address >> 8));
cx_writeb(P1_MADDR0, (unsigned int)address);
cx_read(P1_MDATA0);
cx_read(P1_MADDR0);
return wait_ready_gpio0_bit1(core,1);
}
static int memory_read(struct cx88_core *core, u32 address, u32 *value)
{
int retval;
u32 val;
/* Warning: address is dword address (4 bytes) */
cx_writeb(P1_MADDR2, (unsigned int)(address >> 16) & ~0xC0);
cx_writeb(P1_MADDR1, (unsigned int)(address >> 8));
cx_writeb(P1_MADDR0, (unsigned int)address);
cx_read(P1_MADDR0);
retval = wait_ready_gpio0_bit1(core,1);
cx_writeb(P1_MDATA3, 0);
val = (unsigned char)cx_read(P1_MDATA3) << 24;
cx_writeb(P1_MDATA2, 0);
val |= (unsigned char)cx_read(P1_MDATA2) << 16;
cx_writeb(P1_MDATA1, 0);
val |= (unsigned char)cx_read(P1_MDATA1) << 8;
cx_writeb(P1_MDATA0, 0);
val |= (unsigned char)cx_read(P1_MDATA0);
*value = val;
return retval;
}
static int register_write(struct cx88_core *core, u32 address, u32 value)
{
cx_writeb(P1_RDATA0, (unsigned int)value);
cx_writeb(P1_RDATA1, (unsigned int)(value >> 8));
cx_writeb(P1_RDATA2, (unsigned int)(value >> 16));
cx_writeb(P1_RDATA3, (unsigned int)(value >> 24));
cx_writeb(P1_RADDR0, (unsigned int)address);
cx_writeb(P1_RADDR1, (unsigned int)(address >> 8));
cx_writeb(P1_RRDWR, 1);
cx_read(P1_RDATA0);
cx_read(P1_RADDR0);
return wait_ready_gpio0_bit1(core,1);
}
static int register_read(struct cx88_core *core, u32 address, u32 *value)
{
int retval;
u32 val;
cx_writeb(P1_RADDR0, (unsigned int)address);
cx_writeb(P1_RADDR1, (unsigned int)(address >> 8));
cx_writeb(P1_RRDWR, 0);
cx_read(P1_RADDR0);
retval = wait_ready_gpio0_bit1(core,1);
val = (unsigned char)cx_read(P1_RDATA0);
val |= (unsigned char)cx_read(P1_RDATA1) << 8;
val |= (unsigned char)cx_read(P1_RDATA2) << 16;
val |= (unsigned char)cx_read(P1_RDATA3) << 24;
*value = val;
return retval;
}
/* ------------------------------------------------------------------ */
static int blackbird_mbox_func(void *priv, u32 command, int in, int out, u32 data[CX2341X_MBOX_MAX_DATA])
{
struct cx8802_dev *dev = priv;
unsigned long timeout;
u32 value, flag, retval;
int i;
dprintk(1,"%s: 0x%X\n", __func__, command);
/* this may not be 100% safe if we can't read any memory location
without side effects */
memory_read(dev->core, dev->mailbox - 4, &value);
if (value != 0x12345678) {
dprintk(0, "Firmware and/or mailbox pointer not initialized or corrupted\n");
return -EIO;
}
memory_read(dev->core, dev->mailbox, &flag);
if (flag) {
dprintk(0, "ERROR: Mailbox appears to be in use (%x)\n", flag);
return -EIO;
}
flag |= 1; /* tell 'em we're working on it */
memory_write(dev->core, dev->mailbox, flag);
/* write command + args + fill remaining with zeros */
memory_write(dev->core, dev->mailbox + 1, command); /* command code */
memory_write(dev->core, dev->mailbox + 3, IVTV_API_STD_TIMEOUT); /* timeout */
for (i = 0; i < in; i++) {
memory_write(dev->core, dev->mailbox + 4 + i, data[i]);
dprintk(1, "API Input %d = %d\n", i, data[i]);
}
for (; i < CX2341X_MBOX_MAX_DATA; i++)
memory_write(dev->core, dev->mailbox + 4 + i, 0);
flag |= 3; /* tell 'em we're done writing */
memory_write(dev->core, dev->mailbox, flag);
/* wait for firmware to handle the API command */
timeout = jiffies + msecs_to_jiffies(1000);
for (;;) {
memory_read(dev->core, dev->mailbox, &flag);
if (0 != (flag & 4))
break;
if (time_after(jiffies,timeout)) {
dprintk(0, "ERROR: API Mailbox timeout %x\n", command);
return -EIO;
}
udelay(10);
}
/* read output values */
for (i = 0; i < out; i++) {
memory_read(dev->core, dev->mailbox + 4 + i, data + i);
dprintk(1, "API Output %d = %d\n", i, data[i]);
}
memory_read(dev->core, dev->mailbox + 2, &retval);
dprintk(1, "API result = %d\n",retval);
flag = 0;
memory_write(dev->core, dev->mailbox, flag);
return retval;
}
/* ------------------------------------------------------------------ */
/* We don't need to call the API often, so using just one mailbox will probably suffice */
static int blackbird_api_cmd(struct cx8802_dev *dev, u32 command,
u32 inputcnt, u32 outputcnt, ...)
{
u32 data[CX2341X_MBOX_MAX_DATA];
va_list vargs;
int i, err;
va_start(vargs, outputcnt);
for (i = 0; i < inputcnt; i++) {
data[i] = va_arg(vargs, int);
}
err = blackbird_mbox_func(dev, command, inputcnt, outputcnt, data);
for (i = 0; i < outputcnt; i++) {
int *vptr = va_arg(vargs, int *);
*vptr = data[i];
}
va_end(vargs);
return err;
}
static int blackbird_find_mailbox(struct cx8802_dev *dev)
{
u32 signature[4]={0x12345678, 0x34567812, 0x56781234, 0x78123456};
int signaturecnt=0;
u32 value;
int i;
for (i = 0; i < BLACKBIRD_FIRM_IMAGE_SIZE; i++) {
memory_read(dev->core, i, &value);
if (value == signature[signaturecnt])
signaturecnt++;
else
signaturecnt = 0;
if (4 == signaturecnt) {
dprintk(1, "Mailbox signature found\n");
return i+1;
}
}
dprintk(0, "Mailbox signature values not found!\n");
return -EIO;
}
static int blackbird_load_firmware(struct cx8802_dev *dev)
{
static const unsigned char magic[8] = {
0xa7, 0x0d, 0x00, 0x00, 0x66, 0xbb, 0x55, 0xaa
};
const struct firmware *firmware;
int i, retval = 0;
u32 value = 0;
u32 checksum = 0;
__le32 *dataptr;
retval = register_write(dev->core, IVTV_REG_VPU, 0xFFFFFFED);
retval |= register_write(dev->core, IVTV_REG_HW_BLOCKS, IVTV_CMD_HW_BLOCKS_RST);
retval |= register_write(dev->core, IVTV_REG_ENC_SDRAM_REFRESH, 0x80000640);
retval |= register_write(dev->core, IVTV_REG_ENC_SDRAM_PRECHARGE, 0x1A);
msleep(1);
retval |= register_write(dev->core, IVTV_REG_APU, 0);
if (retval < 0)
dprintk(0, "Error with register_write\n");
retval = request_firmware(&firmware, CX2341X_FIRM_ENC_FILENAME,
&dev->pci->dev);
if (retval != 0) {
pr_err("Hotplug firmware request failed (%s).\n",
CX2341X_FIRM_ENC_FILENAME);
pr_err("Please fix your hotplug setup, the board will not work without firmware loaded!\n");
return -EIO;
}
if (firmware->size != BLACKBIRD_FIRM_IMAGE_SIZE) {
pr_err("Firmware size mismatch (have %zd, expected %d)\n",
firmware->size, BLACKBIRD_FIRM_IMAGE_SIZE);
release_firmware(firmware);
return -EINVAL;
}
if (0 != memcmp(firmware->data, magic, 8)) {
pr_err("Firmware magic mismatch, wrong file?\n");
release_firmware(firmware);
return -EINVAL;
}
/* transfer to the chip */
dprintk(1,"Loading firmware ...\n");
dataptr = (__le32 *)firmware->data;
for (i = 0; i < (firmware->size >> 2); i++) {
value = le32_to_cpu(*dataptr);
checksum += ~value;
memory_write(dev->core, i, value);
dataptr++;
}
/* read back to verify with the checksum */
for (i--; i >= 0; i--) {
memory_read(dev->core, i, &value);
checksum -= ~value;
}
release_firmware(firmware);
if (checksum) {
pr_err("Firmware load might have failed (checksum mismatch).\n");
return -EIO;
}
dprintk(0, "Firmware upload successful.\n");
retval |= register_write(dev->core, IVTV_REG_HW_BLOCKS, IVTV_CMD_HW_BLOCKS_RST);
retval |= register_read(dev->core, IVTV_REG_SPU, &value);
retval |= register_write(dev->core, IVTV_REG_SPU, value & 0xFFFFFFFE);
msleep(1);
retval |= register_read(dev->core, IVTV_REG_VPU, &value);
retval |= register_write(dev->core, IVTV_REG_VPU, value & 0xFFFFFFE8);
if (retval < 0)
dprintk(0, "Error with register_write\n");
return 0;
}
/**
Settings used by the windows tv app for PVR2000:
=================================================================================================================
Profile | Codec | Resolution | CBR/VBR | Video Qlty | V. Bitrate | Frmrate | Audio Codec | A. Bitrate | A. Mode
-----------------------------------------------------------------------------------------------------------------
MPEG-1 | MPEG1 | 352x288PAL | (CBR) | 1000:Optimal | 2000 Kbps | 25fps | MPG1 Layer2 | 224kbps | Stereo
MPEG-2 | MPEG2 | 720x576PAL | VBR | 600 :Good | 4000 Kbps | 25fps | MPG1 Layer2 | 224kbps | Stereo
VCD | MPEG1 | 352x288PAL | (CBR) | 1000:Optimal | 1150 Kbps | 25fps | MPG1 Layer2 | 224kbps | Stereo
DVD | MPEG2 | 720x576PAL | VBR | 600 :Good | 6000 Kbps | 25fps | MPG1 Layer2 | 224kbps | Stereo
DB* DVD | MPEG2 | 720x576PAL | CBR | 600 :Good | 6000 Kbps | 25fps | MPG1 Layer2 | 224kbps | Stereo
=================================================================================================================
*DB: "DirectBurn"
*/
static void blackbird_codec_settings(struct cx8802_dev *dev)
{
struct cx88_core *core = dev->core;
/* assign frame size */
blackbird_api_cmd(dev, CX2341X_ENC_SET_FRAME_SIZE, 2, 0,
core->height, core->width);
dev->cxhdl.width = core->width;
dev->cxhdl.height = core->height;
cx2341x_handler_set_50hz(&dev->cxhdl, dev->core->tvnorm & V4L2_STD_625_50);
cx2341x_handler_setup(&dev->cxhdl);
}
static int blackbird_initialize_codec(struct cx8802_dev *dev)
{
struct cx88_core *core = dev->core;
int version;
int retval;
dprintk(1,"Initialize codec\n");
retval = blackbird_api_cmd(dev, CX2341X_ENC_PING_FW, 0, 0); /* ping */
if (retval < 0) {
/* ping was not successful, reset and upload firmware */
cx_write(MO_SRST_IO, 0); /* SYS_RSTO=0 */
cx_write(MO_SRST_IO, 1); /* SYS_RSTO=1 */
retval = blackbird_load_firmware(dev);
if (retval < 0)
return retval;
retval = blackbird_find_mailbox(dev);
if (retval < 0)
return -1;
dev->mailbox = retval;
retval = blackbird_api_cmd(dev, CX2341X_ENC_PING_FW, 0, 0); /* ping */
if (retval < 0) {
dprintk(0, "ERROR: Firmware ping failed!\n");
return -1;
}
retval = blackbird_api_cmd(dev, CX2341X_ENC_GET_VERSION, 0, 1, &version);
if (retval < 0) {
dprintk(0, "ERROR: Firmware get encoder version failed!\n");
return -1;
}
dprintk(0, "Firmware version is 0x%08x\n", version);
}
cx_write(MO_PINMUX_IO, 0x88); /* 656-8bit IO and enable MPEG parallel IO */
cx_clear(MO_INPUT_FORMAT, 0x100); /* chroma subcarrier lock to normal? */
cx_write(MO_VBOS_CONTROL, 0x84A00); /* no 656 mode, 8-bit pixels, disable VBI */
cx_clear(MO_OUTPUT_FORMAT, 0x0008); /* Normal Y-limits to let the mpeg encoder sync */
blackbird_codec_settings(dev);
blackbird_api_cmd(dev, CX2341X_ENC_SET_NUM_VSYNC_LINES, 2, 0,
BLACKBIRD_FIELD1_SAA7115,
BLACKBIRD_FIELD2_SAA7115
);
blackbird_api_cmd(dev, CX2341X_ENC_SET_PLACEHOLDER, 12, 0,
BLACKBIRD_CUSTOM_EXTENSION_USR_DATA,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
return 0;
}
static int blackbird_start_codec(struct cx8802_dev *dev)
{
struct cx88_core *core = dev->core;
/* start capturing to the host interface */
u32 reg;
int i;
int lastchange = -1;
int lastval = 0;
for (i = 0; (i < 10) && (i < (lastchange + 4)); i++) {
reg = cx_read(AUD_STATUS);
dprintk(1, "AUD_STATUS:%dL: 0x%x\n", i, reg);
if ((reg & 0x0F) != lastval) {
lastval = reg & 0x0F;
lastchange = i;
}
msleep(100);
}
/* unmute audio source */
cx_clear(AUD_VOL_CTL, (1 << 6));
blackbird_api_cmd(dev, CX2341X_ENC_REFRESH_INPUT, 0, 0);
/* initialize the video input */
blackbird_api_cmd(dev, CX2341X_ENC_INITIALIZE_INPUT, 0, 0);
cx2341x_handler_set_busy(&dev->cxhdl, 1);
/* start capturing to the host interface */
blackbird_api_cmd(dev, CX2341X_ENC_START_CAPTURE, 2, 0,
BLACKBIRD_MPEG_CAPTURE,
BLACKBIRD_RAW_BITS_NONE
);
return 0;
}
static int blackbird_stop_codec(struct cx8802_dev *dev)
{
blackbird_api_cmd(dev, CX2341X_ENC_STOP_CAPTURE, 3, 0,
BLACKBIRD_END_NOW,
BLACKBIRD_MPEG_CAPTURE,
BLACKBIRD_RAW_BITS_NONE
);
cx2341x_handler_set_busy(&dev->cxhdl, 0);
return 0;
}
/* ------------------------------------------------------------------ */
static int queue_setup(struct vb2_queue *q, const struct v4l2_format *fmt,
unsigned int *num_buffers, unsigned int *num_planes,
unsigned int sizes[], void *alloc_ctxs[])
{
struct cx8802_dev *dev = q->drv_priv;
*num_planes = 1;
dev->ts_packet_size = 188 * 4;
dev->ts_packet_count = 32;
sizes[0] = dev->ts_packet_size * dev->ts_packet_count;
alloc_ctxs[0] = dev->alloc_ctx;
return 0;
}
static int buffer_prepare(struct vb2_buffer *vb)
{
struct cx8802_dev *dev = vb->vb2_queue->drv_priv;
struct cx88_buffer *buf = container_of(vb, struct cx88_buffer, vb);
return cx8802_buf_prepare(vb->vb2_queue, dev, buf);
}
static void buffer_finish(struct vb2_buffer *vb)
{
struct cx8802_dev *dev = vb->vb2_queue->drv_priv;
struct cx88_buffer *buf = container_of(vb, struct cx88_buffer, vb);
struct cx88_riscmem *risc = &buf->risc;
if (risc->cpu)
pci_free_consistent(dev->pci, risc->size, risc->cpu, risc->dma);
memset(risc, 0, sizeof(*risc));
}
static void buffer_queue(struct vb2_buffer *vb)
{
struct cx8802_dev *dev = vb->vb2_queue->drv_priv;
struct cx88_buffer *buf = container_of(vb, struct cx88_buffer, vb);
cx8802_buf_queue(dev, buf);
}
static int start_streaming(struct vb2_queue *q, unsigned int count)
{
struct cx8802_dev *dev = q->drv_priv;
struct cx88_dmaqueue *dmaq = &dev->mpegq;
struct cx8802_driver *drv;
struct cx88_buffer *buf;
unsigned long flags;
int err;
/* Make sure we can acquire the hardware */
drv = cx8802_get_driver(dev, CX88_MPEG_BLACKBIRD);
if (!drv) {
dprintk(1, "%s: blackbird driver is not loaded\n", __func__);
err = -ENODEV;
goto fail;
}
err = drv->request_acquire(drv);
if (err != 0) {
dprintk(1, "%s: Unable to acquire hardware, %d\n", __func__, err);
goto fail;
}
if (blackbird_initialize_codec(dev) < 0) {
drv->request_release(drv);
err = -EINVAL;
goto fail;
}
err = blackbird_start_codec(dev);
if (err == 0) {
buf = list_entry(dmaq->active.next, struct cx88_buffer, list);
cx8802_start_dma(dev, dmaq, buf);
return 0;
}
fail:
spin_lock_irqsave(&dev->slock, flags);
while (!list_empty(&dmaq->active)) {
struct cx88_buffer *buf = list_entry(dmaq->active.next,
struct cx88_buffer, list);
list_del(&buf->list);
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_QUEUED);
}
spin_unlock_irqrestore(&dev->slock, flags);
return err;
}
static void stop_streaming(struct vb2_queue *q)
{
struct cx8802_dev *dev = q->drv_priv;
struct cx88_dmaqueue *dmaq = &dev->mpegq;
struct cx8802_driver *drv = NULL;
unsigned long flags;
cx8802_cancel_buffers(dev);
blackbird_stop_codec(dev);
/* Make sure we release the hardware */
drv = cx8802_get_driver(dev, CX88_MPEG_BLACKBIRD);
WARN_ON(!drv);
if (drv)
drv->request_release(drv);
spin_lock_irqsave(&dev->slock, flags);
while (!list_empty(&dmaq->active)) {
struct cx88_buffer *buf = list_entry(dmaq->active.next,
struct cx88_buffer, list);
list_del(&buf->list);
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
}
spin_unlock_irqrestore(&dev->slock, flags);
}
static struct vb2_ops blackbird_qops = {
.queue_setup = queue_setup,
.buf_prepare = buffer_prepare,
.buf_finish = buffer_finish,
.buf_queue = buffer_queue,
.wait_prepare = vb2_ops_wait_prepare,
.wait_finish = vb2_ops_wait_finish,
.start_streaming = start_streaming,
.stop_streaming = stop_streaming,
};
/* ------------------------------------------------------------------ */
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
strcpy(cap->driver, "cx88_blackbird");
sprintf(cap->bus_info, "PCI:%s", pci_name(dev->pci));
cx88_querycap(file, core, cap);
return 0;
}
static int vidioc_enum_fmt_vid_cap (struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
if (f->index != 0)
return -EINVAL;
strlcpy(f->description, "MPEG", sizeof(f->description));
f->pixelformat = V4L2_PIX_FMT_MPEG;
f->flags = V4L2_FMT_FLAG_COMPRESSED;
return 0;
}
static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
f->fmt.pix.pixelformat = V4L2_PIX_FMT_MPEG;
f->fmt.pix.bytesperline = 0;
f->fmt.pix.sizeimage = dev->ts_packet_size * dev->ts_packet_count;
f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
f->fmt.pix.width = core->width;
f->fmt.pix.height = core->height;
f->fmt.pix.field = core->field;
return 0;
}
static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
unsigned maxw, maxh;
enum v4l2_field field;
f->fmt.pix.pixelformat = V4L2_PIX_FMT_MPEG;
f->fmt.pix.bytesperline = 0;
f->fmt.pix.sizeimage = dev->ts_packet_size * dev->ts_packet_count;
f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
maxw = norm_maxw(core->tvnorm);
maxh = norm_maxh(core->tvnorm);
field = f->fmt.pix.field;
switch (field) {
case V4L2_FIELD_TOP:
case V4L2_FIELD_BOTTOM:
case V4L2_FIELD_INTERLACED:
case V4L2_FIELD_SEQ_BT:
case V4L2_FIELD_SEQ_TB:
break;
default:
field = (f->fmt.pix.height > maxh / 2)
? V4L2_FIELD_INTERLACED
: V4L2_FIELD_BOTTOM;
break;
}
if (V4L2_FIELD_HAS_T_OR_B(field))
maxh /= 2;
v4l_bound_align_image(&f->fmt.pix.width, 48, maxw, 2,
&f->fmt.pix.height, 32, maxh, 0, 0);
f->fmt.pix.field = field;
return 0;
}
static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
if (vb2_is_busy(&dev->vb2_mpegq))
return -EBUSY;
if (core->v4ldev && (vb2_is_busy(&core->v4ldev->vb2_vidq) ||
vb2_is_busy(&core->v4ldev->vb2_vbiq)))
return -EBUSY;
vidioc_try_fmt_vid_cap(file, priv, f);
core->width = f->fmt.pix.width;
core->height = f->fmt.pix.height;
core->field = f->fmt.pix.field;
cx88_set_scale(core, f->fmt.pix.width, f->fmt.pix.height, f->fmt.pix.field);
blackbird_api_cmd(dev, CX2341X_ENC_SET_FRAME_SIZE, 2, 0,
f->fmt.pix.height, f->fmt.pix.width);
return 0;
}
static int vidioc_s_frequency (struct file *file, void *priv,
const struct v4l2_frequency *f)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
bool streaming;
if (unlikely(UNSET == core->board.tuner_type))
return -EINVAL;
if (unlikely(f->tuner != 0))
return -EINVAL;
streaming = vb2_start_streaming_called(&dev->vb2_mpegq);
if (streaming)
blackbird_stop_codec(dev);
cx88_set_freq (core,f);
blackbird_initialize_codec(dev);
cx88_set_scale(core, core->width, core->height,
core->field);
if (streaming)
blackbird_start_codec(dev);
return 0;
}
static int vidioc_log_status (struct file *file, void *priv)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
char name[32 + 2];
snprintf(name, sizeof(name), "%s/2", core->name);
call_all(core, core, log_status);
v4l2_ctrl_handler_log_status(&dev->cxhdl.hdl, name);
return 0;
}
static int vidioc_enum_input (struct file *file, void *priv,
struct v4l2_input *i)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
return cx88_enum_input (core,i);
}
static int vidioc_g_frequency (struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
if (unlikely(UNSET == core->board.tuner_type))
return -EINVAL;
if (unlikely(f->tuner != 0))
return -EINVAL;
f->frequency = core->freq;
call_all(core, tuner, g_frequency, f);
return 0;
}
static int vidioc_g_input (struct file *file, void *priv, unsigned int *i)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
*i = core->input;
return 0;
}
static int vidioc_s_input (struct file *file, void *priv, unsigned int i)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
if (i >= 4)
return -EINVAL;
if (0 == INPUT(i).type)
return -EINVAL;
cx88_newstation(core);
cx88_video_mux(core,i);
return 0;
}
static int vidioc_g_tuner (struct file *file, void *priv,
struct v4l2_tuner *t)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
u32 reg;
if (unlikely(UNSET == core->board.tuner_type))
return -EINVAL;
if (0 != t->index)
return -EINVAL;
strcpy(t->name, "Television");
t->capability = V4L2_TUNER_CAP_NORM;
t->rangehigh = 0xffffffffUL;
call_all(core, tuner, g_tuner, t);
cx88_get_stereo(core ,t);
reg = cx_read(MO_DEVICE_STATUS);
t->signal = (reg & (1<<5)) ? 0xffff : 0x0000;
return 0;
}
static int vidioc_s_tuner (struct file *file, void *priv,
const struct v4l2_tuner *t)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
if (UNSET == core->board.tuner_type)
return -EINVAL;
if (0 != t->index)
return -EINVAL;
cx88_set_stereo(core, t->audmode, 1);
return 0;
}
static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *tvnorm)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
*tvnorm = core->tvnorm;
return 0;
}
static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id id)
{
struct cx8802_dev *dev = video_drvdata(file);
struct cx88_core *core = dev->core;
return cx88_set_tvnorm(core, id);
}
static const struct v4l2_file_operations mpeg_fops =
{
.owner = THIS_MODULE,
.open = v4l2_fh_open,
.release = vb2_fop_release,
.read = vb2_fop_read,
.poll = vb2_fop_poll,
.mmap = vb2_fop_mmap,
.unlocked_ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops mpeg_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
.vidioc_reqbufs = vb2_ioctl_reqbufs,
.vidioc_querybuf = vb2_ioctl_querybuf,
.vidioc_qbuf = vb2_ioctl_qbuf,
.vidioc_dqbuf = vb2_ioctl_dqbuf,
.vidioc_streamon = vb2_ioctl_streamon,
.vidioc_streamoff = vb2_ioctl_streamoff,
.vidioc_s_frequency = vidioc_s_frequency,
.vidioc_log_status = vidioc_log_status,
.vidioc_enum_input = vidioc_enum_input,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
.vidioc_g_tuner = vidioc_g_tuner,
.vidioc_s_tuner = vidioc_s_tuner,
.vidioc_g_std = vidioc_g_std,
.vidioc_s_std = vidioc_s_std,
.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
};
static struct video_device cx8802_mpeg_template = {
.name = "cx8802",
.fops = &mpeg_fops,
.ioctl_ops = &mpeg_ioctl_ops,
.tvnorms = CX88_NORMS,
};
/* ------------------------------------------------------------------ */
/* The CX8802 MPEG API will call this when we can use the hardware */
static int cx8802_blackbird_advise_acquire(struct cx8802_driver *drv)
{
struct cx88_core *core = drv->core;
int err = 0;
switch (core->boardnr) {
case CX88_BOARD_HAUPPAUGE_HVR1300:
/* By default, core setup will leave the cx22702 out of reset, on the bus.
* We left the hardware on power up with the cx22702 active.
* We're being given access to re-arrange the GPIOs.
* Take the bus off the cx22702 and put the cx23416 on it.
*/
/* Toggle reset on cx22702 leaving i2c active */
cx_set(MO_GP0_IO, 0x00000080);
udelay(1000);
cx_clear(MO_GP0_IO, 0x00000080);
udelay(50);
cx_set(MO_GP0_IO, 0x00000080);
udelay(1000);
/* tri-state the cx22702 pins */
cx_set(MO_GP0_IO, 0x00000004);
udelay(1000);
break;
default:
err = -ENODEV;
}
return err;
}
/* The CX8802 MPEG API will call this when we need to release the hardware */
static int cx8802_blackbird_advise_release(struct cx8802_driver *drv)
{
struct cx88_core *core = drv->core;
int err = 0;
switch (core->boardnr) {
case CX88_BOARD_HAUPPAUGE_HVR1300:
/* Exit leaving the cx23416 on the bus */
break;
default:
err = -ENODEV;
}
return err;
}
static void blackbird_unregister_video(struct cx8802_dev *dev)
{
video_unregister_device(&dev->mpeg_dev);
}
static int blackbird_register_video(struct cx8802_dev *dev)
{
int err;
cx88_vdev_init(dev->core, dev->pci, &dev->mpeg_dev,
&cx8802_mpeg_template, "mpeg");
dev->mpeg_dev.ctrl_handler = &dev->cxhdl.hdl;
video_set_drvdata(&dev->mpeg_dev, dev);
dev->mpeg_dev.queue = &dev->vb2_mpegq;
err = video_register_device(&dev->mpeg_dev, VFL_TYPE_GRABBER, -1);
if (err < 0) {
printk(KERN_INFO "%s/2: can't register mpeg device\n",
dev->core->name);
return err;
}
printk(KERN_INFO "%s/2: registered device %s [mpeg]\n",
dev->core->name, video_device_node_name(&dev->mpeg_dev));
return 0;
}
/* ----------------------------------------------------------- */
static int cx8802_blackbird_probe(struct cx8802_driver *drv)
{
struct cx88_core *core = drv->core;
struct cx8802_dev *dev = core->dvbdev;
struct vb2_queue *q;
int err;
dprintk( 1, "%s\n", __func__);
dprintk( 1, " ->being probed by Card=%d Name=%s, PCI %02x:%02x\n",
core->boardnr,
core->name,
core->pci_bus,
core->pci_slot);
err = -ENODEV;
if (!(core->board.mpeg & CX88_MPEG_BLACKBIRD))
goto fail_core;
dev->cxhdl.port = CX2341X_PORT_STREAMING;
dev->cxhdl.width = core->width;
dev->cxhdl.height = core->height;
dev->cxhdl.func = blackbird_mbox_func;
dev->cxhdl.priv = dev;
err = cx2341x_handler_init(&dev->cxhdl, 36);
if (err)
goto fail_core;
v4l2_ctrl_add_handler(&dev->cxhdl.hdl, &core->video_hdl, NULL);
/* blackbird stuff */
printk("%s/2: cx23416 based mpeg encoder (blackbird reference design)\n",
core->name);
host_setup(dev->core);
blackbird_initialize_codec(dev);
/* initial device configuration: needed ? */
// init_controls(core);
cx88_set_tvnorm(core,core->tvnorm);
cx88_video_mux(core,0);
cx2341x_handler_set_50hz(&dev->cxhdl, core->height == 576);
cx2341x_handler_setup(&dev->cxhdl);
q = &dev->vb2_mpegq;
q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF | VB2_READ;
q->gfp_flags = GFP_DMA32;
q->min_buffers_needed = 2;
q->drv_priv = dev;
q->buf_struct_size = sizeof(struct cx88_buffer);
q->ops = &blackbird_qops;
q->mem_ops = &vb2_dma_sg_memops;
q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
q->lock = &core->lock;
err = vb2_queue_init(q);
if (err < 0)
goto fail_core;
blackbird_register_video(dev);
return 0;
fail_core:
return err;
}
static int cx8802_blackbird_remove(struct cx8802_driver *drv)
{
struct cx88_core *core = drv->core;
struct cx8802_dev *dev = core->dvbdev;
/* blackbird */
blackbird_unregister_video(drv->core->dvbdev);
v4l2_ctrl_handler_free(&dev->cxhdl.hdl);
return 0;
}
static struct cx8802_driver cx8802_blackbird_driver = {
.type_id = CX88_MPEG_BLACKBIRD,
.hw_access = CX8802_DRVCTL_SHARED,
.probe = cx8802_blackbird_probe,
.remove = cx8802_blackbird_remove,
.advise_acquire = cx8802_blackbird_advise_acquire,
.advise_release = cx8802_blackbird_advise_release,
};
static int __init blackbird_init(void)
{
printk(KERN_INFO "cx2388x blackbird driver version %s loaded\n",
CX88_VERSION);
return cx8802_register_driver(&cx8802_blackbird_driver);
}
static void __exit blackbird_fini(void)
{
cx8802_unregister_driver(&cx8802_blackbird_driver);
}
module_init(blackbird_init);
module_exit(blackbird_fini);
| gpl-2.0 |
CSE3320/kernel-code | linux-5.8/drivers/media/usb/gspca/topro.c | 619 | 196347 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* Topro TP6800/6810 webcam driver.
*
* Copyright (C) 2011 Jean-François Moine (http://moinejf.free.fr)
* Copyright (C) 2009 Anders Blomdell (anders.blomdell@control.lth.se)
* Copyright (C) 2008 Thomas Champagne (lafeuil@gmail.com)
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "gspca.h"
MODULE_DESCRIPTION("Topro TP6800/6810 gspca webcam driver");
MODULE_AUTHOR("Jean-Francois Moine <http://moinejf.free.fr>, Anders Blomdell <anders.blomdell@control.lth.se>");
MODULE_LICENSE("GPL");
static int force_sensor = -1;
/* JPEG header */
static const u8 jpeg_head[] = {
0xff, 0xd8, /* jpeg */
/* quantization table quality 50% */
0xff, 0xdb, 0x00, 0x84, /* DQT */
0,
#define JPEG_QT0_OFFSET 7
0x10, 0x0b, 0x0c, 0x0e, 0x0c, 0x0a, 0x10, 0x0e,
0x0d, 0x0e, 0x12, 0x11, 0x10, 0x13, 0x18, 0x28,
0x1a, 0x18, 0x16, 0x16, 0x18, 0x31, 0x23, 0x25,
0x1d, 0x28, 0x3a, 0x33, 0x3d, 0x3c, 0x39, 0x33,
0x38, 0x37, 0x40, 0x48, 0x5c, 0x4e, 0x40, 0x44,
0x57, 0x45, 0x37, 0x38, 0x50, 0x6d, 0x51, 0x57,
0x5f, 0x62, 0x67, 0x68, 0x67, 0x3e, 0x4d, 0x71,
0x79, 0x70, 0x64, 0x78, 0x5c, 0x65, 0x67, 0x63,
1,
#define JPEG_QT1_OFFSET 72
0x11, 0x12, 0x12, 0x18, 0x15, 0x18, 0x2f, 0x1a,
0x1a, 0x2f, 0x63, 0x42, 0x38, 0x42, 0x63, 0x63,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
/* Define Huffman table (thanks to Thomas Kaiser) */
0xff, 0xc4, 0x01, 0x5e,
0x00, 0x00, 0x02, 0x03,
0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02,
0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10,
0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04,
0x07, 0x05, 0x04, 0x06, 0x01, 0x00, 0x00, 0x57,
0x01, 0x02, 0x03, 0x00, 0x11, 0x04, 0x12, 0x21,
0x31, 0x13, 0x41, 0x51, 0x61, 0x05, 0x22, 0x32,
0x14, 0x71, 0x81, 0x91, 0x15, 0x23, 0x42, 0x52,
0x62, 0xa1, 0xb1, 0x06, 0x33, 0x72, 0xc1, 0xd1,
0x24, 0x43, 0x53, 0x82, 0x16, 0x34, 0x92, 0xa2,
0xe1, 0xf1, 0xf0, 0x07, 0x08, 0x17, 0x18, 0x25,
0x26, 0x27, 0x28, 0x35, 0x36, 0x37, 0x38, 0x44,
0x45, 0x46, 0x47, 0x48, 0x54, 0x55, 0x56, 0x57,
0x58, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x73,
0x74, 0x75, 0x76, 0x77, 0x78, 0x83, 0x84, 0x85,
0x86, 0x87, 0x88, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xb2,
0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xc2, 0xc3,
0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xd2, 0xd3, 0xd4,
0xd5, 0xd6, 0xd7, 0xd8, 0xe2, 0xe3, 0xe4, 0xe5,
0xe6, 0xe7, 0xe8, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6,
0xf7, 0xf8, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04,
0x05, 0x06, 0x07, 0x08, 0x09, 0x11, 0x00, 0x02,
0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05,
0x04, 0x06, 0x01, 0x00, 0x00, 0x57, 0x00, 0x01,
0x11, 0x02, 0x21, 0x03, 0x12, 0x31, 0x41, 0x13,
0x22, 0x51, 0x61, 0x04, 0x32, 0x71, 0x05, 0x14,
0x23, 0x42, 0x33, 0x52, 0x81, 0x91, 0xa1, 0xb1,
0xf0, 0x06, 0x15, 0xc1, 0xd1, 0xe1, 0x24, 0x43,
0x62, 0xf1, 0x16, 0x25, 0x34, 0x53, 0x72, 0x82,
0x92, 0x07, 0x08, 0x17, 0x18, 0x26, 0x27, 0x28,
0x35, 0x36, 0x37, 0x38, 0x44, 0x45, 0x46, 0x47,
0x48, 0x54, 0x55, 0x56, 0x57, 0x58, 0x63, 0x64,
0x65, 0x66, 0x67, 0x68, 0x73, 0x74, 0x75, 0x76,
0x77, 0x78, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88,
0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0xa2, 0xa3,
0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xb2, 0xb3, 0xb4,
0xb5, 0xb6, 0xb7, 0xb8, 0xc2, 0xc3, 0xc4, 0xc5,
0xc6, 0xc7, 0xc8, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
0xd7, 0xd8, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
0xe8, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
0xff, 0xc0, 0x00, 0x11, /* SOF0 (start of frame 0 */
0x08, /* data precision */
#define JPEG_HEIGHT_OFFSET 493
0x01, 0xe0, /* height */
0x02, 0x80, /* width */
0x03, /* component number */
0x01,
0x21, /* samples Y = jpeg 422 */
0x00, /* quant Y */
0x02, 0x11, 0x01, /* samples CbCr - quant CbCr */
0x03, 0x11, 0x01,
0xff, 0xda, 0x00, 0x0c, /* SOS (start of scan) */
0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00
#define JPEG_HDR_SZ 521
};
struct sd {
struct gspca_dev gspca_dev; /* !! must be the first item */
struct v4l2_ctrl *jpegqual;
struct v4l2_ctrl *sharpness;
struct v4l2_ctrl *gamma;
struct v4l2_ctrl *blue;
struct v4l2_ctrl *red;
u8 framerate;
u8 quality; /* webcam current JPEG quality (0..16) */
s8 ag_cnt; /* autogain / start counter for tp6810 */
#define AG_CNT_START 13 /* check gain every N frames */
u8 bridge;
u8 sensor;
u8 jpeg_hdr[JPEG_HDR_SZ];
};
enum bridges {
BRIDGE_TP6800,
BRIDGE_TP6810,
};
enum sensors {
SENSOR_CX0342,
SENSOR_SOI763A, /* ~= ov7630 / ov7648 */
NSENSORS
};
static const struct v4l2_pix_format vga_mode[] = {
{320, 240, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 4 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG},
{640, 480, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG}
};
/*
* JPEG quality
* index: webcam compression
* value: JPEG quality in %
*/
static const u8 jpeg_q[17] = {
88, 77, 67, 57, 55, 55, 45, 45, 36, 36, 30, 30, 26, 26, 22, 22, 94
};
#define BULK_OUT_SIZE 0x20
#if BULK_OUT_SIZE > USB_BUF_SZ
#error "USB buffer too small"
#endif
#define DEFAULT_FRAME_RATE 30
static const u8 rates[] = {30, 20, 15, 10, 7, 5};
static const struct framerates framerates[] = {
{
.rates = rates,
.nrates = ARRAY_SIZE(rates)
},
{
.rates = rates,
.nrates = ARRAY_SIZE(rates)
}
};
static const u8 rates_6810[] = {30, 15, 10, 7, 5};
static const struct framerates framerates_6810[] = {
{
.rates = rates_6810,
.nrates = ARRAY_SIZE(rates_6810)
},
{
.rates = rates_6810,
.nrates = ARRAY_SIZE(rates_6810)
}
};
/*
* webcam quality in %
* the last value is the ultra fine quality
*/
/* TP6800 register offsets */
#define TP6800_R10_SIF_TYPE 0x10
#define TP6800_R11_SIF_CONTROL 0x11
#define TP6800_R12_SIF_ADDR_S 0x12
#define TP6800_R13_SIF_TX_DATA 0x13
#define TP6800_R14_SIF_RX_DATA 0x14
#define TP6800_R15_GPIO_PU 0x15
#define TP6800_R16_GPIO_PD 0x16
#define TP6800_R17_GPIO_IO 0x17
#define TP6800_R18_GPIO_DATA 0x18
#define TP6800_R19_SIF_ADDR_S2 0x19
#define TP6800_R1A_SIF_TX_DATA2 0x1a
#define TP6800_R1B_SIF_RX_DATA2 0x1b
#define TP6800_R21_ENDP_1_CTL 0x21
#define TP6800_R2F_TIMING_CFG 0x2f
#define TP6800_R30_SENSOR_CFG 0x30
#define TP6800_R31_PIXEL_START 0x31
#define TP6800_R32_PIXEL_END_L 0x32
#define TP6800_R33_PIXEL_END_H 0x33
#define TP6800_R34_LINE_START 0x34
#define TP6800_R35_LINE_END_L 0x35
#define TP6800_R36_LINE_END_H 0x36
#define TP6800_R37_FRONT_DARK_ST 0x37
#define TP6800_R38_FRONT_DARK_END 0x38
#define TP6800_R39_REAR_DARK_ST_L 0x39
#define TP6800_R3A_REAR_DARK_ST_H 0x3a
#define TP6800_R3B_REAR_DARK_END_L 0x3b
#define TP6800_R3C_REAR_DARK_END_H 0x3c
#define TP6800_R3D_HORIZ_DARK_LINE_L 0x3d
#define TP6800_R3E_HORIZ_DARK_LINE_H 0x3e
#define TP6800_R3F_FRAME_RATE 0x3f
#define TP6800_R50 0x50
#define TP6800_R51 0x51
#define TP6800_R52 0x52
#define TP6800_R53 0x53
#define TP6800_R54_DARK_CFG 0x54
#define TP6800_R55_GAMMA_R 0x55
#define TP6800_R56_GAMMA_G 0x56
#define TP6800_R57_GAMMA_B 0x57
#define TP6800_R5C_EDGE_THRLD 0x5c
#define TP6800_R5D_DEMOSAIC_CFG 0x5d
#define TP6800_R78_FORMAT 0x78
#define TP6800_R79_QUALITY 0x79
#define TP6800_R7A_BLK_THRLD 0x7a
/* CX0342 register offsets */
#define CX0342_SENSOR_ID 0x00
#define CX0342_VERSION_NO 0x01
#define CX0342_ORG_X_L 0x02
#define CX0342_ORG_X_H 0x03
#define CX0342_ORG_Y_L 0x04
#define CX0342_ORG_Y_H 0x05
#define CX0342_STOP_X_L 0x06
#define CX0342_STOP_X_H 0x07
#define CX0342_STOP_Y_L 0x08
#define CX0342_STOP_Y_H 0x09
#define CX0342_FRAME_WIDTH_L 0x0a
#define CX0342_FRAME_WIDTH_H 0x0b
#define CX0342_FRAME_HEIGH_L 0x0c
#define CX0342_FRAME_HEIGH_H 0x0d
#define CX0342_EXPO_LINE_L 0x10
#define CX0342_EXPO_LINE_H 0x11
#define CX0342_EXPO_CLK_L 0x12
#define CX0342_EXPO_CLK_H 0x13
#define CX0342_RAW_GRGAIN_L 0x14
#define CX0342_RAW_GRGAIN_H 0x15
#define CX0342_RAW_GBGAIN_L 0x16
#define CX0342_RAW_GBGAIN_H 0x17
#define CX0342_RAW_RGAIN_L 0x18
#define CX0342_RAW_RGAIN_H 0x19
#define CX0342_RAW_BGAIN_L 0x1a
#define CX0342_RAW_BGAIN_H 0x1b
#define CX0342_GLOBAL_GAIN 0x1c
#define CX0342_SYS_CTRL_0 0x20
#define CX0342_SYS_CTRL_1 0x21
#define CX0342_SYS_CTRL_2 0x22
#define CX0342_BYPASS_MODE 0x23
#define CX0342_SYS_CTRL_3 0x24
#define CX0342_TIMING_EN 0x25
#define CX0342_OUTPUT_CTRL 0x26
#define CX0342_AUTO_ADC_CALIB 0x27
#define CX0342_SYS_CTRL_4 0x28
#define CX0342_ADCGN 0x30
#define CX0342_SLPCR 0x31
#define CX0342_SLPFN_LO 0x32
#define CX0342_ADC_CTL 0x33
#define CX0342_LVRST_BLBIAS 0x34
#define CX0342_VTHSEL 0x35
#define CX0342_RAMP_RIV 0x36
#define CX0342_LDOSEL 0x37
#define CX0342_CLOCK_GEN 0x40
#define CX0342_SOFT_RESET 0x41
#define CX0342_PLL 0x42
#define CX0342_DR_ENH_PULSE_OFFSET_L 0x43
#define CX0342_DR_ENH_PULSE_OFFSET_H 0x44
#define CX0342_DR_ENH_PULSE_POS_L 0x45
#define CX0342_DR_ENH_PULSE_POS_H 0x46
#define CX0342_DR_ENH_PULSE_WIDTH 0x47
#define CX0342_AS_CURRENT_CNT_L 0x48
#define CX0342_AS_CURRENT_CNT_H 0x49
#define CX0342_AS_PREVIOUS_CNT_L 0x4a
#define CX0342_AS_PREVIOUS_CNT_H 0x4b
#define CX0342_SPV_VALUE_L 0x4c
#define CX0342_SPV_VALUE_H 0x4d
#define CX0342_GPXLTHD_L 0x50
#define CX0342_GPXLTHD_H 0x51
#define CX0342_RBPXLTHD_L 0x52
#define CX0342_RBPXLTHD_H 0x53
#define CX0342_PLANETHD_L 0x54
#define CX0342_PLANETHD_H 0x55
#define CX0342_ROWDARK_TH 0x56
#define CX0342_ROWDARK_TOL 0x57
#define CX0342_RB_GAP_L 0x58
#define CX0342_RB_GAP_H 0x59
#define CX0342_G_GAP_L 0x5a
#define CX0342_G_GAP_H 0x5b
#define CX0342_AUTO_ROW_DARK 0x60
#define CX0342_MANUAL_DARK_VALUE 0x61
#define CX0342_GB_DARK_OFFSET 0x62
#define CX0342_GR_DARK_OFFSET 0x63
#define CX0342_RED_DARK_OFFSET 0x64
#define CX0342_BLUE_DARK_OFFSET 0x65
#define CX0342_DATA_SCALING_MULTI 0x66
#define CX0342_AUTOD_Q_FRAME 0x67
#define CX0342_AUTOD_ALLOW_VARI 0x68
#define CX0342_AUTO_DARK_VALUE_L 0x69
#define CX0342_AUTO_DARK_VALUE_H 0x6a
#define CX0342_IO_CTRL_0 0x70
#define CX0342_IO_CTRL_1 0x71
#define CX0342_IO_CTRL_2 0x72
#define CX0342_IDLE_CTRL 0x73
#define CX0342_TEST_MODE 0x74
#define CX0342_FRAME_FIX_DATA_TEST 0x75
#define CX0342_FRAME_CNT_TEST 0x76
#define CX0342_RST_OVERFLOW_L 0x80
#define CX0342_RST_OVERFLOW_H 0x81
#define CX0342_RST_UNDERFLOW_L 0x82
#define CX0342_RST_UNDERFLOW_H 0x83
#define CX0342_DATA_OVERFLOW_L 0x84
#define CX0342_DATA_OVERFLOW_H 0x85
#define CX0342_DATA_UNDERFLOW_L 0x86
#define CX0342_DATA_UNDERFLOW_H 0x87
#define CX0342_CHANNEL_0_0_L_irst 0x90
#define CX0342_CHANNEL_0_0_H_irst 0x91
#define CX0342_CHANNEL_0_1_L_irst 0x92
#define CX0342_CHANNEL_0_1_H_irst 0x93
#define CX0342_CHANNEL_0_2_L_irst 0x94
#define CX0342_CHANNEL_0_2_H_irst 0x95
#define CX0342_CHANNEL_0_3_L_irst 0x96
#define CX0342_CHANNEL_0_3_H_irst 0x97
#define CX0342_CHANNEL_0_4_L_irst 0x98
#define CX0342_CHANNEL_0_4_H_irst 0x99
#define CX0342_CHANNEL_0_5_L_irst 0x9a
#define CX0342_CHANNEL_0_5_H_irst 0x9b
#define CX0342_CHANNEL_0_6_L_irst 0x9c
#define CX0342_CHANNEL_0_6_H_irst 0x9d
#define CX0342_CHANNEL_0_7_L_irst 0x9e
#define CX0342_CHANNEL_0_7_H_irst 0x9f
#define CX0342_CHANNEL_1_0_L_itx 0xa0
#define CX0342_CHANNEL_1_0_H_itx 0xa1
#define CX0342_CHANNEL_1_1_L_itx 0xa2
#define CX0342_CHANNEL_1_1_H_itx 0xa3
#define CX0342_CHANNEL_1_2_L_itx 0xa4
#define CX0342_CHANNEL_1_2_H_itx 0xa5
#define CX0342_CHANNEL_1_3_L_itx 0xa6
#define CX0342_CHANNEL_1_3_H_itx 0xa7
#define CX0342_CHANNEL_1_4_L_itx 0xa8
#define CX0342_CHANNEL_1_4_H_itx 0xa9
#define CX0342_CHANNEL_1_5_L_itx 0xaa
#define CX0342_CHANNEL_1_5_H_itx 0xab
#define CX0342_CHANNEL_1_6_L_itx 0xac
#define CX0342_CHANNEL_1_6_H_itx 0xad
#define CX0342_CHANNEL_1_7_L_itx 0xae
#define CX0342_CHANNEL_1_7_H_itx 0xaf
#define CX0342_CHANNEL_2_0_L_iwl 0xb0
#define CX0342_CHANNEL_2_0_H_iwl 0xb1
#define CX0342_CHANNEL_2_1_L_iwl 0xb2
#define CX0342_CHANNEL_2_1_H_iwl 0xb3
#define CX0342_CHANNEL_2_2_L_iwl 0xb4
#define CX0342_CHANNEL_2_2_H_iwl 0xb5
#define CX0342_CHANNEL_2_3_L_iwl 0xb6
#define CX0342_CHANNEL_2_3_H_iwl 0xb7
#define CX0342_CHANNEL_2_4_L_iwl 0xb8
#define CX0342_CHANNEL_2_4_H_iwl 0xb9
#define CX0342_CHANNEL_2_5_L_iwl 0xba
#define CX0342_CHANNEL_2_5_H_iwl 0xbb
#define CX0342_CHANNEL_2_6_L_iwl 0xbc
#define CX0342_CHANNEL_2_6_H_iwl 0xbd
#define CX0342_CHANNEL_2_7_L_iwl 0xbe
#define CX0342_CHANNEL_2_7_H_iwl 0xbf
#define CX0342_CHANNEL_3_0_L_ensp 0xc0
#define CX0342_CHANNEL_3_0_H_ensp 0xc1
#define CX0342_CHANNEL_3_1_L_ensp 0xc2
#define CX0342_CHANNEL_3_1_H_ensp 0xc3
#define CX0342_CHANNEL_3_2_L_ensp 0xc4
#define CX0342_CHANNEL_3_2_H_ensp 0xc5
#define CX0342_CHANNEL_3_3_L_ensp 0xc6
#define CX0342_CHANNEL_3_3_H_ensp 0xc7
#define CX0342_CHANNEL_3_4_L_ensp 0xc8
#define CX0342_CHANNEL_3_4_H_ensp 0xc9
#define CX0342_CHANNEL_3_5_L_ensp 0xca
#define CX0342_CHANNEL_3_5_H_ensp 0xcb
#define CX0342_CHANNEL_3_6_L_ensp 0xcc
#define CX0342_CHANNEL_3_6_H_ensp 0xcd
#define CX0342_CHANNEL_3_7_L_ensp 0xce
#define CX0342_CHANNEL_3_7_H_ensp 0xcf
#define CX0342_CHANNEL_4_0_L_sela 0xd0
#define CX0342_CHANNEL_4_0_H_sela 0xd1
#define CX0342_CHANNEL_4_1_L_sela 0xd2
#define CX0342_CHANNEL_4_1_H_sela 0xd3
#define CX0342_CHANNEL_5_0_L_intla 0xe0
#define CX0342_CHANNEL_5_0_H_intla 0xe1
#define CX0342_CHANNEL_5_1_L_intla 0xe2
#define CX0342_CHANNEL_5_1_H_intla 0xe3
#define CX0342_CHANNEL_5_2_L_intla 0xe4
#define CX0342_CHANNEL_5_2_H_intla 0xe5
#define CX0342_CHANNEL_5_3_L_intla 0xe6
#define CX0342_CHANNEL_5_3_H_intla 0xe7
#define CX0342_CHANNEL_6_0_L_xa_sel_pos 0xf0
#define CX0342_CHANNEL_6_0_H_xa_sel_pos 0xf1
#define CX0342_CHANNEL_7_1_L_cds_pos 0xf2
#define CX0342_CHANNEL_7_1_H_cds_pos 0xf3
#define CX0342_SENSOR_HEIGHT_L 0xfb
#define CX0342_SENSOR_HEIGHT_H 0xfc
#define CX0342_SENSOR_WIDTH_L 0xfd
#define CX0342_SENSOR_WIDTH_H 0xfe
#define CX0342_VSYNC_HSYNC_READ 0xff
struct cmd {
u8 reg;
u8 val;
};
static const u8 DQT[17][130] = {
/* Define quantization table (thanks to Thomas Kaiser) */
{ /* Quality 0 */
0x00,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x01,
0x04, 0x04, 0x04, 0x06, 0x05, 0x06, 0x0b, 0x06,
0x06, 0x0b, 0x18, 0x10, 0x0e, 0x10, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
},
{ /* Quality 1 */
0x00,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x09, 0x09, 0x09, 0x09, 0x09,
0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,
0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,
0x01,
0x08, 0x09, 0x09, 0x0c, 0x0a, 0x0c, 0x17, 0x0d,
0x0d, 0x17, 0x31, 0x21, 0x1c, 0x21, 0x31, 0x31,
0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
},
{ /* Quality 2 */
0x00,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x06, 0x06, 0x06, 0x04, 0x04, 0x04,
0x04, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
0x06, 0x06, 0x06, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e,
0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e,
0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e,
0x01,
0x0c, 0x0d, 0x0d, 0x12, 0x0f, 0x12, 0x23, 0x13,
0x13, 0x23, 0x4a, 0x31, 0x2a, 0x31, 0x4a, 0x4a,
0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a,
0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a,
0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a,
0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a,
0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a,
0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a,
},
{ /* Quality 3 */
0x00,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04,
0x04, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x13, 0x13, 0x13, 0x13, 0x13,
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
0x01,
0x11, 0x12, 0x12, 0x18, 0x15, 0x18, 0x2f, 0x1a,
0x1a, 0x2f, 0x63, 0x42, 0x38, 0x42, 0x63, 0x63,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
},
{ /* Quality 4 */
0x00,
0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x0a, 0x0a, 0x0a, 0x05, 0x05, 0x05,
0x05, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a,
0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a,
0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a,
0x0a, 0x0a, 0x0a, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x01,
0x11, 0x16, 0x16, 0x1e, 0x1a, 0x1e, 0x3a, 0x20,
0x20, 0x3a, 0x7b, 0x52, 0x46, 0x52, 0x7b, 0x7b,
0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b,
0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b,
0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b,
0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b,
0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b,
0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b,
},
{ /* Quality 5 */
0x00,
0x04, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
0x06, 0x06, 0x0c, 0x0c, 0x0c, 0x06, 0x06, 0x06,
0x06, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
0x0c, 0x0c, 0x0c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c,
0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c,
0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c,
0x01,
0x11, 0x1b, 0x1b, 0x24, 0x1f, 0x24, 0x46, 0x27,
0x27, 0x46, 0x94, 0x63, 0x54, 0x63, 0x94, 0x94,
0x94, 0x94, 0x94, 0x94, 0x94, 0x94, 0x94, 0x94,
0x94, 0x94, 0x94, 0x94, 0x94, 0x94, 0x94, 0x94,
0x94, 0x94, 0x94, 0x94, 0x94, 0x94, 0x94, 0x94,
0x94, 0x94, 0x94, 0x94, 0x94, 0x94, 0x94, 0x94,
0x94, 0x94, 0x94, 0x94, 0x94, 0x94, 0x94, 0x94,
0x94, 0x94, 0x94, 0x94, 0x94, 0x94, 0x94, 0x94,
},
{ /* Quality 6 */
0x00,
0x05, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
0x07, 0x07, 0x0e, 0x0e, 0x0e, 0x07, 0x07, 0x07,
0x07, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e,
0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e,
0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e,
0x0e, 0x0e, 0x0e, 0x21, 0x21, 0x21, 0x21, 0x21,
0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21,
0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21,
0x01,
0x15, 0x1f, 0x1f, 0x2a, 0x24, 0x2a, 0x52, 0x2d,
0x2d, 0x52, 0xad, 0x73, 0x62, 0x73, 0xad, 0xad,
0xad, 0xad, 0xad, 0xad, 0xad, 0xad, 0xad, 0xad,
0xad, 0xad, 0xad, 0xad, 0xad, 0xad, 0xad, 0xad,
0xad, 0xad, 0xad, 0xad, 0xad, 0xad, 0xad, 0xad,
0xad, 0xad, 0xad, 0xad, 0xad, 0xad, 0xad, 0xad,
0xad, 0xad, 0xad, 0xad, 0xad, 0xad, 0xad, 0xad,
0xad, 0xad, 0xad, 0xad, 0xad, 0xad, 0xad, 0xad,
},
{ /* Quality 7 */
0x00,
0x05, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x10, 0x10, 0x10, 0x08, 0x08, 0x08,
0x08, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x10, 0x10, 0x26, 0x26, 0x26, 0x26, 0x26,
0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,
0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,
0x01,
0x15, 0x24, 0x24, 0x30, 0x2a, 0x30, 0x5e, 0x34,
0x34, 0x5e, 0xc6, 0x84, 0x70, 0x84, 0xc6, 0xc6,
0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6,
0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6,
0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6,
0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6,
0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6,
0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6,
},
{ /* Quality 8 */
0x00,
0x06, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a,
0x0a, 0x0a, 0x14, 0x14, 0x14, 0x0a, 0x0a, 0x0a,
0x0a, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14,
0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14,
0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14,
0x14, 0x14, 0x14, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f,
0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f,
0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f,
0x01,
0x19, 0x2d, 0x2d, 0x3c, 0x34, 0x3c, 0x75, 0x41,
0x41, 0x75, 0xf7, 0xa5, 0x8c, 0xa5, 0xf7, 0xf7,
0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7,
0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7,
0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7,
0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7,
0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7,
0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7,
},
{ /* Quality 9 */
0x00,
0x06, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
0x0c, 0x0c, 0x18, 0x18, 0x18, 0x0c, 0x0c, 0x0c,
0x0c, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x39, 0x39, 0x39, 0x39, 0x39,
0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39,
0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39,
0x01,
0x19, 0x36, 0x36, 0x48, 0x3f, 0x48, 0x8d, 0x4e,
0x4e, 0x8d, 0xff, 0xc6, 0xa8, 0xc6, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
},
{ /* Quality 10 */
0x00,
0x07, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e,
0x0e, 0x0e, 0x1c, 0x1c, 0x1c, 0x0e, 0x0e, 0x0e,
0x0e, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c,
0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c,
0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c,
0x1c, 0x1c, 0x1c, 0x42, 0x42, 0x42, 0x42, 0x42,
0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42,
0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42,
0x01,
0x1d, 0x3f, 0x3f, 0x54, 0x49, 0x54, 0xa4, 0x5b,
0x5b, 0xa4, 0xff, 0xe7, 0xc4, 0xe7, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
},
{ /* Quality 11 */
0x00,
0x07, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x10, 0x20, 0x20, 0x20, 0x10, 0x10, 0x10,
0x10, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,
0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,
0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,
0x01,
0x1d, 0x48, 0x48, 0x60, 0x54, 0x60, 0xbc, 0x68,
0x68, 0xbc, 0xff, 0xff, 0xe0, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
},
{ /* Quality 12 */
0x00,
0x08, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14,
0x14, 0x14, 0x28, 0x28, 0x28, 0x14, 0x14, 0x14,
0x14, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28,
0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28,
0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28,
0x28, 0x28, 0x28, 0x5f, 0x5f, 0x5f, 0x5f, 0x5f,
0x5f, 0x5f, 0x5f, 0x5f, 0x5f, 0x5f, 0x5f, 0x5f,
0x5f, 0x5f, 0x5f, 0x5f, 0x5f, 0x5f, 0x5f, 0x5f,
0x01,
0x22, 0x5a, 0x5a, 0x78, 0x69, 0x78, 0xeb, 0x82,
0x82, 0xeb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
},
{ /* Quality 13 */
0x00,
0x08, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x30, 0x30, 0x30, 0x18, 0x18, 0x18,
0x18, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
0x30, 0x30, 0x30, 0x72, 0x72, 0x72, 0x72, 0x72,
0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72,
0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72,
0x01,
0x22, 0x6c, 0x6c, 0x90, 0x7e, 0x90, 0xff, 0x9c,
0x9c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
},
{ /* Quality 14 */
0x00,
0x0a, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c,
0x1c, 0x1c, 0x38, 0x38, 0x38, 0x1c, 0x1c, 0x1c,
0x1c, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38,
0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38,
0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38,
0x38, 0x38, 0x38, 0x85, 0x85, 0x85, 0x85, 0x85,
0x85, 0x85, 0x85, 0x85, 0x85, 0x85, 0x85, 0x85,
0x85, 0x85, 0x85, 0x85, 0x85, 0x85, 0x85, 0x85,
0x01,
0x2a, 0x7e, 0x7e, 0xa8, 0x93, 0xa8, 0xff, 0xb6,
0xb6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
},
{ /* Quality 15 */
0x00,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x40, 0x40, 0x40, 0x20, 0x20, 0x20,
0x20, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
0x40, 0x40, 0x40, 0x98, 0x98, 0x98, 0x98, 0x98,
0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98,
0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98,
0x01,
0x2a, 0x90, 0x90, 0xc0, 0xa8, 0xc0, 0xff, 0xd0,
0xd0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
},
{ /* Quality 16-31 */
0x00,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x01,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
}
};
static const struct cmd tp6810_cx_init_common[] = {
{0x1c, 0x00},
{TP6800_R10_SIF_TYPE, 0x00},
{0x4e, 0x00},
{0x4f, 0x00},
{TP6800_R50, 0xff},
{TP6800_R51, 0x03},
{0x00, 0x07},
{TP6800_R79_QUALITY, 0x03},
{TP6800_R2F_TIMING_CFG, 0x37},
{TP6800_R30_SENSOR_CFG, 0x10},
{TP6800_R21_ENDP_1_CTL, 0x00},
{TP6800_R52, 0x40},
{TP6800_R53, 0x40},
{TP6800_R54_DARK_CFG, 0x40},
{TP6800_R30_SENSOR_CFG, 0x18},
{0x4b, 0x00},
{TP6800_R3F_FRAME_RATE, 0x83},
{TP6800_R79_QUALITY, 0x05},
{TP6800_R21_ENDP_1_CTL, 0x00},
{0x7c, 0x04},
{0x25, 0x14},
{0x26, 0x0f},
{0x7b, 0x10},
};
static const struct cmd tp6810_ov_init_common[] = {
{0x1c, 0x00},
{TP6800_R10_SIF_TYPE, 0x00},
{0x4e, 0x00},
{0x4f, 0x00},
{TP6800_R50, 0xff},
{TP6800_R51, 0x03},
{0x00, 0x07},
{TP6800_R52, 0x40},
{TP6800_R53, 0x40},
{TP6800_R54_DARK_CFG, 0x40},
{TP6800_R79_QUALITY, 0x03},
{TP6800_R2F_TIMING_CFG, 0x17},
{TP6800_R30_SENSOR_CFG, 0x18},
{TP6800_R21_ENDP_1_CTL, 0x00},
{TP6800_R3F_FRAME_RATE, 0x86},
{0x25, 0x18},
{0x26, 0x0f},
{0x7b, 0x90},
};
static const struct cmd tp6810_bridge_start[] = {
{0x59, 0x88},
{0x5a, 0x0f},
{0x5b, 0x4e},
{TP6800_R5C_EDGE_THRLD, 0x63},
{TP6800_R5D_DEMOSAIC_CFG, 0x00},
{0x03, 0x7f},
{0x04, 0x80},
{0x06, 0x00},
{0x00, 0x00},
};
static const struct cmd tp6810_late_start[] = {
{0x7d, 0x01},
{0xb0, 0x04},
{0xb1, 0x04},
{0xb2, 0x04},
{0xb3, 0x04},
{0xb4, 0x04},
{0xb5, 0x04},
{0xb6, 0x08},
{0xb7, 0x08},
{0xb8, 0x04},
{0xb9, 0x04},
{0xba, 0x04},
{0xbb, 0x04},
{0xbc, 0x04},
{0xbd, 0x08},
{0xbe, 0x08},
{0xbf, 0x08},
{0xc0, 0x04},
{0xc1, 0x04},
{0xc2, 0x08},
{0xc3, 0x08},
{0xc4, 0x08},
{0xc5, 0x08},
{0xc6, 0x08},
{0xc7, 0x13},
{0xc8, 0x04},
{0xc9, 0x08},
{0xca, 0x08},
{0xcb, 0x08},
{0xcc, 0x08},
{0xcd, 0x08},
{0xce, 0x13},
{0xcf, 0x13},
{0xd0, 0x08},
{0xd1, 0x08},
{0xd2, 0x08},
{0xd3, 0x08},
{0xd4, 0x08},
{0xd5, 0x13},
{0xd6, 0x13},
{0xd7, 0x13},
{0xd8, 0x08},
{0xd9, 0x08},
{0xda, 0x08},
{0xdb, 0x08},
{0xdc, 0x13},
{0xdd, 0x13},
{0xde, 0x13},
{0xdf, 0x13},
{0xe0, 0x08},
{0xe1, 0x08},
{0xe2, 0x08},
{0xe3, 0x13},
{0xe4, 0x13},
{0xe5, 0x13},
{0xe6, 0x13},
{0xe7, 0x13},
{0xe8, 0x08},
{0xe9, 0x08},
{0xea, 0x13},
{0xeb, 0x13},
{0xec, 0x13},
{0xed, 0x13},
{0xee, 0x13},
{0xef, 0x13},
{0x7d, 0x02},
/* later after isoc start */
{0x7d, 0x08},
{0x7d, 0x00},
};
static const struct cmd cx0342_timing_seq[] = {
{CX0342_CHANNEL_0_1_L_irst, 0x20},
{CX0342_CHANNEL_0_2_L_irst, 0x24},
{CX0342_CHANNEL_0_2_H_irst, 0x00},
{CX0342_CHANNEL_0_3_L_irst, 0x2f},
{CX0342_CHANNEL_0_3_H_irst, 0x00},
{CX0342_CHANNEL_1_0_L_itx, 0x02},
{CX0342_CHANNEL_1_0_H_itx, 0x00},
{CX0342_CHANNEL_1_1_L_itx, 0x20},
{CX0342_CHANNEL_1_1_H_itx, 0x00},
{CX0342_CHANNEL_1_2_L_itx, 0xe4},
{CX0342_CHANNEL_1_2_H_itx, 0x00},
{CX0342_CHANNEL_1_3_L_itx, 0xee},
{CX0342_CHANNEL_1_3_H_itx, 0x00},
{CX0342_CHANNEL_2_0_L_iwl, 0x30},
{CX0342_CHANNEL_2_0_H_iwl, 0x00},
{CX0342_CHANNEL_3_0_L_ensp, 0x34},
{CX0342_CHANNEL_3_1_L_ensp, 0xe2},
{CX0342_CHANNEL_3_1_H_ensp, 0x00},
{CX0342_CHANNEL_3_2_L_ensp, 0xf6},
{CX0342_CHANNEL_3_2_H_ensp, 0x00},
{CX0342_CHANNEL_3_3_L_ensp, 0xf4},
{CX0342_CHANNEL_3_3_H_ensp, 0x02},
{CX0342_CHANNEL_4_0_L_sela, 0x26},
{CX0342_CHANNEL_4_0_H_sela, 0x00},
{CX0342_CHANNEL_4_1_L_sela, 0xe2},
{CX0342_CHANNEL_4_1_H_sela, 0x00},
{CX0342_CHANNEL_5_0_L_intla, 0x26},
{CX0342_CHANNEL_5_1_L_intla, 0x29},
{CX0342_CHANNEL_5_2_L_intla, 0xf0},
{CX0342_CHANNEL_5_2_H_intla, 0x00},
{CX0342_CHANNEL_5_3_L_intla, 0xf3},
{CX0342_CHANNEL_5_3_H_intla, 0x00},
{CX0342_CHANNEL_6_0_L_xa_sel_pos, 0x24},
{CX0342_CHANNEL_7_1_L_cds_pos, 0x02},
{CX0342_TIMING_EN, 0x01},
};
/* define the JPEG header */
static void jpeg_define(u8 *jpeg_hdr,
int height,
int width)
{
memcpy(jpeg_hdr, jpeg_head, sizeof jpeg_head);
jpeg_hdr[JPEG_HEIGHT_OFFSET + 0] = height >> 8;
jpeg_hdr[JPEG_HEIGHT_OFFSET + 1] = height;
jpeg_hdr[JPEG_HEIGHT_OFFSET + 2] = width >> 8;
jpeg_hdr[JPEG_HEIGHT_OFFSET + 3] = width;
}
/* set the JPEG quality for sensor soi763a */
static void jpeg_set_qual(u8 *jpeg_hdr,
int quality)
{
int i, sc;
if (quality <= 0)
sc = 5000;
else if (quality < 50)
sc = 5000 / quality;
else
sc = 200 - quality * 2;
for (i = 0; i < 64; i++) {
jpeg_hdr[JPEG_QT0_OFFSET + i] =
(jpeg_head[JPEG_QT0_OFFSET + i] * sc + 50) / 100;
jpeg_hdr[JPEG_QT1_OFFSET + i] =
(jpeg_head[JPEG_QT1_OFFSET + i] * sc + 50) / 100;
}
}
static void reg_w(struct gspca_dev *gspca_dev, u8 index, u8 value)
{
struct usb_device *dev = gspca_dev->dev;
int ret;
if (gspca_dev->usb_err < 0)
return;
ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
0x0e,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
value, index, NULL, 0, 500);
if (ret < 0) {
pr_err("reg_w err %d\n", ret);
gspca_dev->usb_err = ret;
}
}
/* the returned value is in gspca_dev->usb_buf */
static void reg_r(struct gspca_dev *gspca_dev, u8 index)
{
struct usb_device *dev = gspca_dev->dev;
int ret;
if (gspca_dev->usb_err < 0)
return;
ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
0x0d,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, index, gspca_dev->usb_buf, 1, 500);
if (ret < 0) {
pr_err("reg_r err %d\n", ret);
gspca_dev->usb_err = ret;
}
}
static void reg_w_buf(struct gspca_dev *gspca_dev,
const struct cmd *p, int l)
{
do {
reg_w(gspca_dev, p->reg, p->val);
p++;
} while (--l > 0);
}
static int i2c_w(struct gspca_dev *gspca_dev, u8 index, u8 value)
{
struct sd *sd = (struct sd *) gspca_dev;
reg_w(gspca_dev, TP6800_R11_SIF_CONTROL, 0x00);
reg_w(gspca_dev, TP6800_R19_SIF_ADDR_S2, index);
reg_w(gspca_dev, TP6800_R13_SIF_TX_DATA, value);
reg_w(gspca_dev, TP6800_R11_SIF_CONTROL, 0x01);
if (sd->bridge == BRIDGE_TP6800)
return 0;
msleep(5);
reg_r(gspca_dev, TP6800_R11_SIF_CONTROL);
if (gspca_dev->usb_buf[0] == 0)
return 0;
reg_w(gspca_dev, TP6800_R11_SIF_CONTROL, 0x00);
return -1; /* error */
}
static void i2c_w_buf(struct gspca_dev *gspca_dev,
const struct cmd *p, int l)
{
do {
i2c_w(gspca_dev, p->reg, p->val);
p++;
} while (--l > 0);
}
static int i2c_r(struct gspca_dev *gspca_dev, u8 index, int len)
{
struct sd *sd = (struct sd *) gspca_dev;
int v;
reg_w(gspca_dev, TP6800_R19_SIF_ADDR_S2, index);
reg_w(gspca_dev, TP6800_R11_SIF_CONTROL, 0x02);
msleep(5);
reg_r(gspca_dev, TP6800_R14_SIF_RX_DATA);
v = gspca_dev->usb_buf[0];
if (sd->bridge == BRIDGE_TP6800)
return v;
if (len > 1) {
reg_r(gspca_dev, TP6800_R1B_SIF_RX_DATA2);
v |= (gspca_dev->usb_buf[0] << 8);
}
reg_r(gspca_dev, TP6800_R11_SIF_CONTROL);
if (gspca_dev->usb_buf[0] == 0)
return v;
reg_w(gspca_dev, TP6800_R11_SIF_CONTROL, 0x00);
return -1;
}
static void bulk_w(struct gspca_dev *gspca_dev,
u8 tag,
const u8 *data,
int length)
{
struct usb_device *dev = gspca_dev->dev;
int count, actual_count, ret;
if (gspca_dev->usb_err < 0)
return;
for (;;) {
count = length > BULK_OUT_SIZE - 1
? BULK_OUT_SIZE - 1 : length;
gspca_dev->usb_buf[0] = tag;
memcpy(&gspca_dev->usb_buf[1], data, count);
ret = usb_bulk_msg(dev,
usb_sndbulkpipe(dev, 3),
gspca_dev->usb_buf, count + 1,
&actual_count, 500);
if (ret < 0) {
pr_err("bulk write error %d tag=%02x\n",
ret, tag);
gspca_dev->usb_err = ret;
return;
}
length -= count;
if (length <= 0)
break;
data += count;
}
}
static int probe_6810(struct gspca_dev *gspca_dev)
{
u8 gpio;
int ret;
reg_r(gspca_dev, TP6800_R18_GPIO_DATA);
gpio = gspca_dev->usb_buf[0];
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio | 0x20);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio);
reg_w(gspca_dev, TP6800_R10_SIF_TYPE, 0x04); /* i2c 16 bits */
reg_w(gspca_dev, TP6800_R12_SIF_ADDR_S, 0x21); /* ov??? */
reg_w(gspca_dev, TP6800_R1A_SIF_TX_DATA2, 0x00);
if (i2c_w(gspca_dev, 0x00, 0x00) >= 0)
return SENSOR_SOI763A;
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio | 0x20);
reg_w(gspca_dev, TP6800_R10_SIF_TYPE, 0x00); /* i2c 8 bits */
reg_w(gspca_dev, TP6800_R12_SIF_ADDR_S, 0x7f); /* (unknown i2c) */
if (i2c_w(gspca_dev, 0x00, 0x00) >= 0)
return -2;
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio | 0x20);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio | 0x20);
reg_w(gspca_dev, TP6800_R10_SIF_TYPE, 0x00); /* i2c 8 bits */
reg_w(gspca_dev, TP6800_R12_SIF_ADDR_S, 0x11); /* tas??? / hv??? */
ret = i2c_r(gspca_dev, 0x00, 1);
if (ret > 0)
return -3;
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio | 0x20);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio | 0x20);
reg_w(gspca_dev, TP6800_R12_SIF_ADDR_S, 0x6e); /* po??? */
ret = i2c_r(gspca_dev, 0x00, 1);
if (ret > 0)
return -4;
ret = i2c_r(gspca_dev, 0x01, 1);
if (ret > 0)
return -5;
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio | 0x20);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio | 0x20);
reg_w(gspca_dev, TP6800_R10_SIF_TYPE, 0x04); /* i2c 16 bits */
reg_w(gspca_dev, TP6800_R12_SIF_ADDR_S, 0x5d); /* mi/mt??? */
ret = i2c_r(gspca_dev, 0x00, 2);
if (ret > 0)
return -6;
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio | 0x20);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio | 0x20);
reg_w(gspca_dev, TP6800_R12_SIF_ADDR_S, 0x5c); /* mi/mt??? */
ret = i2c_r(gspca_dev, 0x36, 2);
if (ret > 0)
return -7;
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio | 0x20);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio);
reg_w(gspca_dev, TP6800_R12_SIF_ADDR_S, 0x61); /* (unknown i2c) */
reg_w(gspca_dev, TP6800_R1A_SIF_TX_DATA2, 0x10);
if (i2c_w(gspca_dev, 0xff, 0x00) >= 0)
return -8;
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio | 0x20);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio);
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, gpio | 0x20);
reg_w(gspca_dev, TP6800_R10_SIF_TYPE, 0x00); /* i2c 8 bits */
reg_w(gspca_dev, TP6800_R12_SIF_ADDR_S, 0x20); /* cx0342 */
ret = i2c_r(gspca_dev, 0x00, 1);
if (ret > 0)
return SENSOR_CX0342;
return -9;
}
static void cx0342_6810_init(struct gspca_dev *gspca_dev)
{
static const struct cmd reg_init_1[] = {
{TP6800_R2F_TIMING_CFG, 0x2f},
{0x25, 0x02},
{TP6800_R21_ENDP_1_CTL, 0x00},
{TP6800_R3F_FRAME_RATE, 0x80},
{TP6800_R2F_TIMING_CFG, 0x2f},
{TP6800_R18_GPIO_DATA, 0xe1},
{TP6800_R18_GPIO_DATA, 0xc1},
{TP6800_R18_GPIO_DATA, 0xe1},
{TP6800_R11_SIF_CONTROL, 0x00},
};
static const struct cmd reg_init_2[] = {
{TP6800_R78_FORMAT, 0x48},
{TP6800_R11_SIF_CONTROL, 0x00},
};
static const struct cmd sensor_init[] = {
{CX0342_OUTPUT_CTRL, 0x07},
{CX0342_BYPASS_MODE, 0x58},
{CX0342_GPXLTHD_L, 0x28},
{CX0342_RBPXLTHD_L, 0x28},
{CX0342_PLANETHD_L, 0x50},
{CX0342_PLANETHD_H, 0x03},
{CX0342_RB_GAP_L, 0xff},
{CX0342_RB_GAP_H, 0x07},
{CX0342_G_GAP_L, 0xff},
{CX0342_G_GAP_H, 0x07},
{CX0342_RST_OVERFLOW_L, 0x5c},
{CX0342_RST_OVERFLOW_H, 0x01},
{CX0342_DATA_OVERFLOW_L, 0xfc},
{CX0342_DATA_OVERFLOW_H, 0x03},
{CX0342_DATA_UNDERFLOW_L, 0x00},
{CX0342_DATA_UNDERFLOW_H, 0x00},
{CX0342_SYS_CTRL_0, 0x40},
{CX0342_GLOBAL_GAIN, 0x01},
{CX0342_CLOCK_GEN, 0x00},
{CX0342_SYS_CTRL_0, 0x02},
{CX0342_IDLE_CTRL, 0x05},
{CX0342_ADCGN, 0x00},
{CX0342_ADC_CTL, 0x00},
{CX0342_LVRST_BLBIAS, 0x01},
{CX0342_VTHSEL, 0x0b},
{CX0342_RAMP_RIV, 0x0b},
{CX0342_LDOSEL, 0x07},
{CX0342_SPV_VALUE_L, 0x40},
{CX0342_SPV_VALUE_H, 0x02},
{CX0342_AUTO_ADC_CALIB, 0x81},
{CX0342_TIMING_EN, 0x01},
};
reg_w_buf(gspca_dev, reg_init_1, ARRAY_SIZE(reg_init_1));
reg_w_buf(gspca_dev, tp6810_cx_init_common,
ARRAY_SIZE(tp6810_cx_init_common));
reg_w_buf(gspca_dev, reg_init_2, ARRAY_SIZE(reg_init_2));
reg_w(gspca_dev, TP6800_R12_SIF_ADDR_S, 0x20); /* cx0342 I2C addr */
i2c_w_buf(gspca_dev, sensor_init, ARRAY_SIZE(sensor_init));
i2c_w_buf(gspca_dev, cx0342_timing_seq, ARRAY_SIZE(cx0342_timing_seq));
}
static void soi763a_6810_init(struct gspca_dev *gspca_dev)
{
static const struct cmd reg_init_1[] = {
{TP6800_R2F_TIMING_CFG, 0x2f},
{TP6800_R18_GPIO_DATA, 0xe1},
{0x25, 0x02},
{TP6800_R21_ENDP_1_CTL, 0x00},
{TP6800_R3F_FRAME_RATE, 0x80},
{TP6800_R2F_TIMING_CFG, 0x2f},
{TP6800_R18_GPIO_DATA, 0xc1},
};
static const struct cmd reg_init_2[] = {
{TP6800_R78_FORMAT, 0x54},
};
static const struct cmd sensor_init[] = {
{0x00, 0x00},
{0x01, 0x80},
{0x02, 0x80},
{0x03, 0x90},
{0x04, 0x20},
{0x05, 0x20},
{0x06, 0x80},
{0x07, 0x00},
{0x08, 0xff},
{0x09, 0xff},
{0x0a, 0x76}, /* 7630 = soi673a */
{0x0b, 0x30},
{0x0c, 0x20},
{0x0d, 0x20},
{0x0e, 0xff},
{0x0f, 0xff},
{0x10, 0x41},
{0x15, 0x14},
{0x11, 0x40},
{0x12, 0x48},
{0x13, 0x80},
{0x14, 0x80},
{0x16, 0x03},
{0x28, 0xb0},
{0x71, 0x20},
{0x75, 0x8e},
{0x17, 0x1b},
{0x18, 0xbd},
{0x19, 0x05},
{0x1a, 0xf6},
{0x1b, 0x04},
{0x1c, 0x7f}, /* omnivision */
{0x1d, 0xa2},
{0x1e, 0x00},
{0x1f, 0x00},
{0x20, 0x45},
{0x21, 0x80},
{0x22, 0x80},
{0x23, 0xee},
{0x24, 0x50},
{0x25, 0x7a},
{0x26, 0xa0},
{0x27, 0x9a},
{0x29, 0x30},
{0x2a, 0x80},
{0x2b, 0x00},
{0x2c, 0xac},
{0x2d, 0x05},
{0x2e, 0x80},
{0x2f, 0x3c},
{0x30, 0x22},
{0x31, 0x00},
{0x32, 0x86},
{0x33, 0x08},
{0x34, 0xff},
{0x35, 0xff},
{0x36, 0xff},
{0x37, 0xff},
{0x38, 0xff},
{0x39, 0xff},
{0x3a, 0xfe},
{0x3b, 0xfe},
{0x3c, 0xfe},
{0x3d, 0xfe},
{0x3e, 0xfe},
{0x3f, 0x71},
{0x40, 0xff},
{0x41, 0xff},
{0x42, 0xff},
{0x43, 0xff},
{0x44, 0xff},
{0x45, 0xff},
{0x46, 0xff},
{0x47, 0xff},
{0x48, 0xff},
{0x49, 0xff},
{0x4a, 0xfe},
{0x4b, 0xff},
{0x4c, 0x00},
{0x4d, 0x00},
{0x4e, 0xff},
{0x4f, 0xff},
{0x50, 0xff},
{0x51, 0xff},
{0x52, 0xff},
{0x53, 0xff},
{0x54, 0xff},
{0x55, 0xff},
{0x56, 0xff},
{0x57, 0xff},
{0x58, 0xff},
{0x59, 0xff},
{0x5a, 0xff},
{0x5b, 0xfe},
{0x5c, 0xff},
{0x5d, 0x8f},
{0x5e, 0xff},
{0x5f, 0x8f},
{0x60, 0xa2},
{0x61, 0x4a},
{0x62, 0xf3},
{0x63, 0x75},
{0x64, 0xf0},
{0x65, 0x00},
{0x66, 0x55},
{0x67, 0x92},
{0x68, 0xa0},
{0x69, 0x4a},
{0x6a, 0x22},
{0x6b, 0x00},
{0x6c, 0x33},
{0x6d, 0x44},
{0x6e, 0x22},
{0x6f, 0x84},
{0x70, 0x0b},
{0x72, 0x10},
{0x73, 0x50},
{0x74, 0x21},
{0x76, 0x00},
{0x77, 0xa5},
{0x78, 0x80},
{0x79, 0x80},
{0x7a, 0x80},
{0x7b, 0xe2},
{0x7c, 0x00},
{0x7d, 0xf7},
{0x7e, 0x00},
{0x7f, 0x00},
};
reg_w_buf(gspca_dev, reg_init_1, ARRAY_SIZE(reg_init_1));
reg_w_buf(gspca_dev, tp6810_ov_init_common,
ARRAY_SIZE(tp6810_ov_init_common));
reg_w_buf(gspca_dev, reg_init_2, ARRAY_SIZE(reg_init_2));
i2c_w(gspca_dev, 0x12, 0x80); /* sensor reset */
msleep(10);
i2c_w_buf(gspca_dev, sensor_init, ARRAY_SIZE(sensor_init));
}
/* set the gain and exposure */
static void setexposure(struct gspca_dev *gspca_dev, s32 expo, s32 gain,
s32 blue, s32 red)
{
struct sd *sd = (struct sd *) gspca_dev;
if (sd->sensor == SENSOR_CX0342) {
expo = (expo << 2) - 1;
i2c_w(gspca_dev, CX0342_EXPO_LINE_L, expo);
i2c_w(gspca_dev, CX0342_EXPO_LINE_H, expo >> 8);
if (sd->bridge == BRIDGE_TP6800)
i2c_w(gspca_dev, CX0342_RAW_GBGAIN_H,
gain >> 8);
i2c_w(gspca_dev, CX0342_RAW_GBGAIN_L, gain);
if (sd->bridge == BRIDGE_TP6800)
i2c_w(gspca_dev, CX0342_RAW_GRGAIN_H,
gain >> 8);
i2c_w(gspca_dev, CX0342_RAW_GRGAIN_L, gain);
if (sd->sensor == SENSOR_CX0342) {
if (sd->bridge == BRIDGE_TP6800)
i2c_w(gspca_dev, CX0342_RAW_BGAIN_H,
blue >> 8);
i2c_w(gspca_dev, CX0342_RAW_BGAIN_L, blue);
if (sd->bridge == BRIDGE_TP6800)
i2c_w(gspca_dev, CX0342_RAW_RGAIN_H,
red >> 8);
i2c_w(gspca_dev, CX0342_RAW_RGAIN_L, red);
}
i2c_w(gspca_dev, CX0342_SYS_CTRL_0,
sd->bridge == BRIDGE_TP6800 ? 0x80 : 0x81);
return;
}
/* soi763a */
i2c_w(gspca_dev, 0x10, /* AEC_H (exposure time) */
expo);
/* i2c_w(gspca_dev, 0x76, 0x02); * AEC_L ([1:0] */
i2c_w(gspca_dev, 0x00, /* gain */
gain);
}
/* set the JPEG quantization tables */
static void set_dqt(struct gspca_dev *gspca_dev, u8 q)
{
struct sd *sd = (struct sd *) gspca_dev;
/* update the jpeg quantization tables */
gspca_dbg(gspca_dev, D_STREAM, "q %d -> %d\n", sd->quality, q);
sd->quality = q;
if (q > 16)
q = 16;
if (sd->sensor == SENSOR_SOI763A)
jpeg_set_qual(sd->jpeg_hdr, jpeg_q[q]);
else
memcpy(&sd->jpeg_hdr[JPEG_QT0_OFFSET - 1],
DQT[q], sizeof DQT[0]);
}
/* set the JPEG compression quality factor */
static void setquality(struct gspca_dev *gspca_dev, s32 q)
{
struct sd *sd = (struct sd *) gspca_dev;
if (q != 16)
q = 15 - q;
reg_w(gspca_dev, TP6800_R7A_BLK_THRLD, 0x00);
reg_w(gspca_dev, TP6800_R79_QUALITY, 0x04);
reg_w(gspca_dev, TP6800_R79_QUALITY, q);
/* auto quality */
if (q == 15 && sd->bridge == BRIDGE_TP6810) {
msleep(4);
reg_w(gspca_dev, TP6800_R7A_BLK_THRLD, 0x19);
}
}
static const u8 color_null[18] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const u8 color_gain[NSENSORS][18] = {
[SENSOR_CX0342] =
{0x4c, 0x00, 0xa9, 0x00, 0x31, 0x00, /* Y R/G/B (LE values) */
0xb6, 0x03, 0x6c, 0x03, 0xe0, 0x00, /* U R/G/B */
0xdf, 0x00, 0x46, 0x03, 0xdc, 0x03}, /* V R/G/B */
[SENSOR_SOI763A] =
{0x4c, 0x00, 0x95, 0x00, 0x1d, 0x00, /* Y R/G/B (LE values) */
0xb6, 0x03, 0x6c, 0x03, 0xd7, 0x00, /* U R/G/B */
0xd5, 0x00, 0x46, 0x03, 0xdc, 0x03}, /* V R/G/B */
};
static void setgamma(struct gspca_dev *gspca_dev, s32 gamma)
{
struct sd *sd = (struct sd *) gspca_dev;
#define NGAMMA 6
static const u8 gamma_tb[NGAMMA][3][1024] = {
{ /* gamma 0 - from tp6800 + soi763a */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x02,
0x02, 0x03, 0x05, 0x07, 0x07, 0x08, 0x09, 0x09,
0x0a, 0x0c, 0x0c, 0x0d, 0x0e, 0x0e, 0x10, 0x11,
0x11, 0x12, 0x14, 0x14, 0x15, 0x16, 0x16, 0x17,
0x17, 0x18, 0x1a, 0x1a, 0x1b, 0x1b, 0x1c, 0x1e,
0x1e, 0x1f, 0x1f, 0x20, 0x20, 0x22, 0x23, 0x23,
0x25, 0x25, 0x26, 0x26, 0x27, 0x27, 0x28, 0x28,
0x29, 0x29, 0x2b, 0x2c, 0x2c, 0x2d, 0x2d, 0x2f,
0x2f, 0x30, 0x30, 0x31, 0x31, 0x33, 0x33, 0x34,
0x34, 0x34, 0x35, 0x35, 0x37, 0x37, 0x38, 0x38,
0x39, 0x39, 0x3a, 0x3a, 0x3b, 0x3b, 0x3b, 0x3c,
0x3c, 0x3d, 0x3d, 0x3f, 0x3f, 0x40, 0x40, 0x40,
0x42, 0x42, 0x43, 0x43, 0x44, 0x44, 0x44, 0x45,
0x45, 0x47, 0x47, 0x47, 0x48, 0x48, 0x49, 0x49,
0x4a, 0x4a, 0x4a, 0x4b, 0x4b, 0x4b, 0x4c, 0x4c,
0x4d, 0x4d, 0x4d, 0x4f, 0x4f, 0x50, 0x50, 0x50,
0x52, 0x52, 0x52, 0x53, 0x53, 0x54, 0x54, 0x54,
0x55, 0x55, 0x55, 0x56, 0x56, 0x58, 0x58, 0x58,
0x59, 0x59, 0x59, 0x5a, 0x5a, 0x5a, 0x5b, 0x5b,
0x5b, 0x5c, 0x5c, 0x5c, 0x5e, 0x5e, 0x5e, 0x5f,
0x5f, 0x5f, 0x60, 0x60, 0x60, 0x61, 0x61, 0x61,
0x62, 0x62, 0x62, 0x63, 0x63, 0x63, 0x65, 0x65,
0x65, 0x66, 0x66, 0x66, 0x67, 0x67, 0x67, 0x68,
0x68, 0x68, 0x69, 0x69, 0x69, 0x69, 0x6a, 0x6a,
0x6a, 0x6c, 0x6c, 0x6c, 0x6d, 0x6d, 0x6d, 0x6e,
0x6e, 0x6e, 0x6e, 0x6f, 0x6f, 0x6f, 0x70, 0x70,
0x70, 0x71, 0x71, 0x71, 0x71, 0x73, 0x73, 0x73,
0x74, 0x74, 0x74, 0x74, 0x75, 0x75, 0x75, 0x77,
0x77, 0x77, 0x77, 0x78, 0x78, 0x78, 0x79, 0x79,
0x79, 0x79, 0x7a, 0x7a, 0x7a, 0x7a, 0x7b, 0x7b,
0x7b, 0x7c, 0x7c, 0x7c, 0x7c, 0x7d, 0x7d, 0x7d,
0x7d, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x80,
0x81, 0x81, 0x81, 0x81, 0x82, 0x82, 0x82, 0x82,
0x84, 0x84, 0x84, 0x85, 0x85, 0x85, 0x85, 0x86,
0x86, 0x86, 0x86, 0x88, 0x88, 0x88, 0x88, 0x89,
0x89, 0x89, 0x89, 0x8a, 0x8a, 0x8a, 0x8a, 0x8b,
0x8b, 0x8b, 0x8b, 0x8d, 0x8d, 0x8d, 0x8d, 0x8e,
0x8e, 0x8e, 0x8e, 0x8f, 0x8f, 0x8f, 0x8f, 0x90,
0x90, 0x90, 0x90, 0x90, 0x91, 0x91, 0x91, 0x91,
0x92, 0x92, 0x92, 0x92, 0x93, 0x93, 0x93, 0x93,
0x94, 0x94, 0x94, 0x94, 0x96, 0x96, 0x96, 0x96,
0x96, 0x97, 0x97, 0x97, 0x97, 0x98, 0x98, 0x98,
0x98, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a, 0x9a,
0x9a, 0x9a, 0x9b, 0x9b, 0x9b, 0x9b, 0x9c, 0x9c,
0x9c, 0x9c, 0x9c, 0x9d, 0x9d, 0x9d, 0x9d, 0x9e,
0x9e, 0x9e, 0x9e, 0x9e, 0xa0, 0xa0, 0xa0, 0xa0,
0xa1, 0xa1, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2, 0xa2,
0xa2, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa4, 0xa4,
0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5, 0xa5, 0xa6,
0xa6, 0xa6, 0xa6, 0xa6, 0xa8, 0xa8, 0xa8, 0xa8,
0xa8, 0xa9, 0xa9, 0xa9, 0xa9, 0xab, 0xab, 0xab,
0xab, 0xab, 0xac, 0xac, 0xac, 0xac, 0xac, 0xad,
0xad, 0xad, 0xad, 0xae, 0xae, 0xae, 0xae, 0xae,
0xaf, 0xaf, 0xaf, 0xaf, 0xaf, 0xb0, 0xb0, 0xb0,
0xb0, 0xb0, 0xb1, 0xb1, 0xb1, 0xb1, 0xb1, 0xb2,
0xb2, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3, 0xb3, 0xb3,
0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb6, 0xb6, 0xb6,
0xb6, 0xb6, 0xb7, 0xb7, 0xb7, 0xb7, 0xb7, 0xb8,
0xb8, 0xb8, 0xb8, 0xb8, 0xb9, 0xb9, 0xb9, 0xb9,
0xb9, 0xba, 0xba, 0xba, 0xba, 0xba, 0xbc, 0xbc,
0xbc, 0xbc, 0xbc, 0xbd, 0xbd, 0xbd, 0xbd, 0xbd,
0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbf, 0xbf, 0xbf,
0xbf, 0xbf, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc2,
0xc2, 0xc2, 0xc2, 0xc2, 0xc3, 0xc3, 0xc3, 0xc3,
0xc3, 0xc4, 0xc4, 0xc4, 0xc4, 0xc4, 0xc5, 0xc5,
0xc5, 0xc5, 0xc5, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6,
0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc9, 0xc9, 0xc9,
0xc9, 0xc9, 0xc9, 0xca, 0xca, 0xca, 0xca, 0xca,
0xcb, 0xcb, 0xcb, 0xcb, 0xcb, 0xcc, 0xcc, 0xcc,
0xcc, 0xcc, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xce,
0xce, 0xce, 0xce, 0xce, 0xcf, 0xcf, 0xcf, 0xcf,
0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd1, 0xd1,
0xd1, 0xd1, 0xd1, 0xd1, 0xd3, 0xd3, 0xd3, 0xd3,
0xd3, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd6, 0xd6,
0xd6, 0xd6, 0xd6, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7,
0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd9, 0xd9, 0xd9,
0xd9, 0xd9, 0xda, 0xda, 0xda, 0xda, 0xda, 0xdb,
0xdb, 0xdb, 0xdb, 0xdb, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xdf,
0xdf, 0xdf, 0xdf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe0,
0xe0, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe2, 0xe2,
0xe2, 0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3,
0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5,
0xe5, 0xe5, 0xe6, 0xe6, 0xe6, 0xe6, 0xe6, 0xe7,
0xe7, 0xe7, 0xe7, 0xe7, 0xe8, 0xe8, 0xe8, 0xe8,
0xe8, 0xe9, 0xe9, 0xe9, 0xe9, 0xeb, 0xeb, 0xeb,
0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec, 0xec, 0xed,
0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee,
0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0,
0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf3,
0xf3, 0xf3, 0xf3, 0xf3, 0xf4, 0xf4, 0xf4, 0xf4,
0xf4, 0xf5, 0xf5, 0xf5, 0xf5, 0xf6, 0xf6, 0xf6,
0xf6, 0xf6, 0xf7, 0xf7, 0xf7, 0xf7, 0xf8, 0xf8,
0xf8, 0xf8, 0xf8, 0xf9, 0xf9, 0xf9, 0xf9, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x02,
0x02, 0x03, 0x05, 0x07, 0x07, 0x08, 0x09, 0x09,
0x0a, 0x0c, 0x0c, 0x0d, 0x0e, 0x0e, 0x10, 0x11,
0x11, 0x12, 0x14, 0x14, 0x15, 0x16, 0x16, 0x17,
0x17, 0x18, 0x1a, 0x1a, 0x1b, 0x1b, 0x1c, 0x1e,
0x1e, 0x1f, 0x1f, 0x20, 0x20, 0x22, 0x23, 0x23,
0x25, 0x25, 0x26, 0x26, 0x27, 0x27, 0x28, 0x28,
0x29, 0x29, 0x2b, 0x2c, 0x2c, 0x2d, 0x2d, 0x2f,
0x2f, 0x30, 0x30, 0x31, 0x31, 0x33, 0x33, 0x34,
0x34, 0x34, 0x35, 0x35, 0x37, 0x37, 0x38, 0x38,
0x39, 0x39, 0x3a, 0x3a, 0x3b, 0x3b, 0x3b, 0x3c,
0x3c, 0x3d, 0x3d, 0x3f, 0x3f, 0x40, 0x40, 0x40,
0x42, 0x42, 0x43, 0x43, 0x44, 0x44, 0x44, 0x45,
0x45, 0x47, 0x47, 0x47, 0x48, 0x48, 0x49, 0x49,
0x4a, 0x4a, 0x4a, 0x4b, 0x4b, 0x4b, 0x4c, 0x4c,
0x4d, 0x4d, 0x4d, 0x4f, 0x4f, 0x50, 0x50, 0x50,
0x52, 0x52, 0x52, 0x53, 0x53, 0x54, 0x54, 0x54,
0x55, 0x55, 0x55, 0x56, 0x56, 0x58, 0x58, 0x58,
0x59, 0x59, 0x59, 0x5a, 0x5a, 0x5a, 0x5b, 0x5b,
0x5b, 0x5c, 0x5c, 0x5c, 0x5e, 0x5e, 0x5e, 0x5f,
0x5f, 0x5f, 0x60, 0x60, 0x60, 0x61, 0x61, 0x61,
0x62, 0x62, 0x62, 0x63, 0x63, 0x63, 0x65, 0x65,
0x65, 0x66, 0x66, 0x66, 0x67, 0x67, 0x67, 0x68,
0x68, 0x68, 0x69, 0x69, 0x69, 0x69, 0x6a, 0x6a,
0x6a, 0x6c, 0x6c, 0x6c, 0x6d, 0x6d, 0x6d, 0x6e,
0x6e, 0x6e, 0x6e, 0x6f, 0x6f, 0x6f, 0x70, 0x70,
0x70, 0x71, 0x71, 0x71, 0x71, 0x73, 0x73, 0x73,
0x74, 0x74, 0x74, 0x74, 0x75, 0x75, 0x75, 0x77,
0x77, 0x77, 0x77, 0x78, 0x78, 0x78, 0x79, 0x79,
0x79, 0x79, 0x7a, 0x7a, 0x7a, 0x7a, 0x7b, 0x7b,
0x7b, 0x7c, 0x7c, 0x7c, 0x7c, 0x7d, 0x7d, 0x7d,
0x7d, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x80,
0x81, 0x81, 0x81, 0x81, 0x82, 0x82, 0x82, 0x82,
0x84, 0x84, 0x84, 0x85, 0x85, 0x85, 0x85, 0x86,
0x86, 0x86, 0x86, 0x88, 0x88, 0x88, 0x88, 0x89,
0x89, 0x89, 0x89, 0x8a, 0x8a, 0x8a, 0x8a, 0x8b,
0x8b, 0x8b, 0x8b, 0x8d, 0x8d, 0x8d, 0x8d, 0x8e,
0x8e, 0x8e, 0x8e, 0x8f, 0x8f, 0x8f, 0x8f, 0x90,
0x90, 0x90, 0x90, 0x90, 0x91, 0x91, 0x91, 0x91,
0x92, 0x92, 0x92, 0x92, 0x93, 0x93, 0x93, 0x93,
0x94, 0x94, 0x94, 0x94, 0x96, 0x96, 0x96, 0x96,
0x96, 0x97, 0x97, 0x97, 0x97, 0x98, 0x98, 0x98,
0x98, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a, 0x9a,
0x9a, 0x9a, 0x9b, 0x9b, 0x9b, 0x9b, 0x9c, 0x9c,
0x9c, 0x9c, 0x9c, 0x9d, 0x9d, 0x9d, 0x9d, 0x9e,
0x9e, 0x9e, 0x9e, 0x9e, 0xa0, 0xa0, 0xa0, 0xa0,
0xa1, 0xa1, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2, 0xa2,
0xa2, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa4, 0xa4,
0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5, 0xa5, 0xa6,
0xa6, 0xa6, 0xa6, 0xa6, 0xa8, 0xa8, 0xa8, 0xa8,
0xa8, 0xa9, 0xa9, 0xa9, 0xa9, 0xab, 0xab, 0xab,
0xab, 0xab, 0xac, 0xac, 0xac, 0xac, 0xac, 0xad,
0xad, 0xad, 0xad, 0xae, 0xae, 0xae, 0xae, 0xae,
0xaf, 0xaf, 0xaf, 0xaf, 0xaf, 0xb0, 0xb0, 0xb0,
0xb0, 0xb0, 0xb1, 0xb1, 0xb1, 0xb1, 0xb1, 0xb2,
0xb2, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3, 0xb3, 0xb3,
0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb6, 0xb6, 0xb6,
0xb6, 0xb6, 0xb7, 0xb7, 0xb7, 0xb7, 0xb7, 0xb8,
0xb8, 0xb8, 0xb8, 0xb8, 0xb9, 0xb9, 0xb9, 0xb9,
0xb9, 0xba, 0xba, 0xba, 0xba, 0xba, 0xbc, 0xbc,
0xbc, 0xbc, 0xbc, 0xbd, 0xbd, 0xbd, 0xbd, 0xbd,
0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbf, 0xbf, 0xbf,
0xbf, 0xbf, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc2,
0xc2, 0xc2, 0xc2, 0xc2, 0xc3, 0xc3, 0xc3, 0xc3,
0xc3, 0xc4, 0xc4, 0xc4, 0xc4, 0xc4, 0xc5, 0xc5,
0xc5, 0xc5, 0xc5, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6,
0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc9, 0xc9, 0xc9,
0xc9, 0xc9, 0xc9, 0xca, 0xca, 0xca, 0xca, 0xca,
0xcb, 0xcb, 0xcb, 0xcb, 0xcb, 0xcc, 0xcc, 0xcc,
0xcc, 0xcc, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xce,
0xce, 0xce, 0xce, 0xce, 0xcf, 0xcf, 0xcf, 0xcf,
0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd1, 0xd1,
0xd1, 0xd1, 0xd1, 0xd1, 0xd3, 0xd3, 0xd3, 0xd3,
0xd3, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd6, 0xd6,
0xd6, 0xd6, 0xd6, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7,
0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd9, 0xd9, 0xd9,
0xd9, 0xd9, 0xda, 0xda, 0xda, 0xda, 0xda, 0xdb,
0xdb, 0xdb, 0xdb, 0xdb, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xdf,
0xdf, 0xdf, 0xdf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe0,
0xe0, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe2, 0xe2,
0xe2, 0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3,
0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5,
0xe5, 0xe5, 0xe6, 0xe6, 0xe6, 0xe6, 0xe6, 0xe7,
0xe7, 0xe7, 0xe7, 0xe7, 0xe8, 0xe8, 0xe8, 0xe8,
0xe8, 0xe9, 0xe9, 0xe9, 0xe9, 0xeb, 0xeb, 0xeb,
0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec, 0xec, 0xed,
0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee,
0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0,
0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf3,
0xf3, 0xf3, 0xf3, 0xf3, 0xf4, 0xf4, 0xf4, 0xf4,
0xf4, 0xf5, 0xf5, 0xf5, 0xf5, 0xf6, 0xf6, 0xf6,
0xf6, 0xf6, 0xf7, 0xf7, 0xf7, 0xf7, 0xf8, 0xf8,
0xf8, 0xf8, 0xf8, 0xf9, 0xf9, 0xf9, 0xf9, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x02,
0x02, 0x03, 0x05, 0x07, 0x07, 0x08, 0x09, 0x09,
0x0a, 0x0c, 0x0c, 0x0d, 0x0e, 0x0e, 0x10, 0x11,
0x11, 0x12, 0x14, 0x14, 0x15, 0x16, 0x16, 0x17,
0x17, 0x18, 0x1a, 0x1a, 0x1b, 0x1b, 0x1c, 0x1e,
0x1e, 0x1f, 0x1f, 0x20, 0x20, 0x22, 0x23, 0x23,
0x25, 0x25, 0x26, 0x26, 0x27, 0x27, 0x28, 0x28,
0x29, 0x29, 0x2b, 0x2c, 0x2c, 0x2d, 0x2d, 0x2f,
0x2f, 0x30, 0x30, 0x31, 0x31, 0x33, 0x33, 0x34,
0x34, 0x34, 0x35, 0x35, 0x37, 0x37, 0x38, 0x38,
0x39, 0x39, 0x3a, 0x3a, 0x3b, 0x3b, 0x3b, 0x3c,
0x3c, 0x3d, 0x3d, 0x3f, 0x3f, 0x40, 0x40, 0x40,
0x42, 0x42, 0x43, 0x43, 0x44, 0x44, 0x44, 0x45,
0x45, 0x47, 0x47, 0x47, 0x48, 0x48, 0x49, 0x49,
0x4a, 0x4a, 0x4a, 0x4b, 0x4b, 0x4b, 0x4c, 0x4c,
0x4d, 0x4d, 0x4d, 0x4f, 0x4f, 0x50, 0x50, 0x50,
0x52, 0x52, 0x52, 0x53, 0x53, 0x54, 0x54, 0x54,
0x55, 0x55, 0x55, 0x56, 0x56, 0x58, 0x58, 0x58,
0x59, 0x59, 0x59, 0x5a, 0x5a, 0x5a, 0x5b, 0x5b,
0x5b, 0x5c, 0x5c, 0x5c, 0x5e, 0x5e, 0x5e, 0x5f,
0x5f, 0x5f, 0x60, 0x60, 0x60, 0x61, 0x61, 0x61,
0x62, 0x62, 0x62, 0x63, 0x63, 0x63, 0x65, 0x65,
0x65, 0x66, 0x66, 0x66, 0x67, 0x67, 0x67, 0x68,
0x68, 0x68, 0x69, 0x69, 0x69, 0x69, 0x6a, 0x6a,
0x6a, 0x6c, 0x6c, 0x6c, 0x6d, 0x6d, 0x6d, 0x6e,
0x6e, 0x6e, 0x6e, 0x6f, 0x6f, 0x6f, 0x70, 0x70,
0x70, 0x71, 0x71, 0x71, 0x71, 0x73, 0x73, 0x73,
0x74, 0x74, 0x74, 0x74, 0x75, 0x75, 0x75, 0x76,
0x77, 0x77, 0x77, 0x78, 0x78, 0x78, 0x79, 0x79,
0x79, 0x79, 0x7a, 0x7a, 0x7a, 0x7a, 0x7b, 0x7b,
0x7b, 0x7c, 0x7c, 0x7c, 0x7c, 0x7d, 0x7d, 0x7d,
0x7d, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x80,
0x81, 0x81, 0x81, 0x81, 0x82, 0x82, 0x82, 0x82,
0x84, 0x84, 0x84, 0x85, 0x85, 0x85, 0x85, 0x86,
0x86, 0x86, 0x86, 0x88, 0x88, 0x88, 0x88, 0x89,
0x89, 0x89, 0x89, 0x8a, 0x8a, 0x8a, 0x8a, 0x8b,
0x8b, 0x8b, 0x8b, 0x8d, 0x8d, 0x8d, 0x8d, 0x8e,
0x8e, 0x8e, 0x8e, 0x8f, 0x8f, 0x8f, 0x8f, 0x90,
0x90, 0x90, 0x90, 0x90, 0x91, 0x91, 0x91, 0x91,
0x92, 0x92, 0x92, 0x92, 0x93, 0x93, 0x93, 0x93,
0x94, 0x94, 0x94, 0x94, 0x96, 0x96, 0x96, 0x96,
0x96, 0x97, 0x97, 0x97, 0x97, 0x98, 0x98, 0x98,
0x98, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a, 0x9a,
0x9a, 0x9a, 0x9b, 0x9b, 0x9b, 0x9b, 0x9c, 0x9c,
0x9c, 0x9c, 0x9c, 0x9d, 0x9d, 0x9d, 0x9d, 0x9e,
0x9e, 0x9e, 0x9e, 0x9e, 0xa0, 0xa0, 0xa0, 0xa0,
0xa1, 0xa1, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2, 0xa2,
0xa2, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa4, 0xa4,
0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5, 0xa5, 0xa6,
0xa6, 0xa6, 0xa6, 0xa6, 0xa8, 0xa8, 0xa8, 0xa8,
0xa8, 0xa9, 0xa9, 0xa9, 0xa9, 0xab, 0xab, 0xab,
0xab, 0xab, 0xac, 0xac, 0xac, 0xac, 0xac, 0xad,
0xad, 0xad, 0xad, 0xae, 0xae, 0xae, 0xae, 0xae,
0xaf, 0xaf, 0xaf, 0xaf, 0xaf, 0xb0, 0xb0, 0xb0,
0xb0, 0xb0, 0xb1, 0xb1, 0xb1, 0xb1, 0xb1, 0xb2,
0xb2, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3, 0xb3, 0xb3,
0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb6, 0xb6, 0xb6,
0xb6, 0xb6, 0xb7, 0xb7, 0xb7, 0xb7, 0xb7, 0xb8,
0xb8, 0xb8, 0xb8, 0xb8, 0xb9, 0xb9, 0xb9, 0xb9,
0xb9, 0xba, 0xba, 0xba, 0xba, 0xba, 0xbc, 0xbc,
0xbc, 0xbc, 0xbc, 0xbd, 0xbd, 0xbd, 0xbd, 0xbd,
0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbf, 0xbf, 0xbf,
0xbf, 0xbf, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc2,
0xc2, 0xc2, 0xc2, 0xc2, 0xc3, 0xc3, 0xc3, 0xc3,
0xc3, 0xc4, 0xc4, 0xc4, 0xc4, 0xc4, 0xc5, 0xc5,
0xc5, 0xc5, 0xc5, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6,
0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc9, 0xc9, 0xc9,
0xc9, 0xc9, 0xc9, 0xca, 0xca, 0xca, 0xca, 0xca,
0xcb, 0xcb, 0xcb, 0xcb, 0xcb, 0xcc, 0xcc, 0xcc,
0xcc, 0xcc, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xce,
0xce, 0xce, 0xce, 0xce, 0xcf, 0xcf, 0xcf, 0xcf,
0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd1, 0xd1,
0xd1, 0xd1, 0xd1, 0xd1, 0xd3, 0xd3, 0xd3, 0xd3,
0xd3, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd6, 0xd6,
0xd6, 0xd6, 0xd6, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7,
0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd9, 0xd9, 0xd9,
0xd9, 0xd9, 0xda, 0xda, 0xda, 0xda, 0xda, 0xdb,
0xdb, 0xdb, 0xdb, 0xdb, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xdf,
0xdf, 0xdf, 0xdf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe0,
0xe0, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe2, 0xe2,
0xe2, 0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3,
0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5,
0xe5, 0xe5, 0xe6, 0xe6, 0xe6, 0xe6, 0xe6, 0xe7,
0xe7, 0xe7, 0xe7, 0xe7, 0xe8, 0xe8, 0xe8, 0xe8,
0xe8, 0xe9, 0xe9, 0xe9, 0xe9, 0xeb, 0xeb, 0xeb,
0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec, 0xec, 0xed,
0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee,
0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0,
0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf3,
0xf3, 0xf3, 0xf3, 0xf3, 0xf4, 0xf4, 0xf4, 0xf4,
0xf4, 0xf5, 0xf5, 0xf5, 0xf5, 0xf6, 0xf6, 0xf6,
0xf6, 0xf6, 0xf7, 0xf7, 0xf7, 0xf7, 0xf8, 0xf8,
0xf8, 0xf8, 0xf8, 0xf9, 0xf9, 0xf9, 0xf9, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb}
},
{ /* gamma 1 - from tp6810 + soi763a */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x02, 0x03, 0x05, 0x07, 0x08, 0x09, 0x0a,
0x0c, 0x0d, 0x0e, 0x10, 0x11, 0x12, 0x14, 0x15,
0x16, 0x17, 0x18, 0x1a, 0x1a, 0x1b, 0x1c, 0x1e,
0x1f, 0x20, 0x22, 0x22, 0x23, 0x25, 0x26, 0x27,
0x27, 0x28, 0x29, 0x2b, 0x2b, 0x2c, 0x2d, 0x2f,
0x2f, 0x30, 0x31, 0x33, 0x33, 0x34, 0x35, 0x35,
0x37, 0x38, 0x38, 0x39, 0x3a, 0x3a, 0x3b, 0x3c,
0x3c, 0x3d, 0x3f, 0x3f, 0x40, 0x42, 0x42, 0x43,
0x43, 0x44, 0x45, 0x45, 0x47, 0x47, 0x48, 0x49,
0x49, 0x4a, 0x4a, 0x4b, 0x4b, 0x4c, 0x4d, 0x4d,
0x4f, 0x4f, 0x50, 0x50, 0x52, 0x52, 0x53, 0x53,
0x54, 0x54, 0x55, 0x56, 0x56, 0x58, 0x58, 0x59,
0x59, 0x5a, 0x5a, 0x5b, 0x5b, 0x5c, 0x5c, 0x5e,
0x5e, 0x5e, 0x5f, 0x5f, 0x60, 0x60, 0x61, 0x61,
0x62, 0x62, 0x63, 0x63, 0x65, 0x65, 0x65, 0x66,
0x66, 0x67, 0x67, 0x68, 0x68, 0x69, 0x69, 0x69,
0x6a, 0x6a, 0x6c, 0x6c, 0x6d, 0x6d, 0x6d, 0x6e,
0x6e, 0x6f, 0x6f, 0x6f, 0x70, 0x70, 0x71, 0x71,
0x73, 0x73, 0x73, 0x74, 0x74, 0x74, 0x75, 0x75,
0x77, 0x77, 0x77, 0x78, 0x78, 0x79, 0x79, 0x79,
0x7a, 0x7a, 0x7a, 0x7b, 0x7b, 0x7c, 0x7c, 0x7c,
0x7d, 0x7d, 0x7d, 0x7f, 0x7f, 0x80, 0x80, 0x80,
0x81, 0x81, 0x81, 0x82, 0x82, 0x82, 0x84, 0x84,
0x84, 0x85, 0x85, 0x85, 0x86, 0x86, 0x86, 0x88,
0x88, 0x88, 0x89, 0x89, 0x89, 0x8a, 0x8a, 0x8a,
0x8b, 0x8b, 0x8b, 0x8d, 0x8d, 0x8d, 0x8e, 0x8e,
0x8e, 0x8f, 0x8f, 0x8f, 0x90, 0x90, 0x90, 0x91,
0x91, 0x91, 0x92, 0x92, 0x92, 0x92, 0x93, 0x93,
0x93, 0x94, 0x94, 0x94, 0x96, 0x96, 0x96, 0x97,
0x97, 0x97, 0x97, 0x98, 0x98, 0x98, 0x99, 0x99,
0x99, 0x9a, 0x9a, 0x9a, 0x9a, 0x9b, 0x9b, 0x9b,
0x9c, 0x9c, 0x9c, 0x9c, 0x9d, 0x9d, 0x9d, 0x9e,
0x9e, 0x9e, 0x9e, 0xa0, 0xa0, 0xa0, 0xa1, 0xa1,
0xa1, 0xa1, 0xa2, 0xa2, 0xa2, 0xa2, 0xa3, 0xa3,
0xa3, 0xa4, 0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5,
0xa5, 0xa6, 0xa6, 0xa6, 0xa8, 0xa8, 0xa8, 0xa8,
0xa9, 0xa9, 0xa9, 0xa9, 0xab, 0xab, 0xab, 0xab,
0xac, 0xac, 0xac, 0xad, 0xad, 0xad, 0xad, 0xae,
0xae, 0xae, 0xae, 0xaf, 0xaf, 0xaf, 0xaf, 0xb0,
0xb0, 0xb0, 0xb0, 0xb1, 0xb1, 0xb1, 0xb1, 0xb2,
0xb2, 0xb2, 0xb2, 0xb3, 0xb3, 0xb3, 0xb3, 0xb4,
0xb4, 0xb4, 0xb4, 0xb6, 0xb6, 0xb6, 0xb6, 0xb7,
0xb7, 0xb7, 0xb7, 0xb7, 0xb8, 0xb8, 0xb8, 0xb8,
0xb9, 0xb9, 0xb9, 0xb9, 0xba, 0xba, 0xba, 0xba,
0xbc, 0xbc, 0xbc, 0xbc, 0xbd, 0xbd, 0xbd, 0xbd,
0xbd, 0xbe, 0xbe, 0xbe, 0xbe, 0xbf, 0xbf, 0xbf,
0xbf, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc2, 0xc2,
0xc2, 0xc2, 0xc3, 0xc3, 0xc3, 0xc3, 0xc4, 0xc4,
0xc4, 0xc4, 0xc4, 0xc5, 0xc5, 0xc5, 0xc5, 0xc6,
0xc6, 0xc6, 0xc6, 0xc6, 0xc7, 0xc7, 0xc7, 0xc7,
0xc9, 0xc9, 0xc9, 0xc9, 0xc9, 0xca, 0xca, 0xca,
0xca, 0xcb, 0xcb, 0xcb, 0xcb, 0xcb, 0xcc, 0xcc,
0xcc, 0xcc, 0xcc, 0xcd, 0xcd, 0xcd, 0xcd, 0xce,
0xce, 0xce, 0xce, 0xce, 0xcf, 0xcf, 0xcf, 0xcf,
0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd1, 0xd1, 0xd1,
0xd1, 0xd1, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd4,
0xd4, 0xd4, 0xd4, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6,
0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd8, 0xd8, 0xd8,
0xd8, 0xd8, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xda,
0xda, 0xda, 0xda, 0xda, 0xdb, 0xdb, 0xdb, 0xdb,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde,
0xde, 0xde, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xe0,
0xe0, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe1,
0xe1, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe3, 0xe3,
0xe3, 0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4,
0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6, 0xe6,
0xe6, 0xe6, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe8,
0xe8, 0xe8, 0xe8, 0xe8, 0xe9, 0xe9, 0xe9, 0xe9,
0xe9, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xec,
0xec, 0xec, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed,
0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef,
0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0,
0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf3, 0xf3, 0xf3,
0xf3, 0xf3, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf5,
0xf5, 0xf5, 0xf5, 0xf5, 0xf6, 0xf6, 0xf6, 0xf6,
0xf6, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf8, 0xf8,
0xf8, 0xf8, 0xf8, 0xf8, 0xf9, 0xf9, 0xf9, 0xf9,
0xf9, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa,
0xfa, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc,
0xfc, 0xfc, 0xfd, 0xfd, 0xfd, 0xfd, 0xfd, 0xfe,
0xfe, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03,
0x05, 0x07, 0x07, 0x08, 0x09, 0x0a, 0x0c, 0x0d,
0x0e, 0x10, 0x10, 0x11, 0x12, 0x14, 0x15, 0x15,
0x16, 0x17, 0x18, 0x1a, 0x1a, 0x1b, 0x1c, 0x1e,
0x1e, 0x1f, 0x20, 0x20, 0x22, 0x23, 0x25, 0x25,
0x26, 0x27, 0x27, 0x28, 0x29, 0x29, 0x2b, 0x2c,
0x2c, 0x2d, 0x2d, 0x2f, 0x30, 0x30, 0x31, 0x31,
0x33, 0x34, 0x34, 0x35, 0x35, 0x37, 0x38, 0x38,
0x39, 0x39, 0x3a, 0x3a, 0x3b, 0x3b, 0x3c, 0x3d,
0x3d, 0x3f, 0x3f, 0x40, 0x40, 0x42, 0x42, 0x43,
0x43, 0x44, 0x44, 0x45, 0x45, 0x47, 0x47, 0x48,
0x48, 0x49, 0x49, 0x4a, 0x4a, 0x4b, 0x4b, 0x4c,
0x4c, 0x4d, 0x4d, 0x4d, 0x4f, 0x4f, 0x50, 0x50,
0x52, 0x52, 0x53, 0x53, 0x53, 0x54, 0x54, 0x55,
0x55, 0x56, 0x56, 0x56, 0x58, 0x58, 0x59, 0x59,
0x5a, 0x5a, 0x5a, 0x5b, 0x5b, 0x5c, 0x5c, 0x5c,
0x5e, 0x5e, 0x5f, 0x5f, 0x5f, 0x60, 0x60, 0x60,
0x61, 0x61, 0x62, 0x62, 0x62, 0x63, 0x63, 0x65,
0x65, 0x65, 0x66, 0x66, 0x66, 0x67, 0x67, 0x67,
0x68, 0x68, 0x69, 0x69, 0x69, 0x6a, 0x6a, 0x6a,
0x6c, 0x6c, 0x6c, 0x6d, 0x6d, 0x6d, 0x6e, 0x6e,
0x6e, 0x6f, 0x6f, 0x6f, 0x70, 0x70, 0x70, 0x71,
0x71, 0x71, 0x73, 0x73, 0x73, 0x74, 0x74, 0x74,
0x75, 0x75, 0x75, 0x77, 0x77, 0x77, 0x78, 0x78,
0x78, 0x79, 0x79, 0x79, 0x79, 0x7a, 0x7a, 0x7a,
0x7b, 0x7b, 0x7b, 0x7c, 0x7c, 0x7c, 0x7c, 0x7d,
0x7d, 0x7d, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80,
0x80, 0x81, 0x81, 0x81, 0x82, 0x82, 0x82, 0x82,
0x84, 0x84, 0x84, 0x85, 0x85, 0x85, 0x85, 0x86,
0x86, 0x86, 0x88, 0x88, 0x88, 0x88, 0x89, 0x89,
0x89, 0x89, 0x8a, 0x8a, 0x8a, 0x8b, 0x8b, 0x8b,
0x8b, 0x8d, 0x8d, 0x8d, 0x8d, 0x8e, 0x8e, 0x8e,
0x8e, 0x8f, 0x8f, 0x8f, 0x90, 0x90, 0x90, 0x90,
0x91, 0x91, 0x91, 0x91, 0x92, 0x92, 0x92, 0x92,
0x93, 0x93, 0x93, 0x93, 0x94, 0x94, 0x94, 0x94,
0x96, 0x96, 0x96, 0x96, 0x97, 0x97, 0x97, 0x97,
0x98, 0x98, 0x98, 0x98, 0x99, 0x99, 0x99, 0x99,
0x9a, 0x9a, 0x9a, 0x9a, 0x9a, 0x9b, 0x9b, 0x9b,
0x9b, 0x9c, 0x9c, 0x9c, 0x9c, 0x9d, 0x9d, 0x9d,
0x9d, 0x9e, 0x9e, 0x9e, 0x9e, 0x9e, 0xa0, 0xa0,
0xa0, 0xa0, 0xa1, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2,
0xa2, 0xa2, 0xa2, 0xa3, 0xa3, 0xa3, 0xa3, 0xa4,
0xa4, 0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5, 0xa5,
0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa8, 0xa8, 0xa8,
0xa8, 0xa9, 0xa9, 0xa9, 0xa9, 0xa9, 0xab, 0xab,
0xab, 0xab, 0xac, 0xac, 0xac, 0xac, 0xac, 0xad,
0xad, 0xad, 0xad, 0xad, 0xae, 0xae, 0xae, 0xae,
0xaf, 0xaf, 0xaf, 0xaf, 0xaf, 0xb0, 0xb0, 0xb0,
0xb0, 0xb0, 0xb1, 0xb1, 0xb1, 0xb1, 0xb1, 0xb2,
0xb2, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3, 0xb3, 0xb3,
0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb6, 0xb6, 0xb6,
0xb6, 0xb6, 0xb7, 0xb7, 0xb7, 0xb7, 0xb7, 0xb8,
0xb8, 0xb8, 0xb8, 0xb8, 0xb9, 0xb9, 0xb9, 0xb9,
0xb9, 0xba, 0xba, 0xba, 0xba, 0xba, 0xbc, 0xbc,
0xbc, 0xbc, 0xbc, 0xbd, 0xbd, 0xbd, 0xbd, 0xbd,
0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbf, 0xbf,
0xbf, 0xbf, 0xbf, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc3, 0xc3, 0xc3,
0xc3, 0xc3, 0xc4, 0xc4, 0xc4, 0xc4, 0xc4, 0xc5,
0xc5, 0xc5, 0xc5, 0xc5, 0xc5, 0xc6, 0xc6, 0xc6,
0xc6, 0xc6, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc9,
0xc9, 0xc9, 0xc9, 0xc9, 0xc9, 0xca, 0xca, 0xca,
0xca, 0xca, 0xcb, 0xcb, 0xcb, 0xcb, 0xcb, 0xcc,
0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xce, 0xce, 0xce, 0xce, 0xce, 0xcf,
0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0,
0xd0, 0xd0, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1,
0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd4, 0xd4, 0xd4,
0xd4, 0xd4, 0xd4, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6,
0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd8, 0xd8,
0xd8, 0xd8, 0xd8, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9,
0xd9, 0xda, 0xda, 0xda, 0xda, 0xda, 0xdb, 0xdb,
0xdb, 0xdb, 0xdb, 0xdb, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xdf,
0xdf, 0xdf, 0xdf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe0,
0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe2,
0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe3, 0xe3, 0xe3,
0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4,
0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6, 0xe6,
0xe6, 0xe6, 0xe6, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7,
0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe9, 0xe9,
0xe9, 0xe9, 0xe9, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb,
0xeb, 0xec, 0xec, 0xec, 0xec, 0xec, 0xed, 0xed,
0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee,
0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0,
0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1,
0xf1, 0xf1, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf4,
0xf4, 0xf4, 0xf4, 0xf4, 0xf5, 0xf5, 0xf5, 0xf5,
0xf5, 0xf5, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf7,
0xf7, 0xf7, 0xf7, 0xf7, 0xf8, 0xf8, 0xf8, 0xf8,
0xf8, 0xf8, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa,
0xfa, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfc, 0xfc,
0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc,
0xfc, 0xfd, 0xfd, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe,
0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x02, 0x03, 0x05, 0x05, 0x07,
0x08, 0x09, 0x0a, 0x0a, 0x0c, 0x0d, 0x0e, 0x0e,
0x10, 0x11, 0x12, 0x12, 0x14, 0x15, 0x16, 0x16,
0x17, 0x18, 0x18, 0x1a, 0x1b, 0x1b, 0x1c, 0x1e,
0x1e, 0x1f, 0x1f, 0x20, 0x22, 0x22, 0x23, 0x23,
0x25, 0x26, 0x26, 0x27, 0x27, 0x28, 0x29, 0x29,
0x2b, 0x2b, 0x2c, 0x2c, 0x2d, 0x2d, 0x2f, 0x30,
0x30, 0x31, 0x31, 0x33, 0x33, 0x34, 0x34, 0x35,
0x35, 0x37, 0x37, 0x38, 0x38, 0x39, 0x39, 0x3a,
0x3a, 0x3b, 0x3b, 0x3b, 0x3c, 0x3c, 0x3d, 0x3d,
0x3f, 0x3f, 0x40, 0x40, 0x42, 0x42, 0x42, 0x43,
0x43, 0x44, 0x44, 0x45, 0x45, 0x47, 0x47, 0x47,
0x48, 0x48, 0x49, 0x49, 0x49, 0x4a, 0x4a, 0x4b,
0x4b, 0x4b, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d, 0x4f,
0x4f, 0x50, 0x50, 0x50, 0x52, 0x52, 0x52, 0x53,
0x53, 0x54, 0x54, 0x54, 0x55, 0x55, 0x55, 0x56,
0x56, 0x58, 0x58, 0x58, 0x59, 0x59, 0x59, 0x5a,
0x5a, 0x5a, 0x5b, 0x5b, 0x5b, 0x5c, 0x5c, 0x5c,
0x5e, 0x5e, 0x5e, 0x5f, 0x5f, 0x5f, 0x60, 0x60,
0x60, 0x61, 0x61, 0x61, 0x62, 0x62, 0x62, 0x63,
0x63, 0x63, 0x65, 0x65, 0x65, 0x66, 0x66, 0x66,
0x66, 0x67, 0x67, 0x67, 0x68, 0x68, 0x68, 0x69,
0x69, 0x69, 0x6a, 0x6a, 0x6a, 0x6a, 0x6c, 0x6c,
0x6c, 0x6d, 0x6d, 0x6d, 0x6d, 0x6e, 0x6e, 0x6e,
0x6f, 0x6f, 0x6f, 0x6f, 0x70, 0x70, 0x70, 0x71,
0x71, 0x71, 0x71, 0x73, 0x73, 0x73, 0x74, 0x74,
0x74, 0x74, 0x75, 0x75, 0x75, 0x75, 0x77, 0x77,
0x77, 0x78, 0x78, 0x78, 0x78, 0x79, 0x79, 0x79,
0x79, 0x7a, 0x7a, 0x7a, 0x7a, 0x7b, 0x7b, 0x7b,
0x7b, 0x7c, 0x7c, 0x7c, 0x7c, 0x7d, 0x7d, 0x7d,
0x7d, 0x7f, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80,
0x80, 0x81, 0x81, 0x81, 0x81, 0x82, 0x82, 0x82,
0x82, 0x84, 0x84, 0x84, 0x84, 0x85, 0x85, 0x85,
0x85, 0x86, 0x86, 0x86, 0x86, 0x88, 0x88, 0x88,
0x88, 0x88, 0x89, 0x89, 0x89, 0x89, 0x8a, 0x8a,
0x8a, 0x8a, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8d,
0x8d, 0x8d, 0x8d, 0x8e, 0x8e, 0x8e, 0x8e, 0x8e,
0x8f, 0x8f, 0x8f, 0x8f, 0x90, 0x90, 0x90, 0x90,
0x90, 0x91, 0x91, 0x91, 0x91, 0x92, 0x92, 0x92,
0x92, 0x92, 0x93, 0x93, 0x93, 0x93, 0x94, 0x94,
0x94, 0x94, 0x94, 0x96, 0x96, 0x96, 0x96, 0x96,
0x97, 0x97, 0x97, 0x97, 0x97, 0x98, 0x98, 0x98,
0x98, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a, 0x9a,
0x9a, 0x9a, 0x9a, 0x9b, 0x9b, 0x9b, 0x9b, 0x9b,
0x9c, 0x9c, 0x9c, 0x9c, 0x9c, 0x9d, 0x9d, 0x9d,
0x9d, 0x9d, 0x9e, 0x9e, 0x9e, 0x9e, 0x9e, 0xa0,
0xa0, 0xa0, 0xa0, 0xa0, 0xa1, 0xa1, 0xa1, 0xa1,
0xa1, 0xa2, 0xa2, 0xa2, 0xa2, 0xa2, 0xa3, 0xa3,
0xa3, 0xa3, 0xa3, 0xa4, 0xa4, 0xa4, 0xa4, 0xa4,
0xa4, 0xa5, 0xa5, 0xa5, 0xa5, 0xa5, 0xa6, 0xa6,
0xa6, 0xa6, 0xa6, 0xa8, 0xa8, 0xa8, 0xa8, 0xa8,
0xa9, 0xa9, 0xa9, 0xa9, 0xa9, 0xa9, 0xab, 0xab,
0xab, 0xab, 0xab, 0xac, 0xac, 0xac, 0xac, 0xac,
0xad, 0xad, 0xad, 0xad, 0xad, 0xad, 0xae, 0xae,
0xae, 0xae, 0xae, 0xaf, 0xaf, 0xaf, 0xaf, 0xaf,
0xaf, 0xb0, 0xb0, 0xb0, 0xb0, 0xb0, 0xb1, 0xb1,
0xb1, 0xb1, 0xb1, 0xb1, 0xb2, 0xb2, 0xb2, 0xb2,
0xb2, 0xb3, 0xb3, 0xb3, 0xb3, 0xb3, 0xb3, 0xb4,
0xb4, 0xb4, 0xb4, 0xb4, 0xb6, 0xb6, 0xb6, 0xb6,
0xb6, 0xb6, 0xb7, 0xb7, 0xb7, 0xb7, 0xb7, 0xb7,
0xb8, 0xb8, 0xb8, 0xb8, 0xb8, 0xb9, 0xb9, 0xb9,
0xb9, 0xb9, 0xb9, 0xba, 0xba, 0xba, 0xba, 0xba,
0xba, 0xbc, 0xbc, 0xbc, 0xbc, 0xbc, 0xbd, 0xbd,
0xbd, 0xbd, 0xbd, 0xbd, 0xbe, 0xbe, 0xbe, 0xbe,
0xbe, 0xbe, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf,
0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc2, 0xc2,
0xc2, 0xc2, 0xc2, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3,
0xc3, 0xc4, 0xc4, 0xc4, 0xc4, 0xc4, 0xc4, 0xc5,
0xc5, 0xc5, 0xc5, 0xc5, 0xc5, 0xc6, 0xc6, 0xc6,
0xc6, 0xc6, 0xc6, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7,
0xc7, 0xc9, 0xc9, 0xc9, 0xc9, 0xc9, 0xca, 0xca,
0xca, 0xca, 0xca, 0xca, 0xcb, 0xcb, 0xcb, 0xcb,
0xcb, 0xcb, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xce, 0xce,
0xce, 0xce, 0xce, 0xce, 0xcf, 0xcf, 0xcf, 0xcf,
0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0,
0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd3, 0xd3,
0xd3, 0xd3, 0xd3, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4,
0xd4, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd7,
0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd8, 0xd8, 0xd8,
0xd8, 0xd8, 0xd8, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9,
0xd9, 0xda, 0xda, 0xda, 0xda, 0xda, 0xda, 0xdb,
0xdb, 0xdb, 0xdb, 0xdb, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde,
0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xe0, 0xe0,
0xe0, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe1,
0xe1, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe3,
0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe4, 0xe4, 0xe4,
0xe4, 0xe4, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5,
0xe6, 0xe6, 0xe6, 0xe6, 0xe6, 0xe6, 0xe7, 0xe7,
0xe7, 0xe7, 0xe7, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8,
0xe8, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xeb, 0xeb,
0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec,
0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xee,
0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef,
0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1,
0xf1, 0xf1, 0xf1, 0xf1, 0xf3, 0xf3, 0xf3, 0xf3,
0xf3, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf5, 0xf5,
0xf5, 0xf5, 0xf5, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6,
0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf8, 0xf8, 0xf8,
0xf8, 0xf8, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa,
0xfa, 0xfb, 0xfb, 0xfb, 0xfb, 0xfc, 0xfc, 0xfc,
0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfd,
0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
},
{ /* gamma 2 */
{0x00, 0x01, 0x02, 0x05, 0x07, 0x08, 0x0a, 0x0c,
0x0d, 0x0e, 0x10, 0x12, 0x14, 0x15, 0x16, 0x17,
0x18, 0x1a, 0x1b, 0x1c, 0x1e, 0x1f, 0x20, 0x22,
0x23, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2b, 0x2c,
0x2d, 0x2d, 0x2f, 0x30, 0x31, 0x33, 0x34, 0x34,
0x35, 0x37, 0x38, 0x38, 0x39, 0x3a, 0x3b, 0x3b,
0x3c, 0x3d, 0x3f, 0x3f, 0x40, 0x42, 0x42, 0x43,
0x44, 0x44, 0x45, 0x47, 0x47, 0x48, 0x49, 0x49,
0x4a, 0x4b, 0x4b, 0x4c, 0x4c, 0x4d, 0x4f, 0x4f,
0x50, 0x50, 0x52, 0x53, 0x53, 0x54, 0x54, 0x55,
0x55, 0x56, 0x56, 0x58, 0x58, 0x59, 0x5a, 0x5a,
0x5b, 0x5b, 0x5c, 0x5c, 0x5e, 0x5e, 0x5f, 0x5f,
0x60, 0x60, 0x61, 0x61, 0x62, 0x62, 0x63, 0x63,
0x65, 0x65, 0x65, 0x66, 0x66, 0x67, 0x67, 0x68,
0x68, 0x69, 0x69, 0x6a, 0x6a, 0x6a, 0x6c, 0x6c,
0x6d, 0x6d, 0x6e, 0x6e, 0x6e, 0x6f, 0x6f, 0x70,
0x70, 0x70, 0x71, 0x71, 0x73, 0x73, 0x73, 0x74,
0x74, 0x75, 0x75, 0x75, 0x77, 0x77, 0x78, 0x78,
0x78, 0x79, 0x79, 0x79, 0x7a, 0x7a, 0x7b, 0x7b,
0x7b, 0x7c, 0x7c, 0x7c, 0x7d, 0x7d, 0x7f, 0x7f,
0x7f, 0x80, 0x80, 0x80, 0x81, 0x81, 0x81, 0x82,
0x82, 0x82, 0x84, 0x84, 0x84, 0x85, 0x85, 0x85,
0x86, 0x86, 0x86, 0x88, 0x88, 0x88, 0x89, 0x89,
0x89, 0x8a, 0x8a, 0x8a, 0x8b, 0x8b, 0x8b, 0x8d,
0x8d, 0x8d, 0x8d, 0x8e, 0x8e, 0x8e, 0x8f, 0x8f,
0x8f, 0x90, 0x90, 0x90, 0x91, 0x91, 0x91, 0x91,
0x92, 0x92, 0x92, 0x93, 0x93, 0x93, 0x93, 0x94,
0x94, 0x94, 0x96, 0x96, 0x96, 0x97, 0x97, 0x97,
0x97, 0x98, 0x98, 0x98, 0x98, 0x99, 0x99, 0x99,
0x9a, 0x9a, 0x9a, 0x9a, 0x9b, 0x9b, 0x9b, 0x9b,
0x9c, 0x9c, 0x9c, 0x9d, 0x9d, 0x9d, 0x9d, 0x9e,
0x9e, 0x9e, 0x9e, 0xa0, 0xa0, 0xa0, 0xa0, 0xa1,
0xa1, 0xa1, 0xa1, 0xa2, 0xa2, 0xa2, 0xa2, 0xa3,
0xa3, 0xa3, 0xa4, 0xa4, 0xa4, 0xa4, 0xa5, 0xa5,
0xa5, 0xa5, 0xa5, 0xa6, 0xa6, 0xa6, 0xa6, 0xa8,
0xa8, 0xa8, 0xa8, 0xa9, 0xa9, 0xa9, 0xa9, 0xab,
0xab, 0xab, 0xab, 0xac, 0xac, 0xac, 0xac, 0xad,
0xad, 0xad, 0xad, 0xad, 0xae, 0xae, 0xae, 0xae,
0xaf, 0xaf, 0xaf, 0xaf, 0xb0, 0xb0, 0xb0, 0xb0,
0xb0, 0xb1, 0xb1, 0xb1, 0xb1, 0xb2, 0xb2, 0xb2,
0xb2, 0xb2, 0xb3, 0xb3, 0xb3, 0xb3, 0xb4, 0xb4,
0xb4, 0xb4, 0xb4, 0xb6, 0xb6, 0xb6, 0xb6, 0xb7,
0xb7, 0xb7, 0xb7, 0xb7, 0xb8, 0xb8, 0xb8, 0xb8,
0xb8, 0xb9, 0xb9, 0xb9, 0xb9, 0xba, 0xba, 0xba,
0xba, 0xba, 0xbc, 0xbc, 0xbc, 0xbc, 0xbc, 0xbd,
0xbd, 0xbd, 0xbd, 0xbd, 0xbe, 0xbe, 0xbe, 0xbe,
0xbe, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf, 0xc0, 0xc0,
0xc0, 0xc0, 0xc0, 0xc2, 0xc2, 0xc2, 0xc2, 0xc3,
0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc4, 0xc4, 0xc4,
0xc4, 0xc4, 0xc5, 0xc5, 0xc5, 0xc5, 0xc5, 0xc6,
0xc6, 0xc6, 0xc6, 0xc6, 0xc7, 0xc7, 0xc7, 0xc7,
0xc7, 0xc9, 0xc9, 0xc9, 0xc9, 0xc9, 0xca, 0xca,
0xca, 0xca, 0xca, 0xcb, 0xcb, 0xcb, 0xcb, 0xcb,
0xcb, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xce, 0xce, 0xce, 0xce, 0xce,
0xce, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0,
0xd0, 0xd0, 0xd0, 0xd0, 0xd1, 0xd1, 0xd1, 0xd1,
0xd1, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd4, 0xd4,
0xd4, 0xd4, 0xd4, 0xd4, 0xd6, 0xd6, 0xd6, 0xd6,
0xd6, 0xd6, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd8,
0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd9, 0xd9, 0xd9,
0xd9, 0xd9, 0xda, 0xda, 0xda, 0xda, 0xda, 0xda,
0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde, 0xde, 0xde,
0xde, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xe0,
0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1,
0xe1, 0xe1, 0xe1, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2,
0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe4, 0xe4,
0xe4, 0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5, 0xe5,
0xe5, 0xe5, 0xe6, 0xe6, 0xe6, 0xe6, 0xe6, 0xe6,
0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe8, 0xe8,
0xe8, 0xe8, 0xe8, 0xe8, 0xe9, 0xe9, 0xe9, 0xe9,
0xe9, 0xe9, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb,
0xec, 0xec, 0xec, 0xec, 0xec, 0xed, 0xed, 0xed,
0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee,
0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0,
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1,
0xf1, 0xf1, 0xf1, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3,
0xf3, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf5,
0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf6, 0xf6, 0xf6,
0xf6, 0xf6, 0xf6, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7,
0xf7, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf9,
0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xfa, 0xfa, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa,
0xfa, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb},
{0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x05,
0x07, 0x08, 0x09, 0x0a, 0x0d, 0x0e, 0x10, 0x11,
0x12, 0x14, 0x15, 0x16, 0x16, 0x17, 0x18, 0x1a,
0x1b, 0x1c, 0x1e, 0x1f, 0x20, 0x20, 0x22, 0x23,
0x25, 0x26, 0x26, 0x27, 0x28, 0x29, 0x29, 0x2b,
0x2c, 0x2d, 0x2d, 0x2f, 0x30, 0x30, 0x31, 0x33,
0x33, 0x34, 0x35, 0x35, 0x37, 0x38, 0x38, 0x39,
0x3a, 0x3a, 0x3b, 0x3b, 0x3c, 0x3d, 0x3d, 0x3f,
0x3f, 0x40, 0x42, 0x42, 0x43, 0x43, 0x44, 0x44,
0x45, 0x45, 0x47, 0x47, 0x48, 0x48, 0x49, 0x4a,
0x4a, 0x4b, 0x4b, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d,
0x4f, 0x4f, 0x50, 0x50, 0x52, 0x52, 0x53, 0x53,
0x54, 0x54, 0x55, 0x55, 0x56, 0x56, 0x56, 0x58,
0x58, 0x59, 0x59, 0x5a, 0x5a, 0x5a, 0x5b, 0x5b,
0x5c, 0x5c, 0x5c, 0x5e, 0x5e, 0x5f, 0x5f, 0x5f,
0x60, 0x60, 0x61, 0x61, 0x61, 0x62, 0x62, 0x63,
0x63, 0x63, 0x65, 0x65, 0x65, 0x66, 0x66, 0x67,
0x67, 0x67, 0x68, 0x68, 0x68, 0x69, 0x69, 0x69,
0x6a, 0x6a, 0x6c, 0x6c, 0x6c, 0x6d, 0x6d, 0x6d,
0x6e, 0x6e, 0x6e, 0x6f, 0x6f, 0x6f, 0x70, 0x70,
0x70, 0x71, 0x71, 0x71, 0x73, 0x73, 0x73, 0x73,
0x74, 0x74, 0x74, 0x75, 0x75, 0x75, 0x77, 0x77,
0x77, 0x78, 0x78, 0x78, 0x79, 0x79, 0x79, 0x79,
0x7a, 0x7a, 0x7a, 0x7b, 0x7b, 0x7b, 0x7b, 0x7c,
0x7c, 0x7c, 0x7d, 0x7d, 0x7d, 0x7d, 0x7f, 0x7f,
0x7f, 0x80, 0x80, 0x80, 0x80, 0x81, 0x81, 0x81,
0x82, 0x82, 0x82, 0x82, 0x84, 0x84, 0x84, 0x84,
0x85, 0x85, 0x85, 0x85, 0x86, 0x86, 0x86, 0x88,
0x88, 0x88, 0x88, 0x89, 0x89, 0x89, 0x89, 0x8a,
0x8a, 0x8a, 0x8a, 0x8b, 0x8b, 0x8b, 0x8b, 0x8d,
0x8d, 0x8d, 0x8d, 0x8e, 0x8e, 0x8e, 0x8e, 0x8f,
0x8f, 0x8f, 0x8f, 0x90, 0x90, 0x90, 0x90, 0x91,
0x91, 0x91, 0x91, 0x91, 0x92, 0x92, 0x92, 0x92,
0x93, 0x93, 0x93, 0x93, 0x94, 0x94, 0x94, 0x94,
0x94, 0x96, 0x96, 0x96, 0x96, 0x97, 0x97, 0x97,
0x97, 0x98, 0x98, 0x98, 0x98, 0x98, 0x99, 0x99,
0x99, 0x99, 0x99, 0x9a, 0x9a, 0x9a, 0x9a, 0x9b,
0x9b, 0x9b, 0x9b, 0x9b, 0x9c, 0x9c, 0x9c, 0x9c,
0x9d, 0x9d, 0x9d, 0x9d, 0x9d, 0x9e, 0x9e, 0x9e,
0x9e, 0x9e, 0xa0, 0xa0, 0xa0, 0xa0, 0xa0, 0xa1,
0xa1, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2, 0xa2, 0xa2,
0xa2, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa4, 0xa4,
0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5, 0xa5, 0xa5,
0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa8, 0xa8, 0xa8,
0xa8, 0xa8, 0xa9, 0xa9, 0xa9, 0xa9, 0xa9, 0xab,
0xab, 0xab, 0xab, 0xab, 0xac, 0xac, 0xac, 0xac,
0xac, 0xac, 0xad, 0xad, 0xad, 0xad, 0xad, 0xae,
0xae, 0xae, 0xae, 0xae, 0xaf, 0xaf, 0xaf, 0xaf,
0xaf, 0xaf, 0xb0, 0xb0, 0xb0, 0xb0, 0xb0, 0xb1,
0xb1, 0xb1, 0xb1, 0xb1, 0xb1, 0xb2, 0xb2, 0xb2,
0xb2, 0xb2, 0xb3, 0xb3, 0xb3, 0xb3, 0xb3, 0xb3,
0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb6, 0xb6,
0xb6, 0xb6, 0xb6, 0xb7, 0xb7, 0xb7, 0xb7, 0xb7,
0xb7, 0xb8, 0xb8, 0xb8, 0xb8, 0xb8, 0xb8, 0xb9,
0xb9, 0xb9, 0xb9, 0xb9, 0xba, 0xba, 0xba, 0xba,
0xba, 0xba, 0xbc, 0xbc, 0xbc, 0xbc, 0xbc, 0xbc,
0xbd, 0xbd, 0xbd, 0xbd, 0xbd, 0xbd, 0xbe, 0xbe,
0xbe, 0xbe, 0xbe, 0xbe, 0xbf, 0xbf, 0xbf, 0xbf,
0xbf, 0xbf, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc3, 0xc3,
0xc3, 0xc3, 0xc3, 0xc3, 0xc4, 0xc4, 0xc4, 0xc4,
0xc4, 0xc4, 0xc5, 0xc5, 0xc5, 0xc5, 0xc5, 0xc5,
0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc7, 0xc7,
0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc9, 0xc9, 0xc9,
0xc9, 0xc9, 0xc9, 0xca, 0xca, 0xca, 0xca, 0xca,
0xca, 0xcb, 0xcb, 0xcb, 0xcb, 0xcb, 0xcb, 0xcc,
0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xce, 0xce, 0xce, 0xce,
0xce, 0xce, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf,
0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd1,
0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd3, 0xd3,
0xd3, 0xd3, 0xd3, 0xd3, 0xd4, 0xd4, 0xd4, 0xd4,
0xd4, 0xd4, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6,
0xd6, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd8,
0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd9, 0xd9,
0xd9, 0xd9, 0xd9, 0xd9, 0xda, 0xda, 0xda, 0xda,
0xda, 0xda, 0xda, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb,
0xdb, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xdf, 0xdf,
0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xe0, 0xe0, 0xe0,
0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1,
0xe1, 0xe1, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2,
0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe4,
0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5,
0xe5, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6, 0xe6, 0xe6,
0xe6, 0xe6, 0xe6, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7,
0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe9,
0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xeb, 0xeb, 0xeb,
0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec,
0xec, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed,
0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef,
0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0,
0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1,
0xf1, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf4,
0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf5, 0xf5,
0xf5, 0xf5, 0xf5, 0xf5, 0xf6, 0xf6, 0xf6, 0xf6,
0xf6, 0xf6, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7,
0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf9, 0xf9,
0xf9, 0xf9, 0xf9, 0xf9, 0xfa, 0xfa, 0xfa, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb},
{0x00, 0x00, 0x00, 0x01, 0x02, 0x05, 0x07, 0x08,
0x09, 0x0a, 0x0c, 0x0e, 0x10, 0x11, 0x12, 0x14,
0x15, 0x16, 0x17, 0x18, 0x1a, 0x1b, 0x1c, 0x1e,
0x1f, 0x20, 0x20, 0x22, 0x23, 0x25, 0x26, 0x27,
0x28, 0x28, 0x29, 0x2b, 0x2c, 0x2d, 0x2d, 0x2f,
0x30, 0x31, 0x31, 0x33, 0x34, 0x35, 0x35, 0x37,
0x38, 0x38, 0x39, 0x3a, 0x3a, 0x3b, 0x3c, 0x3c,
0x3d, 0x3f, 0x3f, 0x40, 0x40, 0x42, 0x43, 0x43,
0x44, 0x44, 0x45, 0x47, 0x47, 0x48, 0x48, 0x49,
0x4a, 0x4a, 0x4b, 0x4b, 0x4c, 0x4c, 0x4d, 0x4d,
0x4f, 0x4f, 0x50, 0x50, 0x52, 0x52, 0x53, 0x53,
0x54, 0x54, 0x55, 0x55, 0x56, 0x56, 0x58, 0x58,
0x59, 0x59, 0x5a, 0x5a, 0x5b, 0x5b, 0x5c, 0x5c,
0x5c, 0x5e, 0x5e, 0x5f, 0x5f, 0x60, 0x60, 0x61,
0x61, 0x61, 0x62, 0x62, 0x63, 0x63, 0x65, 0x65,
0x65, 0x66, 0x66, 0x67, 0x67, 0x67, 0x68, 0x68,
0x69, 0x69, 0x69, 0x6a, 0x6a, 0x6a, 0x6c, 0x6c,
0x6d, 0x6d, 0x6d, 0x6e, 0x6e, 0x6e, 0x6f, 0x6f,
0x70, 0x70, 0x70, 0x71, 0x71, 0x71, 0x73, 0x73,
0x73, 0x74, 0x74, 0x74, 0x75, 0x75, 0x75, 0x77,
0x77, 0x78, 0x78, 0x78, 0x79, 0x79, 0x79, 0x7a,
0x7a, 0x7a, 0x7a, 0x7b, 0x7b, 0x7b, 0x7c, 0x7c,
0x7c, 0x7d, 0x7d, 0x7d, 0x7f, 0x7f, 0x7f, 0x80,
0x80, 0x80, 0x81, 0x81, 0x81, 0x81, 0x82, 0x82,
0x82, 0x84, 0x84, 0x84, 0x85, 0x85, 0x85, 0x85,
0x86, 0x86, 0x86, 0x88, 0x88, 0x88, 0x88, 0x89,
0x89, 0x89, 0x8a, 0x8a, 0x8a, 0x8a, 0x8b, 0x8b,
0x8b, 0x8b, 0x8d, 0x8d, 0x8d, 0x8e, 0x8e, 0x8e,
0x8e, 0x8f, 0x8f, 0x8f, 0x8f, 0x90, 0x90, 0x90,
0x91, 0x91, 0x91, 0x91, 0x92, 0x92, 0x92, 0x92,
0x93, 0x93, 0x93, 0x93, 0x94, 0x94, 0x94, 0x94,
0x96, 0x96, 0x96, 0x96, 0x97, 0x97, 0x97, 0x97,
0x98, 0x98, 0x98, 0x98, 0x99, 0x99, 0x99, 0x99,
0x9a, 0x9a, 0x9a, 0x9a, 0x9b, 0x9b, 0x9b, 0x9b,
0x9b, 0x9c, 0x9c, 0x9c, 0x9c, 0x9d, 0x9d, 0x9d,
0x9d, 0x9e, 0x9e, 0x9e, 0x9e, 0x9e, 0xa0, 0xa0,
0xa0, 0xa0, 0xa1, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2,
0xa2, 0xa2, 0xa2, 0xa3, 0xa3, 0xa3, 0xa3, 0xa4,
0xa4, 0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5, 0xa5,
0xa5, 0xa6, 0xa6, 0xa6, 0xa6, 0xa8, 0xa8, 0xa8,
0xa8, 0xa8, 0xa9, 0xa9, 0xa9, 0xa9, 0xa9, 0xab,
0xab, 0xab, 0xab, 0xab, 0xac, 0xac, 0xac, 0xac,
0xad, 0xad, 0xad, 0xad, 0xad, 0xae, 0xae, 0xae,
0xae, 0xae, 0xaf, 0xaf, 0xaf, 0xaf, 0xaf, 0xb0,
0xb0, 0xb0, 0xb0, 0xb0, 0xb1, 0xb1, 0xb1, 0xb1,
0xb1, 0xb2, 0xb2, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3,
0xb3, 0xb3, 0xb3, 0xb4, 0xb3, 0xb4, 0xb4, 0xb4,
0xb6, 0xb6, 0xb6, 0xb6, 0xb6, 0xb6, 0xb7, 0xb7,
0xb7, 0xb7, 0xb7, 0xb8, 0xb8, 0xb8, 0xb8, 0xb8,
0xb9, 0xb9, 0xb9, 0xb9, 0xb9, 0xb9, 0xba, 0xba,
0xba, 0xba, 0xba, 0xbc, 0xbc, 0xbc, 0xbc, 0xbc,
0xbd, 0xbd, 0xbd, 0xbd, 0xbd, 0xbd, 0xbe, 0xbe,
0xbe, 0xbe, 0xbe, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf,
0xbf, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc2, 0xc2,
0xc2, 0xc2, 0xc2, 0xc2, 0xc3, 0xc3, 0xc3, 0xc3,
0xc3, 0xc3, 0xc4, 0xc4, 0xc4, 0xc4, 0xc4, 0xc5,
0xc5, 0xc5, 0xc5, 0xc5, 0xc5, 0xc6, 0xc6, 0xc6,
0xc6, 0xc6, 0xc6, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7,
0xc9, 0xc9, 0xc9, 0xc9, 0xc9, 0xc9, 0xca, 0xca,
0xca, 0xca, 0xca, 0xca, 0xcb, 0xcb, 0xcb, 0xcb,
0xcb, 0xcb, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xce, 0xce,
0xce, 0xce, 0xce, 0xce, 0xcf, 0xcf, 0xcf, 0xcf,
0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0,
0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd3, 0xd3,
0xd3, 0xd3, 0xd3, 0xd3, 0xd4, 0xd4, 0xd4, 0xd4,
0xd4, 0xd4, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6,
0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd8, 0xd8,
0xd8, 0xd8, 0xd8, 0xd8, 0xd9, 0xd9, 0xd9, 0xd9,
0xd9, 0xd9, 0xda, 0xda, 0xda, 0xda, 0xda, 0xda,
0xda, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde,
0xde, 0xde, 0xde, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf,
0xdf, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0,
0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe2, 0xe2,
0xe2, 0xe2, 0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe3,
0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4,
0xe4, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe6,
0xe6, 0xe6, 0xe6, 0xe6, 0xe6, 0xe7, 0xe7, 0xe7,
0xe7, 0xe7, 0xe7, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8,
0xe8, 0xe8, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9,
0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xec,
0xec, 0xec, 0xec, 0xec, 0xec, 0xed, 0xed, 0xed,
0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee,
0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0,
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1,
0xf1, 0xf1, 0xf1, 0xf1, 0xf3, 0xf3, 0xf3, 0xf3,
0xf3, 0xf3, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4,
0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf6, 0xf6,
0xf6, 0xf6, 0xf6, 0xf6, 0xf7, 0xf7, 0xf7, 0xf7,
0xf7, 0xf7, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8,
0xf8, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa,
0xfa, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb}
},
{ /* gamma 3 - from tp6810 + cx0342 */
{0x08, 0x09, 0x0c, 0x0d, 0x10, 0x11, 0x14, 0x15,
0x17, 0x18, 0x1a, 0x1c, 0x1e, 0x1f, 0x20, 0x23,
0x25, 0x26, 0x27, 0x28, 0x2b, 0x2c, 0x2d, 0x2f,
0x30, 0x31, 0x33, 0x34, 0x35, 0x37, 0x38, 0x39,
0x3a, 0x3b, 0x3c, 0x3d, 0x3f, 0x40, 0x42, 0x43,
0x44, 0x45, 0x47, 0x48, 0x48, 0x49, 0x4a, 0x4b,
0x4c, 0x4d, 0x4d, 0x4f, 0x50, 0x52, 0x53, 0x53,
0x54, 0x55, 0x56, 0x56, 0x58, 0x59, 0x5a, 0x5a,
0x5b, 0x5c, 0x5c, 0x5e, 0x5f, 0x5f, 0x60, 0x61,
0x61, 0x62, 0x63, 0x63, 0x65, 0x66, 0x66, 0x67,
0x68, 0x68, 0x69, 0x69, 0x6a, 0x6c, 0x6c, 0x6d,
0x6d, 0x6e, 0x6f, 0x6f, 0x70, 0x70, 0x71, 0x73,
0x73, 0x74, 0x74, 0x75, 0x75, 0x77, 0x77, 0x78,
0x78, 0x79, 0x7a, 0x7a, 0x7b, 0x7b, 0x7c, 0x7c,
0x7d, 0x7d, 0x7f, 0x7f, 0x80, 0x80, 0x81, 0x81,
0x82, 0x82, 0x84, 0x84, 0x85, 0x85, 0x86, 0x86,
0x86, 0x88, 0x88, 0x89, 0x89, 0x8a, 0x8a, 0x8b,
0x8b, 0x8d, 0x8d, 0x8d, 0x8e, 0x8e, 0x8f, 0x8f,
0x90, 0x90, 0x91, 0x91, 0x91, 0x92, 0x92, 0x93,
0x93, 0x93, 0x94, 0x94, 0x96, 0x96, 0x97, 0x97,
0x97, 0x98, 0x98, 0x99, 0x99, 0x99, 0x9a, 0x9a,
0x9a, 0x9b, 0x9b, 0x9c, 0x9c, 0x9c, 0x9d, 0x9d,
0x9e, 0x9e, 0x9e, 0xa0, 0xa0, 0xa0, 0xa1, 0xa1,
0xa2, 0xa2, 0xa2, 0xa3, 0xa3, 0xa3, 0xa4, 0xa4,
0xa4, 0xa5, 0xa5, 0xa5, 0xa6, 0xa6, 0xa8, 0xa8,
0xa8, 0xa9, 0xa9, 0xa9, 0xab, 0xab, 0xab, 0xac,
0xac, 0xac, 0xad, 0xad, 0xad, 0xae, 0xae, 0xae,
0xaf, 0xaf, 0xaf, 0xb0, 0xb0, 0xb0, 0xb1, 0xb1,
0xb1, 0xb2, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3, 0xb3,
0xb4, 0xb4, 0xb4, 0xb6, 0xb6, 0xb6, 0xb7, 0xb7,
0xb7, 0xb8, 0xb8, 0xb8, 0xb8, 0xb9, 0xb9, 0xb9,
0xba, 0xba, 0xba, 0xbc, 0xbc, 0xbc, 0xbc, 0xbd,
0xbd, 0xbd, 0xbe, 0xbe, 0xbe, 0xbe, 0xbf, 0xbf,
0xbf, 0xc0, 0xc0, 0xc0, 0xc0, 0xc2, 0xc2, 0xc2,
0xc3, 0xc3, 0xc3, 0xc3, 0xc4, 0xc4, 0xc4, 0xc5,
0xc5, 0xc5, 0xc5, 0xc6, 0xc6, 0xc6, 0xc6, 0xc7,
0xc7, 0xc7, 0xc9, 0xc9, 0xc9, 0xc9, 0xca, 0xca,
0xca, 0xca, 0xcb, 0xcb, 0xcb, 0xcb, 0xcc, 0xcc,
0xcc, 0xcd, 0xcd, 0xcd, 0xcd, 0xce, 0xce, 0xce,
0xce, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0,
0xd0, 0xd1, 0xd1, 0xd1, 0xd1, 0xd3, 0xd3, 0xd3,
0xd3, 0xd4, 0xd4, 0xd4, 0xd4, 0xd6, 0xd6, 0xd6,
0xd6, 0xd7, 0xd7, 0xd7, 0xd7, 0xd8, 0xd8, 0xd8,
0xd8, 0xd9, 0xd9, 0xd9, 0xd9, 0xda, 0xda, 0xda,
0xda, 0xda, 0xdb, 0xdb, 0xdb, 0xdb, 0xdd, 0xdd,
0xdd, 0xdd, 0xde, 0xde, 0xde, 0xde, 0xdf, 0xdf,
0xdf, 0xdf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe0, 0xe1,
0xe1, 0xe1, 0xe1, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2,
0xe3, 0xe3, 0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe4,
0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6, 0xe6,
0xe6, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe8, 0xe8,
0xe8, 0xe8, 0xe8, 0xe9, 0xe9, 0xe9, 0xe9, 0xeb,
0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec,
0xed, 0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee,
0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0,
0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1,
0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf4, 0xf4, 0xf4,
0xf4, 0xf4, 0xf5, 0xf5, 0xf5, 0xf5, 0xf6, 0xf6,
0xf6, 0xf6, 0xf6, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7,
0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf9, 0xf9, 0xf9,
0xf9, 0xf9, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc,
0xfc, 0xfc, 0xfc, 0xfd, 0xfd, 0xfd, 0xfd, 0xfd,
0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0x03, 0x05, 0x07, 0x09, 0x0a, 0x0c, 0x0d, 0x10,
0x11, 0x12, 0x14, 0x15, 0x17, 0x18, 0x1a, 0x1b,
0x1c, 0x1e, 0x1f, 0x20, 0x22, 0x23, 0x25, 0x26,
0x27, 0x28, 0x29, 0x2b, 0x2c, 0x2c, 0x2d, 0x2f,
0x30, 0x31, 0x33, 0x33, 0x34, 0x35, 0x37, 0x38,
0x38, 0x39, 0x3a, 0x3b, 0x3b, 0x3c, 0x3d, 0x3f,
0x3f, 0x40, 0x42, 0x42, 0x43, 0x44, 0x45, 0x45,
0x47, 0x47, 0x48, 0x49, 0x49, 0x4a, 0x4b, 0x4b,
0x4c, 0x4d, 0x4d, 0x4f, 0x4f, 0x50, 0x52, 0x52,
0x53, 0x53, 0x54, 0x54, 0x55, 0x55, 0x56, 0x58,
0x58, 0x59, 0x59, 0x5a, 0x5a, 0x5b, 0x5b, 0x5c,
0x5c, 0x5e, 0x5e, 0x5f, 0x5f, 0x60, 0x60, 0x61,
0x61, 0x62, 0x62, 0x63, 0x63, 0x65, 0x65, 0x66,
0x66, 0x67, 0x67, 0x67, 0x68, 0x68, 0x69, 0x69,
0x6a, 0x6a, 0x6c, 0x6c, 0x6c, 0x6d, 0x6d, 0x6e,
0x6e, 0x6f, 0x6f, 0x6f, 0x70, 0x70, 0x71, 0x71,
0x71, 0x73, 0x73, 0x74, 0x74, 0x74, 0x75, 0x75,
0x77, 0x77, 0x77, 0x78, 0x78, 0x79, 0x79, 0x79,
0x7a, 0x7a, 0x7a, 0x7b, 0x7b, 0x7b, 0x7c, 0x7c,
0x7d, 0x7d, 0x7d, 0x7f, 0x7f, 0x7f, 0x80, 0x80,
0x80, 0x81, 0x81, 0x81, 0x82, 0x82, 0x82, 0x84,
0x84, 0x84, 0x85, 0x85, 0x85, 0x86, 0x86, 0x86,
0x88, 0x88, 0x88, 0x89, 0x89, 0x89, 0x8a, 0x8a,
0x8a, 0x8b, 0x8b, 0x8b, 0x8d, 0x8d, 0x8d, 0x8e,
0x8e, 0x8e, 0x8e, 0x8f, 0x8f, 0x8f, 0x90, 0x90,
0x90, 0x91, 0x91, 0x91, 0x91, 0x92, 0x92, 0x92,
0x93, 0x93, 0x93, 0x93, 0x94, 0x94, 0x94, 0x96,
0x96, 0x96, 0x96, 0x97, 0x97, 0x97, 0x98, 0x98,
0x98, 0x98, 0x99, 0x99, 0x99, 0x9a, 0x9a, 0x9a,
0x9a, 0x9b, 0x9b, 0x9b, 0x9b, 0x9c, 0x9c, 0x9c,
0x9c, 0x9d, 0x9d, 0x9d, 0x9e, 0x9e, 0x9e, 0x9e,
0xa0, 0xa0, 0xa0, 0xa0, 0xa1, 0xa1, 0xa1, 0xa1,
0xa2, 0xa2, 0xa2, 0xa2, 0xa3, 0xa3, 0xa3, 0xa3,
0xa4, 0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5, 0xa5,
0xa6, 0xa6, 0xa6, 0xa6, 0xa8, 0xa8, 0xa8, 0xa8,
0xa9, 0xa9, 0xa9, 0xa9, 0xa9, 0xab, 0xab, 0xab,
0xab, 0xac, 0xac, 0xac, 0xac, 0xad, 0xad, 0xad,
0xad, 0xad, 0xae, 0xae, 0xae, 0xae, 0xaf, 0xaf,
0xaf, 0xaf, 0xb0, 0xb0, 0xb0, 0xb0, 0xb0, 0xb1,
0xb1, 0xb1, 0xb1, 0xb2, 0xb2, 0xb2, 0xb2, 0xb2,
0xb3, 0xb3, 0xb3, 0xb3, 0xb3, 0xb4, 0xb4, 0xb4,
0xb4, 0xb6, 0xb6, 0xb6, 0xb6, 0xb6, 0xb7, 0xb7,
0xb7, 0xb7, 0xb7, 0xb8, 0xb8, 0xb8, 0xb8, 0xb9,
0xb9, 0xb9, 0xb9, 0xb9, 0xba, 0xba, 0xba, 0xba,
0xba, 0xbc, 0xbc, 0xbc, 0xbc, 0xbc, 0xbd, 0xbd,
0xbd, 0xbd, 0xbd, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe,
0xbf, 0xbf, 0xbf, 0xbf, 0xbf, 0xc0, 0xc0, 0xc0,
0xc0, 0xc0, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc3,
0xc3, 0xc3, 0xc3, 0xc3, 0xc4, 0xc4, 0xc4, 0xc4,
0xc4, 0xc5, 0xc5, 0xc5, 0xc5, 0xc5, 0xc6, 0xc6,
0xc6, 0xc6, 0xc6, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7,
0xc7, 0xc9, 0xc9, 0xc9, 0xc9, 0xc9, 0xca, 0xca,
0xca, 0xca, 0xca, 0xcb, 0xcb, 0xcb, 0xcb, 0xcb,
0xcb, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xce, 0xce, 0xce, 0xce,
0xce, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0,
0xd0, 0xd0, 0xd0, 0xd0, 0xd1, 0xd1, 0xd1, 0xd1,
0xd1, 0xd1, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd4,
0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd6, 0xd6, 0xd6,
0xd6, 0xd6, 0xd6, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7,
0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd9, 0xd9,
0xd9, 0xd9, 0xd9, 0xd9, 0xda, 0xda, 0xda, 0xda,
0xda, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde,
0xde, 0xde, 0xde, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf,
0xdf, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe1,
0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe2, 0xe2, 0xe2,
0xe2, 0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3,
0xe3, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe5,
0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6, 0xe6,
0xe6, 0xe6, 0xe6, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7,
0xe7, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe9,
0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xeb, 0xeb, 0xeb,
0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec, 0xec,
0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xee,
0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef,
0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0,
0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf3,
0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf4, 0xf4, 0xf4,
0xf4, 0xf4, 0xf4, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5,
0xf5, 0xf5, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6,
0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf8, 0xf8,
0xf8, 0xf8, 0xf8, 0xf8, 0xf9, 0xf9, 0xf9, 0xf9,
0xf9, 0xf9, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfc, 0xfc, 0xfc, 0xfc,
0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc,
0xfd, 0xfd, 0xfd, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe,
0xfe, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0x07, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14,
0x16, 0x17, 0x18, 0x1b, 0x1c, 0x1e, 0x1f, 0x20,
0x23, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2b, 0x2d,
0x2f, 0x30, 0x31, 0x33, 0x34, 0x35, 0x37, 0x38,
0x39, 0x3a, 0x3b, 0x3b, 0x3c, 0x3d, 0x3f, 0x40,
0x42, 0x43, 0x44, 0x44, 0x45, 0x47, 0x48, 0x49,
0x4a, 0x4a, 0x4b, 0x4c, 0x4d, 0x4d, 0x4f, 0x50,
0x52, 0x52, 0x53, 0x54, 0x55, 0x55, 0x56, 0x58,
0x58, 0x59, 0x5a, 0x5b, 0x5b, 0x5c, 0x5e, 0x5e,
0x5f, 0x5f, 0x60, 0x61, 0x61, 0x62, 0x63, 0x63,
0x65, 0x65, 0x66, 0x67, 0x67, 0x68, 0x68, 0x69,
0x6a, 0x6a, 0x6c, 0x6c, 0x6d, 0x6d, 0x6e, 0x6e,
0x6f, 0x70, 0x70, 0x71, 0x71, 0x73, 0x73, 0x74,
0x74, 0x75, 0x75, 0x77, 0x77, 0x78, 0x78, 0x79,
0x79, 0x7a, 0x7a, 0x7b, 0x7b, 0x7c, 0x7c, 0x7d,
0x7d, 0x7f, 0x7f, 0x80, 0x80, 0x81, 0x81, 0x81,
0x82, 0x82, 0x84, 0x84, 0x85, 0x85, 0x86, 0x86,
0x88, 0x88, 0x88, 0x89, 0x89, 0x8a, 0x8a, 0x8b,
0x8b, 0x8b, 0x8d, 0x8d, 0x8e, 0x8e, 0x8e, 0x8f,
0x8f, 0x90, 0x90, 0x90, 0x91, 0x91, 0x92, 0x92,
0x92, 0x93, 0x93, 0x94, 0x94, 0x94, 0x96, 0x96,
0x96, 0x97, 0x97, 0x98, 0x98, 0x98, 0x99, 0x99,
0x99, 0x9a, 0x9a, 0x9b, 0x9b, 0x9b, 0x9c, 0x9c,
0x9c, 0x9d, 0x9d, 0x9d, 0x9e, 0x9e, 0x9e, 0xa0,
0xa0, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2, 0xa2, 0xa3,
0xa3, 0xa3, 0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5,
0xa6, 0xa6, 0xa6, 0xa8, 0xa8, 0xa8, 0xa8, 0xa9,
0xa9, 0xa9, 0xab, 0xab, 0xab, 0xac, 0xac, 0xac,
0xad, 0xad, 0xad, 0xae, 0xae, 0xae, 0xaf, 0xaf,
0xaf, 0xaf, 0xb0, 0xb0, 0xb0, 0xb1, 0xb1, 0xb1,
0xb2, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3, 0xb3, 0xb4,
0xb4, 0xb4, 0xb4, 0xb6, 0xb6, 0xb6, 0xb7, 0xb7,
0xb7, 0xb7, 0xb8, 0xb8, 0xb8, 0xb9, 0xb9, 0xb9,
0xb9, 0xba, 0xba, 0xba, 0xbc, 0xbc, 0xbc, 0xbc,
0xbd, 0xbd, 0xbd, 0xbd, 0xbe, 0xbe, 0xbe, 0xbf,
0xbf, 0xbf, 0xbf, 0xc0, 0xc0, 0xc0, 0xc0, 0xc2,
0xc2, 0xc2, 0xc2, 0xc3, 0xc3, 0xc3, 0xc3, 0xc4,
0xc4, 0xc4, 0xc5, 0xc5, 0xc5, 0xc5, 0xc6, 0xc6,
0xc6, 0xc6, 0xc7, 0xc7, 0xc7, 0xc7, 0xc9, 0xc9,
0xc9, 0xc9, 0xca, 0xca, 0xca, 0xca, 0xcb, 0xcb,
0xcb, 0xcb, 0xcc, 0xcc, 0xcc, 0xcc, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xce, 0xce, 0xce, 0xce, 0xcf,
0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd1,
0xd1, 0xd1, 0xd1, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3,
0xd4, 0xd4, 0xd4, 0xd4, 0xd6, 0xd6, 0xd6, 0xd6,
0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd8, 0xd8, 0xd8,
0xd8, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xda, 0xda,
0xda, 0xda, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdd,
0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde, 0xde, 0xde,
0xdf, 0xdf, 0xdf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe0,
0xe0, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe2, 0xe2,
0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe4,
0xe4, 0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5, 0xe5,
0xe6, 0xe6, 0xe6, 0xe6, 0xe6, 0xe7, 0xe7, 0xe7,
0xe7, 0xe7, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe9,
0xe9, 0xe9, 0xe9, 0xe9, 0xeb, 0xeb, 0xeb, 0xeb,
0xeb, 0xec, 0xec, 0xec, 0xec, 0xec, 0xed, 0xed,
0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee,
0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0,
0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf3,
0xf3, 0xf3, 0xf3, 0xf3, 0xf4, 0xf4, 0xf4, 0xf4,
0xf4, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf6, 0xf6,
0xf6, 0xf6, 0xf6, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7,
0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf9, 0xf9, 0xf9,
0xf9, 0xf9, 0xf9, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc,
0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfd, 0xfd, 0xfd,
0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
},
{ /* gamma 4 - from tp6800 + soi763a */
{0x11, 0x14, 0x15, 0x17, 0x1a, 0x1b, 0x1e, 0x1f,
0x22, 0x23, 0x25, 0x27, 0x28, 0x2b, 0x2c, 0x2d,
0x2f, 0x31, 0x33, 0x34, 0x35, 0x38, 0x39, 0x3a,
0x3b, 0x3c, 0x3d, 0x40, 0x42, 0x43, 0x44, 0x45,
0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4f,
0x50, 0x52, 0x53, 0x53, 0x54, 0x55, 0x56, 0x58,
0x59, 0x5a, 0x5b, 0x5b, 0x5c, 0x5e, 0x5f, 0x60,
0x61, 0x61, 0x62, 0x63, 0x65, 0x65, 0x66, 0x67,
0x68, 0x68, 0x69, 0x6a, 0x6c, 0x6c, 0x6d, 0x6e,
0x6f, 0x6f, 0x70, 0x71, 0x71, 0x73, 0x74, 0x74,
0x75, 0x77, 0x77, 0x78, 0x79, 0x79, 0x7a, 0x7a,
0x7b, 0x7c, 0x7c, 0x7d, 0x7f, 0x7f, 0x80, 0x80,
0x81, 0x81, 0x82, 0x84, 0x84, 0x85, 0x85, 0x86,
0x86, 0x88, 0x89, 0x89, 0x8a, 0x8a, 0x8b, 0x8b,
0x8d, 0x8d, 0x8e, 0x8e, 0x8f, 0x90, 0x90, 0x91,
0x91, 0x92, 0x92, 0x93, 0x93, 0x94, 0x94, 0x96,
0x96, 0x97, 0x97, 0x98, 0x98, 0x98, 0x99, 0x99,
0x9a, 0x9a, 0x9b, 0x9b, 0x9c, 0x9c, 0x9d, 0x9d,
0x9e, 0x9e, 0xa0, 0xa0, 0xa0, 0xa1, 0xa1, 0xa2,
0xa2, 0xa3, 0xa3, 0xa3, 0xa4, 0xa4, 0xa5, 0xa5,
0xa6, 0xa6, 0xa6, 0xa8, 0xa8, 0xa9, 0xa9, 0xab,
0xab, 0xab, 0xac, 0xac, 0xad, 0xad, 0xad, 0xae,
0xae, 0xaf, 0xaf, 0xaf, 0xb0, 0xb0, 0xb1, 0xb1,
0xb1, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3, 0xb4, 0xb4,
0xb4, 0xb6, 0xb6, 0xb6, 0xb7, 0xb7, 0xb8, 0xb8,
0xb8, 0xb9, 0xb9, 0xb9, 0xba, 0xba, 0xba, 0xbc,
0xbc, 0xbd, 0xbd, 0xbd, 0xbe, 0xbe, 0xbe, 0xbf,
0xbf, 0xbf, 0xc0, 0xc0, 0xc0, 0xc2, 0xc2, 0xc2,
0xc3, 0xc3, 0xc3, 0xc4, 0xc4, 0xc4, 0xc5, 0xc5,
0xc5, 0xc6, 0xc6, 0xc6, 0xc7, 0xc7, 0xc7, 0xc9,
0xc9, 0xc9, 0xca, 0xca, 0xca, 0xcb, 0xcb, 0xcb,
0xcb, 0xcc, 0xcc, 0xcc, 0xcd, 0xcd, 0xcd, 0xce,
0xce, 0xce, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0,
0xd0, 0xd1, 0xd1, 0xd1, 0xd3, 0xd3, 0xd3, 0xd3,
0xd4, 0xd4, 0xd4, 0xd6, 0xd6, 0xd6, 0xd7, 0xd7,
0xd7, 0xd7, 0xd8, 0xd8, 0xd8, 0xd9, 0xd9, 0xd9,
0xd9, 0xda, 0xda, 0xda, 0xdb, 0xdb, 0xdb, 0xdb,
0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde, 0xde, 0xdf,
0xdf, 0xdf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1,
0xe1, 0xe1, 0xe2, 0xe2, 0xe2, 0xe2, 0xe3, 0xe3,
0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5,
0xe5, 0xe6, 0xe6, 0xe6, 0xe6, 0xe7, 0xe7, 0xe7,
0xe7, 0xe8, 0xe8, 0xe8, 0xe8, 0xe9, 0xe9, 0xe9,
0xe9, 0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec,
0xec, 0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee,
0xee, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0,
0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf3, 0xf3, 0xf3,
0xf3, 0xf4, 0xf4, 0xf4, 0xf4, 0xf5, 0xf5, 0xf5,
0xf5, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf7, 0xf7,
0xf7, 0xf7, 0xf8, 0xf8, 0xf8, 0xf8, 0xf9, 0xf9,
0xf9, 0xf9, 0xfa, 0xf9, 0xfa, 0xfa, 0xfa, 0xfa,
0xfa, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb},
{0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x11, 0x14, 0x15,
0x16, 0x17, 0x1a, 0x1b, 0x1c, 0x1e, 0x1f, 0x20,
0x23, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2b, 0x2c,
0x2d, 0x2f, 0x30, 0x31, 0x33, 0x34, 0x34, 0x35,
0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3c, 0x3d,
0x3f, 0x40, 0x42, 0x42, 0x43, 0x44, 0x45, 0x45,
0x47, 0x48, 0x49, 0x49, 0x4a, 0x4b, 0x4b, 0x4c,
0x4d, 0x4f, 0x4f, 0x50, 0x52, 0x52, 0x53, 0x54,
0x54, 0x55, 0x55, 0x56, 0x58, 0x58, 0x59, 0x5a,
0x5a, 0x5b, 0x5b, 0x5c, 0x5e, 0x5e, 0x5f, 0x5f,
0x60, 0x60, 0x61, 0x61, 0x62, 0x63, 0x63, 0x65,
0x65, 0x66, 0x66, 0x67, 0x67, 0x68, 0x68, 0x69,
0x69, 0x6a, 0x6a, 0x6c, 0x6c, 0x6d, 0x6d, 0x6e,
0x6e, 0x6f, 0x6f, 0x70, 0x70, 0x71, 0x71, 0x73,
0x73, 0x74, 0x74, 0x74, 0x75, 0x75, 0x77, 0x77,
0x78, 0x78, 0x79, 0x79, 0x79, 0x7a, 0x7a, 0x7b,
0x7b, 0x7c, 0x7c, 0x7c, 0x7d, 0x7d, 0x7f, 0x7f,
0x7f, 0x80, 0x80, 0x81, 0x81, 0x81, 0x82, 0x82,
0x84, 0x84, 0x84, 0x85, 0x85, 0x86, 0x86, 0x86,
0x88, 0x88, 0x88, 0x89, 0x89, 0x8a, 0x8a, 0x8a,
0x8b, 0x8b, 0x8b, 0x8d, 0x8d, 0x8d, 0x8e, 0x8e,
0x8e, 0x8f, 0x8f, 0x90, 0x90, 0x90, 0x91, 0x91,
0x91, 0x92, 0x92, 0x92, 0x93, 0x93, 0x93, 0x94,
0x94, 0x94, 0x96, 0x96, 0x96, 0x97, 0x97, 0x97,
0x98, 0x98, 0x98, 0x98, 0x99, 0x99, 0x99, 0x9a,
0x9a, 0x9a, 0x9b, 0x9b, 0x9b, 0x9c, 0x9c, 0x9c,
0x9c, 0x9d, 0x9d, 0x9d, 0x9e, 0x9e, 0x9e, 0xa0,
0xa0, 0xa0, 0xa0, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2,
0xa2, 0xa3, 0xa3, 0xa3, 0xa3, 0xa4, 0xa4, 0xa4,
0xa5, 0xa5, 0xa5, 0xa5, 0xa6, 0xa6, 0xa6, 0xa6,
0xa8, 0xa8, 0xa8, 0xa9, 0xa9, 0xa9, 0xa9, 0xab,
0xaa, 0xab, 0xab, 0xac, 0xac, 0xac, 0xad, 0xad,
0xad, 0xad, 0xae, 0xae, 0xae, 0xae, 0xaf, 0xaf,
0xaf, 0xaf, 0xb0, 0xb0, 0xb0, 0xb0, 0xb1, 0xb1,
0xb1, 0xb1, 0xb2, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3,
0xb3, 0xb3, 0xb4, 0xb4, 0xb4, 0xb4, 0xb6, 0xb6,
0xb6, 0xb6, 0xb7, 0xb7, 0xb7, 0xb7, 0xb8, 0xb8,
0xb8, 0xb8, 0xb9, 0xb9, 0xb9, 0xb9, 0xba, 0xba,
0xba, 0xba, 0xba, 0xbc, 0xbc, 0xbc, 0xbc, 0xbd,
0xbd, 0xbd, 0xbd, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe,
0xbf, 0xbf, 0xbf, 0xbf, 0xc0, 0xc0, 0xc0, 0xc0,
0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc3, 0xc3, 0xc3,
0xc3, 0xc4, 0xc4, 0xc4, 0xc4, 0xc4, 0xc5, 0xc5,
0xc5, 0xc5, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc7,
0xc7, 0xc7, 0xc7, 0xc7, 0xc9, 0xc9, 0xc9, 0xc9,
0xca, 0xca, 0xca, 0xca, 0xca, 0xcb, 0xcb, 0xcb,
0xcb, 0xcb, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xce, 0xce, 0xce, 0xce,
0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0,
0xd0, 0xd0, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd3,
0xd3, 0xd3, 0xd3, 0xd3, 0xd4, 0xd4, 0xd4, 0xd4,
0xd4, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd7, 0xd7,
0xd7, 0xd7, 0xd7, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8,
0xd8, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xda, 0xda,
0xda, 0xda, 0xda, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde,
0xde, 0xde, 0xde, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf,
0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1,
0xe1, 0xe1, 0xe1, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2,
0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe4, 0xe4,
0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5,
0xe5, 0xe6, 0xe6, 0xe6, 0xe6, 0xe6, 0xe7, 0xe7,
0xe7, 0xe7, 0xe7, 0xe7, 0xe8, 0xe8, 0xe8, 0xe8,
0xe8, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xeb,
0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec,
0xec, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed,
0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef,
0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0,
0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf3,
0xf3, 0xf3, 0xf3, 0xf3, 0xf4, 0xf4, 0xf4, 0xf4,
0xf4, 0xf4, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5,
0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf7, 0xf7,
0xf7, 0xf7, 0xf7, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8,
0xf8, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa,
0xfa, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb},
{0x0d, 0x10, 0x11, 0x14, 0x15, 0x17, 0x18, 0x1b,
0x1c, 0x1e, 0x20, 0x22, 0x23, 0x26, 0x27, 0x28,
0x29, 0x2b, 0x2d, 0x2f, 0x30, 0x31, 0x33, 0x34,
0x35, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d,
0x3f, 0x40, 0x42, 0x43, 0x44, 0x45, 0x47, 0x48,
0x49, 0x4a, 0x4b, 0x4b, 0x4c, 0x4d, 0x4f, 0x50,
0x52, 0x52, 0x53, 0x54, 0x55, 0x56, 0x56, 0x58,
0x59, 0x5a, 0x5a, 0x5b, 0x5c, 0x5e, 0x5e, 0x5f,
0x60, 0x60, 0x61, 0x62, 0x62, 0x63, 0x65, 0x65,
0x66, 0x67, 0x67, 0x68, 0x69, 0x69, 0x6a, 0x6c,
0x6c, 0x6d, 0x6d, 0x6e, 0x6f, 0x6f, 0x70, 0x70,
0x71, 0x73, 0x73, 0x74, 0x74, 0x75, 0x75, 0x77,
0x78, 0x78, 0x79, 0x79, 0x7a, 0x7a, 0x7b, 0x7b,
0x7c, 0x7c, 0x7d, 0x7d, 0x7f, 0x7f, 0x80, 0x80,
0x81, 0x81, 0x82, 0x82, 0x84, 0x84, 0x85, 0x85,
0x86, 0x86, 0x88, 0x88, 0x89, 0x89, 0x8a, 0x8a,
0x8b, 0x8b, 0x8d, 0x8d, 0x8d, 0x8e, 0x8e, 0x8f,
0x8f, 0x90, 0x90, 0x91, 0x91, 0x91, 0x92, 0x92,
0x93, 0x93, 0x94, 0x94, 0x94, 0x96, 0x96, 0x97,
0x97, 0x98, 0x98, 0x98, 0x99, 0x99, 0x9a, 0x9a,
0x9a, 0x9b, 0x9b, 0x9c, 0x9c, 0x9c, 0x9d, 0x9d,
0x9d, 0x9e, 0x9e, 0xa0, 0xa0, 0xa0, 0xa1, 0xa1,
0xa1, 0xa2, 0xa2, 0xa3, 0xa3, 0xa3, 0xa4, 0xa4,
0xa4, 0xa5, 0xa5, 0xa5, 0xa6, 0xa6, 0xa8, 0xa8,
0xa8, 0xa9, 0xa9, 0xa9, 0xab, 0xab, 0xab, 0xac,
0xac, 0xac, 0xad, 0xad, 0xad, 0xae, 0xae, 0xae,
0xaf, 0xaf, 0xaf, 0xb0, 0xb0, 0xb0, 0xb1, 0xb1,
0xb1, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3, 0xb3, 0xb4,
0xb4, 0xb4, 0xb6, 0xb6, 0xb6, 0xb6, 0xb7, 0xb7,
0xb7, 0xb8, 0xb8, 0xb8, 0xb9, 0xb9, 0xb9, 0xba,
0xba, 0xba, 0xba, 0xbc, 0xbc, 0xbc, 0xbd, 0xbd,
0xbd, 0xbe, 0xbe, 0xbe, 0xbe, 0xbf, 0xbf, 0xbf,
0xc0, 0xc0, 0xc0, 0xc0, 0xc2, 0xc2, 0xc2, 0xc3,
0xc3, 0xc3, 0xc3, 0xc4, 0xc4, 0xc4, 0xc5, 0xc5,
0xc5, 0xc5, 0xc6, 0xc6, 0xc6, 0xc6, 0xc7, 0xc7,
0xc7, 0xc9, 0xc9, 0xc9, 0xc9, 0xca, 0xca, 0xca,
0xca, 0xcb, 0xcb, 0xcb, 0xcc, 0xcc, 0xcc, 0xcc,
0xcd, 0xcd, 0xcd, 0xcd, 0xce, 0xce, 0xce, 0xce,
0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0xd0,
0xd1, 0xd1, 0xd1, 0xd1, 0xd3, 0xd3, 0xd3, 0xd3,
0xd4, 0xd4, 0xd4, 0xd4, 0xd6, 0xd6, 0xd6, 0xd6,
0xd7, 0xd7, 0xd7, 0xd7, 0xd8, 0xd8, 0xd8, 0xd8,
0xd9, 0xd9, 0xd9, 0xd9, 0xda, 0xda, 0xda, 0xda,
0xdb, 0xdb, 0xdb, 0xdb, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xde, 0xde, 0xde, 0xde, 0xdf, 0xdf, 0xdf,
0xdf, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1,
0xe1, 0xe1, 0xe2, 0xe2, 0xe2, 0xe2, 0xe3, 0xe3,
0xe3, 0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe4, 0xe5,
0xe5, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6, 0xe6, 0xe6,
0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe8, 0xe8, 0xe8,
0xe8, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xeb, 0xeb,
0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec, 0xec, 0xed,
0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee,
0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0,
0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf3,
0xf3, 0xf3, 0xf3, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4,
0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf6, 0xf6, 0xf6,
0xf6, 0xf6, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf8,
0xf8, 0xf8, 0xf8, 0xf8, 0xf9, 0xf9, 0xf9, 0xf9,
0xf9, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa,
0xfa, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb}
},
{ /* gamma 5 */
{0x16, 0x18, 0x19, 0x1b, 0x1d, 0x1e, 0x20, 0x21,
0x23, 0x24, 0x25, 0x27, 0x28, 0x2a, 0x2b, 0x2c,
0x2d, 0x2f, 0x30, 0x31, 0x32, 0x34, 0x35, 0x36,
0x37, 0x38, 0x39, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x4a, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e,
0x4f, 0x50, 0x51, 0x51, 0x52, 0x53, 0x54, 0x55,
0x56, 0x56, 0x57, 0x58, 0x59, 0x59, 0x5a, 0x5b,
0x5c, 0x5c, 0x5d, 0x5e, 0x5f, 0x5f, 0x60, 0x61,
0x62, 0x62, 0x63, 0x64, 0x64, 0x65, 0x66, 0x66,
0x67, 0x68, 0x68, 0x69, 0x6a, 0x6a, 0x6b, 0x6b,
0x6c, 0x6d, 0x6d, 0x6e, 0x6f, 0x6f, 0x70, 0x70,
0x71, 0x71, 0x72, 0x73, 0x73, 0x74, 0x74, 0x75,
0x75, 0x76, 0x77, 0x77, 0x78, 0x78, 0x79, 0x79,
0x7a, 0x7a, 0x7b, 0x7b, 0x7c, 0x7d, 0x7d, 0x7e,
0x7e, 0x7f, 0x7f, 0x80, 0x80, 0x81, 0x81, 0x82,
0x82, 0x83, 0x83, 0x84, 0x84, 0x84, 0x85, 0x85,
0x86, 0x86, 0x87, 0x87, 0x88, 0x88, 0x89, 0x89,
0x8a, 0x8a, 0x8b, 0x8b, 0x8b, 0x8c, 0x8c, 0x8d,
0x8d, 0x8e, 0x8e, 0x8e, 0x8f, 0x8f, 0x90, 0x90,
0x91, 0x91, 0x91, 0x92, 0x92, 0x93, 0x93, 0x94,
0x94, 0x94, 0x95, 0x95, 0x96, 0x96, 0x96, 0x97,
0x97, 0x98, 0x98, 0x98, 0x99, 0x99, 0x9a, 0x9a,
0x9a, 0x9b, 0x9b, 0x9b, 0x9c, 0x9c, 0x9d, 0x9d,
0x9d, 0x9e, 0x9e, 0x9e, 0x9f, 0x9f, 0xa0, 0xa0,
0xa0, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2, 0xa2, 0xa3,
0xa3, 0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5, 0xa6,
0xa6, 0xa6, 0xa7, 0xa7, 0xa7, 0xa8, 0xa8, 0xa8,
0xa9, 0xa9, 0xa9, 0xaa, 0xaa, 0xaa, 0xab, 0xab,
0xab, 0xac, 0xac, 0xac, 0xad, 0xad, 0xad, 0xae,
0xae, 0xae, 0xaf, 0xaf, 0xaf, 0xb0, 0xb0, 0xb0,
0xb0, 0xb1, 0xb1, 0xb1, 0xb2, 0xb2, 0xb2, 0xb3,
0xb3, 0xb3, 0xb4, 0xb4, 0xb4, 0xb4, 0xb5, 0xb5,
0xb5, 0xb6, 0xb6, 0xb6, 0xb7, 0xb7, 0xb7, 0xb7,
0xb8, 0xb8, 0xb8, 0xb9, 0xb9, 0xb9, 0xba, 0xba,
0xba, 0xba, 0xbb, 0xbb, 0xbb, 0xbc, 0xbc, 0xbc,
0xbc, 0xbd, 0xbd, 0xbd, 0xbe, 0xbe, 0xbe, 0xbe,
0xbf, 0xbf, 0xbf, 0xc0, 0xc0, 0xc0, 0xc0, 0xc1,
0xc1, 0xc1, 0xc1, 0xc2, 0xc2, 0xc2, 0xc3, 0xc3,
0xc3, 0xc3, 0xc4, 0xc4, 0xc4, 0xc4, 0xc5, 0xc5,
0xc5, 0xc5, 0xc6, 0xc6, 0xc6, 0xc7, 0xc7, 0xc7,
0xc7, 0xc8, 0xc8, 0xc8, 0xc8, 0xc9, 0xc9, 0xc9,
0xc9, 0xca, 0xca, 0xca, 0xca, 0xcb, 0xcb, 0xcb,
0xcb, 0xcc, 0xcc, 0xcc, 0xcc, 0xcd, 0xcd, 0xcd,
0xcd, 0xce, 0xce, 0xce, 0xce, 0xcf, 0xcf, 0xcf,
0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd1, 0xd1, 0xd1,
0xd1, 0xd2, 0xd2, 0xd2, 0xd2, 0xd3, 0xd3, 0xd3,
0xd3, 0xd4, 0xd4, 0xd4, 0xd4, 0xd5, 0xd5, 0xd5,
0xd5, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd7, 0xd7,
0xd7, 0xd7, 0xd8, 0xd8, 0xd8, 0xd8, 0xd9, 0xd9,
0xd9, 0xd9, 0xda, 0xda, 0xda, 0xda, 0xda, 0xdb,
0xdb, 0xdb, 0xdb, 0xdc, 0xdc, 0xdc, 0xdc, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde, 0xde,
0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xe0, 0xe0, 0xe0,
0xe0, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe2, 0xe2,
0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe4,
0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5,
0xe6, 0xe6, 0xe6, 0xe6, 0xe7, 0xe7, 0xe7, 0xe7,
0xe7, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe9, 0xe9,
0xe9, 0xe9, 0xea, 0xea, 0xea, 0xea, 0xea, 0xeb,
0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec,
0xed, 0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee,
0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0,
0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1,
0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf3, 0xf3, 0xf3,
0xf3, 0xf3, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf5,
0xf5, 0xf5, 0xf5, 0xf5, 0xf6, 0xf6, 0xf6, 0xf6,
0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf8, 0xf8, 0xf8,
0xf8, 0xf8, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfd, 0xfd,
0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0x0f, 0x11, 0x12, 0x14, 0x15, 0x16, 0x18, 0x19,
0x1a, 0x1b, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22,
0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x31, 0x32,
0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x38, 0x39,
0x3a, 0x3b, 0x3c, 0x3c, 0x3d, 0x3e, 0x3f, 0x3f,
0x40, 0x41, 0x42, 0x42, 0x43, 0x44, 0x44, 0x45,
0x46, 0x47, 0x47, 0x48, 0x49, 0x49, 0x4a, 0x4b,
0x4b, 0x4c, 0x4c, 0x4d, 0x4e, 0x4e, 0x4f, 0x50,
0x50, 0x51, 0x51, 0x52, 0x53, 0x53, 0x54, 0x54,
0x55, 0x55, 0x56, 0x56, 0x57, 0x58, 0x58, 0x59,
0x59, 0x5a, 0x5a, 0x5b, 0x5b, 0x5c, 0x5c, 0x5d,
0x5d, 0x5e, 0x5e, 0x5f, 0x5f, 0x60, 0x60, 0x61,
0x61, 0x62, 0x62, 0x63, 0x63, 0x64, 0x64, 0x65,
0x65, 0x66, 0x66, 0x66, 0x67, 0x67, 0x68, 0x68,
0x69, 0x69, 0x6a, 0x6a, 0x6a, 0x6b, 0x6b, 0x6c,
0x6c, 0x6d, 0x6d, 0x6d, 0x6e, 0x6e, 0x6f, 0x6f,
0x6f, 0x70, 0x70, 0x71, 0x71, 0x71, 0x72, 0x72,
0x73, 0x73, 0x73, 0x74, 0x74, 0x75, 0x75, 0x75,
0x76, 0x76, 0x76, 0x77, 0x77, 0x78, 0x78, 0x78,
0x79, 0x79, 0x79, 0x7a, 0x7a, 0x7a, 0x7b, 0x7b,
0x7b, 0x7c, 0x7c, 0x7d, 0x7d, 0x7d, 0x7e, 0x7e,
0x7e, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x81,
0x81, 0x81, 0x82, 0x82, 0x82, 0x83, 0x83, 0x83,
0x84, 0x84, 0x84, 0x84, 0x85, 0x85, 0x85, 0x86,
0x86, 0x86, 0x87, 0x87, 0x87, 0x88, 0x88, 0x88,
0x88, 0x89, 0x89, 0x89, 0x8a, 0x8a, 0x8a, 0x8b,
0x8b, 0x8b, 0x8b, 0x8c, 0x8c, 0x8c, 0x8d, 0x8d,
0x8d, 0x8e, 0x8e, 0x8e, 0x8e, 0x8f, 0x8f, 0x8f,
0x90, 0x90, 0x90, 0x90, 0x91, 0x91, 0x91, 0x91,
0x92, 0x92, 0x92, 0x93, 0x93, 0x93, 0x93, 0x94,
0x94, 0x94, 0x94, 0x95, 0x95, 0x95, 0x96, 0x96,
0x96, 0x96, 0x97, 0x97, 0x97, 0x97, 0x98, 0x98,
0x98, 0x98, 0x99, 0x99, 0x99, 0x99, 0x9a, 0x9a,
0x9a, 0x9a, 0x9b, 0x9b, 0x9b, 0x9b, 0x9c, 0x9c,
0x9c, 0x9c, 0x9d, 0x9d, 0x9d, 0x9d, 0x9e, 0x9e,
0x9e, 0x9e, 0x9f, 0x9f, 0x9f, 0x9f, 0xa0, 0xa0,
0xa0, 0xa0, 0xa1, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2,
0xa2, 0xa2, 0xa2, 0xa3, 0xa3, 0xa3, 0xa3, 0xa4,
0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5, 0xa5, 0xa5,
0xa6, 0xa6, 0xa6, 0xa6, 0xa7, 0xa7, 0xa7, 0xa7,
0xa8, 0xa8, 0xa8, 0xa8, 0xa8, 0xa9, 0xa9, 0xa9,
0xa9, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xab, 0xab,
0xab, 0xab, 0xac, 0xac, 0xac, 0xac, 0xac, 0xad,
0xad, 0xad, 0xad, 0xad, 0xae, 0xae, 0xae, 0xae,
0xaf, 0xaf, 0xaf, 0xaf, 0xaf, 0xb0, 0xb0, 0xb0,
0xb0, 0xb0, 0xb1, 0xb1, 0xb1, 0xb1, 0xb1, 0xb2,
0xb2, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3, 0xb3, 0xb3,
0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb5, 0xb5, 0xb5,
0xb5, 0xb5, 0xb6, 0xb6, 0xb6, 0xb6, 0xb6, 0xb7,
0xb7, 0xb7, 0xb7, 0xb7, 0xb8, 0xb8, 0xb8, 0xb8,
0xb8, 0xb9, 0xb9, 0xb9, 0xb9, 0xb9, 0xba, 0xba,
0xba, 0xba, 0xba, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb,
0xbb, 0xbc, 0xbc, 0xbc, 0xbc, 0xbc, 0xbd, 0xbd,
0xbd, 0xbd, 0xbd, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe,
0xbf, 0xbf, 0xbf, 0xbf, 0xbf, 0xc0, 0xc0, 0xc0,
0xc0, 0xc0, 0xc0, 0xc1, 0xc1, 0xc1, 0xc1, 0xc1,
0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc3, 0xc3, 0xc3,
0xc3, 0xc3, 0xc3, 0xc4, 0xc4, 0xc4, 0xc4, 0xc4,
0xc5, 0xc5, 0xc5, 0xc5, 0xc5, 0xc5, 0xc6, 0xc6,
0xc6, 0xc6, 0xc6, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7,
0xc7, 0xc8, 0xc8, 0xc8, 0xc8, 0xc8, 0xc9, 0xc9,
0xc9, 0xc9, 0xc9, 0xc9, 0xca, 0xca, 0xca, 0xca,
0xca, 0xcb, 0xcb, 0xcb, 0xcb, 0xcb, 0xcb, 0xcc,
0xcc, 0xcc, 0xcc, 0xcc, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xce, 0xce, 0xce, 0xce, 0xce, 0xce,
0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0,
0xd0, 0xd0, 0xd0, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1,
0xd1, 0xd2, 0xd2, 0xd2, 0xd2, 0xd2, 0xd2, 0xd3,
0xd3, 0xd3, 0xd3, 0xd3, 0xd4, 0xd4, 0xd4, 0xd4,
0xd4, 0xd4, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5,
0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd7, 0xd7,
0xd7, 0xd7, 0xd7, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8,
0xd8, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xda,
0xda, 0xda, 0xda, 0xda, 0xda, 0xdb, 0xdb, 0xdb,
0xdb, 0xdb, 0xdb, 0xdc, 0xdc, 0xdc, 0xdc, 0xdc,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xde, 0xde,
0xde, 0xde, 0xde, 0xde, 0xdf, 0xdf, 0xdf, 0xdf,
0xdf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0,
0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe2, 0xe2,
0xe2, 0xe2, 0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe3,
0xe3, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe5,
0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6, 0xe6,
0xe6, 0xe6, 0xe6, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7,
0xe7, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe9, 0xe9,
0xe9, 0xe9, 0xe9, 0xe9, 0xea, 0xea, 0xea, 0xea,
0xea, 0xea, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb,
0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xed, 0xed,
0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee,
0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0,
0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1,
0xf1, 0xf1, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2,
0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf4, 0xf4, 0xf4,
0xf4, 0xf4, 0xf4, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5,
0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf7, 0xf7,
0xf7, 0xf7, 0xf7, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8,
0xf8, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xfa, 0xfa,
0xfa, 0xfa, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb, 0xfb,
0xfb, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfd, 0xfd,
0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe,
0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0x13, 0x15, 0x16, 0x18, 0x19, 0x1b, 0x1c, 0x1e,
0x1f, 0x20, 0x22, 0x23, 0x24, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31,
0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41,
0x42, 0x43, 0x44, 0x44, 0x45, 0x46, 0x47, 0x48,
0x49, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4d, 0x4e,
0x4f, 0x50, 0x50, 0x51, 0x52, 0x53, 0x53, 0x54,
0x55, 0x55, 0x56, 0x57, 0x57, 0x58, 0x59, 0x59,
0x5a, 0x5b, 0x5b, 0x5c, 0x5d, 0x5d, 0x5e, 0x5f,
0x5f, 0x60, 0x60, 0x61, 0x62, 0x62, 0x63, 0x63,
0x64, 0x65, 0x65, 0x66, 0x66, 0x67, 0x67, 0x68,
0x69, 0x69, 0x6a, 0x6a, 0x6b, 0x6b, 0x6c, 0x6c,
0x6d, 0x6d, 0x6e, 0x6e, 0x6f, 0x6f, 0x70, 0x70,
0x71, 0x71, 0x72, 0x72, 0x73, 0x73, 0x74, 0x74,
0x75, 0x75, 0x76, 0x76, 0x77, 0x77, 0x78, 0x78,
0x79, 0x79, 0x7a, 0x7a, 0x7a, 0x7b, 0x7b, 0x7c,
0x7c, 0x7d, 0x7d, 0x7e, 0x7e, 0x7e, 0x7f, 0x7f,
0x80, 0x80, 0x81, 0x81, 0x81, 0x82, 0x82, 0x83,
0x83, 0x84, 0x84, 0x84, 0x85, 0x85, 0x86, 0x86,
0x86, 0x87, 0x87, 0x88, 0x88, 0x88, 0x89, 0x89,
0x89, 0x8a, 0x8a, 0x8b, 0x8b, 0x8b, 0x8c, 0x8c,
0x8c, 0x8d, 0x8d, 0x8e, 0x8e, 0x8e, 0x8f, 0x8f,
0x8f, 0x90, 0x90, 0x90, 0x91, 0x91, 0x92, 0x92,
0x92, 0x93, 0x93, 0x93, 0x94, 0x94, 0x94, 0x95,
0x95, 0x95, 0x96, 0x96, 0x96, 0x97, 0x97, 0x97,
0x98, 0x98, 0x98, 0x99, 0x99, 0x99, 0x9a, 0x9a,
0x9a, 0x9b, 0x9b, 0x9b, 0x9c, 0x9c, 0x9c, 0x9d,
0x9d, 0x9d, 0x9e, 0x9e, 0x9e, 0x9e, 0x9f, 0x9f,
0x9f, 0xa0, 0xa0, 0xa0, 0xa1, 0xa1, 0xa1, 0xa2,
0xa2, 0xa2, 0xa2, 0xa3, 0xa3, 0xa3, 0xa4, 0xa4,
0xa4, 0xa5, 0xa5, 0xa5, 0xa5, 0xa6, 0xa6, 0xa6,
0xa7, 0xa7, 0xa7, 0xa7, 0xa8, 0xa8, 0xa8, 0xa9,
0xa9, 0xa9, 0xa9, 0xaa, 0xaa, 0xaa, 0xab, 0xab,
0xab, 0xab, 0xac, 0xac, 0xac, 0xac, 0xad, 0xad,
0xad, 0xae, 0xae, 0xae, 0xae, 0xaf, 0xaf, 0xaf,
0xaf, 0xb0, 0xb0, 0xb0, 0xb1, 0xb1, 0xb1, 0xb1,
0xb2, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3, 0xb3, 0xb3,
0xb4, 0xb4, 0xb4, 0xb4, 0xb5, 0xb5, 0xb5, 0xb5,
0xb6, 0xb6, 0xb6, 0xb6, 0xb7, 0xb7, 0xb7, 0xb7,
0xb8, 0xb8, 0xb8, 0xb8, 0xb9, 0xb9, 0xb9, 0xb9,
0xba, 0xba, 0xba, 0xba, 0xbb, 0xbb, 0xbb, 0xbb,
0xbc, 0xbc, 0xbc, 0xbc, 0xbd, 0xbd, 0xbd, 0xbd,
0xbe, 0xbe, 0xbe, 0xbe, 0xbf, 0xbf, 0xbf, 0xbf,
0xbf, 0xc0, 0xc0, 0xc0, 0xc0, 0xc1, 0xc1, 0xc1,
0xc1, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc3, 0xc3,
0xc3, 0xc3, 0xc4, 0xc4, 0xc4, 0xc4, 0xc5, 0xc5,
0xc5, 0xc5, 0xc5, 0xc6, 0xc6, 0xc6, 0xc6, 0xc7,
0xc7, 0xc7, 0xc7, 0xc7, 0xc8, 0xc8, 0xc8, 0xc8,
0xc9, 0xc9, 0xc9, 0xc9, 0xc9, 0xca, 0xca, 0xca,
0xca, 0xcb, 0xcb, 0xcb, 0xcb, 0xcb, 0xcc, 0xcc,
0xcc, 0xcc, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xce,
0xce, 0xce, 0xce, 0xce, 0xcf, 0xcf, 0xcf, 0xcf,
0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd1, 0xd1, 0xd1,
0xd1, 0xd1, 0xd2, 0xd2, 0xd2, 0xd2, 0xd2, 0xd3,
0xd3, 0xd3, 0xd3, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4,
0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd6, 0xd6, 0xd6,
0xd6, 0xd6, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd8,
0xd8, 0xd8, 0xd8, 0xd8, 0xd9, 0xd9, 0xd9, 0xd9,
0xd9, 0xda, 0xda, 0xda, 0xda, 0xda, 0xdb, 0xdb,
0xdb, 0xdb, 0xdb, 0xdc, 0xdc, 0xdc, 0xdc, 0xdc,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde,
0xde, 0xde, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xe0,
0xe0, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe1,
0xe1, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe3, 0xe3,
0xe3, 0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4,
0xe4, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6,
0xe6, 0xe6, 0xe6, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7,
0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe9, 0xe9, 0xe9,
0xe9, 0xe9, 0xe9, 0xea, 0xea, 0xea, 0xea, 0xea,
0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec,
0xec, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed,
0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef,
0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0,
0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf2, 0xf2, 0xf2,
0xf2, 0xf2, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3,
0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf5, 0xf5, 0xf5,
0xf5, 0xf5, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6,
0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf8, 0xf8, 0xf8,
0xf8, 0xf8, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9,
0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb,
0xfb, 0xfb, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc,
0xfd, 0xfd, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe,
0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
},
};
reg_w(gspca_dev, TP6800_R21_ENDP_1_CTL, 0x00);
if (sd->bridge == BRIDGE_TP6810)
reg_w(gspca_dev, 0x02, 0x28);
/* msleep(50); */
bulk_w(gspca_dev, 0x00, gamma_tb[gamma][0], 1024);
bulk_w(gspca_dev, 0x01, gamma_tb[gamma][1], 1024);
bulk_w(gspca_dev, 0x02, gamma_tb[gamma][2], 1024);
if (sd->bridge == BRIDGE_TP6810) {
int i;
reg_w(gspca_dev, 0x02, 0x2b);
reg_w(gspca_dev, 0x02, 0x28);
for (i = 0; i < 6; i++)
reg_w(gspca_dev, TP6800_R55_GAMMA_R,
gamma_tb[gamma][0][i]);
reg_w(gspca_dev, 0x02, 0x2b);
reg_w(gspca_dev, 0x02, 0x28);
for (i = 0; i < 6; i++)
reg_w(gspca_dev, TP6800_R56_GAMMA_G,
gamma_tb[gamma][1][i]);
reg_w(gspca_dev, 0x02, 0x2b);
reg_w(gspca_dev, 0x02, 0x28);
for (i = 0; i < 6; i++)
reg_w(gspca_dev, TP6800_R57_GAMMA_B,
gamma_tb[gamma][2][i]);
reg_w(gspca_dev, 0x02, 0x28);
}
reg_w(gspca_dev, TP6800_R21_ENDP_1_CTL, 0x03);
/* msleep(50); */
}
static void setsharpness(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
if (sd->bridge == BRIDGE_TP6800) {
val |= 0x08; /* grid compensation enable */
if (gspca_dev->pixfmt.width == 640)
reg_w(gspca_dev, TP6800_R78_FORMAT, 0x00); /* vga */
else
val |= 0x04; /* scaling down enable */
reg_w(gspca_dev, TP6800_R5D_DEMOSAIC_CFG, val);
} else {
val = (val << 5) | 0x08;
reg_w(gspca_dev, 0x59, val);
}
}
static void setautogain(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->ag_cnt = val ? AG_CNT_START : -1;
}
/* set the resolution for sensor cx0342 */
static void set_resolution(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
reg_w(gspca_dev, TP6800_R21_ENDP_1_CTL, 0x00);
if (gspca_dev->pixfmt.width == 320) {
reg_w(gspca_dev, TP6800_R3F_FRAME_RATE, 0x06);
msleep(100);
i2c_w(gspca_dev, CX0342_AUTO_ADC_CALIB, 0x01);
msleep(100);
reg_w(gspca_dev, TP6800_R21_ENDP_1_CTL, 0x03);
reg_w(gspca_dev, TP6800_R78_FORMAT, 0x01); /* qvga */
reg_w(gspca_dev, TP6800_R5D_DEMOSAIC_CFG, 0x0d);
i2c_w(gspca_dev, CX0342_EXPO_LINE_L, 0x37);
i2c_w(gspca_dev, CX0342_EXPO_LINE_H, 0x01);
} else {
reg_w(gspca_dev, TP6800_R3F_FRAME_RATE, 0x05);
msleep(100);
i2c_w(gspca_dev, CX0342_AUTO_ADC_CALIB, 0x01);
msleep(100);
reg_w(gspca_dev, TP6800_R21_ENDP_1_CTL, 0x03);
reg_w(gspca_dev, TP6800_R78_FORMAT, 0x00); /* vga */
reg_w(gspca_dev, TP6800_R5D_DEMOSAIC_CFG, 0x09);
i2c_w(gspca_dev, CX0342_EXPO_LINE_L, 0xcf);
i2c_w(gspca_dev, CX0342_EXPO_LINE_H, 0x00);
}
i2c_w(gspca_dev, CX0342_SYS_CTRL_0, 0x01);
bulk_w(gspca_dev, 0x03, color_gain[SENSOR_CX0342],
ARRAY_SIZE(color_gain[0]));
setgamma(gspca_dev, v4l2_ctrl_g_ctrl(sd->gamma));
if (sd->sensor == SENSOR_SOI763A)
setquality(gspca_dev, v4l2_ctrl_g_ctrl(sd->jpegqual));
}
/* convert the frame rate to a tp68x0 value */
static int get_fr_idx(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int i;
if (sd->bridge == BRIDGE_TP6800) {
for (i = 0; i < ARRAY_SIZE(rates) - 1; i++) {
if (sd->framerate >= rates[i])
break;
}
i = 6 - i; /* 1 = 5fps .. 6 = 30fps */
/* 640x480 * 30 fps does not work */
if (i == 6 /* if 30 fps */
&& gspca_dev->pixfmt.width == 640)
i = 0x05; /* 15 fps */
} else {
for (i = 0; i < ARRAY_SIZE(rates_6810) - 1; i++) {
if (sd->framerate >= rates_6810[i])
break;
}
i = 7 - i; /* 3 = 5fps .. 7 = 30fps */
/* 640x480 * 30 fps does not work */
if (i == 7 /* if 30 fps */
&& gspca_dev->pixfmt.width == 640)
i = 6; /* 15 fps */
i |= 0x80; /* clock * 1 */
}
return i;
}
static void setframerate(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 fr_idx;
fr_idx = get_fr_idx(gspca_dev);
if (sd->bridge == BRIDGE_TP6810) {
reg_r(gspca_dev, 0x7b);
reg_w(gspca_dev, 0x7b,
sd->sensor == SENSOR_CX0342 ? 0x10 : 0x90);
if (val >= 128)
fr_idx = 0xf0; /* lower frame rate */
}
reg_w(gspca_dev, TP6800_R3F_FRAME_RATE, fr_idx);
if (sd->sensor == SENSOR_CX0342)
i2c_w(gspca_dev, CX0342_AUTO_ADC_CALIB, 0x01);
}
static void setrgain(struct gspca_dev *gspca_dev, s32 rgain)
{
i2c_w(gspca_dev, CX0342_RAW_RGAIN_H, rgain >> 8);
i2c_w(gspca_dev, CX0342_RAW_RGAIN_L, rgain);
i2c_w(gspca_dev, CX0342_SYS_CTRL_0, 0x80);
}
static int sd_setgain(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 val = gspca_dev->gain->val;
if (sd->sensor == SENSOR_CX0342) {
s32 old = gspca_dev->gain->cur.val ?
gspca_dev->gain->cur.val : 1;
sd->blue->val = sd->blue->val * val / old;
if (sd->blue->val > 4095)
sd->blue->val = 4095;
sd->red->val = sd->red->val * val / old;
if (sd->red->val > 4095)
sd->red->val = 4095;
}
if (gspca_dev->streaming) {
if (sd->sensor == SENSOR_CX0342)
setexposure(gspca_dev, gspca_dev->exposure->val,
gspca_dev->gain->val,
sd->blue->val, sd->red->val);
else
setexposure(gspca_dev, gspca_dev->exposure->val,
gspca_dev->gain->val, 0, 0);
}
return gspca_dev->usb_err;
}
static void setbgain(struct gspca_dev *gspca_dev, s32 bgain)
{
i2c_w(gspca_dev, CX0342_RAW_BGAIN_H, bgain >> 8);
i2c_w(gspca_dev, CX0342_RAW_BGAIN_L, bgain);
i2c_w(gspca_dev, CX0342_SYS_CTRL_0, 0x80);
}
/* this function is called at probe time */
static int sd_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->bridge = id->driver_info;
gspca_dev->cam.cam_mode = vga_mode;
gspca_dev->cam.nmodes = ARRAY_SIZE(vga_mode);
gspca_dev->cam.mode_framerates = sd->bridge == BRIDGE_TP6800 ?
framerates : framerates_6810;
sd->framerate = DEFAULT_FRAME_RATE;
return 0;
}
/* this function is called at probe and resume time */
static int sd_init(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
static const struct cmd tp6800_preinit[] = {
{TP6800_R10_SIF_TYPE, 0x01}, /* sif */
{TP6800_R11_SIF_CONTROL, 0x01},
{TP6800_R15_GPIO_PU, 0x9f},
{TP6800_R16_GPIO_PD, 0x9f},
{TP6800_R17_GPIO_IO, 0x80},
{TP6800_R18_GPIO_DATA, 0x40}, /* LED off */
};
static const struct cmd tp6810_preinit[] = {
{TP6800_R2F_TIMING_CFG, 0x2f},
{TP6800_R15_GPIO_PU, 0x6f},
{TP6800_R16_GPIO_PD, 0x40},
{TP6800_R17_GPIO_IO, 0x9f},
{TP6800_R18_GPIO_DATA, 0xc1}, /* LED off */
};
if (sd->bridge == BRIDGE_TP6800)
reg_w_buf(gspca_dev, tp6800_preinit,
ARRAY_SIZE(tp6800_preinit));
else
reg_w_buf(gspca_dev, tp6810_preinit,
ARRAY_SIZE(tp6810_preinit));
msleep(15);
reg_r(gspca_dev, TP6800_R18_GPIO_DATA);
gspca_dbg(gspca_dev, D_PROBE, "gpio: %02x\n", gspca_dev->usb_buf[0]);
/* values:
* 0x80: snapshot button
* 0x40: LED
* 0x20: (bridge / sensor) reset for tp6810 ?
* 0x07: sensor type ?
*/
/* guess the sensor type */
if (force_sensor >= 0) {
sd->sensor = force_sensor;
} else {
if (sd->bridge == BRIDGE_TP6800) {
/*fixme: not sure this is working*/
switch (gspca_dev->usb_buf[0] & 0x07) {
case 0:
sd->sensor = SENSOR_SOI763A;
break;
case 1:
sd->sensor = SENSOR_CX0342;
break;
}
} else {
int sensor;
sensor = probe_6810(gspca_dev);
if (sensor < 0) {
pr_warn("Unknown sensor %d - forced to soi763a\n",
-sensor);
sensor = SENSOR_SOI763A;
}
sd->sensor = sensor;
}
}
if (sd->sensor == SENSOR_SOI763A) {
pr_info("Sensor soi763a\n");
if (sd->bridge == BRIDGE_TP6810) {
soi763a_6810_init(gspca_dev);
}
} else {
pr_info("Sensor cx0342\n");
if (sd->bridge == BRIDGE_TP6810) {
cx0342_6810_init(gspca_dev);
}
}
set_dqt(gspca_dev, 0);
return 0;
}
/* This function is called before choosing the alt setting */
static int sd_isoc_init(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
static const struct cmd cx_sensor_init[] = {
{CX0342_AUTO_ADC_CALIB, 0x81},
{CX0342_EXPO_LINE_L, 0x37},
{CX0342_EXPO_LINE_H, 0x01},
{CX0342_RAW_GRGAIN_L, 0x00},
{CX0342_RAW_GBGAIN_L, 0x00},
{CX0342_RAW_RGAIN_L, 0x00},
{CX0342_RAW_BGAIN_L, 0x00},
{CX0342_SYS_CTRL_0, 0x81},
};
static const struct cmd cx_bridge_init[] = {
{0x4d, 0x00},
{0x4c, 0xff},
{0x4e, 0xff},
{0x4f, 0x00},
};
static const struct cmd ov_sensor_init[] = {
{0x10, 0x75}, /* exposure */
{0x76, 0x03},
{0x00, 0x00}, /* gain */
};
static const struct cmd ov_bridge_init[] = {
{0x7b, 0x90},
{TP6800_R3F_FRAME_RATE, 0x87},
};
if (sd->bridge == BRIDGE_TP6800)
return 0;
if (sd->sensor == SENSOR_CX0342) {
reg_w(gspca_dev, TP6800_R12_SIF_ADDR_S, 0x20);
reg_w(gspca_dev, TP6800_R3F_FRAME_RATE, 0x87);
i2c_w_buf(gspca_dev, cx_sensor_init,
ARRAY_SIZE(cx_sensor_init));
reg_w_buf(gspca_dev, cx_bridge_init,
ARRAY_SIZE(cx_bridge_init));
bulk_w(gspca_dev, 0x03, color_null, sizeof color_null);
reg_w(gspca_dev, 0x59, 0x40);
} else {
reg_w(gspca_dev, TP6800_R12_SIF_ADDR_S, 0x21);
i2c_w_buf(gspca_dev, ov_sensor_init,
ARRAY_SIZE(ov_sensor_init));
reg_r(gspca_dev, 0x7b);
reg_w_buf(gspca_dev, ov_bridge_init,
ARRAY_SIZE(ov_bridge_init));
}
reg_w(gspca_dev, TP6800_R78_FORMAT,
gspca_dev->curr_mode ? 0x00 : 0x01);
return gspca_dev->usb_err;
}
static void set_led(struct gspca_dev *gspca_dev, int on)
{
u8 data;
reg_r(gspca_dev, TP6800_R18_GPIO_DATA);
data = gspca_dev->usb_buf[0];
if (on)
data &= ~0x40;
else
data |= 0x40;
reg_w(gspca_dev, TP6800_R18_GPIO_DATA, data);
}
static void cx0342_6800_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
static const struct cmd reg_init[] = {
/* fixme: is this useful? */
{TP6800_R17_GPIO_IO, 0x9f},
{TP6800_R16_GPIO_PD, 0x40},
{TP6800_R10_SIF_TYPE, 0x00}, /* i2c 8 bits */
{TP6800_R50, 0x00},
{TP6800_R51, 0x00},
{TP6800_R52, 0xff},
{TP6800_R53, 0x03},
{TP6800_R54_DARK_CFG, 0x07},
{TP6800_R5C_EDGE_THRLD, 0x40},
{TP6800_R7A_BLK_THRLD, 0x40},
{TP6800_R2F_TIMING_CFG, 0x17},
{TP6800_R30_SENSOR_CFG, 0x18}, /* G1B..RG0 */
{TP6800_R37_FRONT_DARK_ST, 0x00},
{TP6800_R38_FRONT_DARK_END, 0x00},
{TP6800_R39_REAR_DARK_ST_L, 0x00},
{TP6800_R3A_REAR_DARK_ST_H, 0x00},
{TP6800_R3B_REAR_DARK_END_L, 0x00},
{TP6800_R3C_REAR_DARK_END_H, 0x00},
{TP6800_R3D_HORIZ_DARK_LINE_L, 0x00},
{TP6800_R3E_HORIZ_DARK_LINE_H, 0x00},
{TP6800_R21_ENDP_1_CTL, 0x03},
{TP6800_R31_PIXEL_START, 0x0b},
{TP6800_R32_PIXEL_END_L, 0x8a},
{TP6800_R33_PIXEL_END_H, 0x02},
{TP6800_R34_LINE_START, 0x0e},
{TP6800_R35_LINE_END_L, 0xf4},
{TP6800_R36_LINE_END_H, 0x01},
{TP6800_R78_FORMAT, 0x00},
{TP6800_R12_SIF_ADDR_S, 0x20}, /* cx0342 i2c addr */
};
static const struct cmd sensor_init[] = {
{CX0342_OUTPUT_CTRL, 0x07},
{CX0342_BYPASS_MODE, 0x58},
{CX0342_GPXLTHD_L, 0x16},
{CX0342_RBPXLTHD_L, 0x16},
{CX0342_PLANETHD_L, 0xc0},
{CX0342_PLANETHD_H, 0x03},
{CX0342_RB_GAP_L, 0xff},
{CX0342_RB_GAP_H, 0x07},
{CX0342_G_GAP_L, 0xff},
{CX0342_G_GAP_H, 0x07},
{CX0342_RST_OVERFLOW_L, 0x5c},
{CX0342_RST_OVERFLOW_H, 0x01},
{CX0342_DATA_OVERFLOW_L, 0xfc},
{CX0342_DATA_OVERFLOW_H, 0x03},
{CX0342_DATA_UNDERFLOW_L, 0x00},
{CX0342_DATA_UNDERFLOW_H, 0x00},
{CX0342_SYS_CTRL_0, 0x40},
{CX0342_GLOBAL_GAIN, 0x01},
{CX0342_CLOCK_GEN, 0x00},
{CX0342_SYS_CTRL_0, 0x02},
{CX0342_IDLE_CTRL, 0x05},
{CX0342_ADCGN, 0x00},
{CX0342_ADC_CTL, 0x00},
{CX0342_LVRST_BLBIAS, 0x01},
{CX0342_VTHSEL, 0x0b},
{CX0342_RAMP_RIV, 0x0b},
{CX0342_LDOSEL, 0x07},
{CX0342_SPV_VALUE_L, 0x40},
{CX0342_SPV_VALUE_H, 0x02},
};
reg_w_buf(gspca_dev, reg_init, ARRAY_SIZE(reg_init));
i2c_w_buf(gspca_dev, sensor_init, ARRAY_SIZE(sensor_init));
i2c_w_buf(gspca_dev, cx0342_timing_seq, ARRAY_SIZE(cx0342_timing_seq));
reg_w(gspca_dev, TP6800_R5C_EDGE_THRLD, 0x10);
reg_w(gspca_dev, TP6800_R54_DARK_CFG, 0x00);
i2c_w(gspca_dev, CX0342_EXPO_LINE_H, 0x00);
i2c_w(gspca_dev, CX0342_SYS_CTRL_0, 0x01);
if (sd->sensor == SENSOR_CX0342)
setexposure(gspca_dev, v4l2_ctrl_g_ctrl(gspca_dev->exposure),
v4l2_ctrl_g_ctrl(gspca_dev->gain),
v4l2_ctrl_g_ctrl(sd->blue),
v4l2_ctrl_g_ctrl(sd->red));
else
setexposure(gspca_dev, v4l2_ctrl_g_ctrl(gspca_dev->exposure),
v4l2_ctrl_g_ctrl(gspca_dev->gain), 0, 0);
set_led(gspca_dev, 1);
set_resolution(gspca_dev);
}
static void cx0342_6810_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
static const struct cmd sensor_init_2[] = {
{CX0342_EXPO_LINE_L, 0x6f},
{CX0342_EXPO_LINE_H, 0x02},
{CX0342_RAW_GRGAIN_L, 0x00},
{CX0342_RAW_GBGAIN_L, 0x00},
{CX0342_RAW_RGAIN_L, 0x00},
{CX0342_RAW_BGAIN_L, 0x00},
{CX0342_SYS_CTRL_0, 0x81},
};
static const struct cmd bridge_init_2[] = {
{0x4d, 0x00},
{0x4c, 0xff},
{0x4e, 0xff},
{0x4f, 0x00},
{TP6800_R7A_BLK_THRLD, 0x00},
{TP6800_R79_QUALITY, 0x04},
{TP6800_R79_QUALITY, 0x01},
};
static const struct cmd bridge_init_3[] = {
{TP6800_R31_PIXEL_START, 0x08},
{TP6800_R32_PIXEL_END_L, 0x87},
{TP6800_R33_PIXEL_END_H, 0x02},
{TP6800_R34_LINE_START, 0x0e},
{TP6800_R35_LINE_END_L, 0xf4},
{TP6800_R36_LINE_END_H, 0x01},
};
static const struct cmd sensor_init_3[] = {
{CX0342_AUTO_ADC_CALIB, 0x81},
{CX0342_EXPO_LINE_L, 0x6f},
{CX0342_EXPO_LINE_H, 0x02},
{CX0342_RAW_GRGAIN_L, 0x00},
{CX0342_RAW_GBGAIN_L, 0x00},
{CX0342_RAW_RGAIN_L, 0x00},
{CX0342_RAW_BGAIN_L, 0x00},
{CX0342_SYS_CTRL_0, 0x81},
};
static const struct cmd bridge_init_5[] = {
{0x4d, 0x00},
{0x4c, 0xff},
{0x4e, 0xff},
{0x4f, 0x00},
};
static const struct cmd sensor_init_4[] = {
{CX0342_EXPO_LINE_L, 0xd3},
{CX0342_EXPO_LINE_H, 0x01},
/*fixme: gains, but 00..80 only*/
{CX0342_RAW_GRGAIN_L, 0x40},
{CX0342_RAW_GBGAIN_L, 0x40},
{CX0342_RAW_RGAIN_L, 0x40},
{CX0342_RAW_BGAIN_L, 0x40},
{CX0342_SYS_CTRL_0, 0x81},
};
static const struct cmd sensor_init_5[] = {
{CX0342_IDLE_CTRL, 0x05},
{CX0342_ADCGN, 0x00},
{CX0342_ADC_CTL, 0x00},
{CX0342_LVRST_BLBIAS, 0x01},
{CX0342_VTHSEL, 0x0b},
{CX0342_RAMP_RIV, 0x0b},
{CX0342_LDOSEL, 0x07},
{CX0342_SPV_VALUE_L, 0x40},
{CX0342_SPV_VALUE_H, 0x02},
{CX0342_AUTO_ADC_CALIB, 0x81},
};
reg_w(gspca_dev, 0x22, gspca_dev->alt);
i2c_w_buf(gspca_dev, sensor_init_2, ARRAY_SIZE(sensor_init_2));
reg_w_buf(gspca_dev, bridge_init_2, ARRAY_SIZE(bridge_init_2));
reg_w_buf(gspca_dev, tp6810_cx_init_common,
ARRAY_SIZE(tp6810_cx_init_common));
reg_w_buf(gspca_dev, bridge_init_3, ARRAY_SIZE(bridge_init_3));
if (gspca_dev->curr_mode) {
reg_w(gspca_dev, 0x4a, 0x7f);
reg_w(gspca_dev, 0x07, 0x05);
reg_w(gspca_dev, TP6800_R78_FORMAT, 0x00); /* vga */
} else {
reg_w(gspca_dev, 0x4a, 0xff);
reg_w(gspca_dev, 0x07, 0x85);
reg_w(gspca_dev, TP6800_R78_FORMAT, 0x01); /* qvga */
}
setgamma(gspca_dev, v4l2_ctrl_g_ctrl(sd->gamma));
reg_w_buf(gspca_dev, tp6810_bridge_start,
ARRAY_SIZE(tp6810_bridge_start));
setsharpness(gspca_dev, v4l2_ctrl_g_ctrl(sd->sharpness));
bulk_w(gspca_dev, 0x03, color_gain[SENSOR_CX0342],
ARRAY_SIZE(color_gain[0]));
reg_w(gspca_dev, TP6800_R3F_FRAME_RATE, 0x87);
i2c_w_buf(gspca_dev, sensor_init_3, ARRAY_SIZE(sensor_init_3));
reg_w_buf(gspca_dev, bridge_init_5, ARRAY_SIZE(bridge_init_5));
i2c_w_buf(gspca_dev, sensor_init_4, ARRAY_SIZE(sensor_init_4));
reg_w_buf(gspca_dev, bridge_init_5, ARRAY_SIZE(bridge_init_5));
i2c_w_buf(gspca_dev, sensor_init_5, ARRAY_SIZE(sensor_init_5));
set_led(gspca_dev, 1);
/* setquality(gspca_dev, v4l2_ctrl_g_ctrl(sd->jpegqual)); */
}
static void soi763a_6800_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
static const struct cmd reg_init[] = {
{TP6800_R79_QUALITY, 0x04},
{TP6800_R79_QUALITY, 0x01},
{TP6800_R10_SIF_TYPE, 0x00}, /* i2c 8 bits */
{TP6800_R50, 0x00},
{TP6800_R51, 0x00},
{TP6800_R52, 0xff},
{TP6800_R53, 0x03},
{TP6800_R54_DARK_CFG, 0x07},
{TP6800_R5C_EDGE_THRLD, 0x40},
{TP6800_R79_QUALITY, 0x03},
{TP6800_R7A_BLK_THRLD, 0x40},
{TP6800_R2F_TIMING_CFG, 0x46},
{TP6800_R30_SENSOR_CFG, 0x10}, /* BG1..G0R */
{TP6800_R37_FRONT_DARK_ST, 0x00},
{TP6800_R38_FRONT_DARK_END, 0x00},
{TP6800_R39_REAR_DARK_ST_L, 0x00},
{TP6800_R3A_REAR_DARK_ST_H, 0x00},
{TP6800_R3B_REAR_DARK_END_L, 0x00},
{TP6800_R3C_REAR_DARK_END_H, 0x00},
{TP6800_R3D_HORIZ_DARK_LINE_L, 0x00},
{TP6800_R3E_HORIZ_DARK_LINE_H, 0x00},
{TP6800_R21_ENDP_1_CTL, 0x03},
{TP6800_R3F_FRAME_RATE, 0x04}, /* 15 fps */
{TP6800_R5D_DEMOSAIC_CFG, 0x0e}, /* scale down - medium edge */
{TP6800_R31_PIXEL_START, 0x1b},
{TP6800_R32_PIXEL_END_L, 0x9a},
{TP6800_R33_PIXEL_END_H, 0x02},
{TP6800_R34_LINE_START, 0x0f},
{TP6800_R35_LINE_END_L, 0xf4},
{TP6800_R36_LINE_END_H, 0x01},
{TP6800_R78_FORMAT, 0x01}, /* qvga */
{TP6800_R12_SIF_ADDR_S, 0x21}, /* soi763a i2c addr */
{TP6800_R1A_SIF_TX_DATA2, 0x00},
};
static const struct cmd sensor_init[] = {
{0x12, 0x48}, /* mirror - RGB */
{0x13, 0xa0}, /* clock - no AGC nor AEC */
{0x03, 0xa4}, /* saturation */
{0x04, 0x30}, /* hue */
{0x05, 0x88}, /* contrast */
{0x06, 0x60}, /* brightness */
{0x10, 0x41}, /* AEC */
{0x11, 0x40}, /* clock rate */
{0x13, 0xa0},
{0x14, 0x00}, /* 640x480 */
{0x15, 0x14},
{0x1f, 0x41},
{0x20, 0x80},
{0x23, 0xee},
{0x24, 0x50},
{0x25, 0x7a},
{0x26, 0x00},
{0x27, 0xe2},
{0x28, 0xb0},
{0x2a, 0x00},
{0x2b, 0x00},
{0x2d, 0x81},
{0x2f, 0x9d},
{0x60, 0x80},
{0x61, 0x00},
{0x62, 0x88},
{0x63, 0x11},
{0x64, 0x89},
{0x65, 0x00},
{0x67, 0x94},
{0x68, 0x7a},
{0x69, 0x0f},
{0x6c, 0x80},
{0x6d, 0x80},
{0x6e, 0x80},
{0x6f, 0xff},
{0x71, 0x20},
{0x74, 0x20},
{0x75, 0x86},
{0x77, 0xb5},
{0x17, 0x18}, /* H href start */
{0x18, 0xbf}, /* H href end */
{0x19, 0x03}, /* V start */
{0x1a, 0xf8}, /* V end */
{0x01, 0x80}, /* blue gain */
{0x02, 0x80}, /* red gain */
};
reg_w_buf(gspca_dev, reg_init, ARRAY_SIZE(reg_init));
i2c_w(gspca_dev, 0x12, 0x80); /* sensor reset */
msleep(10);
i2c_w_buf(gspca_dev, sensor_init, ARRAY_SIZE(sensor_init));
reg_w(gspca_dev, TP6800_R5C_EDGE_THRLD, 0x10);
reg_w(gspca_dev, TP6800_R54_DARK_CFG, 0x00);
setsharpness(gspca_dev, v4l2_ctrl_g_ctrl(sd->sharpness));
bulk_w(gspca_dev, 0x03, color_gain[SENSOR_SOI763A],
ARRAY_SIZE(color_gain[0]));
set_led(gspca_dev, 1);
if (sd->sensor == SENSOR_CX0342)
setexposure(gspca_dev, v4l2_ctrl_g_ctrl(gspca_dev->exposure),
v4l2_ctrl_g_ctrl(gspca_dev->gain),
v4l2_ctrl_g_ctrl(sd->blue),
v4l2_ctrl_g_ctrl(sd->red));
else
setexposure(gspca_dev, v4l2_ctrl_g_ctrl(gspca_dev->exposure),
v4l2_ctrl_g_ctrl(gspca_dev->gain), 0, 0);
if (sd->sensor == SENSOR_SOI763A)
setquality(gspca_dev, v4l2_ctrl_g_ctrl(sd->jpegqual));
setgamma(gspca_dev, v4l2_ctrl_g_ctrl(sd->gamma));
}
static void soi763a_6810_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
static const struct cmd bridge_init_2[] = {
{TP6800_R7A_BLK_THRLD, 0x00},
{TP6800_R79_QUALITY, 0x04},
{TP6800_R79_QUALITY, 0x01},
};
static const struct cmd bridge_init_3[] = {
{TP6800_R31_PIXEL_START, 0x20},
{TP6800_R32_PIXEL_END_L, 0x9f},
{TP6800_R33_PIXEL_END_H, 0x02},
{TP6800_R34_LINE_START, 0x13},
{TP6800_R35_LINE_END_L, 0xf8},
{TP6800_R36_LINE_END_H, 0x01},
};
static const struct cmd bridge_init_6[] = {
{0x08, 0xff},
{0x09, 0xff},
{0x0a, 0x5f},
{0x0b, 0x80},
};
reg_w(gspca_dev, 0x22, gspca_dev->alt);
bulk_w(gspca_dev, 0x03, color_null, sizeof color_null);
reg_w(gspca_dev, 0x59, 0x40);
if (sd->sensor == SENSOR_CX0342)
setexposure(gspca_dev, v4l2_ctrl_g_ctrl(gspca_dev->exposure),
v4l2_ctrl_g_ctrl(gspca_dev->gain),
v4l2_ctrl_g_ctrl(sd->blue),
v4l2_ctrl_g_ctrl(sd->red));
else
setexposure(gspca_dev, v4l2_ctrl_g_ctrl(gspca_dev->exposure),
v4l2_ctrl_g_ctrl(gspca_dev->gain), 0, 0);
reg_w_buf(gspca_dev, bridge_init_2, ARRAY_SIZE(bridge_init_2));
reg_w_buf(gspca_dev, tp6810_ov_init_common,
ARRAY_SIZE(tp6810_ov_init_common));
reg_w_buf(gspca_dev, bridge_init_3, ARRAY_SIZE(bridge_init_3));
if (gspca_dev->curr_mode) {
reg_w(gspca_dev, 0x4a, 0x7f);
reg_w(gspca_dev, 0x07, 0x05);
reg_w(gspca_dev, TP6800_R78_FORMAT, 0x00); /* vga */
} else {
reg_w(gspca_dev, 0x4a, 0xff);
reg_w(gspca_dev, 0x07, 0x85);
reg_w(gspca_dev, TP6800_R78_FORMAT, 0x01); /* qvga */
}
setgamma(gspca_dev, v4l2_ctrl_g_ctrl(sd->gamma));
reg_w_buf(gspca_dev, tp6810_bridge_start,
ARRAY_SIZE(tp6810_bridge_start));
if (gspca_dev->curr_mode) {
reg_w(gspca_dev, 0x4f, 0x00);
reg_w(gspca_dev, 0x4e, 0x7c);
}
reg_w(gspca_dev, 0x00, 0x00);
setsharpness(gspca_dev, v4l2_ctrl_g_ctrl(sd->sharpness));
bulk_w(gspca_dev, 0x03, color_gain[SENSOR_SOI763A],
ARRAY_SIZE(color_gain[0]));
set_led(gspca_dev, 1);
reg_w(gspca_dev, TP6800_R3F_FRAME_RATE, 0xf0);
if (sd->sensor == SENSOR_CX0342)
setexposure(gspca_dev, v4l2_ctrl_g_ctrl(gspca_dev->exposure),
v4l2_ctrl_g_ctrl(gspca_dev->gain),
v4l2_ctrl_g_ctrl(sd->blue),
v4l2_ctrl_g_ctrl(sd->red));
else
setexposure(gspca_dev, v4l2_ctrl_g_ctrl(gspca_dev->exposure),
v4l2_ctrl_g_ctrl(gspca_dev->gain), 0, 0);
reg_w_buf(gspca_dev, bridge_init_6, ARRAY_SIZE(bridge_init_6));
}
/* -- start the camera -- */
static int sd_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
jpeg_define(sd->jpeg_hdr, gspca_dev->pixfmt.height,
gspca_dev->pixfmt.width);
set_dqt(gspca_dev, sd->quality);
if (sd->bridge == BRIDGE_TP6800) {
if (sd->sensor == SENSOR_CX0342)
cx0342_6800_start(gspca_dev);
else
soi763a_6800_start(gspca_dev);
} else {
if (sd->sensor == SENSOR_CX0342)
cx0342_6810_start(gspca_dev);
else
soi763a_6810_start(gspca_dev);
reg_w_buf(gspca_dev, tp6810_late_start,
ARRAY_SIZE(tp6810_late_start));
reg_w(gspca_dev, 0x80, 0x03);
reg_w(gspca_dev, 0x82, gspca_dev->curr_mode ? 0x0a : 0x0e);
if (sd->sensor == SENSOR_CX0342)
setexposure(gspca_dev,
v4l2_ctrl_g_ctrl(gspca_dev->exposure),
v4l2_ctrl_g_ctrl(gspca_dev->gain),
v4l2_ctrl_g_ctrl(sd->blue),
v4l2_ctrl_g_ctrl(sd->red));
else
setexposure(gspca_dev,
v4l2_ctrl_g_ctrl(gspca_dev->exposure),
v4l2_ctrl_g_ctrl(gspca_dev->gain), 0, 0);
if (sd->sensor == SENSOR_SOI763A)
setquality(gspca_dev,
v4l2_ctrl_g_ctrl(sd->jpegqual));
if (sd->bridge == BRIDGE_TP6810)
setautogain(gspca_dev,
v4l2_ctrl_g_ctrl(gspca_dev->autogain));
}
setframerate(gspca_dev, v4l2_ctrl_g_ctrl(gspca_dev->exposure));
return gspca_dev->usb_err;
}
static void sd_stopN(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
if (sd->bridge == BRIDGE_TP6800)
reg_w(gspca_dev, TP6800_R2F_TIMING_CFG, 0x03);
set_led(gspca_dev, 0);
reg_w(gspca_dev, TP6800_R21_ENDP_1_CTL, 0x00);
}
static void sd_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data,
int len)
{
struct sd *sd = (struct sd *) gspca_dev;
/* the start of frame contains:
* ff d8
* ff fe
* width / 16
* height / 8
* quality
*/
if (sd->bridge == BRIDGE_TP6810) {
if (*data != 0x5a) {
/*fixme: don't discard the whole frame..*/
if (*data == 0xaa || *data == 0x00)
return;
if (*data > 0xc0) {
gspca_dbg(gspca_dev, D_FRAM, "bad frame\n");
gspca_dev->last_packet_type = DISCARD_PACKET;
return;
}
}
data++;
len--;
if (len < 2) {
gspca_dev->last_packet_type = DISCARD_PACKET;
return;
}
if (*data == 0xff && data[1] == 0xd8) {
/*fixme: there may be information in the 4 high bits*/
if (len < 7) {
gspca_dev->last_packet_type = DISCARD_PACKET;
return;
}
if ((data[6] & 0x0f) != sd->quality)
set_dqt(gspca_dev, data[6] & 0x0f);
gspca_frame_add(gspca_dev, FIRST_PACKET,
sd->jpeg_hdr, JPEG_HDR_SZ);
gspca_frame_add(gspca_dev, INTER_PACKET,
data + 7, len - 7);
} else if (data[len - 2] == 0xff && data[len - 1] == 0xd9) {
gspca_frame_add(gspca_dev, LAST_PACKET,
data, len);
} else {
gspca_frame_add(gspca_dev, INTER_PACKET,
data, len);
}
return;
}
switch (*data) {
case 0x55:
gspca_frame_add(gspca_dev, LAST_PACKET, data, 0);
if (len < 8
|| data[1] != 0xff || data[2] != 0xd8
|| data[3] != 0xff || data[4] != 0xfe) {
/* Have only seen this with corrupt frames */
gspca_dev->last_packet_type = DISCARD_PACKET;
return;
}
if (data[7] != sd->quality)
set_dqt(gspca_dev, data[7]);
gspca_frame_add(gspca_dev, FIRST_PACKET,
sd->jpeg_hdr, JPEG_HDR_SZ);
gspca_frame_add(gspca_dev, INTER_PACKET,
data + 8, len - 8);
break;
case 0xaa:
gspca_dev->last_packet_type = DISCARD_PACKET;
break;
case 0xcc:
if (len >= 3 && (data[1] != 0xff || data[2] != 0xd8))
gspca_frame_add(gspca_dev, INTER_PACKET,
data + 1, len - 1);
else
gspca_dev->last_packet_type = DISCARD_PACKET;
break;
}
}
static void sd_dq_callback(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int ret, alen;
int luma, expo;
if (sd->ag_cnt < 0)
return;
if (--sd->ag_cnt > 5)
return;
switch (sd->ag_cnt) {
/* case 5: */
default:
reg_w(gspca_dev, 0x7d, 0x00);
break;
case 4:
reg_w(gspca_dev, 0x27, 0xb0);
break;
case 3:
reg_w(gspca_dev, 0x0c, 0x01);
break;
case 2:
ret = usb_bulk_msg(gspca_dev->dev,
usb_rcvbulkpipe(gspca_dev->dev, 0x02),
gspca_dev->usb_buf,
32,
&alen,
500);
if (ret < 0) {
pr_err("bulk err %d\n", ret);
break;
}
/* values not used (unknown) */
break;
case 1:
reg_w(gspca_dev, 0x27, 0xd0);
break;
case 0:
ret = usb_bulk_msg(gspca_dev->dev,
usb_rcvbulkpipe(gspca_dev->dev, 0x02),
gspca_dev->usb_buf,
32,
&alen,
500);
if (ret < 0) {
pr_err("bulk err %d\n", ret);
break;
}
luma = ((gspca_dev->usb_buf[8] << 8) + gspca_dev->usb_buf[7] +
(gspca_dev->usb_buf[11] << 8) + gspca_dev->usb_buf[10] +
(gspca_dev->usb_buf[14] << 8) + gspca_dev->usb_buf[13] +
(gspca_dev->usb_buf[17] << 8) + gspca_dev->usb_buf[16] +
(gspca_dev->usb_buf[20] << 8) + gspca_dev->usb_buf[19] +
(gspca_dev->usb_buf[23] << 8) + gspca_dev->usb_buf[22] +
(gspca_dev->usb_buf[26] << 8) + gspca_dev->usb_buf[25] +
(gspca_dev->usb_buf[29] << 8) + gspca_dev->usb_buf[28])
/ 8;
if (gspca_dev->pixfmt.width == 640)
luma /= 4;
reg_w(gspca_dev, 0x7d, 0x00);
expo = v4l2_ctrl_g_ctrl(gspca_dev->exposure);
ret = gspca_expo_autogain(gspca_dev, luma,
60, /* desired luma */
6, /* dead zone */
2, /* gain knee */
70); /* expo knee */
sd->ag_cnt = AG_CNT_START;
if (sd->bridge == BRIDGE_TP6810) {
int new_expo = v4l2_ctrl_g_ctrl(gspca_dev->exposure);
if ((expo >= 128 && new_expo < 128)
|| (expo < 128 && new_expo >= 128))
setframerate(gspca_dev, new_expo);
}
break;
}
}
/* get stream parameters (framerate) */
static void sd_get_streamparm(struct gspca_dev *gspca_dev,
struct v4l2_streamparm *parm)
{
struct sd *sd = (struct sd *) gspca_dev;
struct v4l2_captureparm *cp = &parm->parm.capture;
struct v4l2_fract *tpf = &cp->timeperframe;
int fr, i;
tpf->numerator = 1;
i = get_fr_idx(gspca_dev);
if (i & 0x80) {
if (sd->bridge == BRIDGE_TP6800)
fr = rates[6 - (i & 0x07)];
else
fr = rates_6810[7 - (i & 0x07)];
} else {
fr = rates[6 - i];
}
tpf->denominator = fr;
}
/* set stream parameters (framerate) */
static void sd_set_streamparm(struct gspca_dev *gspca_dev,
struct v4l2_streamparm *parm)
{
struct sd *sd = (struct sd *) gspca_dev;
struct v4l2_captureparm *cp = &parm->parm.capture;
struct v4l2_fract *tpf = &cp->timeperframe;
int fr, i;
if (tpf->numerator == 0 || tpf->denominator == 0)
sd->framerate = DEFAULT_FRAME_RATE;
else
sd->framerate = tpf->denominator / tpf->numerator;
if (gspca_dev->streaming)
setframerate(gspca_dev, v4l2_ctrl_g_ctrl(gspca_dev->exposure));
/* Return the actual framerate */
i = get_fr_idx(gspca_dev);
if (i & 0x80)
fr = rates_6810[7 - (i & 0x07)];
else
fr = rates[6 - i];
tpf->numerator = 1;
tpf->denominator = fr;
}
static int sd_set_jcomp(struct gspca_dev *gspca_dev,
const struct v4l2_jpegcompression *jcomp)
{
struct sd *sd = (struct sd *) gspca_dev;
if (sd->sensor != SENSOR_SOI763A)
return -ENOTTY;
v4l2_ctrl_s_ctrl(sd->jpegqual, jcomp->quality);
return 0;
}
static int sd_get_jcomp(struct gspca_dev *gspca_dev,
struct v4l2_jpegcompression *jcomp)
{
struct sd *sd = (struct sd *) gspca_dev;
if (sd->sensor != SENSOR_SOI763A)
return -ENOTTY;
memset(jcomp, 0, sizeof *jcomp);
jcomp->quality = v4l2_ctrl_g_ctrl(sd->jpegqual);
jcomp->jpeg_markers = V4L2_JPEG_MARKER_DHT
| V4L2_JPEG_MARKER_DQT;
return 0;
}
static int sd_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct gspca_dev *gspca_dev =
container_of(ctrl->handler, struct gspca_dev, ctrl_handler);
struct sd *sd = (struct sd *)gspca_dev;
gspca_dev->usb_err = 0;
if (!gspca_dev->streaming)
return 0;
switch (ctrl->id) {
case V4L2_CID_SHARPNESS:
setsharpness(gspca_dev, ctrl->val);
break;
case V4L2_CID_GAMMA:
setgamma(gspca_dev, ctrl->val);
break;
case V4L2_CID_BLUE_BALANCE:
setbgain(gspca_dev, ctrl->val);
break;
case V4L2_CID_RED_BALANCE:
setrgain(gspca_dev, ctrl->val);
break;
case V4L2_CID_EXPOSURE:
sd_setgain(gspca_dev);
break;
case V4L2_CID_AUTOGAIN:
if (ctrl->val)
break;
sd_setgain(gspca_dev);
break;
case V4L2_CID_JPEG_COMPRESSION_QUALITY:
jpeg_set_qual(sd->jpeg_hdr, ctrl->val);
break;
}
return gspca_dev->usb_err;
}
static const struct v4l2_ctrl_ops sd_ctrl_ops = {
.s_ctrl = sd_s_ctrl,
};
static int sd_init_controls(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *)gspca_dev;
struct v4l2_ctrl_handler *hdl = &gspca_dev->ctrl_handler;
gspca_dev->vdev.ctrl_handler = hdl;
v4l2_ctrl_handler_init(hdl, 4);
gspca_dev->exposure = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_EXPOSURE, 1, 0xdc, 1, 0x4e);
if (sd->sensor == SENSOR_CX0342) {
sd->red = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_RED_BALANCE, 0, 4095, 1, 256);
sd->blue = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_BLUE_BALANCE, 0, 4095, 1, 256);
}
if (sd->sensor == SENSOR_SOI763A)
gspca_dev->gain = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_GAIN, 0, 15, 1, 3);
else
gspca_dev->gain = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_GAIN, 0, 4095, 1, 256);
sd->sharpness = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_SHARPNESS, 0, 3, 1, 2);
sd->gamma = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_GAMMA, 0, NGAMMA - 1, 1,
(sd->sensor == SENSOR_SOI763A &&
sd->bridge == BRIDGE_TP6800) ? 0 : 1);
if (sd->bridge == BRIDGE_TP6810)
gspca_dev->autogain = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_AUTOGAIN, 0, 1, 1, 1);
if (sd->sensor == SENSOR_SOI763A)
sd->jpegqual = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_JPEG_COMPRESSION_QUALITY,
0, 15, 1, (sd->bridge == BRIDGE_TP6810) ? 0 : 13);
if (hdl->error) {
pr_err("Could not initialize controls\n");
return hdl->error;
}
if (gspca_dev->autogain)
v4l2_ctrl_auto_cluster(3, &gspca_dev->autogain, 0, false);
else
v4l2_ctrl_cluster(2, &gspca_dev->exposure);
return 0;
}
static const struct sd_desc sd_desc = {
.name = KBUILD_MODNAME,
.config = sd_config,
.init = sd_init,
.init_controls = sd_init_controls,
.isoc_init = sd_isoc_init,
.start = sd_start,
.stopN = sd_stopN,
.pkt_scan = sd_pkt_scan,
.dq_callback = sd_dq_callback,
.get_streamparm = sd_get_streamparm,
.set_streamparm = sd_set_streamparm,
.get_jcomp = sd_get_jcomp,
.set_jcomp = sd_set_jcomp,
};
static const struct usb_device_id device_table[] = {
{USB_DEVICE(0x06a2, 0x0003), .driver_info = BRIDGE_TP6800},
{USB_DEVICE(0x06a2, 0x6810), .driver_info = BRIDGE_TP6810},
{} /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, device_table);
static int sd_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
return gspca_dev_probe(interface, id, &sd_desc, sizeof(struct sd),
THIS_MODULE);
}
static struct usb_driver sd_driver = {
.name = KBUILD_MODNAME,
.id_table = device_table,
.probe = sd_probe,
.disconnect = gspca_disconnect,
#ifdef CONFIG_PM
.suspend = gspca_suspend,
.resume = gspca_resume,
.reset_resume = gspca_resume,
#endif
};
module_usb_driver(sd_driver);
module_param(force_sensor, int, 0644);
MODULE_PARM_DESC(force_sensor,
"Force sensor. 0: cx0342, 1: soi763a");
| gpl-2.0 |
vcgato29/linux | drivers/staging/fbtft/fb_hx8353d.c | 619 | 4377 | /*
* FB driver for the HX8353D LCD Controller
*
* Copyright (c) 2014 Petr Olivka
* Copyright (c) 2013 Noralf Tronnes
*
* 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/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include "fbtft.h"
#define DRVNAME "fb_hx8353d"
#define DEFAULT_GAMMA "50 77 40 08 BF 00 03 0F 00 01 73 00 72 03 B0 0F 08 00 0F"
static int init_display(struct fbtft_par *par)
{
fbtft_par_dbg(DEBUG_INIT_DISPLAY, par, "%s()\n", __func__);
par->fbtftops.reset(par);
mdelay(150);
/* SETEXTC */
write_reg(par, 0xB9, 0xFF, 0x83, 0x53);
/* RADJ */
write_reg(par, 0xB0, 0x3C, 0x01);
/* VCOM */
write_reg(par, 0xB6, 0x94, 0x6C, 0x50);
/* PWR */
write_reg(par, 0xB1, 0x00, 0x01, 0x1B, 0x03, 0x01, 0x08, 0x77, 0x89);
/* COLMOD */
write_reg(par, 0x3A, 0x05);
/* MEM ACCESS */
write_reg(par, 0x36, 0xC0);
/* SLPOUT - Sleep out & booster on */
write_reg(par, 0x11);
mdelay(150);
/* DISPON - Display On */
write_reg(par, 0x29);
/* RGBSET */
write_reg(par, 0x2D,
0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30,
32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62,
0, 1, 2, 3, 4, 5, 6, 7, 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,
0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30,
32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62);
return 0;
};
static void set_addr_win(struct fbtft_par *par, int xs, int ys, int xe, int ye)
{
fbtft_par_dbg(DEBUG_SET_ADDR_WIN, par,
"%s(xs=%d, ys=%d, xe=%d, ye=%d)\n", __func__, xs, ys, xe, ye);
/* column address */
write_reg(par, 0x2a, xs >> 8, xs & 0xff, xe >> 8, xe & 0xff);
/* Row address */
write_reg(par, 0x2b, ys >> 8, ys & 0xff, ye >> 8, ye & 0xff);
/* memory write */
write_reg(par, 0x2c);
}
#define my (1 << 7)
#define mx (1 << 6)
#define mv (1 << 5)
static int set_var(struct fbtft_par *par)
{
fbtft_par_dbg(DEBUG_INIT_DISPLAY, par, "%s()\n", __func__);
/* madctl - memory data access control
rgb/bgr:
1. mode selection pin srgb
rgb h/w pin for color filter setting: 0=rgb, 1=bgr
2. madctl rgb bit
rgb-bgr order color filter panel: 0=rgb, 1=bgr */
switch (par->info->var.rotate) {
case 0:
write_reg(par, 0x36, mx | my | (par->bgr << 3));
break;
case 270:
write_reg(par, 0x36, my | mv | (par->bgr << 3));
break;
case 180:
write_reg(par, 0x36, par->bgr << 3);
break;
case 90:
write_reg(par, 0x36, mx | mv | (par->bgr << 3));
break;
}
return 0;
}
/*
gamma string format:
*/
static int set_gamma(struct fbtft_par *par, unsigned long *curves)
{
fbtft_par_dbg(DEBUG_INIT_DISPLAY, par, "%s()\n", __func__);
write_reg(par, 0xE0,
curves[0], curves[1], curves[2], curves[3],
curves[4], curves[5], curves[6], curves[7],
curves[8], curves[9], curves[10], curves[11],
curves[12], curves[13], curves[14], curves[15],
curves[16], curves[17], curves[18]);
return 0;
}
static struct fbtft_display display = {
.regwidth = 8,
.width = 128,
.height = 160,
.gamma_num = 1,
.gamma_len = 19,
.gamma = DEFAULT_GAMMA,
.fbtftops = {
.init_display = init_display,
.set_addr_win = set_addr_win,
.set_var = set_var,
.set_gamma = set_gamma,
},
};
FBTFT_REGISTER_DRIVER(DRVNAME, "himax,hx8353d", &display);
MODULE_ALIAS("spi:" DRVNAME);
MODULE_ALIAS("platform:" DRVNAME);
MODULE_ALIAS("spi:hx8353d");
MODULE_ALIAS("platform:hx8353d");
MODULE_DESCRIPTION("FB driver for the HX8353D LCD Controller");
MODULE_AUTHOR("Petr Olivka");
MODULE_LICENSE("GPL");
| gpl-2.0 |
penberg/linux | drivers/watchdog/asm9260_wdt.c | 619 | 8636 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* Watchdog driver for Alphascale ASM9260.
*
* Copyright (c) 2014 Oleksij Rempel <linux@rempel-privat.de>
*/
#include <linux/bitops.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/reset.h>
#include <linux/watchdog.h>
#define CLOCK_FREQ 1000000
/* Watchdog Mode register */
#define HW_WDMOD 0x00
/* Wake interrupt. Set by HW, can't be cleared. */
#define BM_MOD_WDINT BIT(3)
/* This bit set if timeout reached. Cleared by SW. */
#define BM_MOD_WDTOF BIT(2)
/* HW Reset on timeout */
#define BM_MOD_WDRESET BIT(1)
/* WD enable */
#define BM_MOD_WDEN BIT(0)
/*
* Watchdog Timer Constant register
* Minimal value is 0xff, the meaning of this value
* depends on used clock: T = WDCLK * (0xff + 1) * 4
*/
#define HW_WDTC 0x04
#define BM_WDTC_MAX(freq) (0x7fffffff / (freq))
/* Watchdog Feed register */
#define HW_WDFEED 0x08
/* Watchdog Timer Value register */
#define HW_WDTV 0x0c
#define ASM9260_WDT_DEFAULT_TIMEOUT 30
enum asm9260_wdt_mode {
HW_RESET,
SW_RESET,
DEBUG,
};
struct asm9260_wdt_priv {
struct device *dev;
struct watchdog_device wdd;
struct clk *clk;
struct clk *clk_ahb;
struct reset_control *rst;
void __iomem *iobase;
int irq;
unsigned long wdt_freq;
enum asm9260_wdt_mode mode;
};
static int asm9260_wdt_feed(struct watchdog_device *wdd)
{
struct asm9260_wdt_priv *priv = watchdog_get_drvdata(wdd);
iowrite32(0xaa, priv->iobase + HW_WDFEED);
iowrite32(0x55, priv->iobase + HW_WDFEED);
return 0;
}
static unsigned int asm9260_wdt_gettimeleft(struct watchdog_device *wdd)
{
struct asm9260_wdt_priv *priv = watchdog_get_drvdata(wdd);
u32 counter;
counter = ioread32(priv->iobase + HW_WDTV);
return counter / priv->wdt_freq;
}
static int asm9260_wdt_updatetimeout(struct watchdog_device *wdd)
{
struct asm9260_wdt_priv *priv = watchdog_get_drvdata(wdd);
u32 counter;
counter = wdd->timeout * priv->wdt_freq;
iowrite32(counter, priv->iobase + HW_WDTC);
return 0;
}
static int asm9260_wdt_enable(struct watchdog_device *wdd)
{
struct asm9260_wdt_priv *priv = watchdog_get_drvdata(wdd);
u32 mode = 0;
if (priv->mode == HW_RESET)
mode = BM_MOD_WDRESET;
iowrite32(BM_MOD_WDEN | mode, priv->iobase + HW_WDMOD);
asm9260_wdt_updatetimeout(wdd);
asm9260_wdt_feed(wdd);
return 0;
}
static int asm9260_wdt_disable(struct watchdog_device *wdd)
{
struct asm9260_wdt_priv *priv = watchdog_get_drvdata(wdd);
/* The only way to disable WD is to reset it. */
reset_control_assert(priv->rst);
reset_control_deassert(priv->rst);
return 0;
}
static int asm9260_wdt_settimeout(struct watchdog_device *wdd, unsigned int to)
{
wdd->timeout = to;
asm9260_wdt_updatetimeout(wdd);
return 0;
}
static void asm9260_wdt_sys_reset(struct asm9260_wdt_priv *priv)
{
/* init WD if it was not started */
iowrite32(BM_MOD_WDEN | BM_MOD_WDRESET, priv->iobase + HW_WDMOD);
iowrite32(0xff, priv->iobase + HW_WDTC);
/* first pass correct sequence */
asm9260_wdt_feed(&priv->wdd);
/*
* Then write wrong pattern to the feed to trigger reset
* ASAP.
*/
iowrite32(0xff, priv->iobase + HW_WDFEED);
mdelay(1000);
}
static irqreturn_t asm9260_wdt_irq(int irq, void *devid)
{
struct asm9260_wdt_priv *priv = devid;
u32 stat;
stat = ioread32(priv->iobase + HW_WDMOD);
if (!(stat & BM_MOD_WDINT))
return IRQ_NONE;
if (priv->mode == DEBUG) {
dev_info(priv->dev, "Watchdog Timeout. Do nothing.\n");
} else {
dev_info(priv->dev, "Watchdog Timeout. Doing SW Reset.\n");
asm9260_wdt_sys_reset(priv);
}
return IRQ_HANDLED;
}
static int asm9260_restart(struct watchdog_device *wdd, unsigned long action,
void *data)
{
struct asm9260_wdt_priv *priv = watchdog_get_drvdata(wdd);
asm9260_wdt_sys_reset(priv);
return 0;
}
static const struct watchdog_info asm9260_wdt_ident = {
.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING
| WDIOF_MAGICCLOSE,
.identity = "Alphascale asm9260 Watchdog",
};
static const struct watchdog_ops asm9260_wdt_ops = {
.owner = THIS_MODULE,
.start = asm9260_wdt_enable,
.stop = asm9260_wdt_disable,
.get_timeleft = asm9260_wdt_gettimeleft,
.ping = asm9260_wdt_feed,
.set_timeout = asm9260_wdt_settimeout,
.restart = asm9260_restart,
};
static void asm9260_clk_disable_unprepare(void *data)
{
clk_disable_unprepare(data);
}
static int asm9260_wdt_get_dt_clks(struct asm9260_wdt_priv *priv)
{
int err;
unsigned long clk;
priv->clk = devm_clk_get(priv->dev, "mod");
if (IS_ERR(priv->clk)) {
dev_err(priv->dev, "Failed to get \"mod\" clk\n");
return PTR_ERR(priv->clk);
}
/* configure AHB clock */
priv->clk_ahb = devm_clk_get(priv->dev, "ahb");
if (IS_ERR(priv->clk_ahb)) {
dev_err(priv->dev, "Failed to get \"ahb\" clk\n");
return PTR_ERR(priv->clk_ahb);
}
err = clk_prepare_enable(priv->clk_ahb);
if (err) {
dev_err(priv->dev, "Failed to enable ahb_clk!\n");
return err;
}
err = devm_add_action_or_reset(priv->dev,
asm9260_clk_disable_unprepare,
priv->clk_ahb);
if (err)
return err;
err = clk_set_rate(priv->clk, CLOCK_FREQ);
if (err) {
dev_err(priv->dev, "Failed to set rate!\n");
return err;
}
err = clk_prepare_enable(priv->clk);
if (err) {
dev_err(priv->dev, "Failed to enable clk!\n");
return err;
}
err = devm_add_action_or_reset(priv->dev,
asm9260_clk_disable_unprepare,
priv->clk);
if (err)
return err;
/* wdt has internal divider */
clk = clk_get_rate(priv->clk);
if (!clk) {
dev_err(priv->dev, "Failed, clk is 0!\n");
return -EINVAL;
}
priv->wdt_freq = clk / 2;
return 0;
}
static void asm9260_wdt_get_dt_mode(struct asm9260_wdt_priv *priv)
{
const char *tmp;
int ret;
/* default mode */
priv->mode = HW_RESET;
ret = of_property_read_string(priv->dev->of_node,
"alphascale,mode", &tmp);
if (ret < 0)
return;
if (!strcmp(tmp, "hw"))
priv->mode = HW_RESET;
else if (!strcmp(tmp, "sw"))
priv->mode = SW_RESET;
else if (!strcmp(tmp, "debug"))
priv->mode = DEBUG;
else
dev_warn(priv->dev, "unknown reset-type: %s. Using default \"hw\" mode.",
tmp);
}
static int asm9260_wdt_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct asm9260_wdt_priv *priv;
struct watchdog_device *wdd;
int ret;
static const char * const mode_name[] = { "hw", "sw", "debug", };
priv = devm_kzalloc(dev, sizeof(struct asm9260_wdt_priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->dev = dev;
priv->iobase = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(priv->iobase))
return PTR_ERR(priv->iobase);
priv->rst = devm_reset_control_get_exclusive(dev, "wdt_rst");
if (IS_ERR(priv->rst))
return PTR_ERR(priv->rst);
ret = asm9260_wdt_get_dt_clks(priv);
if (ret)
return ret;
wdd = &priv->wdd;
wdd->info = &asm9260_wdt_ident;
wdd->ops = &asm9260_wdt_ops;
wdd->min_timeout = 1;
wdd->max_timeout = BM_WDTC_MAX(priv->wdt_freq);
wdd->parent = dev;
watchdog_set_drvdata(wdd, priv);
/*
* If 'timeout-sec' unspecified in devicetree, assume a 30 second
* default, unless the max timeout is less than 30 seconds, then use
* the max instead.
*/
wdd->timeout = ASM9260_WDT_DEFAULT_TIMEOUT;
watchdog_init_timeout(wdd, 0, dev);
asm9260_wdt_get_dt_mode(priv);
if (priv->mode != HW_RESET)
priv->irq = platform_get_irq(pdev, 0);
if (priv->irq > 0) {
/*
* Not all supported platforms specify an interrupt for the
* watchdog, so let's make it optional.
*/
ret = devm_request_irq(dev, priv->irq, asm9260_wdt_irq, 0,
pdev->name, priv);
if (ret < 0)
dev_warn(dev, "failed to request IRQ\n");
}
watchdog_set_restart_priority(wdd, 128);
watchdog_stop_on_reboot(wdd);
watchdog_stop_on_unregister(wdd);
ret = devm_watchdog_register_device(dev, wdd);
if (ret)
return ret;
platform_set_drvdata(pdev, priv);
dev_info(dev, "Watchdog enabled (timeout: %d sec, mode: %s)\n",
wdd->timeout, mode_name[priv->mode]);
return 0;
}
static const struct of_device_id asm9260_wdt_of_match[] = {
{ .compatible = "alphascale,asm9260-wdt"},
{},
};
MODULE_DEVICE_TABLE(of, asm9260_wdt_of_match);
static struct platform_driver asm9260_wdt_driver = {
.driver = {
.name = "asm9260-wdt",
.of_match_table = asm9260_wdt_of_match,
},
.probe = asm9260_wdt_probe,
};
module_platform_driver(asm9260_wdt_driver);
MODULE_DESCRIPTION("asm9260 WatchDog Timer Driver");
MODULE_AUTHOR("Oleksij Rempel <linux@rempel-privat.de>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
627656505/linux | drivers/hwmon/adm1026.c | 1643 | 58945 | /*
* adm1026.c - Part of lm_sensors, Linux kernel modules for hardware
* monitoring
* Copyright (C) 2002, 2003 Philip Pokorny <ppokorny@penguincomputing.com>
* Copyright (C) 2004 Justin Thiessen <jthiessen@penguincomputing.com>
*
* Chip details at:
*
* <http://www.onsemi.com/PowerSolutions/product.do?id=ADM1026>
*
* 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/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/hwmon-vid.h>
#include <linux/err.h>
#include <linux/mutex.h>
/* Addresses to scan */
static const unsigned short normal_i2c[] = { 0x2c, 0x2d, 0x2e, I2C_CLIENT_END };
static int gpio_input[17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1 };
static int gpio_output[17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1 };
static int gpio_inverted[17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1 };
static int gpio_normal[17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1 };
static int gpio_fan[8] = { -1, -1, -1, -1, -1, -1, -1, -1 };
module_param_array(gpio_input, int, NULL, 0);
MODULE_PARM_DESC(gpio_input, "List of GPIO pins (0-16) to program as inputs");
module_param_array(gpio_output, int, NULL, 0);
MODULE_PARM_DESC(gpio_output,
"List of GPIO pins (0-16) to program as outputs");
module_param_array(gpio_inverted, int, NULL, 0);
MODULE_PARM_DESC(gpio_inverted,
"List of GPIO pins (0-16) to program as inverted");
module_param_array(gpio_normal, int, NULL, 0);
MODULE_PARM_DESC(gpio_normal,
"List of GPIO pins (0-16) to program as normal/non-inverted");
module_param_array(gpio_fan, int, NULL, 0);
MODULE_PARM_DESC(gpio_fan, "List of GPIO pins (0-7) to program as fan tachs");
/* Many ADM1026 constants specified below */
/* The ADM1026 registers */
#define ADM1026_REG_CONFIG1 0x00
#define CFG1_MONITOR 0x01
#define CFG1_INT_ENABLE 0x02
#define CFG1_INT_CLEAR 0x04
#define CFG1_AIN8_9 0x08
#define CFG1_THERM_HOT 0x10
#define CFG1_DAC_AFC 0x20
#define CFG1_PWM_AFC 0x40
#define CFG1_RESET 0x80
#define ADM1026_REG_CONFIG2 0x01
/* CONFIG2 controls FAN0/GPIO0 through FAN7/GPIO7 */
#define ADM1026_REG_CONFIG3 0x07
#define CFG3_GPIO16_ENABLE 0x01
#define CFG3_CI_CLEAR 0x02
#define CFG3_VREF_250 0x04
#define CFG3_GPIO16_DIR 0x40
#define CFG3_GPIO16_POL 0x80
#define ADM1026_REG_E2CONFIG 0x13
#define E2CFG_READ 0x01
#define E2CFG_WRITE 0x02
#define E2CFG_ERASE 0x04
#define E2CFG_ROM 0x08
#define E2CFG_CLK_EXT 0x80
/*
* There are 10 general analog inputs and 7 dedicated inputs
* They are:
* 0 - 9 = AIN0 - AIN9
* 10 = Vbat
* 11 = 3.3V Standby
* 12 = 3.3V Main
* 13 = +5V
* 14 = Vccp (CPU core voltage)
* 15 = +12V
* 16 = -12V
*/
static u16 ADM1026_REG_IN[] = {
0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
0x36, 0x37, 0x27, 0x29, 0x26, 0x2a,
0x2b, 0x2c, 0x2d, 0x2e, 0x2f
};
static u16 ADM1026_REG_IN_MIN[] = {
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d,
0x5e, 0x5f, 0x6d, 0x49, 0x6b, 0x4a,
0x4b, 0x4c, 0x4d, 0x4e, 0x4f
};
static u16 ADM1026_REG_IN_MAX[] = {
0x50, 0x51, 0x52, 0x53, 0x54, 0x55,
0x56, 0x57, 0x6c, 0x41, 0x6a, 0x42,
0x43, 0x44, 0x45, 0x46, 0x47
};
/*
* Temperatures are:
* 0 - Internal
* 1 - External 1
* 2 - External 2
*/
static u16 ADM1026_REG_TEMP[] = { 0x1f, 0x28, 0x29 };
static u16 ADM1026_REG_TEMP_MIN[] = { 0x69, 0x48, 0x49 };
static u16 ADM1026_REG_TEMP_MAX[] = { 0x68, 0x40, 0x41 };
static u16 ADM1026_REG_TEMP_TMIN[] = { 0x10, 0x11, 0x12 };
static u16 ADM1026_REG_TEMP_THERM[] = { 0x0d, 0x0e, 0x0f };
static u16 ADM1026_REG_TEMP_OFFSET[] = { 0x1e, 0x6e, 0x6f };
#define ADM1026_REG_FAN(nr) (0x38 + (nr))
#define ADM1026_REG_FAN_MIN(nr) (0x60 + (nr))
#define ADM1026_REG_FAN_DIV_0_3 0x02
#define ADM1026_REG_FAN_DIV_4_7 0x03
#define ADM1026_REG_DAC 0x04
#define ADM1026_REG_PWM 0x05
#define ADM1026_REG_GPIO_CFG_0_3 0x08
#define ADM1026_REG_GPIO_CFG_4_7 0x09
#define ADM1026_REG_GPIO_CFG_8_11 0x0a
#define ADM1026_REG_GPIO_CFG_12_15 0x0b
/* CFG_16 in REG_CFG3 */
#define ADM1026_REG_GPIO_STATUS_0_7 0x24
#define ADM1026_REG_GPIO_STATUS_8_15 0x25
/* STATUS_16 in REG_STATUS4 */
#define ADM1026_REG_GPIO_MASK_0_7 0x1c
#define ADM1026_REG_GPIO_MASK_8_15 0x1d
/* MASK_16 in REG_MASK4 */
#define ADM1026_REG_COMPANY 0x16
#define ADM1026_REG_VERSTEP 0x17
/* These are the recognized values for the above regs */
#define ADM1026_COMPANY_ANALOG_DEV 0x41
#define ADM1026_VERSTEP_GENERIC 0x40
#define ADM1026_VERSTEP_ADM1026 0x44
#define ADM1026_REG_MASK1 0x18
#define ADM1026_REG_MASK2 0x19
#define ADM1026_REG_MASK3 0x1a
#define ADM1026_REG_MASK4 0x1b
#define ADM1026_REG_STATUS1 0x20
#define ADM1026_REG_STATUS2 0x21
#define ADM1026_REG_STATUS3 0x22
#define ADM1026_REG_STATUS4 0x23
#define ADM1026_FAN_ACTIVATION_TEMP_HYST -6
#define ADM1026_FAN_CONTROL_TEMP_RANGE 20
#define ADM1026_PWM_MAX 255
/*
* Conversions. Rounding and limit checking is only done on the TO_REG
* variants. Note that you should be a bit careful with which arguments
* these macros are called: arguments may be evaluated more than once.
*/
/*
* IN are scaled according to built-in resistors. These are the
* voltages corresponding to 3/4 of full scale (192 or 0xc0)
* NOTE: The -12V input needs an additional factor to account
* for the Vref pullup resistor.
* NEG12_OFFSET = SCALE * Vref / V-192 - Vref
* = 13875 * 2.50 / 1.875 - 2500
* = 16000
*
* The values in this table are based on Table II, page 15 of the
* datasheet.
*/
static int adm1026_scaling[] = { /* .001 Volts */
2250, 2250, 2250, 2250, 2250, 2250,
1875, 1875, 1875, 1875, 3000, 3330,
3330, 4995, 2250, 12000, 13875
};
#define NEG12_OFFSET 16000
#define SCALE(val, from, to) (((val)*(to) + ((from)/2))/(from))
#define INS_TO_REG(n, val) (clamp_val(SCALE(val, adm1026_scaling[n], 192),\
0, 255))
#define INS_FROM_REG(n, val) (SCALE(val, 192, adm1026_scaling[n]))
/*
* FAN speed is measured using 22.5kHz clock and counts for 2 pulses
* and we assume a 2 pulse-per-rev fan tach signal
* 22500 kHz * 60 (sec/min) * 2 (pulse) / 2 (pulse/rev) == 1350000
*/
#define FAN_TO_REG(val, div) ((val) <= 0 ? 0xff : \
clamp_val(1350000 / ((val) * (div)), \
1, 254))
#define FAN_FROM_REG(val, div) ((val) == 0 ? -1 : (val) == 0xff ? 0 : \
1350000 / ((val) * (div)))
#define DIV_FROM_REG(val) (1 << (val))
#define DIV_TO_REG(val) ((val) >= 8 ? 3 : (val) >= 4 ? 2 : (val) >= 2 ? 1 : 0)
/* Temperature is reported in 1 degC increments */
#define TEMP_TO_REG(val) (clamp_val(((val) + ((val) < 0 ? -500 : 500)) \
/ 1000, -127, 127))
#define TEMP_FROM_REG(val) ((val) * 1000)
#define OFFSET_TO_REG(val) (clamp_val(((val) + ((val) < 0 ? -500 : 500)) \
/ 1000, -127, 127))
#define OFFSET_FROM_REG(val) ((val) * 1000)
#define PWM_TO_REG(val) (clamp_val(val, 0, 255))
#define PWM_FROM_REG(val) (val)
#define PWM_MIN_TO_REG(val) ((val) & 0xf0)
#define PWM_MIN_FROM_REG(val) (((val) & 0xf0) + ((val) >> 4))
/*
* Analog output is a voltage, and scaled to millivolts. The datasheet
* indicates that the DAC could be used to drive the fans, but in our
* example board (Arima HDAMA) it isn't connected to the fans at all.
*/
#define DAC_TO_REG(val) (clamp_val(((((val) * 255) + 500) / 2500), 0, 255))
#define DAC_FROM_REG(val) (((val) * 2500) / 255)
/*
* Chip sampling rates
*
* Some sensors are not updated more frequently than once per second
* so it doesn't make sense to read them more often than that.
* We cache the results and return the saved data if the driver
* is called again before a second has elapsed.
*
* Also, there is significant configuration data for this chip
* So, we keep the config data up to date in the cache
* when it is written and only sample it once every 5 *minutes*
*/
#define ADM1026_DATA_INTERVAL (1 * HZ)
#define ADM1026_CONFIG_INTERVAL (5 * 60 * HZ)
/*
* We allow for multiple chips in a single system.
*
* For each registered ADM1026, we need to keep state information
* at client->data. The adm1026_data structure is dynamically
* allocated, when a new client structure is allocated.
*/
struct pwm_data {
u8 pwm;
u8 enable;
u8 auto_pwm_min;
};
struct adm1026_data {
struct i2c_client *client;
const struct attribute_group *groups[3];
struct mutex update_lock;
int valid; /* !=0 if following fields are valid */
unsigned long last_reading; /* In jiffies */
unsigned long last_config; /* In jiffies */
u8 in[17]; /* Register value */
u8 in_max[17]; /* Register value */
u8 in_min[17]; /* Register value */
s8 temp[3]; /* Register value */
s8 temp_min[3]; /* Register value */
s8 temp_max[3]; /* Register value */
s8 temp_tmin[3]; /* Register value */
s8 temp_crit[3]; /* Register value */
s8 temp_offset[3]; /* Register value */
u8 fan[8]; /* Register value */
u8 fan_min[8]; /* Register value */
u8 fan_div[8]; /* Decoded value */
struct pwm_data pwm1; /* Pwm control values */
u8 vrm; /* VRM version */
u8 analog_out; /* Register value (DAC) */
long alarms; /* Register encoding, combined */
long alarm_mask; /* Register encoding, combined */
long gpio; /* Register encoding, combined */
long gpio_mask; /* Register encoding, combined */
u8 gpio_config[17]; /* Decoded value */
u8 config1; /* Register value */
u8 config2; /* Register value */
u8 config3; /* Register value */
};
static int adm1026_read_value(struct i2c_client *client, u8 reg)
{
int res;
if (reg < 0x80) {
/* "RAM" locations */
res = i2c_smbus_read_byte_data(client, reg) & 0xff;
} else {
/* EEPROM, do nothing */
res = 0;
}
return res;
}
static int adm1026_write_value(struct i2c_client *client, u8 reg, int value)
{
int res;
if (reg < 0x80) {
/* "RAM" locations */
res = i2c_smbus_write_byte_data(client, reg, value);
} else {
/* EEPROM, do nothing */
res = 0;
}
return res;
}
static struct adm1026_data *adm1026_update_device(struct device *dev)
{
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
int i;
long value, alarms, gpio;
mutex_lock(&data->update_lock);
if (!data->valid
|| time_after(jiffies,
data->last_reading + ADM1026_DATA_INTERVAL)) {
/* Things that change quickly */
dev_dbg(&client->dev, "Reading sensor values\n");
for (i = 0; i <= 16; ++i) {
data->in[i] =
adm1026_read_value(client, ADM1026_REG_IN[i]);
}
for (i = 0; i <= 7; ++i) {
data->fan[i] =
adm1026_read_value(client, ADM1026_REG_FAN(i));
}
for (i = 0; i <= 2; ++i) {
/*
* NOTE: temp[] is s8 and we assume 2's complement
* "conversion" in the assignment
*/
data->temp[i] =
adm1026_read_value(client, ADM1026_REG_TEMP[i]);
}
data->pwm1.pwm = adm1026_read_value(client,
ADM1026_REG_PWM);
data->analog_out = adm1026_read_value(client,
ADM1026_REG_DAC);
/* GPIO16 is MSbit of alarms, move it to gpio */
alarms = adm1026_read_value(client, ADM1026_REG_STATUS4);
gpio = alarms & 0x80 ? 0x0100 : 0; /* GPIO16 */
alarms &= 0x7f;
alarms <<= 8;
alarms |= adm1026_read_value(client, ADM1026_REG_STATUS3);
alarms <<= 8;
alarms |= adm1026_read_value(client, ADM1026_REG_STATUS2);
alarms <<= 8;
alarms |= adm1026_read_value(client, ADM1026_REG_STATUS1);
data->alarms = alarms;
/* Read the GPIO values */
gpio |= adm1026_read_value(client,
ADM1026_REG_GPIO_STATUS_8_15);
gpio <<= 8;
gpio |= adm1026_read_value(client,
ADM1026_REG_GPIO_STATUS_0_7);
data->gpio = gpio;
data->last_reading = jiffies;
} /* last_reading */
if (!data->valid ||
time_after(jiffies, data->last_config + ADM1026_CONFIG_INTERVAL)) {
/* Things that don't change often */
dev_dbg(&client->dev, "Reading config values\n");
for (i = 0; i <= 16; ++i) {
data->in_min[i] = adm1026_read_value(client,
ADM1026_REG_IN_MIN[i]);
data->in_max[i] = adm1026_read_value(client,
ADM1026_REG_IN_MAX[i]);
}
value = adm1026_read_value(client, ADM1026_REG_FAN_DIV_0_3)
| (adm1026_read_value(client, ADM1026_REG_FAN_DIV_4_7)
<< 8);
for (i = 0; i <= 7; ++i) {
data->fan_min[i] = adm1026_read_value(client,
ADM1026_REG_FAN_MIN(i));
data->fan_div[i] = DIV_FROM_REG(value & 0x03);
value >>= 2;
}
for (i = 0; i <= 2; ++i) {
/*
* NOTE: temp_xxx[] are s8 and we assume 2's
* complement "conversion" in the assignment
*/
data->temp_min[i] = adm1026_read_value(client,
ADM1026_REG_TEMP_MIN[i]);
data->temp_max[i] = adm1026_read_value(client,
ADM1026_REG_TEMP_MAX[i]);
data->temp_tmin[i] = adm1026_read_value(client,
ADM1026_REG_TEMP_TMIN[i]);
data->temp_crit[i] = adm1026_read_value(client,
ADM1026_REG_TEMP_THERM[i]);
data->temp_offset[i] = adm1026_read_value(client,
ADM1026_REG_TEMP_OFFSET[i]);
}
/* Read the STATUS/alarm masks */
alarms = adm1026_read_value(client, ADM1026_REG_MASK4);
gpio = alarms & 0x80 ? 0x0100 : 0; /* GPIO16 */
alarms = (alarms & 0x7f) << 8;
alarms |= adm1026_read_value(client, ADM1026_REG_MASK3);
alarms <<= 8;
alarms |= adm1026_read_value(client, ADM1026_REG_MASK2);
alarms <<= 8;
alarms |= adm1026_read_value(client, ADM1026_REG_MASK1);
data->alarm_mask = alarms;
/* Read the GPIO values */
gpio |= adm1026_read_value(client,
ADM1026_REG_GPIO_MASK_8_15);
gpio <<= 8;
gpio |= adm1026_read_value(client, ADM1026_REG_GPIO_MASK_0_7);
data->gpio_mask = gpio;
/* Read various values from CONFIG1 */
data->config1 = adm1026_read_value(client,
ADM1026_REG_CONFIG1);
if (data->config1 & CFG1_PWM_AFC) {
data->pwm1.enable = 2;
data->pwm1.auto_pwm_min =
PWM_MIN_FROM_REG(data->pwm1.pwm);
}
/* Read the GPIO config */
data->config2 = adm1026_read_value(client,
ADM1026_REG_CONFIG2);
data->config3 = adm1026_read_value(client,
ADM1026_REG_CONFIG3);
data->gpio_config[16] = (data->config3 >> 6) & 0x03;
value = 0;
for (i = 0; i <= 15; ++i) {
if ((i & 0x03) == 0) {
value = adm1026_read_value(client,
ADM1026_REG_GPIO_CFG_0_3 + i/4);
}
data->gpio_config[i] = value & 0x03;
value >>= 2;
}
data->last_config = jiffies;
} /* last_config */
data->valid = 1;
mutex_unlock(&data->update_lock);
return data;
}
static ssize_t show_in(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", INS_FROM_REG(nr, data->in[nr]));
}
static ssize_t show_in_min(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", INS_FROM_REG(nr, data->in_min[nr]));
}
static ssize_t set_in_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_min[nr] = INS_TO_REG(nr, val);
adm1026_write_value(client, ADM1026_REG_IN_MIN[nr], data->in_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_in_max(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", INS_FROM_REG(nr, data->in_max[nr]));
}
static ssize_t set_in_max(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_max[nr] = INS_TO_REG(nr, val);
adm1026_write_value(client, ADM1026_REG_IN_MAX[nr], data->in_max[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define in_reg(offset) \
static SENSOR_DEVICE_ATTR(in##offset##_input, S_IRUGO, show_in, \
NULL, offset); \
static SENSOR_DEVICE_ATTR(in##offset##_min, S_IRUGO | S_IWUSR, \
show_in_min, set_in_min, offset); \
static SENSOR_DEVICE_ATTR(in##offset##_max, S_IRUGO | S_IWUSR, \
show_in_max, set_in_max, offset);
in_reg(0);
in_reg(1);
in_reg(2);
in_reg(3);
in_reg(4);
in_reg(5);
in_reg(6);
in_reg(7);
in_reg(8);
in_reg(9);
in_reg(10);
in_reg(11);
in_reg(12);
in_reg(13);
in_reg(14);
in_reg(15);
static ssize_t show_in16(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", INS_FROM_REG(16, data->in[16]) -
NEG12_OFFSET);
}
static ssize_t show_in16_min(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", INS_FROM_REG(16, data->in_min[16])
- NEG12_OFFSET);
}
static ssize_t set_in16_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_min[16] = INS_TO_REG(16, val + NEG12_OFFSET);
adm1026_write_value(client, ADM1026_REG_IN_MIN[16], data->in_min[16]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_in16_max(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", INS_FROM_REG(16, data->in_max[16])
- NEG12_OFFSET);
}
static ssize_t set_in16_max(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_max[16] = INS_TO_REG(16, val+NEG12_OFFSET);
adm1026_write_value(client, ADM1026_REG_IN_MAX[16], data->in_max[16]);
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(in16_input, S_IRUGO, show_in16, NULL, 16);
static SENSOR_DEVICE_ATTR(in16_min, S_IRUGO | S_IWUSR, show_in16_min,
set_in16_min, 16);
static SENSOR_DEVICE_ATTR(in16_max, S_IRUGO | S_IWUSR, show_in16_max,
set_in16_max, 16);
/* Now add fan read/write functions */
static ssize_t show_fan(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan[nr],
data->fan_div[nr]));
}
static ssize_t show_fan_min(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan_min[nr],
data->fan_div[nr]));
}
static ssize_t set_fan_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->fan_min[nr] = FAN_TO_REG(val, data->fan_div[nr]);
adm1026_write_value(client, ADM1026_REG_FAN_MIN(nr),
data->fan_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define fan_offset(offset) \
static SENSOR_DEVICE_ATTR(fan##offset##_input, S_IRUGO, show_fan, NULL, \
offset - 1); \
static SENSOR_DEVICE_ATTR(fan##offset##_min, S_IRUGO | S_IWUSR, \
show_fan_min, set_fan_min, offset - 1);
fan_offset(1);
fan_offset(2);
fan_offset(3);
fan_offset(4);
fan_offset(5);
fan_offset(6);
fan_offset(7);
fan_offset(8);
/* Adjust fan_min to account for new fan divisor */
static void fixup_fan_min(struct device *dev, int fan, int old_div)
{
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
int new_min;
int new_div = data->fan_div[fan];
/* 0 and 0xff are special. Don't adjust them */
if (data->fan_min[fan] == 0 || data->fan_min[fan] == 0xff)
return;
new_min = data->fan_min[fan] * old_div / new_div;
new_min = clamp_val(new_min, 1, 254);
data->fan_min[fan] = new_min;
adm1026_write_value(client, ADM1026_REG_FAN_MIN(fan), new_min);
}
/* Now add fan_div read/write functions */
static ssize_t show_fan_div(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", data->fan_div[nr]);
}
static ssize_t set_fan_div(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long val;
int orig_div, new_div;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
new_div = DIV_TO_REG(val);
mutex_lock(&data->update_lock);
orig_div = data->fan_div[nr];
data->fan_div[nr] = DIV_FROM_REG(new_div);
if (nr < 4) { /* 0 <= nr < 4 */
adm1026_write_value(client, ADM1026_REG_FAN_DIV_0_3,
(DIV_TO_REG(data->fan_div[0]) << 0) |
(DIV_TO_REG(data->fan_div[1]) << 2) |
(DIV_TO_REG(data->fan_div[2]) << 4) |
(DIV_TO_REG(data->fan_div[3]) << 6));
} else { /* 3 < nr < 8 */
adm1026_write_value(client, ADM1026_REG_FAN_DIV_4_7,
(DIV_TO_REG(data->fan_div[4]) << 0) |
(DIV_TO_REG(data->fan_div[5]) << 2) |
(DIV_TO_REG(data->fan_div[6]) << 4) |
(DIV_TO_REG(data->fan_div[7]) << 6));
}
if (data->fan_div[nr] != orig_div)
fixup_fan_min(dev, nr, orig_div);
mutex_unlock(&data->update_lock);
return count;
}
#define fan_offset_div(offset) \
static SENSOR_DEVICE_ATTR(fan##offset##_div, S_IRUGO | S_IWUSR, \
show_fan_div, set_fan_div, offset - 1);
fan_offset_div(1);
fan_offset_div(2);
fan_offset_div(3);
fan_offset_div(4);
fan_offset_div(5);
fan_offset_div(6);
fan_offset_div(7);
fan_offset_div(8);
/* Temps */
static ssize_t show_temp(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp[nr]));
}
static ssize_t show_temp_min(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_min[nr]));
}
static ssize_t set_temp_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_min[nr] = TEMP_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_TEMP_MIN[nr],
data->temp_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_temp_max(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_max[nr]));
}
static ssize_t set_temp_max(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_max[nr] = TEMP_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_TEMP_MAX[nr],
data->temp_max[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define temp_reg(offset) \
static SENSOR_DEVICE_ATTR(temp##offset##_input, S_IRUGO, show_temp, \
NULL, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_min, S_IRUGO | S_IWUSR, \
show_temp_min, set_temp_min, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_max, S_IRUGO | S_IWUSR, \
show_temp_max, set_temp_max, offset - 1);
temp_reg(1);
temp_reg(2);
temp_reg(3);
static ssize_t show_temp_offset(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_offset[nr]));
}
static ssize_t set_temp_offset(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_offset[nr] = TEMP_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_TEMP_OFFSET[nr],
data->temp_offset[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define temp_offset_reg(offset) \
static SENSOR_DEVICE_ATTR(temp##offset##_offset, S_IRUGO | S_IWUSR, \
show_temp_offset, set_temp_offset, offset - 1);
temp_offset_reg(1);
temp_offset_reg(2);
temp_offset_reg(3);
static ssize_t show_temp_auto_point1_temp_hyst(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(
ADM1026_FAN_ACTIVATION_TEMP_HYST + data->temp_tmin[nr]));
}
static ssize_t show_temp_auto_point2_temp(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_tmin[nr] +
ADM1026_FAN_CONTROL_TEMP_RANGE));
}
static ssize_t show_temp_auto_point1_temp(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_tmin[nr]));
}
static ssize_t set_temp_auto_point1_temp(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_tmin[nr] = TEMP_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_TEMP_TMIN[nr],
data->temp_tmin[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define temp_auto_point(offset) \
static SENSOR_DEVICE_ATTR(temp##offset##_auto_point1_temp, \
S_IRUGO | S_IWUSR, show_temp_auto_point1_temp, \
set_temp_auto_point1_temp, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_auto_point1_temp_hyst, S_IRUGO,\
show_temp_auto_point1_temp_hyst, NULL, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_auto_point2_temp, S_IRUGO, \
show_temp_auto_point2_temp, NULL, offset - 1);
temp_auto_point(1);
temp_auto_point(2);
temp_auto_point(3);
static ssize_t show_temp_crit_enable(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", (data->config1 & CFG1_THERM_HOT) >> 4);
}
static ssize_t set_temp_crit_enable(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
if (val > 1)
return -EINVAL;
mutex_lock(&data->update_lock);
data->config1 = (data->config1 & ~CFG1_THERM_HOT) | (val << 4);
adm1026_write_value(client, ADM1026_REG_CONFIG1, data->config1);
mutex_unlock(&data->update_lock);
return count;
}
#define temp_crit_enable(offset) \
static DEVICE_ATTR(temp##offset##_crit_enable, S_IRUGO | S_IWUSR, \
show_temp_crit_enable, set_temp_crit_enable);
temp_crit_enable(1);
temp_crit_enable(2);
temp_crit_enable(3);
static ssize_t show_temp_crit(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_crit[nr]));
}
static ssize_t set_temp_crit(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_crit[nr] = TEMP_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_TEMP_THERM[nr],
data->temp_crit[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define temp_crit_reg(offset) \
static SENSOR_DEVICE_ATTR(temp##offset##_crit, S_IRUGO | S_IWUSR, \
show_temp_crit, set_temp_crit, offset - 1);
temp_crit_reg(1);
temp_crit_reg(2);
temp_crit_reg(3);
static ssize_t show_analog_out_reg(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", DAC_FROM_REG(data->analog_out));
}
static ssize_t set_analog_out_reg(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->analog_out = DAC_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_DAC, data->analog_out);
mutex_unlock(&data->update_lock);
return count;
}
static DEVICE_ATTR(analog_out, S_IRUGO | S_IWUSR, show_analog_out_reg,
set_analog_out_reg);
static ssize_t show_vid_reg(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
int vid = (data->gpio >> 11) & 0x1f;
dev_dbg(dev, "Setting VID from GPIO11-15.\n");
return sprintf(buf, "%d\n", vid_from_reg(vid, data->vrm));
}
static DEVICE_ATTR(cpu0_vid, S_IRUGO, show_vid_reg, NULL);
static ssize_t show_vrm_reg(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", data->vrm);
}
static ssize_t store_vrm_reg(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct adm1026_data *data = dev_get_drvdata(dev);
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
if (val > 255)
return -EINVAL;
data->vrm = val;
return count;
}
static DEVICE_ATTR(vrm, S_IRUGO | S_IWUSR, show_vrm_reg, store_vrm_reg);
static ssize_t show_alarms_reg(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%ld\n", data->alarms);
}
static DEVICE_ATTR(alarms, S_IRUGO, show_alarms_reg, NULL);
static ssize_t show_alarm(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
int bitnr = to_sensor_dev_attr(attr)->index;
return sprintf(buf, "%ld\n", (data->alarms >> bitnr) & 1);
}
static SENSOR_DEVICE_ATTR(temp2_alarm, S_IRUGO, show_alarm, NULL, 0);
static SENSOR_DEVICE_ATTR(temp3_alarm, S_IRUGO, show_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(in9_alarm, S_IRUGO, show_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(in11_alarm, S_IRUGO, show_alarm, NULL, 2);
static SENSOR_DEVICE_ATTR(in12_alarm, S_IRUGO, show_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(in13_alarm, S_IRUGO, show_alarm, NULL, 4);
static SENSOR_DEVICE_ATTR(in14_alarm, S_IRUGO, show_alarm, NULL, 5);
static SENSOR_DEVICE_ATTR(in15_alarm, S_IRUGO, show_alarm, NULL, 6);
static SENSOR_DEVICE_ATTR(in16_alarm, S_IRUGO, show_alarm, NULL, 7);
static SENSOR_DEVICE_ATTR(in0_alarm, S_IRUGO, show_alarm, NULL, 8);
static SENSOR_DEVICE_ATTR(in1_alarm, S_IRUGO, show_alarm, NULL, 9);
static SENSOR_DEVICE_ATTR(in2_alarm, S_IRUGO, show_alarm, NULL, 10);
static SENSOR_DEVICE_ATTR(in3_alarm, S_IRUGO, show_alarm, NULL, 11);
static SENSOR_DEVICE_ATTR(in4_alarm, S_IRUGO, show_alarm, NULL, 12);
static SENSOR_DEVICE_ATTR(in5_alarm, S_IRUGO, show_alarm, NULL, 13);
static SENSOR_DEVICE_ATTR(in6_alarm, S_IRUGO, show_alarm, NULL, 14);
static SENSOR_DEVICE_ATTR(in7_alarm, S_IRUGO, show_alarm, NULL, 15);
static SENSOR_DEVICE_ATTR(fan1_alarm, S_IRUGO, show_alarm, NULL, 16);
static SENSOR_DEVICE_ATTR(fan2_alarm, S_IRUGO, show_alarm, NULL, 17);
static SENSOR_DEVICE_ATTR(fan3_alarm, S_IRUGO, show_alarm, NULL, 18);
static SENSOR_DEVICE_ATTR(fan4_alarm, S_IRUGO, show_alarm, NULL, 19);
static SENSOR_DEVICE_ATTR(fan5_alarm, S_IRUGO, show_alarm, NULL, 20);
static SENSOR_DEVICE_ATTR(fan6_alarm, S_IRUGO, show_alarm, NULL, 21);
static SENSOR_DEVICE_ATTR(fan7_alarm, S_IRUGO, show_alarm, NULL, 22);
static SENSOR_DEVICE_ATTR(fan8_alarm, S_IRUGO, show_alarm, NULL, 23);
static SENSOR_DEVICE_ATTR(temp1_alarm, S_IRUGO, show_alarm, NULL, 24);
static SENSOR_DEVICE_ATTR(in10_alarm, S_IRUGO, show_alarm, NULL, 25);
static SENSOR_DEVICE_ATTR(in8_alarm, S_IRUGO, show_alarm, NULL, 26);
static ssize_t show_alarm_mask(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%ld\n", data->alarm_mask);
}
static ssize_t set_alarm_mask(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
unsigned long mask;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->alarm_mask = val & 0x7fffffff;
mask = data->alarm_mask
| (data->gpio_mask & 0x10000 ? 0x80000000 : 0);
adm1026_write_value(client, ADM1026_REG_MASK1,
mask & 0xff);
mask >>= 8;
adm1026_write_value(client, ADM1026_REG_MASK2,
mask & 0xff);
mask >>= 8;
adm1026_write_value(client, ADM1026_REG_MASK3,
mask & 0xff);
mask >>= 8;
adm1026_write_value(client, ADM1026_REG_MASK4,
mask & 0xff);
mutex_unlock(&data->update_lock);
return count;
}
static DEVICE_ATTR(alarm_mask, S_IRUGO | S_IWUSR, show_alarm_mask,
set_alarm_mask);
static ssize_t show_gpio(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%ld\n", data->gpio);
}
static ssize_t set_gpio(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long gpio;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->gpio = val & 0x1ffff;
gpio = data->gpio;
adm1026_write_value(client, ADM1026_REG_GPIO_STATUS_0_7, gpio & 0xff);
gpio >>= 8;
adm1026_write_value(client, ADM1026_REG_GPIO_STATUS_8_15, gpio & 0xff);
gpio = ((gpio >> 1) & 0x80) | (data->alarms >> 24 & 0x7f);
adm1026_write_value(client, ADM1026_REG_STATUS4, gpio & 0xff);
mutex_unlock(&data->update_lock);
return count;
}
static DEVICE_ATTR(gpio, S_IRUGO | S_IWUSR, show_gpio, set_gpio);
static ssize_t show_gpio_mask(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%ld\n", data->gpio_mask);
}
static ssize_t set_gpio_mask(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long mask;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->gpio_mask = val & 0x1ffff;
mask = data->gpio_mask;
adm1026_write_value(client, ADM1026_REG_GPIO_MASK_0_7, mask & 0xff);
mask >>= 8;
adm1026_write_value(client, ADM1026_REG_GPIO_MASK_8_15, mask & 0xff);
mask = ((mask >> 1) & 0x80) | (data->alarm_mask >> 24 & 0x7f);
adm1026_write_value(client, ADM1026_REG_MASK1, mask & 0xff);
mutex_unlock(&data->update_lock);
return count;
}
static DEVICE_ATTR(gpio_mask, S_IRUGO | S_IWUSR, show_gpio_mask, set_gpio_mask);
static ssize_t show_pwm_reg(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", PWM_FROM_REG(data->pwm1.pwm));
}
static ssize_t set_pwm_reg(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
if (data->pwm1.enable == 1) {
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->pwm1.pwm = PWM_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_PWM, data->pwm1.pwm);
mutex_unlock(&data->update_lock);
}
return count;
}
static ssize_t show_auto_pwm_min(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", data->pwm1.auto_pwm_min);
}
static ssize_t set_auto_pwm_min(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t count)
{
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->pwm1.auto_pwm_min = clamp_val(val, 0, 255);
if (data->pwm1.enable == 2) { /* apply immediately */
data->pwm1.pwm = PWM_TO_REG((data->pwm1.pwm & 0x0f) |
PWM_MIN_TO_REG(data->pwm1.auto_pwm_min));
adm1026_write_value(client, ADM1026_REG_PWM, data->pwm1.pwm);
}
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_auto_pwm_max(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", ADM1026_PWM_MAX);
}
static ssize_t show_pwm_enable(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", data->pwm1.enable);
}
static ssize_t set_pwm_enable(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct adm1026_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
int old_enable;
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
if (val >= 3)
return -EINVAL;
mutex_lock(&data->update_lock);
old_enable = data->pwm1.enable;
data->pwm1.enable = val;
data->config1 = (data->config1 & ~CFG1_PWM_AFC)
| ((val == 2) ? CFG1_PWM_AFC : 0);
adm1026_write_value(client, ADM1026_REG_CONFIG1, data->config1);
if (val == 2) { /* apply pwm1_auto_pwm_min to pwm1 */
data->pwm1.pwm = PWM_TO_REG((data->pwm1.pwm & 0x0f) |
PWM_MIN_TO_REG(data->pwm1.auto_pwm_min));
adm1026_write_value(client, ADM1026_REG_PWM, data->pwm1.pwm);
} else if (!((old_enable == 1) && (val == 1))) {
/* set pwm to safe value */
data->pwm1.pwm = 255;
adm1026_write_value(client, ADM1026_REG_PWM, data->pwm1.pwm);
}
mutex_unlock(&data->update_lock);
return count;
}
/* enable PWM fan control */
static DEVICE_ATTR(pwm1, S_IRUGO | S_IWUSR, show_pwm_reg, set_pwm_reg);
static DEVICE_ATTR(pwm2, S_IRUGO | S_IWUSR, show_pwm_reg, set_pwm_reg);
static DEVICE_ATTR(pwm3, S_IRUGO | S_IWUSR, show_pwm_reg, set_pwm_reg);
static DEVICE_ATTR(pwm1_enable, S_IRUGO | S_IWUSR, show_pwm_enable,
set_pwm_enable);
static DEVICE_ATTR(pwm2_enable, S_IRUGO | S_IWUSR, show_pwm_enable,
set_pwm_enable);
static DEVICE_ATTR(pwm3_enable, S_IRUGO | S_IWUSR, show_pwm_enable,
set_pwm_enable);
static DEVICE_ATTR(temp1_auto_point1_pwm, S_IRUGO | S_IWUSR,
show_auto_pwm_min, set_auto_pwm_min);
static DEVICE_ATTR(temp2_auto_point1_pwm, S_IRUGO | S_IWUSR,
show_auto_pwm_min, set_auto_pwm_min);
static DEVICE_ATTR(temp3_auto_point1_pwm, S_IRUGO | S_IWUSR,
show_auto_pwm_min, set_auto_pwm_min);
static DEVICE_ATTR(temp1_auto_point2_pwm, S_IRUGO, show_auto_pwm_max, NULL);
static DEVICE_ATTR(temp2_auto_point2_pwm, S_IRUGO, show_auto_pwm_max, NULL);
static DEVICE_ATTR(temp3_auto_point2_pwm, S_IRUGO, show_auto_pwm_max, NULL);
static struct attribute *adm1026_attributes[] = {
&sensor_dev_attr_in0_input.dev_attr.attr,
&sensor_dev_attr_in0_max.dev_attr.attr,
&sensor_dev_attr_in0_min.dev_attr.attr,
&sensor_dev_attr_in0_alarm.dev_attr.attr,
&sensor_dev_attr_in1_input.dev_attr.attr,
&sensor_dev_attr_in1_max.dev_attr.attr,
&sensor_dev_attr_in1_min.dev_attr.attr,
&sensor_dev_attr_in1_alarm.dev_attr.attr,
&sensor_dev_attr_in2_input.dev_attr.attr,
&sensor_dev_attr_in2_max.dev_attr.attr,
&sensor_dev_attr_in2_min.dev_attr.attr,
&sensor_dev_attr_in2_alarm.dev_attr.attr,
&sensor_dev_attr_in3_input.dev_attr.attr,
&sensor_dev_attr_in3_max.dev_attr.attr,
&sensor_dev_attr_in3_min.dev_attr.attr,
&sensor_dev_attr_in3_alarm.dev_attr.attr,
&sensor_dev_attr_in4_input.dev_attr.attr,
&sensor_dev_attr_in4_max.dev_attr.attr,
&sensor_dev_attr_in4_min.dev_attr.attr,
&sensor_dev_attr_in4_alarm.dev_attr.attr,
&sensor_dev_attr_in5_input.dev_attr.attr,
&sensor_dev_attr_in5_max.dev_attr.attr,
&sensor_dev_attr_in5_min.dev_attr.attr,
&sensor_dev_attr_in5_alarm.dev_attr.attr,
&sensor_dev_attr_in6_input.dev_attr.attr,
&sensor_dev_attr_in6_max.dev_attr.attr,
&sensor_dev_attr_in6_min.dev_attr.attr,
&sensor_dev_attr_in6_alarm.dev_attr.attr,
&sensor_dev_attr_in7_input.dev_attr.attr,
&sensor_dev_attr_in7_max.dev_attr.attr,
&sensor_dev_attr_in7_min.dev_attr.attr,
&sensor_dev_attr_in7_alarm.dev_attr.attr,
&sensor_dev_attr_in10_input.dev_attr.attr,
&sensor_dev_attr_in10_max.dev_attr.attr,
&sensor_dev_attr_in10_min.dev_attr.attr,
&sensor_dev_attr_in10_alarm.dev_attr.attr,
&sensor_dev_attr_in11_input.dev_attr.attr,
&sensor_dev_attr_in11_max.dev_attr.attr,
&sensor_dev_attr_in11_min.dev_attr.attr,
&sensor_dev_attr_in11_alarm.dev_attr.attr,
&sensor_dev_attr_in12_input.dev_attr.attr,
&sensor_dev_attr_in12_max.dev_attr.attr,
&sensor_dev_attr_in12_min.dev_attr.attr,
&sensor_dev_attr_in12_alarm.dev_attr.attr,
&sensor_dev_attr_in13_input.dev_attr.attr,
&sensor_dev_attr_in13_max.dev_attr.attr,
&sensor_dev_attr_in13_min.dev_attr.attr,
&sensor_dev_attr_in13_alarm.dev_attr.attr,
&sensor_dev_attr_in14_input.dev_attr.attr,
&sensor_dev_attr_in14_max.dev_attr.attr,
&sensor_dev_attr_in14_min.dev_attr.attr,
&sensor_dev_attr_in14_alarm.dev_attr.attr,
&sensor_dev_attr_in15_input.dev_attr.attr,
&sensor_dev_attr_in15_max.dev_attr.attr,
&sensor_dev_attr_in15_min.dev_attr.attr,
&sensor_dev_attr_in15_alarm.dev_attr.attr,
&sensor_dev_attr_in16_input.dev_attr.attr,
&sensor_dev_attr_in16_max.dev_attr.attr,
&sensor_dev_attr_in16_min.dev_attr.attr,
&sensor_dev_attr_in16_alarm.dev_attr.attr,
&sensor_dev_attr_fan1_input.dev_attr.attr,
&sensor_dev_attr_fan1_div.dev_attr.attr,
&sensor_dev_attr_fan1_min.dev_attr.attr,
&sensor_dev_attr_fan1_alarm.dev_attr.attr,
&sensor_dev_attr_fan2_input.dev_attr.attr,
&sensor_dev_attr_fan2_div.dev_attr.attr,
&sensor_dev_attr_fan2_min.dev_attr.attr,
&sensor_dev_attr_fan2_alarm.dev_attr.attr,
&sensor_dev_attr_fan3_input.dev_attr.attr,
&sensor_dev_attr_fan3_div.dev_attr.attr,
&sensor_dev_attr_fan3_min.dev_attr.attr,
&sensor_dev_attr_fan3_alarm.dev_attr.attr,
&sensor_dev_attr_fan4_input.dev_attr.attr,
&sensor_dev_attr_fan4_div.dev_attr.attr,
&sensor_dev_attr_fan4_min.dev_attr.attr,
&sensor_dev_attr_fan4_alarm.dev_attr.attr,
&sensor_dev_attr_fan5_input.dev_attr.attr,
&sensor_dev_attr_fan5_div.dev_attr.attr,
&sensor_dev_attr_fan5_min.dev_attr.attr,
&sensor_dev_attr_fan5_alarm.dev_attr.attr,
&sensor_dev_attr_fan6_input.dev_attr.attr,
&sensor_dev_attr_fan6_div.dev_attr.attr,
&sensor_dev_attr_fan6_min.dev_attr.attr,
&sensor_dev_attr_fan6_alarm.dev_attr.attr,
&sensor_dev_attr_fan7_input.dev_attr.attr,
&sensor_dev_attr_fan7_div.dev_attr.attr,
&sensor_dev_attr_fan7_min.dev_attr.attr,
&sensor_dev_attr_fan7_alarm.dev_attr.attr,
&sensor_dev_attr_fan8_input.dev_attr.attr,
&sensor_dev_attr_fan8_div.dev_attr.attr,
&sensor_dev_attr_fan8_min.dev_attr.attr,
&sensor_dev_attr_fan8_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp1_min.dev_attr.attr,
&sensor_dev_attr_temp1_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp2_min.dev_attr.attr,
&sensor_dev_attr_temp2_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_offset.dev_attr.attr,
&sensor_dev_attr_temp2_offset.dev_attr.attr,
&sensor_dev_attr_temp1_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_temp2_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_temp1_auto_point1_temp_hyst.dev_attr.attr,
&sensor_dev_attr_temp2_auto_point1_temp_hyst.dev_attr.attr,
&sensor_dev_attr_temp1_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_temp2_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_temp1_crit.dev_attr.attr,
&sensor_dev_attr_temp2_crit.dev_attr.attr,
&dev_attr_temp1_crit_enable.attr,
&dev_attr_temp2_crit_enable.attr,
&dev_attr_cpu0_vid.attr,
&dev_attr_vrm.attr,
&dev_attr_alarms.attr,
&dev_attr_alarm_mask.attr,
&dev_attr_gpio.attr,
&dev_attr_gpio_mask.attr,
&dev_attr_pwm1.attr,
&dev_attr_pwm2.attr,
&dev_attr_pwm3.attr,
&dev_attr_pwm1_enable.attr,
&dev_attr_pwm2_enable.attr,
&dev_attr_pwm3_enable.attr,
&dev_attr_temp1_auto_point1_pwm.attr,
&dev_attr_temp2_auto_point1_pwm.attr,
&dev_attr_temp1_auto_point2_pwm.attr,
&dev_attr_temp2_auto_point2_pwm.attr,
&dev_attr_analog_out.attr,
NULL
};
static const struct attribute_group adm1026_group = {
.attrs = adm1026_attributes,
};
static struct attribute *adm1026_attributes_temp3[] = {
&sensor_dev_attr_temp3_input.dev_attr.attr,
&sensor_dev_attr_temp3_max.dev_attr.attr,
&sensor_dev_attr_temp3_min.dev_attr.attr,
&sensor_dev_attr_temp3_alarm.dev_attr.attr,
&sensor_dev_attr_temp3_offset.dev_attr.attr,
&sensor_dev_attr_temp3_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_temp3_auto_point1_temp_hyst.dev_attr.attr,
&sensor_dev_attr_temp3_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_temp3_crit.dev_attr.attr,
&dev_attr_temp3_crit_enable.attr,
&dev_attr_temp3_auto_point1_pwm.attr,
&dev_attr_temp3_auto_point2_pwm.attr,
NULL
};
static const struct attribute_group adm1026_group_temp3 = {
.attrs = adm1026_attributes_temp3,
};
static struct attribute *adm1026_attributes_in8_9[] = {
&sensor_dev_attr_in8_input.dev_attr.attr,
&sensor_dev_attr_in8_max.dev_attr.attr,
&sensor_dev_attr_in8_min.dev_attr.attr,
&sensor_dev_attr_in8_alarm.dev_attr.attr,
&sensor_dev_attr_in9_input.dev_attr.attr,
&sensor_dev_attr_in9_max.dev_attr.attr,
&sensor_dev_attr_in9_min.dev_attr.attr,
&sensor_dev_attr_in9_alarm.dev_attr.attr,
NULL
};
static const struct attribute_group adm1026_group_in8_9 = {
.attrs = adm1026_attributes_in8_9,
};
/* Return 0 if detection is successful, -ENODEV otherwise */
static int adm1026_detect(struct i2c_client *client,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
int address = client->addr;
int company, verstep;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) {
/* We need to be able to do byte I/O */
return -ENODEV;
}
/* Now, we do the remaining detection. */
company = adm1026_read_value(client, ADM1026_REG_COMPANY);
verstep = adm1026_read_value(client, ADM1026_REG_VERSTEP);
dev_dbg(&adapter->dev,
"Detecting device at %d,0x%02x with COMPANY: 0x%02x and VERSTEP: 0x%02x\n",
i2c_adapter_id(client->adapter), client->addr,
company, verstep);
/* Determine the chip type. */
dev_dbg(&adapter->dev, "Autodetecting device at %d,0x%02x...\n",
i2c_adapter_id(adapter), address);
if (company == ADM1026_COMPANY_ANALOG_DEV
&& verstep == ADM1026_VERSTEP_ADM1026) {
/* Analog Devices ADM1026 */
} else if (company == ADM1026_COMPANY_ANALOG_DEV
&& (verstep & 0xf0) == ADM1026_VERSTEP_GENERIC) {
dev_err(&adapter->dev,
"Unrecognized stepping 0x%02x. Defaulting to ADM1026.\n",
verstep);
} else if ((verstep & 0xf0) == ADM1026_VERSTEP_GENERIC) {
dev_err(&adapter->dev,
"Found version/stepping 0x%02x. Assuming generic ADM1026.\n",
verstep);
} else {
dev_dbg(&adapter->dev, "Autodetection failed\n");
/* Not an ADM1026... */
return -ENODEV;
}
strlcpy(info->type, "adm1026", I2C_NAME_SIZE);
return 0;
}
static void adm1026_print_gpio(struct i2c_client *client)
{
struct adm1026_data *data = i2c_get_clientdata(client);
int i;
dev_dbg(&client->dev, "GPIO config is:\n");
for (i = 0; i <= 7; ++i) {
if (data->config2 & (1 << i)) {
dev_dbg(&client->dev, "\t%sGP%s%d\n",
data->gpio_config[i] & 0x02 ? "" : "!",
data->gpio_config[i] & 0x01 ? "OUT" : "IN",
i);
} else {
dev_dbg(&client->dev, "\tFAN%d\n", i);
}
}
for (i = 8; i <= 15; ++i) {
dev_dbg(&client->dev, "\t%sGP%s%d\n",
data->gpio_config[i] & 0x02 ? "" : "!",
data->gpio_config[i] & 0x01 ? "OUT" : "IN",
i);
}
if (data->config3 & CFG3_GPIO16_ENABLE) {
dev_dbg(&client->dev, "\t%sGP%s16\n",
data->gpio_config[16] & 0x02 ? "" : "!",
data->gpio_config[16] & 0x01 ? "OUT" : "IN");
} else {
/* GPIO16 is THERM */
dev_dbg(&client->dev, "\tTHERM\n");
}
}
static void adm1026_fixup_gpio(struct i2c_client *client)
{
struct adm1026_data *data = i2c_get_clientdata(client);
int i;
int value;
/* Make the changes requested. */
/*
* We may need to unlock/stop monitoring or soft-reset the
* chip before we can make changes. This hasn't been
* tested much. FIXME
*/
/* Make outputs */
for (i = 0; i <= 16; ++i) {
if (gpio_output[i] >= 0 && gpio_output[i] <= 16)
data->gpio_config[gpio_output[i]] |= 0x01;
/* if GPIO0-7 is output, it isn't a FAN tach */
if (gpio_output[i] >= 0 && gpio_output[i] <= 7)
data->config2 |= 1 << gpio_output[i];
}
/* Input overrides output */
for (i = 0; i <= 16; ++i) {
if (gpio_input[i] >= 0 && gpio_input[i] <= 16)
data->gpio_config[gpio_input[i]] &= ~0x01;
/* if GPIO0-7 is input, it isn't a FAN tach */
if (gpio_input[i] >= 0 && gpio_input[i] <= 7)
data->config2 |= 1 << gpio_input[i];
}
/* Inverted */
for (i = 0; i <= 16; ++i) {
if (gpio_inverted[i] >= 0 && gpio_inverted[i] <= 16)
data->gpio_config[gpio_inverted[i]] &= ~0x02;
}
/* Normal overrides inverted */
for (i = 0; i <= 16; ++i) {
if (gpio_normal[i] >= 0 && gpio_normal[i] <= 16)
data->gpio_config[gpio_normal[i]] |= 0x02;
}
/* Fan overrides input and output */
for (i = 0; i <= 7; ++i) {
if (gpio_fan[i] >= 0 && gpio_fan[i] <= 7)
data->config2 &= ~(1 << gpio_fan[i]);
}
/* Write new configs to registers */
adm1026_write_value(client, ADM1026_REG_CONFIG2, data->config2);
data->config3 = (data->config3 & 0x3f)
| ((data->gpio_config[16] & 0x03) << 6);
adm1026_write_value(client, ADM1026_REG_CONFIG3, data->config3);
for (i = 15, value = 0; i >= 0; --i) {
value <<= 2;
value |= data->gpio_config[i] & 0x03;
if ((i & 0x03) == 0) {
adm1026_write_value(client,
ADM1026_REG_GPIO_CFG_0_3 + i/4,
value);
value = 0;
}
}
/* Print the new config */
adm1026_print_gpio(client);
}
static void adm1026_init_client(struct i2c_client *client)
{
int value, i;
struct adm1026_data *data = i2c_get_clientdata(client);
dev_dbg(&client->dev, "Initializing device\n");
/* Read chip config */
data->config1 = adm1026_read_value(client, ADM1026_REG_CONFIG1);
data->config2 = adm1026_read_value(client, ADM1026_REG_CONFIG2);
data->config3 = adm1026_read_value(client, ADM1026_REG_CONFIG3);
/* Inform user of chip config */
dev_dbg(&client->dev, "ADM1026_REG_CONFIG1 is: 0x%02x\n",
data->config1);
if ((data->config1 & CFG1_MONITOR) == 0) {
dev_dbg(&client->dev,
"Monitoring not currently enabled.\n");
}
if (data->config1 & CFG1_INT_ENABLE) {
dev_dbg(&client->dev,
"SMBALERT interrupts are enabled.\n");
}
if (data->config1 & CFG1_AIN8_9) {
dev_dbg(&client->dev,
"in8 and in9 enabled. temp3 disabled.\n");
} else {
dev_dbg(&client->dev,
"temp3 enabled. in8 and in9 disabled.\n");
}
if (data->config1 & CFG1_THERM_HOT) {
dev_dbg(&client->dev,
"Automatic THERM, PWM, and temp limits enabled.\n");
}
if (data->config3 & CFG3_GPIO16_ENABLE) {
dev_dbg(&client->dev,
"GPIO16 enabled. THERM pin disabled.\n");
} else {
dev_dbg(&client->dev,
"THERM pin enabled. GPIO16 disabled.\n");
}
if (data->config3 & CFG3_VREF_250)
dev_dbg(&client->dev, "Vref is 2.50 Volts.\n");
else
dev_dbg(&client->dev, "Vref is 1.82 Volts.\n");
/* Read and pick apart the existing GPIO configuration */
value = 0;
for (i = 0; i <= 15; ++i) {
if ((i & 0x03) == 0) {
value = adm1026_read_value(client,
ADM1026_REG_GPIO_CFG_0_3 + i / 4);
}
data->gpio_config[i] = value & 0x03;
value >>= 2;
}
data->gpio_config[16] = (data->config3 >> 6) & 0x03;
/* ... and then print it */
adm1026_print_gpio(client);
/*
* If the user asks us to reprogram the GPIO config, then
* do it now.
*/
if (gpio_input[0] != -1 || gpio_output[0] != -1
|| gpio_inverted[0] != -1 || gpio_normal[0] != -1
|| gpio_fan[0] != -1) {
adm1026_fixup_gpio(client);
}
/*
* WE INTENTIONALLY make no changes to the limits,
* offsets, pwms, fans and zones. If they were
* configured, we don't want to mess with them.
* If they weren't, the default is 100% PWM, no
* control and will suffice until 'sensors -s'
* can be run by the user. We DO set the default
* value for pwm1.auto_pwm_min to its maximum
* so that enabling automatic pwm fan control
* without first setting a value for pwm1.auto_pwm_min
* will not result in potentially dangerous fan speed decrease.
*/
data->pwm1.auto_pwm_min = 255;
/* Start monitoring */
value = adm1026_read_value(client, ADM1026_REG_CONFIG1);
/* Set MONITOR, clear interrupt acknowledge and s/w reset */
value = (value | CFG1_MONITOR) & (~CFG1_INT_CLEAR & ~CFG1_RESET);
dev_dbg(&client->dev, "Setting CONFIG to: 0x%02x\n", value);
data->config1 = value;
adm1026_write_value(client, ADM1026_REG_CONFIG1, value);
/* initialize fan_div[] to hardware defaults */
value = adm1026_read_value(client, ADM1026_REG_FAN_DIV_0_3) |
(adm1026_read_value(client, ADM1026_REG_FAN_DIV_4_7) << 8);
for (i = 0; i <= 7; ++i) {
data->fan_div[i] = DIV_FROM_REG(value & 0x03);
value >>= 2;
}
}
static int adm1026_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct device *dev = &client->dev;
struct device *hwmon_dev;
struct adm1026_data *data;
data = devm_kzalloc(dev, sizeof(struct adm1026_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
i2c_set_clientdata(client, data);
data->client = client;
mutex_init(&data->update_lock);
/* Set the VRM version */
data->vrm = vid_which_vrm();
/* Initialize the ADM1026 chip */
adm1026_init_client(client);
/* sysfs hooks */
data->groups[0] = &adm1026_group;
if (data->config1 & CFG1_AIN8_9)
data->groups[1] = &adm1026_group_in8_9;
else
data->groups[1] = &adm1026_group_temp3;
hwmon_dev = devm_hwmon_device_register_with_groups(dev, client->name,
data, data->groups);
return PTR_ERR_OR_ZERO(hwmon_dev);
}
static const struct i2c_device_id adm1026_id[] = {
{ "adm1026", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, adm1026_id);
static struct i2c_driver adm1026_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "adm1026",
},
.probe = adm1026_probe,
.id_table = adm1026_id,
.detect = adm1026_detect,
.address_list = normal_i2c,
};
module_i2c_driver(adm1026_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Philip Pokorny <ppokorny@penguincomputing.com>, "
"Justin Thiessen <jthiessen@penguincomputing.com>");
MODULE_DESCRIPTION("ADM1026 driver");
| gpl-2.0 |
himalock/LGL2220d | drivers/iommu/iommu.c | 2155 | 24603 | /*
* Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
* Author: Joerg Roedel <joerg.roedel@amd.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/bug.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/iommu.h>
#include <linux/scatterlist.h>
#include <linux/idr.h>
#include <linux/notifier.h>
#include <linux/err.h>
static struct kset *iommu_group_kset;
static struct idr iommu_group_idr;
static struct mutex iommu_group_mutex;
struct iommu_group {
struct kobject kobj;
struct kobject *devices_kobj;
struct list_head devices;
struct mutex mutex;
struct blocking_notifier_head notifier;
void *iommu_data;
void (*iommu_data_release)(void *iommu_data);
char *name;
int id;
};
struct iommu_device {
struct list_head list;
struct device *dev;
char *name;
};
struct iommu_group_attribute {
struct attribute attr;
ssize_t (*show)(struct iommu_group *group, char *buf);
ssize_t (*store)(struct iommu_group *group,
const char *buf, size_t count);
};
#define IOMMU_GROUP_ATTR(_name, _mode, _show, _store) \
struct iommu_group_attribute iommu_group_attr_##_name = \
__ATTR(_name, _mode, _show, _store)
#define to_iommu_group_attr(_attr) \
container_of(_attr, struct iommu_group_attribute, attr)
#define to_iommu_group(_kobj) \
container_of(_kobj, struct iommu_group, kobj)
static ssize_t iommu_group_attr_show(struct kobject *kobj,
struct attribute *__attr, char *buf)
{
struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
struct iommu_group *group = to_iommu_group(kobj);
ssize_t ret = -EIO;
if (attr->show)
ret = attr->show(group, buf);
return ret;
}
static ssize_t iommu_group_attr_store(struct kobject *kobj,
struct attribute *__attr,
const char *buf, size_t count)
{
struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
struct iommu_group *group = to_iommu_group(kobj);
ssize_t ret = -EIO;
if (attr->store)
ret = attr->store(group, buf, count);
return ret;
}
static const struct sysfs_ops iommu_group_sysfs_ops = {
.show = iommu_group_attr_show,
.store = iommu_group_attr_store,
};
static int iommu_group_create_file(struct iommu_group *group,
struct iommu_group_attribute *attr)
{
return sysfs_create_file(&group->kobj, &attr->attr);
}
static void iommu_group_remove_file(struct iommu_group *group,
struct iommu_group_attribute *attr)
{
sysfs_remove_file(&group->kobj, &attr->attr);
}
static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
{
return sprintf(buf, "%s\n", group->name);
}
static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
static void iommu_group_release(struct kobject *kobj)
{
struct iommu_group *group = to_iommu_group(kobj);
if (group->iommu_data_release)
group->iommu_data_release(group->iommu_data);
mutex_lock(&iommu_group_mutex);
idr_remove(&iommu_group_idr, group->id);
mutex_unlock(&iommu_group_mutex);
kfree(group->name);
kfree(group);
}
static struct kobj_type iommu_group_ktype = {
.sysfs_ops = &iommu_group_sysfs_ops,
.release = iommu_group_release,
};
/**
* iommu_group_alloc - Allocate a new group
* @name: Optional name to associate with group, visible in sysfs
*
* This function is called by an iommu driver to allocate a new iommu
* group. The iommu group represents the minimum granularity of the iommu.
* Upon successful return, the caller holds a reference to the supplied
* group in order to hold the group until devices are added. Use
* iommu_group_put() to release this extra reference count, allowing the
* group to be automatically reclaimed once it has no devices or external
* references.
*/
struct iommu_group *iommu_group_alloc(void)
{
struct iommu_group *group;
int ret;
group = kzalloc(sizeof(*group), GFP_KERNEL);
if (!group)
return ERR_PTR(-ENOMEM);
group->kobj.kset = iommu_group_kset;
mutex_init(&group->mutex);
INIT_LIST_HEAD(&group->devices);
BLOCKING_INIT_NOTIFIER_HEAD(&group->notifier);
mutex_lock(&iommu_group_mutex);
again:
if (unlikely(0 == idr_pre_get(&iommu_group_idr, GFP_KERNEL))) {
kfree(group);
mutex_unlock(&iommu_group_mutex);
return ERR_PTR(-ENOMEM);
}
ret = idr_get_new_above(&iommu_group_idr, group, 1, &group->id);
if (ret == -EAGAIN)
goto again;
mutex_unlock(&iommu_group_mutex);
if (ret == -ENOSPC) {
kfree(group);
return ERR_PTR(ret);
}
ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
NULL, "%d", group->id);
if (ret) {
mutex_lock(&iommu_group_mutex);
idr_remove(&iommu_group_idr, group->id);
mutex_unlock(&iommu_group_mutex);
kfree(group);
return ERR_PTR(ret);
}
group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
if (!group->devices_kobj) {
kobject_put(&group->kobj); /* triggers .release & free */
return ERR_PTR(-ENOMEM);
}
/*
* The devices_kobj holds a reference on the group kobject, so
* as long as that exists so will the group. We can therefore
* use the devices_kobj for reference counting.
*/
kobject_put(&group->kobj);
return group;
}
EXPORT_SYMBOL_GPL(iommu_group_alloc);
/**
* iommu_group_get_iommudata - retrieve iommu_data registered for a group
* @group: the group
*
* iommu drivers can store data in the group for use when doing iommu
* operations. This function provides a way to retrieve it. Caller
* should hold a group reference.
*/
void *iommu_group_get_iommudata(struct iommu_group *group)
{
return group->iommu_data;
}
EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
/**
* iommu_group_set_iommudata - set iommu_data for a group
* @group: the group
* @iommu_data: new data
* @release: release function for iommu_data
*
* iommu drivers can store data in the group for use when doing iommu
* operations. This function provides a way to set the data after
* the group has been allocated. Caller should hold a group reference.
*/
void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
void (*release)(void *iommu_data))
{
group->iommu_data = iommu_data;
group->iommu_data_release = release;
}
EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
/**
* iommu_group_set_name - set name for a group
* @group: the group
* @name: name
*
* Allow iommu driver to set a name for a group. When set it will
* appear in a name attribute file under the group in sysfs.
*/
int iommu_group_set_name(struct iommu_group *group, const char *name)
{
int ret;
if (group->name) {
iommu_group_remove_file(group, &iommu_group_attr_name);
kfree(group->name);
group->name = NULL;
if (!name)
return 0;
}
group->name = kstrdup(name, GFP_KERNEL);
if (!group->name)
return -ENOMEM;
ret = iommu_group_create_file(group, &iommu_group_attr_name);
if (ret) {
kfree(group->name);
group->name = NULL;
return ret;
}
return 0;
}
EXPORT_SYMBOL_GPL(iommu_group_set_name);
/**
* iommu_group_add_device - add a device to an iommu group
* @group: the group into which to add the device (reference should be held)
* @dev: the device
*
* This function is called by an iommu driver to add a device into a
* group. Adding a device increments the group reference count.
*/
int iommu_group_add_device(struct iommu_group *group, struct device *dev)
{
int ret, i = 0;
struct iommu_device *device;
device = kzalloc(sizeof(*device), GFP_KERNEL);
if (!device)
return -ENOMEM;
device->dev = dev;
ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
if (ret) {
kfree(device);
return ret;
}
device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
rename:
if (!device->name) {
sysfs_remove_link(&dev->kobj, "iommu_group");
kfree(device);
return -ENOMEM;
}
ret = sysfs_create_link_nowarn(group->devices_kobj,
&dev->kobj, device->name);
if (ret) {
kfree(device->name);
if (ret == -EEXIST && i >= 0) {
/*
* Account for the slim chance of collision
* and append an instance to the name.
*/
device->name = kasprintf(GFP_KERNEL, "%s.%d",
kobject_name(&dev->kobj), i++);
goto rename;
}
sysfs_remove_link(&dev->kobj, "iommu_group");
kfree(device);
return ret;
}
kobject_get(group->devices_kobj);
dev->iommu_group = group;
mutex_lock(&group->mutex);
list_add_tail(&device->list, &group->devices);
mutex_unlock(&group->mutex);
/* Notify any listeners about change to group. */
blocking_notifier_call_chain(&group->notifier,
IOMMU_GROUP_NOTIFY_ADD_DEVICE, dev);
return 0;
}
EXPORT_SYMBOL_GPL(iommu_group_add_device);
/**
* iommu_group_remove_device - remove a device from it's current group
* @dev: device to be removed
*
* This function is called by an iommu driver to remove the device from
* it's current group. This decrements the iommu group reference count.
*/
void iommu_group_remove_device(struct device *dev)
{
struct iommu_group *group = dev->iommu_group;
struct iommu_device *tmp_device, *device = NULL;
/* Pre-notify listeners that a device is being removed. */
blocking_notifier_call_chain(&group->notifier,
IOMMU_GROUP_NOTIFY_DEL_DEVICE, dev);
mutex_lock(&group->mutex);
list_for_each_entry(tmp_device, &group->devices, list) {
if (tmp_device->dev == dev) {
device = tmp_device;
list_del(&device->list);
break;
}
}
mutex_unlock(&group->mutex);
if (!device)
return;
sysfs_remove_link(group->devices_kobj, device->name);
sysfs_remove_link(&dev->kobj, "iommu_group");
kfree(device->name);
kfree(device);
dev->iommu_group = NULL;
kobject_put(group->devices_kobj);
}
EXPORT_SYMBOL_GPL(iommu_group_remove_device);
/**
* iommu_group_for_each_dev - iterate over each device in the group
* @group: the group
* @data: caller opaque data to be passed to callback function
* @fn: caller supplied callback function
*
* This function is called by group users to iterate over group devices.
* Callers should hold a reference count to the group during callback.
* The group->mutex is held across callbacks, which will block calls to
* iommu_group_add/remove_device.
*/
int iommu_group_for_each_dev(struct iommu_group *group, void *data,
int (*fn)(struct device *, void *))
{
struct iommu_device *device;
int ret = 0;
mutex_lock(&group->mutex);
list_for_each_entry(device, &group->devices, list) {
ret = fn(device->dev, data);
if (ret)
break;
}
mutex_unlock(&group->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
/**
* iommu_group_get - Return the group for a device and increment reference
* @dev: get the group that this device belongs to
*
* This function is called by iommu drivers and users to get the group
* for the specified device. If found, the group is returned and the group
* reference in incremented, else NULL.
*/
struct iommu_group *iommu_group_get(struct device *dev)
{
struct iommu_group *group = dev->iommu_group;
if (group)
kobject_get(group->devices_kobj);
return group;
}
EXPORT_SYMBOL_GPL(iommu_group_get);
/**
* iommu_group_find - Find and return the group based on the group name.
* Also increment the reference count.
* @name: the name of the group
*
* This function is called by iommu drivers and clients to get the group
* by the specified name. If found, the group is returned and the group
* reference is incremented, else NULL.
*/
struct iommu_group *iommu_group_find(const char *name)
{
struct iommu_group *group;
int next = 0;
mutex_lock(&iommu_group_mutex);
while ((group = idr_get_next(&iommu_group_idr, &next))) {
if (group->name) {
if (strcmp(group->name, name) == 0)
break;
}
++next;
}
mutex_unlock(&iommu_group_mutex);
if (group)
kobject_get(group->devices_kobj);
return group;
}
EXPORT_SYMBOL_GPL(iommu_group_find);
/**
* iommu_group_put - Decrement group reference
* @group: the group to use
*
* This function is called by iommu drivers and users to release the
* iommu group. Once the reference count is zero, the group is released.
*/
void iommu_group_put(struct iommu_group *group)
{
if (group)
kobject_put(group->devices_kobj);
}
EXPORT_SYMBOL_GPL(iommu_group_put);
/**
* iommu_group_register_notifier - Register a notifier for group changes
* @group: the group to watch
* @nb: notifier block to signal
*
* This function allows iommu group users to track changes in a group.
* See include/linux/iommu.h for actions sent via this notifier. Caller
* should hold a reference to the group throughout notifier registration.
*/
int iommu_group_register_notifier(struct iommu_group *group,
struct notifier_block *nb)
{
return blocking_notifier_chain_register(&group->notifier, nb);
}
EXPORT_SYMBOL_GPL(iommu_group_register_notifier);
/**
* iommu_group_unregister_notifier - Unregister a notifier
* @group: the group to watch
* @nb: notifier block to signal
*
* Unregister a previously registered group notifier block.
*/
int iommu_group_unregister_notifier(struct iommu_group *group,
struct notifier_block *nb)
{
return blocking_notifier_chain_unregister(&group->notifier, nb);
}
EXPORT_SYMBOL_GPL(iommu_group_unregister_notifier);
/**
* iommu_group_id - Return ID for a group
* @group: the group to ID
*
* Return the unique ID for the group matching the sysfs group number.
*/
int iommu_group_id(struct iommu_group *group)
{
return group->id;
}
EXPORT_SYMBOL_GPL(iommu_group_id);
static int add_iommu_group(struct device *dev, void *data)
{
struct iommu_ops *ops = data;
if (!ops->add_device)
return -ENODEV;
WARN_ON(dev->iommu_group);
ops->add_device(dev);
return 0;
}
static int iommu_bus_notifier(struct notifier_block *nb,
unsigned long action, void *data)
{
struct device *dev = data;
struct iommu_ops *ops = dev->bus->iommu_ops;
struct iommu_group *group;
unsigned long group_action = 0;
/*
* ADD/DEL call into iommu driver ops if provided, which may
* result in ADD/DEL notifiers to group->notifier
*/
if (action == BUS_NOTIFY_ADD_DEVICE) {
if (ops->add_device)
return ops->add_device(dev);
} else if (action == BUS_NOTIFY_DEL_DEVICE) {
if (ops->remove_device && dev->iommu_group) {
ops->remove_device(dev);
return 0;
}
}
/*
* Remaining BUS_NOTIFYs get filtered and republished to the
* group, if anyone is listening
*/
group = iommu_group_get(dev);
if (!group)
return 0;
switch (action) {
case BUS_NOTIFY_BIND_DRIVER:
group_action = IOMMU_GROUP_NOTIFY_BIND_DRIVER;
break;
case BUS_NOTIFY_BOUND_DRIVER:
group_action = IOMMU_GROUP_NOTIFY_BOUND_DRIVER;
break;
case BUS_NOTIFY_UNBIND_DRIVER:
group_action = IOMMU_GROUP_NOTIFY_UNBIND_DRIVER;
break;
case BUS_NOTIFY_UNBOUND_DRIVER:
group_action = IOMMU_GROUP_NOTIFY_UNBOUND_DRIVER;
break;
}
if (group_action)
blocking_notifier_call_chain(&group->notifier,
group_action, dev);
iommu_group_put(group);
return 0;
}
static struct notifier_block iommu_bus_nb = {
.notifier_call = iommu_bus_notifier,
};
static void iommu_bus_init(struct bus_type *bus, struct iommu_ops *ops)
{
bus_register_notifier(bus, &iommu_bus_nb);
bus_for_each_dev(bus, NULL, ops, add_iommu_group);
}
/**
* bus_set_iommu - set iommu-callbacks for the bus
* @bus: bus.
* @ops: the callbacks provided by the iommu-driver
*
* This function is called by an iommu driver to set the iommu methods
* used for a particular bus. Drivers for devices on that bus can use
* the iommu-api after these ops are registered.
* This special function is needed because IOMMUs are usually devices on
* the bus itself, so the iommu drivers are not initialized when the bus
* is set up. With this function the iommu-driver can set the iommu-ops
* afterwards.
*/
int bus_set_iommu(struct bus_type *bus, struct iommu_ops *ops)
{
if (bus->iommu_ops != NULL)
return -EBUSY;
bus->iommu_ops = ops;
/* Do IOMMU specific setup for this bus-type */
iommu_bus_init(bus, ops);
return 0;
}
EXPORT_SYMBOL_GPL(bus_set_iommu);
bool iommu_present(struct bus_type *bus)
{
return bus->iommu_ops != NULL;
}
EXPORT_SYMBOL_GPL(iommu_present);
/**
* iommu_set_fault_handler() - set a fault handler for an iommu domain
* @domain: iommu domain
* @handler: fault handler
* @token: user data, will be passed back to the fault handler
*
* This function should be used by IOMMU users which want to be notified
* whenever an IOMMU fault happens.
*
* The fault handler itself should return 0 on success, and an appropriate
* error code otherwise.
*/
void iommu_set_fault_handler(struct iommu_domain *domain,
iommu_fault_handler_t handler,
void *token)
{
BUG_ON(!domain);
domain->handler = handler;
domain->handler_token = token;
}
EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
struct iommu_domain *iommu_domain_alloc(struct bus_type *bus, int flags)
{
struct iommu_domain *domain;
int ret;
if (bus == NULL || bus->iommu_ops == NULL)
return NULL;
domain = kzalloc(sizeof(*domain), GFP_KERNEL);
if (!domain)
return NULL;
domain->ops = bus->iommu_ops;
ret = domain->ops->domain_init(domain, flags);
if (ret)
goto out_free;
return domain;
out_free:
kfree(domain);
return NULL;
}
EXPORT_SYMBOL_GPL(iommu_domain_alloc);
void iommu_domain_free(struct iommu_domain *domain)
{
if (likely(domain->ops->domain_destroy != NULL))
domain->ops->domain_destroy(domain);
kfree(domain);
}
EXPORT_SYMBOL_GPL(iommu_domain_free);
int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
{
if (unlikely(domain->ops->attach_dev == NULL))
return -ENODEV;
return domain->ops->attach_dev(domain, dev);
}
EXPORT_SYMBOL_GPL(iommu_attach_device);
void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
{
if (unlikely(domain->ops->detach_dev == NULL))
return;
domain->ops->detach_dev(domain, dev);
}
EXPORT_SYMBOL_GPL(iommu_detach_device);
/*
* IOMMU groups are really the natrual working unit of the IOMMU, but
* the IOMMU API works on domains and devices. Bridge that gap by
* iterating over the devices in a group. Ideally we'd have a single
* device which represents the requestor ID of the group, but we also
* allow IOMMU drivers to create policy defined minimum sets, where
* the physical hardware may be able to distiguish members, but we
* wish to group them at a higher level (ex. untrusted multi-function
* PCI devices). Thus we attach each device.
*/
static int iommu_group_do_attach_device(struct device *dev, void *data)
{
struct iommu_domain *domain = data;
return iommu_attach_device(domain, dev);
}
int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
{
return iommu_group_for_each_dev(group, domain,
iommu_group_do_attach_device);
}
EXPORT_SYMBOL_GPL(iommu_attach_group);
static int iommu_group_do_detach_device(struct device *dev, void *data)
{
struct iommu_domain *domain = data;
iommu_detach_device(domain, dev);
return 0;
}
void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
{
iommu_group_for_each_dev(group, domain, iommu_group_do_detach_device);
}
EXPORT_SYMBOL_GPL(iommu_detach_group);
phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain,
unsigned long iova)
{
if (unlikely(domain->ops->iova_to_phys == NULL))
return 0;
return domain->ops->iova_to_phys(domain, iova);
}
EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
int iommu_domain_has_cap(struct iommu_domain *domain,
unsigned long cap)
{
if (unlikely(domain->ops->domain_has_cap == NULL))
return 0;
return domain->ops->domain_has_cap(domain, cap);
}
EXPORT_SYMBOL_GPL(iommu_domain_has_cap);
int iommu_map(struct iommu_domain *domain, unsigned long iova,
phys_addr_t paddr, size_t size, int prot)
{
unsigned long orig_iova = iova;
unsigned int min_pagesz;
size_t orig_size = size;
int ret = 0;
if (unlikely(domain->ops->map == NULL))
return -ENODEV;
/* find out the minimum page size supported */
min_pagesz = 1 << __ffs(domain->ops->pgsize_bitmap);
/*
* both the virtual address and the physical one, as well as
* the size of the mapping, must be aligned (at least) to the
* size of the smallest page supported by the hardware
*/
if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
pr_err("unaligned: iova 0x%lx pa 0x%lx size 0x%lx min_pagesz "
"0x%x\n", iova, (unsigned long)paddr,
(unsigned long)size, min_pagesz);
return -EINVAL;
}
pr_debug("map: iova 0x%lx pa 0x%lx size 0x%lx\n", iova,
(unsigned long)paddr, (unsigned long)size);
while (size) {
unsigned long pgsize, addr_merge = iova | paddr;
unsigned int pgsize_idx;
/* Max page size that still fits into 'size' */
pgsize_idx = __fls(size);
/* need to consider alignment requirements ? */
if (likely(addr_merge)) {
/* Max page size allowed by both iova and paddr */
unsigned int align_pgsize_idx = __ffs(addr_merge);
pgsize_idx = min(pgsize_idx, align_pgsize_idx);
}
/* build a mask of acceptable page sizes */
pgsize = (1UL << (pgsize_idx + 1)) - 1;
/* throw away page sizes not supported by the hardware */
pgsize &= domain->ops->pgsize_bitmap;
/* make sure we're still sane */
BUG_ON(!pgsize);
/* pick the biggest page */
pgsize_idx = __fls(pgsize);
pgsize = 1UL << pgsize_idx;
pr_debug("mapping: iova 0x%lx pa 0x%lx pgsize %lu\n", iova,
(unsigned long)paddr, pgsize);
ret = domain->ops->map(domain, iova, paddr, pgsize, prot);
if (ret)
break;
iova += pgsize;
paddr += pgsize;
size -= pgsize;
}
/* unroll mapping in case something went wrong */
if (ret)
iommu_unmap(domain, orig_iova, orig_size - size);
return ret;
}
EXPORT_SYMBOL_GPL(iommu_map);
size_t iommu_unmap(struct iommu_domain *domain, unsigned long iova, size_t size)
{
size_t unmapped_page, unmapped = 0;
unsigned int min_pagesz;
if (unlikely(domain->ops->unmap == NULL))
return -ENODEV;
/* find out the minimum page size supported */
min_pagesz = 1 << __ffs(domain->ops->pgsize_bitmap);
/*
* The virtual address, as well as the size of the mapping, must be
* aligned (at least) to the size of the smallest page supported
* by the hardware
*/
if (!IS_ALIGNED(iova | size, min_pagesz)) {
pr_err("unaligned: iova 0x%lx size 0x%lx min_pagesz 0x%x\n",
iova, (unsigned long)size, min_pagesz);
return -EINVAL;
}
pr_debug("unmap this: iova 0x%lx size 0x%lx\n", iova,
(unsigned long)size);
/*
* Keep iterating until we either unmap 'size' bytes (or more)
* or we hit an area that isn't mapped.
*/
while (unmapped < size) {
size_t left = size - unmapped;
unmapped_page = domain->ops->unmap(domain, iova, left);
if (!unmapped_page)
break;
pr_debug("unmapped: iova 0x%lx size %lx\n", iova,
(unsigned long)unmapped_page);
iova += unmapped_page;
unmapped += unmapped_page;
}
return unmapped;
}
EXPORT_SYMBOL_GPL(iommu_unmap);
int iommu_map_range(struct iommu_domain *domain, unsigned int iova,
struct scatterlist *sg, unsigned int len, int prot)
{
if (unlikely(domain->ops->map_range == NULL))
return -ENODEV;
BUG_ON(iova & (~PAGE_MASK));
return domain->ops->map_range(domain, iova, sg, len, prot);
}
EXPORT_SYMBOL_GPL(iommu_map_range);
int iommu_unmap_range(struct iommu_domain *domain, unsigned int iova,
unsigned int len)
{
if (unlikely(domain->ops->unmap_range == NULL))
return -ENODEV;
BUG_ON(iova & (~PAGE_MASK));
return domain->ops->unmap_range(domain, iova, len);
}
EXPORT_SYMBOL_GPL(iommu_unmap_range);
phys_addr_t iommu_get_pt_base_addr(struct iommu_domain *domain)
{
if (unlikely(domain->ops->get_pt_base_addr == NULL))
return 0;
return domain->ops->get_pt_base_addr(domain);
}
EXPORT_SYMBOL_GPL(iommu_get_pt_base_addr);
static int __init iommu_init(void)
{
iommu_group_kset = kset_create_and_add("iommu_groups",
NULL, kernel_kobj);
idr_init(&iommu_group_idr);
mutex_init(&iommu_group_mutex);
BUG_ON(!iommu_group_kset);
return 0;
}
subsys_initcall(iommu_init);
| gpl-2.0 |
tiagovignatti/drm-intel | drivers/usb/misc/emi26.c | 2155 | 7823 | /*
* Emagic EMI 2|6 usb audio interface firmware loader.
* Copyright (C) 2002
* Tapio Laxström (tapio.laxstrom@iptime.fi)
*
* 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.
*
* emi26.c,v 1.13 2002/03/08 13:10:26 tapio Exp
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/delay.h>
#include <linux/firmware.h>
#include <linux/ihex.h>
#define EMI26_VENDOR_ID 0x086a /* Emagic Soft-und Hardware GmBH */
#define EMI26_PRODUCT_ID 0x0100 /* EMI 2|6 without firmware */
#define EMI26B_PRODUCT_ID 0x0102 /* EMI 2|6 without firmware */
#define ANCHOR_LOAD_INTERNAL 0xA0 /* Vendor specific request code for Anchor Upload/Download (This one is implemented in the core) */
#define ANCHOR_LOAD_EXTERNAL 0xA3 /* This command is not implemented in the core. Requires firmware */
#define ANCHOR_LOAD_FPGA 0xA5 /* This command is not implemented in the core. Requires firmware. Emagic extension */
#define MAX_INTERNAL_ADDRESS 0x1B3F /* This is the highest internal RAM address for the AN2131Q */
#define CPUCS_REG 0x7F92 /* EZ-USB Control and Status Register. Bit 0 controls 8051 reset */
#define INTERNAL_RAM(address) (address <= MAX_INTERNAL_ADDRESS)
static int emi26_writememory( struct usb_device *dev, int address,
const unsigned char *data, int length,
__u8 bRequest);
static int emi26_set_reset(struct usb_device *dev, unsigned char reset_bit);
static int emi26_load_firmware (struct usb_device *dev);
static int emi26_probe(struct usb_interface *intf, const struct usb_device_id *id);
static void emi26_disconnect(struct usb_interface *intf);
/* thanks to drivers/usb/serial/keyspan_pda.c code */
static int emi26_writememory (struct usb_device *dev, int address,
const unsigned char *data, int length,
__u8 request)
{
int result;
unsigned char *buffer = kmemdup(data, length, GFP_KERNEL);
if (!buffer) {
dev_err(&dev->dev, "kmalloc(%d) failed.\n", length);
return -ENOMEM;
}
/* Note: usb_control_msg returns negative value on error or length of the
* data that was written! */
result = usb_control_msg (dev, usb_sndctrlpipe(dev, 0), request, 0x40, address, 0, buffer, length, 300);
kfree (buffer);
return result;
}
/* thanks to drivers/usb/serial/keyspan_pda.c code */
static int emi26_set_reset (struct usb_device *dev, unsigned char reset_bit)
{
int response;
dev_info(&dev->dev, "%s - %d\n", __func__, reset_bit);
/* printk(KERN_DEBUG "%s - %d", __func__, reset_bit); */
response = emi26_writememory (dev, CPUCS_REG, &reset_bit, 1, 0xa0);
if (response < 0) {
dev_err(&dev->dev, "set_reset (%d) failed\n", reset_bit);
}
return response;
}
#define FW_LOAD_SIZE 1023
static int emi26_load_firmware (struct usb_device *dev)
{
const struct firmware *loader_fw = NULL;
const struct firmware *bitstream_fw = NULL;
const struct firmware *firmware_fw = NULL;
const struct ihex_binrec *rec;
int err = -ENOMEM;
int i;
__u32 addr; /* Address to write */
__u8 *buf;
buf = kmalloc(FW_LOAD_SIZE, GFP_KERNEL);
if (!buf)
goto wraperr;
err = request_ihex_firmware(&loader_fw, "emi26/loader.fw", &dev->dev);
if (err)
goto nofw;
err = request_ihex_firmware(&bitstream_fw, "emi26/bitstream.fw",
&dev->dev);
if (err)
goto nofw;
err = request_ihex_firmware(&firmware_fw, "emi26/firmware.fw",
&dev->dev);
if (err) {
nofw:
dev_err(&dev->dev, "%s - request_firmware() failed\n",
__func__);
goto wraperr;
}
/* Assert reset (stop the CPU in the EMI) */
err = emi26_set_reset(dev,1);
if (err < 0)
goto wraperr;
rec = (const struct ihex_binrec *)loader_fw->data;
/* 1. We need to put the loader for the FPGA into the EZ-USB */
while (rec) {
err = emi26_writememory(dev, be32_to_cpu(rec->addr),
rec->data, be16_to_cpu(rec->len),
ANCHOR_LOAD_INTERNAL);
if (err < 0)
goto wraperr;
rec = ihex_next_binrec(rec);
}
/* De-assert reset (let the CPU run) */
err = emi26_set_reset(dev,0);
if (err < 0)
goto wraperr;
msleep(250); /* let device settle */
/* 2. We upload the FPGA firmware into the EMI
* Note: collect up to 1023 (yes!) bytes and send them with
* a single request. This is _much_ faster! */
rec = (const struct ihex_binrec *)bitstream_fw->data;
do {
i = 0;
addr = be32_to_cpu(rec->addr);
/* intel hex records are terminated with type 0 element */
while (rec && (i + be16_to_cpu(rec->len) < FW_LOAD_SIZE)) {
memcpy(buf + i, rec->data, be16_to_cpu(rec->len));
i += be16_to_cpu(rec->len);
rec = ihex_next_binrec(rec);
}
err = emi26_writememory(dev, addr, buf, i, ANCHOR_LOAD_FPGA);
if (err < 0)
goto wraperr;
} while (rec);
/* Assert reset (stop the CPU in the EMI) */
err = emi26_set_reset(dev,1);
if (err < 0)
goto wraperr;
/* 3. We need to put the loader for the firmware into the EZ-USB (again...) */
for (rec = (const struct ihex_binrec *)loader_fw->data;
rec; rec = ihex_next_binrec(rec)) {
err = emi26_writememory(dev, be32_to_cpu(rec->addr),
rec->data, be16_to_cpu(rec->len),
ANCHOR_LOAD_INTERNAL);
if (err < 0)
goto wraperr;
}
msleep(250); /* let device settle */
/* De-assert reset (let the CPU run) */
err = emi26_set_reset(dev,0);
if (err < 0)
goto wraperr;
/* 4. We put the part of the firmware that lies in the external RAM into the EZ-USB */
for (rec = (const struct ihex_binrec *)firmware_fw->data;
rec; rec = ihex_next_binrec(rec)) {
if (!INTERNAL_RAM(be32_to_cpu(rec->addr))) {
err = emi26_writememory(dev, be32_to_cpu(rec->addr),
rec->data, be16_to_cpu(rec->len),
ANCHOR_LOAD_EXTERNAL);
if (err < 0)
goto wraperr;
}
}
/* Assert reset (stop the CPU in the EMI) */
err = emi26_set_reset(dev,1);
if (err < 0)
goto wraperr;
for (rec = (const struct ihex_binrec *)firmware_fw->data;
rec; rec = ihex_next_binrec(rec)) {
if (INTERNAL_RAM(be32_to_cpu(rec->addr))) {
err = emi26_writememory(dev, be32_to_cpu(rec->addr),
rec->data, be16_to_cpu(rec->len),
ANCHOR_LOAD_INTERNAL);
if (err < 0)
goto wraperr;
}
}
/* De-assert reset (let the CPU run) */
err = emi26_set_reset(dev,0);
if (err < 0)
goto wraperr;
msleep(250); /* let device settle */
/* return 1 to fail the driver inialization
* and give real driver change to load */
err = 1;
wraperr:
if (err < 0)
dev_err(&dev->dev,"%s - error loading firmware: error = %d\n",
__func__, err);
release_firmware(loader_fw);
release_firmware(bitstream_fw);
release_firmware(firmware_fw);
kfree(buf);
return err;
}
static const struct usb_device_id id_table[] = {
{ USB_DEVICE(EMI26_VENDOR_ID, EMI26_PRODUCT_ID) },
{ USB_DEVICE(EMI26_VENDOR_ID, EMI26B_PRODUCT_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, id_table);
static int emi26_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(intf);
dev_info(&intf->dev, "%s start\n", __func__);
emi26_load_firmware(dev);
/* do not return the driver context, let real audio driver do that */
return -EIO;
}
static void emi26_disconnect(struct usb_interface *intf)
{
}
static struct usb_driver emi26_driver = {
.name = "emi26 - firmware loader",
.probe = emi26_probe,
.disconnect = emi26_disconnect,
.id_table = id_table,
};
module_usb_driver(emi26_driver);
MODULE_AUTHOR("Tapio Laxström");
MODULE_DESCRIPTION("Emagic EMI 2|6 firmware loader.");
MODULE_LICENSE("GPL");
MODULE_FIRMWARE("emi26/loader.fw");
MODULE_FIRMWARE("emi26/bitstream.fw");
MODULE_FIRMWARE("emi26/firmware.fw");
/* vi:ai:syntax=c:sw=8:ts=8:tw=80
*/
| gpl-2.0 |
NXTnet/android_kernel_samsung_msm8916-caf | drivers/hwmon/pc87427.c | 2155 | 40613 | /*
* pc87427.c - hardware monitoring driver for the
* National Semiconductor PC87427 Super-I/O chip
* Copyright (C) 2006, 2008, 2010 Jean Delvare <khali@linux-fr.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* 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.
*
* Supports the following chips:
*
* Chip #vin #fan #pwm #temp devid
* PC87427 - 8 4 6 0xF2
*
* This driver assumes that no more than one chip is present.
* Only fans are fully supported so far. Temperatures are in read-only
* mode, and voltages aren't supported at all.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/platform_device.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/sysfs.h>
#include <linux/ioport.h>
#include <linux/acpi.h>
#include <linux/io.h>
static unsigned short force_id;
module_param(force_id, ushort, 0);
MODULE_PARM_DESC(force_id, "Override the detected device ID");
static struct platform_device *pdev;
#define DRVNAME "pc87427"
/*
* The lock mutex protects both the I/O accesses (needed because the
* device is using banked registers) and the register cache (needed to keep
* the data in the registers and the cache in sync at any time).
*/
struct pc87427_data {
struct device *hwmon_dev;
struct mutex lock;
int address[2];
const char *name;
unsigned long last_updated; /* in jiffies */
u8 fan_enabled; /* bit vector */
u16 fan[8]; /* register values */
u16 fan_min[8]; /* register values */
u8 fan_status[8]; /* register values */
u8 pwm_enabled; /* bit vector */
u8 pwm_auto_ok; /* bit vector */
u8 pwm_enable[4]; /* register values */
u8 pwm[4]; /* register values */
u8 temp_enabled; /* bit vector */
s16 temp[6]; /* register values */
s8 temp_min[6]; /* register values */
s8 temp_max[6]; /* register values */
s8 temp_crit[6]; /* register values */
u8 temp_status[6]; /* register values */
u8 temp_type[6]; /* register values */
};
struct pc87427_sio_data {
unsigned short address[2];
u8 has_fanin;
u8 has_fanout;
};
/*
* Super-I/O registers and operations
*/
#define SIOREG_LDSEL 0x07 /* Logical device select */
#define SIOREG_DEVID 0x20 /* Device ID */
#define SIOREG_CF2 0x22 /* Configuration 2 */
#define SIOREG_CF3 0x23 /* Configuration 3 */
#define SIOREG_CF4 0x24 /* Configuration 4 */
#define SIOREG_CF5 0x25 /* Configuration 5 */
#define SIOREG_CFB 0x2B /* Configuration B */
#define SIOREG_CFC 0x2C /* Configuration C */
#define SIOREG_CFD 0x2D /* Configuration D */
#define SIOREG_ACT 0x30 /* Device activation */
#define SIOREG_MAP 0x50 /* I/O or memory mapping */
#define SIOREG_IOBASE 0x60 /* I/O base address */
static const u8 logdev[2] = { 0x09, 0x14 };
static const char *logdev_str[2] = { DRVNAME " FMC", DRVNAME " HMC" };
#define LD_FAN 0
#define LD_IN 1
#define LD_TEMP 1
static inline void superio_outb(int sioaddr, int reg, int val)
{
outb(reg, sioaddr);
outb(val, sioaddr + 1);
}
static inline int superio_inb(int sioaddr, int reg)
{
outb(reg, sioaddr);
return inb(sioaddr + 1);
}
static inline void superio_exit(int sioaddr)
{
outb(0x02, sioaddr);
outb(0x02, sioaddr + 1);
}
/*
* Logical devices
*/
#define REGION_LENGTH 32
#define PC87427_REG_BANK 0x0f
#define BANK_FM(nr) (nr)
#define BANK_FT(nr) (0x08 + (nr))
#define BANK_FC(nr) (0x10 + (nr) * 2)
#define BANK_TM(nr) (nr)
#define BANK_VM(nr) (0x08 + (nr))
/*
* I/O access functions
*/
/* ldi is the logical device index */
static inline int pc87427_read8(struct pc87427_data *data, u8 ldi, u8 reg)
{
return inb(data->address[ldi] + reg);
}
/* Must be called with data->lock held, except during init */
static inline int pc87427_read8_bank(struct pc87427_data *data, u8 ldi,
u8 bank, u8 reg)
{
outb(bank, data->address[ldi] + PC87427_REG_BANK);
return inb(data->address[ldi] + reg);
}
/* Must be called with data->lock held, except during init */
static inline void pc87427_write8_bank(struct pc87427_data *data, u8 ldi,
u8 bank, u8 reg, u8 value)
{
outb(bank, data->address[ldi] + PC87427_REG_BANK);
outb(value, data->address[ldi] + reg);
}
/*
* Fan registers and conversions
*/
/* fan data registers are 16-bit wide */
#define PC87427_REG_FAN 0x12
#define PC87427_REG_FAN_MIN 0x14
#define PC87427_REG_FAN_STATUS 0x10
#define FAN_STATUS_STALL (1 << 3)
#define FAN_STATUS_LOSPD (1 << 1)
#define FAN_STATUS_MONEN (1 << 0)
/*
* Dedicated function to read all registers related to a given fan input.
* This saves us quite a few locks and bank selections.
* Must be called with data->lock held.
* nr is from 0 to 7
*/
static void pc87427_readall_fan(struct pc87427_data *data, u8 nr)
{
int iobase = data->address[LD_FAN];
outb(BANK_FM(nr), iobase + PC87427_REG_BANK);
data->fan[nr] = inw(iobase + PC87427_REG_FAN);
data->fan_min[nr] = inw(iobase + PC87427_REG_FAN_MIN);
data->fan_status[nr] = inb(iobase + PC87427_REG_FAN_STATUS);
/* Clear fan alarm bits */
outb(data->fan_status[nr], iobase + PC87427_REG_FAN_STATUS);
}
/*
* The 2 LSB of fan speed registers are used for something different.
* The actual 2 LSB of the measurements are not available.
*/
static inline unsigned long fan_from_reg(u16 reg)
{
reg &= 0xfffc;
if (reg == 0x0000 || reg == 0xfffc)
return 0;
return 5400000UL / reg;
}
/* The 2 LSB of the fan speed limit registers are not significant. */
static inline u16 fan_to_reg(unsigned long val)
{
if (val < 83UL)
return 0xffff;
if (val >= 1350000UL)
return 0x0004;
return ((1350000UL + val / 2) / val) << 2;
}
/*
* PWM registers and conversions
*/
#define PC87427_REG_PWM_ENABLE 0x10
#define PC87427_REG_PWM_DUTY 0x12
#define PWM_ENABLE_MODE_MASK (7 << 4)
#define PWM_ENABLE_CTLEN (1 << 0)
#define PWM_MODE_MANUAL (0 << 4)
#define PWM_MODE_AUTO (1 << 4)
#define PWM_MODE_OFF (2 << 4)
#define PWM_MODE_ON (7 << 4)
/*
* Dedicated function to read all registers related to a given PWM output.
* This saves us quite a few locks and bank selections.
* Must be called with data->lock held.
* nr is from 0 to 3
*/
static void pc87427_readall_pwm(struct pc87427_data *data, u8 nr)
{
int iobase = data->address[LD_FAN];
outb(BANK_FC(nr), iobase + PC87427_REG_BANK);
data->pwm_enable[nr] = inb(iobase + PC87427_REG_PWM_ENABLE);
data->pwm[nr] = inb(iobase + PC87427_REG_PWM_DUTY);
}
static inline int pwm_enable_from_reg(u8 reg)
{
switch (reg & PWM_ENABLE_MODE_MASK) {
case PWM_MODE_ON:
return 0;
case PWM_MODE_MANUAL:
case PWM_MODE_OFF:
return 1;
case PWM_MODE_AUTO:
return 2;
default:
return -EPROTO;
}
}
static inline u8 pwm_enable_to_reg(unsigned long val, u8 pwmval)
{
switch (val) {
default:
return PWM_MODE_ON;
case 1:
return pwmval ? PWM_MODE_MANUAL : PWM_MODE_OFF;
case 2:
return PWM_MODE_AUTO;
}
}
/*
* Temperature registers and conversions
*/
#define PC87427_REG_TEMP_STATUS 0x10
#define PC87427_REG_TEMP 0x14
#define PC87427_REG_TEMP_MAX 0x18
#define PC87427_REG_TEMP_MIN 0x19
#define PC87427_REG_TEMP_CRIT 0x1a
#define PC87427_REG_TEMP_TYPE 0x1d
#define TEMP_STATUS_CHANEN (1 << 0)
#define TEMP_STATUS_LOWFLG (1 << 1)
#define TEMP_STATUS_HIGHFLG (1 << 2)
#define TEMP_STATUS_CRITFLG (1 << 3)
#define TEMP_STATUS_SENSERR (1 << 5)
#define TEMP_TYPE_MASK (3 << 5)
#define TEMP_TYPE_THERMISTOR (1 << 5)
#define TEMP_TYPE_REMOTE_DIODE (2 << 5)
#define TEMP_TYPE_LOCAL_DIODE (3 << 5)
/*
* Dedicated function to read all registers related to a given temperature
* input. This saves us quite a few locks and bank selections.
* Must be called with data->lock held.
* nr is from 0 to 5
*/
static void pc87427_readall_temp(struct pc87427_data *data, u8 nr)
{
int iobase = data->address[LD_TEMP];
outb(BANK_TM(nr), iobase + PC87427_REG_BANK);
data->temp[nr] = le16_to_cpu(inw(iobase + PC87427_REG_TEMP));
data->temp_max[nr] = inb(iobase + PC87427_REG_TEMP_MAX);
data->temp_min[nr] = inb(iobase + PC87427_REG_TEMP_MIN);
data->temp_crit[nr] = inb(iobase + PC87427_REG_TEMP_CRIT);
data->temp_type[nr] = inb(iobase + PC87427_REG_TEMP_TYPE);
data->temp_status[nr] = inb(iobase + PC87427_REG_TEMP_STATUS);
/* Clear fan alarm bits */
outb(data->temp_status[nr], iobase + PC87427_REG_TEMP_STATUS);
}
static inline unsigned int temp_type_from_reg(u8 reg)
{
switch (reg & TEMP_TYPE_MASK) {
case TEMP_TYPE_THERMISTOR:
return 4;
case TEMP_TYPE_REMOTE_DIODE:
case TEMP_TYPE_LOCAL_DIODE:
return 3;
default:
return 0;
}
}
/*
* We assume 8-bit thermal sensors; 9-bit thermal sensors are possible
* too, but I have no idea how to figure out when they are used.
*/
static inline long temp_from_reg(s16 reg)
{
return reg * 1000 / 256;
}
static inline long temp_from_reg8(s8 reg)
{
return reg * 1000;
}
/*
* Data interface
*/
static struct pc87427_data *pc87427_update_device(struct device *dev)
{
struct pc87427_data *data = dev_get_drvdata(dev);
int i;
mutex_lock(&data->lock);
if (!time_after(jiffies, data->last_updated + HZ)
&& data->last_updated)
goto done;
/* Fans */
for (i = 0; i < 8; i++) {
if (!(data->fan_enabled & (1 << i)))
continue;
pc87427_readall_fan(data, i);
}
/* PWM outputs */
for (i = 0; i < 4; i++) {
if (!(data->pwm_enabled & (1 << i)))
continue;
pc87427_readall_pwm(data, i);
}
/* Temperature channels */
for (i = 0; i < 6; i++) {
if (!(data->temp_enabled & (1 << i)))
continue;
pc87427_readall_temp(data, i);
}
data->last_updated = jiffies;
done:
mutex_unlock(&data->lock);
return data;
}
static ssize_t show_fan_input(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%lu\n", fan_from_reg(data->fan[nr]));
}
static ssize_t show_fan_min(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%lu\n", fan_from_reg(data->fan_min[nr]));
}
static ssize_t show_fan_alarm(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%d\n", !!(data->fan_status[nr]
& FAN_STATUS_LOSPD));
}
static ssize_t show_fan_fault(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%d\n", !!(data->fan_status[nr]
& FAN_STATUS_STALL));
}
static ssize_t set_fan_min(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct pc87427_data *data = dev_get_drvdata(dev);
int nr = to_sensor_dev_attr(devattr)->index;
unsigned long val;
int iobase = data->address[LD_FAN];
if (kstrtoul(buf, 10, &val) < 0)
return -EINVAL;
mutex_lock(&data->lock);
outb(BANK_FM(nr), iobase + PC87427_REG_BANK);
/*
* The low speed limit registers are read-only while monitoring
* is enabled, so we have to disable monitoring, then change the
* limit, and finally enable monitoring again.
*/
outb(0, iobase + PC87427_REG_FAN_STATUS);
data->fan_min[nr] = fan_to_reg(val);
outw(data->fan_min[nr], iobase + PC87427_REG_FAN_MIN);
outb(FAN_STATUS_MONEN, iobase + PC87427_REG_FAN_STATUS);
mutex_unlock(&data->lock);
return count;
}
static SENSOR_DEVICE_ATTR(fan1_input, S_IRUGO, show_fan_input, NULL, 0);
static SENSOR_DEVICE_ATTR(fan2_input, S_IRUGO, show_fan_input, NULL, 1);
static SENSOR_DEVICE_ATTR(fan3_input, S_IRUGO, show_fan_input, NULL, 2);
static SENSOR_DEVICE_ATTR(fan4_input, S_IRUGO, show_fan_input, NULL, 3);
static SENSOR_DEVICE_ATTR(fan5_input, S_IRUGO, show_fan_input, NULL, 4);
static SENSOR_DEVICE_ATTR(fan6_input, S_IRUGO, show_fan_input, NULL, 5);
static SENSOR_DEVICE_ATTR(fan7_input, S_IRUGO, show_fan_input, NULL, 6);
static SENSOR_DEVICE_ATTR(fan8_input, S_IRUGO, show_fan_input, NULL, 7);
static SENSOR_DEVICE_ATTR(fan1_min, S_IWUSR | S_IRUGO,
show_fan_min, set_fan_min, 0);
static SENSOR_DEVICE_ATTR(fan2_min, S_IWUSR | S_IRUGO,
show_fan_min, set_fan_min, 1);
static SENSOR_DEVICE_ATTR(fan3_min, S_IWUSR | S_IRUGO,
show_fan_min, set_fan_min, 2);
static SENSOR_DEVICE_ATTR(fan4_min, S_IWUSR | S_IRUGO,
show_fan_min, set_fan_min, 3);
static SENSOR_DEVICE_ATTR(fan5_min, S_IWUSR | S_IRUGO,
show_fan_min, set_fan_min, 4);
static SENSOR_DEVICE_ATTR(fan6_min, S_IWUSR | S_IRUGO,
show_fan_min, set_fan_min, 5);
static SENSOR_DEVICE_ATTR(fan7_min, S_IWUSR | S_IRUGO,
show_fan_min, set_fan_min, 6);
static SENSOR_DEVICE_ATTR(fan8_min, S_IWUSR | S_IRUGO,
show_fan_min, set_fan_min, 7);
static SENSOR_DEVICE_ATTR(fan1_alarm, S_IRUGO, show_fan_alarm, NULL, 0);
static SENSOR_DEVICE_ATTR(fan2_alarm, S_IRUGO, show_fan_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(fan3_alarm, S_IRUGO, show_fan_alarm, NULL, 2);
static SENSOR_DEVICE_ATTR(fan4_alarm, S_IRUGO, show_fan_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(fan5_alarm, S_IRUGO, show_fan_alarm, NULL, 4);
static SENSOR_DEVICE_ATTR(fan6_alarm, S_IRUGO, show_fan_alarm, NULL, 5);
static SENSOR_DEVICE_ATTR(fan7_alarm, S_IRUGO, show_fan_alarm, NULL, 6);
static SENSOR_DEVICE_ATTR(fan8_alarm, S_IRUGO, show_fan_alarm, NULL, 7);
static SENSOR_DEVICE_ATTR(fan1_fault, S_IRUGO, show_fan_fault, NULL, 0);
static SENSOR_DEVICE_ATTR(fan2_fault, S_IRUGO, show_fan_fault, NULL, 1);
static SENSOR_DEVICE_ATTR(fan3_fault, S_IRUGO, show_fan_fault, NULL, 2);
static SENSOR_DEVICE_ATTR(fan4_fault, S_IRUGO, show_fan_fault, NULL, 3);
static SENSOR_DEVICE_ATTR(fan5_fault, S_IRUGO, show_fan_fault, NULL, 4);
static SENSOR_DEVICE_ATTR(fan6_fault, S_IRUGO, show_fan_fault, NULL, 5);
static SENSOR_DEVICE_ATTR(fan7_fault, S_IRUGO, show_fan_fault, NULL, 6);
static SENSOR_DEVICE_ATTR(fan8_fault, S_IRUGO, show_fan_fault, NULL, 7);
static struct attribute *pc87427_attributes_fan[8][5] = {
{
&sensor_dev_attr_fan1_input.dev_attr.attr,
&sensor_dev_attr_fan1_min.dev_attr.attr,
&sensor_dev_attr_fan1_alarm.dev_attr.attr,
&sensor_dev_attr_fan1_fault.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_fan2_input.dev_attr.attr,
&sensor_dev_attr_fan2_min.dev_attr.attr,
&sensor_dev_attr_fan2_alarm.dev_attr.attr,
&sensor_dev_attr_fan2_fault.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_fan3_input.dev_attr.attr,
&sensor_dev_attr_fan3_min.dev_attr.attr,
&sensor_dev_attr_fan3_alarm.dev_attr.attr,
&sensor_dev_attr_fan3_fault.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_fan4_input.dev_attr.attr,
&sensor_dev_attr_fan4_min.dev_attr.attr,
&sensor_dev_attr_fan4_alarm.dev_attr.attr,
&sensor_dev_attr_fan4_fault.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_fan5_input.dev_attr.attr,
&sensor_dev_attr_fan5_min.dev_attr.attr,
&sensor_dev_attr_fan5_alarm.dev_attr.attr,
&sensor_dev_attr_fan5_fault.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_fan6_input.dev_attr.attr,
&sensor_dev_attr_fan6_min.dev_attr.attr,
&sensor_dev_attr_fan6_alarm.dev_attr.attr,
&sensor_dev_attr_fan6_fault.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_fan7_input.dev_attr.attr,
&sensor_dev_attr_fan7_min.dev_attr.attr,
&sensor_dev_attr_fan7_alarm.dev_attr.attr,
&sensor_dev_attr_fan7_fault.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_fan8_input.dev_attr.attr,
&sensor_dev_attr_fan8_min.dev_attr.attr,
&sensor_dev_attr_fan8_alarm.dev_attr.attr,
&sensor_dev_attr_fan8_fault.dev_attr.attr,
NULL
}
};
static const struct attribute_group pc87427_group_fan[8] = {
{ .attrs = pc87427_attributes_fan[0] },
{ .attrs = pc87427_attributes_fan[1] },
{ .attrs = pc87427_attributes_fan[2] },
{ .attrs = pc87427_attributes_fan[3] },
{ .attrs = pc87427_attributes_fan[4] },
{ .attrs = pc87427_attributes_fan[5] },
{ .attrs = pc87427_attributes_fan[6] },
{ .attrs = pc87427_attributes_fan[7] },
};
/*
* Must be called with data->lock held and pc87427_readall_pwm() freshly
* called
*/
static void update_pwm_enable(struct pc87427_data *data, int nr, u8 mode)
{
int iobase = data->address[LD_FAN];
data->pwm_enable[nr] &= ~PWM_ENABLE_MODE_MASK;
data->pwm_enable[nr] |= mode;
outb(data->pwm_enable[nr], iobase + PC87427_REG_PWM_ENABLE);
}
static ssize_t show_pwm_enable(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
int pwm_enable;
pwm_enable = pwm_enable_from_reg(data->pwm_enable[nr]);
if (pwm_enable < 0)
return pwm_enable;
return sprintf(buf, "%d\n", pwm_enable);
}
static ssize_t set_pwm_enable(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct pc87427_data *data = dev_get_drvdata(dev);
int nr = to_sensor_dev_attr(devattr)->index;
unsigned long val;
if (kstrtoul(buf, 10, &val) < 0 || val > 2)
return -EINVAL;
/* Can't go to automatic mode if it isn't configured */
if (val == 2 && !(data->pwm_auto_ok & (1 << nr)))
return -EINVAL;
mutex_lock(&data->lock);
pc87427_readall_pwm(data, nr);
update_pwm_enable(data, nr, pwm_enable_to_reg(val, data->pwm[nr]));
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_pwm(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%d\n", (int)data->pwm[nr]);
}
static ssize_t set_pwm(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct pc87427_data *data = dev_get_drvdata(dev);
int nr = to_sensor_dev_attr(devattr)->index;
unsigned long val;
int iobase = data->address[LD_FAN];
u8 mode;
if (kstrtoul(buf, 10, &val) < 0 || val > 0xff)
return -EINVAL;
mutex_lock(&data->lock);
pc87427_readall_pwm(data, nr);
mode = data->pwm_enable[nr] & PWM_ENABLE_MODE_MASK;
if (mode != PWM_MODE_MANUAL && mode != PWM_MODE_OFF) {
dev_notice(dev,
"Can't set PWM%d duty cycle while not in manual mode\n",
nr + 1);
mutex_unlock(&data->lock);
return -EPERM;
}
/* We may have to change the mode */
if (mode == PWM_MODE_MANUAL && val == 0) {
/* Transition from Manual to Off */
update_pwm_enable(data, nr, PWM_MODE_OFF);
mode = PWM_MODE_OFF;
dev_dbg(dev, "Switching PWM%d from %s to %s\n", nr + 1,
"manual", "off");
} else if (mode == PWM_MODE_OFF && val != 0) {
/* Transition from Off to Manual */
update_pwm_enable(data, nr, PWM_MODE_MANUAL);
mode = PWM_MODE_MANUAL;
dev_dbg(dev, "Switching PWM%d from %s to %s\n", nr + 1,
"off", "manual");
}
data->pwm[nr] = val;
if (mode == PWM_MODE_MANUAL)
outb(val, iobase + PC87427_REG_PWM_DUTY);
mutex_unlock(&data->lock);
return count;
}
static SENSOR_DEVICE_ATTR(pwm1_enable, S_IWUSR | S_IRUGO,
show_pwm_enable, set_pwm_enable, 0);
static SENSOR_DEVICE_ATTR(pwm2_enable, S_IWUSR | S_IRUGO,
show_pwm_enable, set_pwm_enable, 1);
static SENSOR_DEVICE_ATTR(pwm3_enable, S_IWUSR | S_IRUGO,
show_pwm_enable, set_pwm_enable, 2);
static SENSOR_DEVICE_ATTR(pwm4_enable, S_IWUSR | S_IRUGO,
show_pwm_enable, set_pwm_enable, 3);
static SENSOR_DEVICE_ATTR(pwm1, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 0);
static SENSOR_DEVICE_ATTR(pwm2, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 1);
static SENSOR_DEVICE_ATTR(pwm3, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 2);
static SENSOR_DEVICE_ATTR(pwm4, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 3);
static struct attribute *pc87427_attributes_pwm[4][3] = {
{
&sensor_dev_attr_pwm1_enable.dev_attr.attr,
&sensor_dev_attr_pwm1.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_pwm2_enable.dev_attr.attr,
&sensor_dev_attr_pwm2.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_pwm3_enable.dev_attr.attr,
&sensor_dev_attr_pwm3.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_pwm4_enable.dev_attr.attr,
&sensor_dev_attr_pwm4.dev_attr.attr,
NULL
}
};
static const struct attribute_group pc87427_group_pwm[4] = {
{ .attrs = pc87427_attributes_pwm[0] },
{ .attrs = pc87427_attributes_pwm[1] },
{ .attrs = pc87427_attributes_pwm[2] },
{ .attrs = pc87427_attributes_pwm[3] },
};
static ssize_t show_temp_input(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%ld\n", temp_from_reg(data->temp[nr]));
}
static ssize_t show_temp_min(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%ld\n", temp_from_reg8(data->temp_min[nr]));
}
static ssize_t show_temp_max(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%ld\n", temp_from_reg8(data->temp_max[nr]));
}
static ssize_t show_temp_crit(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%ld\n", temp_from_reg8(data->temp_crit[nr]));
}
static ssize_t show_temp_type(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%u\n", temp_type_from_reg(data->temp_type[nr]));
}
static ssize_t show_temp_min_alarm(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%d\n", !!(data->temp_status[nr]
& TEMP_STATUS_LOWFLG));
}
static ssize_t show_temp_max_alarm(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%d\n", !!(data->temp_status[nr]
& TEMP_STATUS_HIGHFLG));
}
static ssize_t show_temp_crit_alarm(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%d\n", !!(data->temp_status[nr]
& TEMP_STATUS_CRITFLG));
}
static ssize_t show_temp_fault(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = pc87427_update_device(dev);
int nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%d\n", !!(data->temp_status[nr]
& TEMP_STATUS_SENSERR));
}
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_temp_input, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_temp_input, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_input, S_IRUGO, show_temp_input, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_input, S_IRUGO, show_temp_input, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_input, S_IRUGO, show_temp_input, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_input, S_IRUGO, show_temp_input, NULL, 5);
static SENSOR_DEVICE_ATTR(temp1_min, S_IRUGO, show_temp_min, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_min, S_IRUGO, show_temp_min, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_min, S_IRUGO, show_temp_min, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_min, S_IRUGO, show_temp_min, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_min, S_IRUGO, show_temp_min, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_min, S_IRUGO, show_temp_min, NULL, 5);
static SENSOR_DEVICE_ATTR(temp1_max, S_IRUGO, show_temp_max, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_max, S_IRUGO, show_temp_max, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_max, S_IRUGO, show_temp_max, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_max, S_IRUGO, show_temp_max, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_max, S_IRUGO, show_temp_max, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_max, S_IRUGO, show_temp_max, NULL, 5);
static SENSOR_DEVICE_ATTR(temp1_crit, S_IRUGO, show_temp_crit, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_crit, S_IRUGO, show_temp_crit, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_crit, S_IRUGO, show_temp_crit, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_crit, S_IRUGO, show_temp_crit, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_crit, S_IRUGO, show_temp_crit, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_crit, S_IRUGO, show_temp_crit, NULL, 5);
static SENSOR_DEVICE_ATTR(temp1_type, S_IRUGO, show_temp_type, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_type, S_IRUGO, show_temp_type, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_type, S_IRUGO, show_temp_type, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_type, S_IRUGO, show_temp_type, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_type, S_IRUGO, show_temp_type, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_type, S_IRUGO, show_temp_type, NULL, 5);
static SENSOR_DEVICE_ATTR(temp1_min_alarm, S_IRUGO,
show_temp_min_alarm, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_min_alarm, S_IRUGO,
show_temp_min_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_min_alarm, S_IRUGO,
show_temp_min_alarm, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_min_alarm, S_IRUGO,
show_temp_min_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_min_alarm, S_IRUGO,
show_temp_min_alarm, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_min_alarm, S_IRUGO,
show_temp_min_alarm, NULL, 5);
static SENSOR_DEVICE_ATTR(temp1_max_alarm, S_IRUGO,
show_temp_max_alarm, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_max_alarm, S_IRUGO,
show_temp_max_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_max_alarm, S_IRUGO,
show_temp_max_alarm, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_max_alarm, S_IRUGO,
show_temp_max_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_max_alarm, S_IRUGO,
show_temp_max_alarm, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_max_alarm, S_IRUGO,
show_temp_max_alarm, NULL, 5);
static SENSOR_DEVICE_ATTR(temp1_crit_alarm, S_IRUGO,
show_temp_crit_alarm, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_crit_alarm, S_IRUGO,
show_temp_crit_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_crit_alarm, S_IRUGO,
show_temp_crit_alarm, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_crit_alarm, S_IRUGO,
show_temp_crit_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_crit_alarm, S_IRUGO,
show_temp_crit_alarm, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_crit_alarm, S_IRUGO,
show_temp_crit_alarm, NULL, 5);
static SENSOR_DEVICE_ATTR(temp1_fault, S_IRUGO, show_temp_fault, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_fault, S_IRUGO, show_temp_fault, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_fault, S_IRUGO, show_temp_fault, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_fault, S_IRUGO, show_temp_fault, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_fault, S_IRUGO, show_temp_fault, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_fault, S_IRUGO, show_temp_fault, NULL, 5);
static struct attribute *pc87427_attributes_temp[6][10] = {
{
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp1_min.dev_attr.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp1_crit.dev_attr.attr,
&sensor_dev_attr_temp1_type.dev_attr.attr,
&sensor_dev_attr_temp1_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_crit_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_fault.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp2_min.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp2_crit.dev_attr.attr,
&sensor_dev_attr_temp2_type.dev_attr.attr,
&sensor_dev_attr_temp2_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_crit_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_fault.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_temp3_input.dev_attr.attr,
&sensor_dev_attr_temp3_min.dev_attr.attr,
&sensor_dev_attr_temp3_max.dev_attr.attr,
&sensor_dev_attr_temp3_crit.dev_attr.attr,
&sensor_dev_attr_temp3_type.dev_attr.attr,
&sensor_dev_attr_temp3_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp3_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp3_crit_alarm.dev_attr.attr,
&sensor_dev_attr_temp3_fault.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_temp4_input.dev_attr.attr,
&sensor_dev_attr_temp4_min.dev_attr.attr,
&sensor_dev_attr_temp4_max.dev_attr.attr,
&sensor_dev_attr_temp4_crit.dev_attr.attr,
&sensor_dev_attr_temp4_type.dev_attr.attr,
&sensor_dev_attr_temp4_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp4_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp4_crit_alarm.dev_attr.attr,
&sensor_dev_attr_temp4_fault.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_temp5_input.dev_attr.attr,
&sensor_dev_attr_temp5_min.dev_attr.attr,
&sensor_dev_attr_temp5_max.dev_attr.attr,
&sensor_dev_attr_temp5_crit.dev_attr.attr,
&sensor_dev_attr_temp5_type.dev_attr.attr,
&sensor_dev_attr_temp5_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp5_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp5_crit_alarm.dev_attr.attr,
&sensor_dev_attr_temp5_fault.dev_attr.attr,
NULL
}, {
&sensor_dev_attr_temp6_input.dev_attr.attr,
&sensor_dev_attr_temp6_min.dev_attr.attr,
&sensor_dev_attr_temp6_max.dev_attr.attr,
&sensor_dev_attr_temp6_crit.dev_attr.attr,
&sensor_dev_attr_temp6_type.dev_attr.attr,
&sensor_dev_attr_temp6_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp6_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp6_crit_alarm.dev_attr.attr,
&sensor_dev_attr_temp6_fault.dev_attr.attr,
NULL
}
};
static const struct attribute_group pc87427_group_temp[6] = {
{ .attrs = pc87427_attributes_temp[0] },
{ .attrs = pc87427_attributes_temp[1] },
{ .attrs = pc87427_attributes_temp[2] },
{ .attrs = pc87427_attributes_temp[3] },
{ .attrs = pc87427_attributes_temp[4] },
{ .attrs = pc87427_attributes_temp[5] },
};
static ssize_t show_name(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct pc87427_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", data->name);
}
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
/*
* Device detection, attach and detach
*/
static int pc87427_request_regions(struct platform_device *pdev,
int count)
{
struct resource *res;
int i;
for (i = 0; i < count; i++) {
res = platform_get_resource(pdev, IORESOURCE_IO, i);
if (!res) {
dev_err(&pdev->dev, "Missing resource #%d\n", i);
return -ENOENT;
}
if (!devm_request_region(&pdev->dev, res->start,
resource_size(res), DRVNAME)) {
dev_err(&pdev->dev,
"Failed to request region 0x%lx-0x%lx\n",
(unsigned long)res->start,
(unsigned long)res->end);
return -EBUSY;
}
}
return 0;
}
static void pc87427_init_device(struct device *dev)
{
struct pc87427_sio_data *sio_data = dev->platform_data;
struct pc87427_data *data = dev_get_drvdata(dev);
int i;
u8 reg;
/* The FMC module should be ready */
reg = pc87427_read8(data, LD_FAN, PC87427_REG_BANK);
if (!(reg & 0x80))
dev_warn(dev, "%s module not ready!\n", "FMC");
/* Check which fans are enabled */
for (i = 0; i < 8; i++) {
if (!(sio_data->has_fanin & (1 << i))) /* Not wired */
continue;
reg = pc87427_read8_bank(data, LD_FAN, BANK_FM(i),
PC87427_REG_FAN_STATUS);
if (reg & FAN_STATUS_MONEN)
data->fan_enabled |= (1 << i);
}
if (!data->fan_enabled) {
dev_dbg(dev, "Enabling monitoring of all fans\n");
for (i = 0; i < 8; i++) {
if (!(sio_data->has_fanin & (1 << i))) /* Not wired */
continue;
pc87427_write8_bank(data, LD_FAN, BANK_FM(i),
PC87427_REG_FAN_STATUS,
FAN_STATUS_MONEN);
}
data->fan_enabled = sio_data->has_fanin;
}
/* Check which PWM outputs are enabled */
for (i = 0; i < 4; i++) {
if (!(sio_data->has_fanout & (1 << i))) /* Not wired */
continue;
reg = pc87427_read8_bank(data, LD_FAN, BANK_FC(i),
PC87427_REG_PWM_ENABLE);
if (reg & PWM_ENABLE_CTLEN)
data->pwm_enabled |= (1 << i);
/*
* We don't expose an interface to reconfigure the automatic
* fan control mode, so only allow to return to this mode if
* it was originally set.
*/
if ((reg & PWM_ENABLE_MODE_MASK) == PWM_MODE_AUTO) {
dev_dbg(dev, "PWM%d is in automatic control mode\n",
i + 1);
data->pwm_auto_ok |= (1 << i);
}
}
/* The HMC module should be ready */
reg = pc87427_read8(data, LD_TEMP, PC87427_REG_BANK);
if (!(reg & 0x80))
dev_warn(dev, "%s module not ready!\n", "HMC");
/* Check which temperature channels are enabled */
for (i = 0; i < 6; i++) {
reg = pc87427_read8_bank(data, LD_TEMP, BANK_TM(i),
PC87427_REG_TEMP_STATUS);
if (reg & TEMP_STATUS_CHANEN)
data->temp_enabled |= (1 << i);
}
}
static void pc87427_remove_files(struct device *dev)
{
struct pc87427_data *data = dev_get_drvdata(dev);
int i;
device_remove_file(dev, &dev_attr_name);
for (i = 0; i < 8; i++) {
if (!(data->fan_enabled & (1 << i)))
continue;
sysfs_remove_group(&dev->kobj, &pc87427_group_fan[i]);
}
for (i = 0; i < 4; i++) {
if (!(data->pwm_enabled & (1 << i)))
continue;
sysfs_remove_group(&dev->kobj, &pc87427_group_pwm[i]);
}
for (i = 0; i < 6; i++) {
if (!(data->temp_enabled & (1 << i)))
continue;
sysfs_remove_group(&dev->kobj, &pc87427_group_temp[i]);
}
}
static int pc87427_probe(struct platform_device *pdev)
{
struct pc87427_sio_data *sio_data = pdev->dev.platform_data;
struct pc87427_data *data;
int i, err, res_count;
data = devm_kzalloc(&pdev->dev, sizeof(struct pc87427_data),
GFP_KERNEL);
if (!data) {
pr_err("Out of memory\n");
return -ENOMEM;
}
data->address[0] = sio_data->address[0];
data->address[1] = sio_data->address[1];
res_count = (data->address[0] != 0) + (data->address[1] != 0);
err = pc87427_request_regions(pdev, res_count);
if (err)
return err;
mutex_init(&data->lock);
data->name = "pc87427";
platform_set_drvdata(pdev, data);
pc87427_init_device(&pdev->dev);
/* Register sysfs hooks */
err = device_create_file(&pdev->dev, &dev_attr_name);
if (err)
return err;
for (i = 0; i < 8; i++) {
if (!(data->fan_enabled & (1 << i)))
continue;
err = sysfs_create_group(&pdev->dev.kobj,
&pc87427_group_fan[i]);
if (err)
goto exit_remove_files;
}
for (i = 0; i < 4; i++) {
if (!(data->pwm_enabled & (1 << i)))
continue;
err = sysfs_create_group(&pdev->dev.kobj,
&pc87427_group_pwm[i]);
if (err)
goto exit_remove_files;
}
for (i = 0; i < 6; i++) {
if (!(data->temp_enabled & (1 << i)))
continue;
err = sysfs_create_group(&pdev->dev.kobj,
&pc87427_group_temp[i]);
if (err)
goto exit_remove_files;
}
data->hwmon_dev = hwmon_device_register(&pdev->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
dev_err(&pdev->dev, "Class registration failed (%d)\n", err);
goto exit_remove_files;
}
return 0;
exit_remove_files:
pc87427_remove_files(&pdev->dev);
return err;
}
static int pc87427_remove(struct platform_device *pdev)
{
struct pc87427_data *data = platform_get_drvdata(pdev);
hwmon_device_unregister(data->hwmon_dev);
pc87427_remove_files(&pdev->dev);
return 0;
}
static struct platform_driver pc87427_driver = {
.driver = {
.owner = THIS_MODULE,
.name = DRVNAME,
},
.probe = pc87427_probe,
.remove = pc87427_remove,
};
static int __init pc87427_device_add(const struct pc87427_sio_data *sio_data)
{
struct resource res[2] = {
{ .flags = IORESOURCE_IO },
{ .flags = IORESOURCE_IO },
};
int err, i, res_count;
res_count = 0;
for (i = 0; i < 2; i++) {
if (!sio_data->address[i])
continue;
res[res_count].start = sio_data->address[i];
res[res_count].end = sio_data->address[i] + REGION_LENGTH - 1;
res[res_count].name = logdev_str[i];
err = acpi_check_resource_conflict(&res[res_count]);
if (err)
goto exit;
res_count++;
}
pdev = platform_device_alloc(DRVNAME, res[0].start);
if (!pdev) {
err = -ENOMEM;
pr_err("Device allocation failed\n");
goto exit;
}
err = platform_device_add_resources(pdev, res, res_count);
if (err) {
pr_err("Device resource addition failed (%d)\n", err);
goto exit_device_put;
}
err = platform_device_add_data(pdev, sio_data,
sizeof(struct pc87427_sio_data));
if (err) {
pr_err("Platform data allocation failed\n");
goto exit_device_put;
}
err = platform_device_add(pdev);
if (err) {
pr_err("Device addition failed (%d)\n", err);
goto exit_device_put;
}
return 0;
exit_device_put:
platform_device_put(pdev);
exit:
return err;
}
static int __init pc87427_find(int sioaddr, struct pc87427_sio_data *sio_data)
{
u16 val;
u8 cfg, cfg_b;
int i, err = 0;
/* Identify device */
val = force_id ? force_id : superio_inb(sioaddr, SIOREG_DEVID);
if (val != 0xf2) { /* PC87427 */
err = -ENODEV;
goto exit;
}
for (i = 0; i < 2; i++) {
sio_data->address[i] = 0;
/* Select logical device */
superio_outb(sioaddr, SIOREG_LDSEL, logdev[i]);
val = superio_inb(sioaddr, SIOREG_ACT);
if (!(val & 0x01)) {
pr_info("Logical device 0x%02x not activated\n",
logdev[i]);
continue;
}
val = superio_inb(sioaddr, SIOREG_MAP);
if (val & 0x01) {
pr_warn("Logical device 0x%02x is memory-mapped, can't use\n",
logdev[i]);
continue;
}
val = (superio_inb(sioaddr, SIOREG_IOBASE) << 8)
| superio_inb(sioaddr, SIOREG_IOBASE + 1);
if (!val) {
pr_info("I/O base address not set for logical device 0x%02x\n",
logdev[i]);
continue;
}
sio_data->address[i] = val;
}
/* No point in loading the driver if everything is disabled */
if (!sio_data->address[0] && !sio_data->address[1]) {
err = -ENODEV;
goto exit;
}
/* Check which fan inputs are wired */
sio_data->has_fanin = (1 << 2) | (1 << 3); /* FANIN2, FANIN3 */
cfg = superio_inb(sioaddr, SIOREG_CF2);
if (!(cfg & (1 << 3)))
sio_data->has_fanin |= (1 << 0); /* FANIN0 */
if (!(cfg & (1 << 2)))
sio_data->has_fanin |= (1 << 4); /* FANIN4 */
cfg = superio_inb(sioaddr, SIOREG_CFD);
if (!(cfg & (1 << 0)))
sio_data->has_fanin |= (1 << 1); /* FANIN1 */
cfg = superio_inb(sioaddr, SIOREG_CF4);
if (!(cfg & (1 << 0)))
sio_data->has_fanin |= (1 << 7); /* FANIN7 */
cfg_b = superio_inb(sioaddr, SIOREG_CFB);
if (!(cfg & (1 << 1)) && (cfg_b & (1 << 3)))
sio_data->has_fanin |= (1 << 5); /* FANIN5 */
cfg = superio_inb(sioaddr, SIOREG_CF3);
if ((cfg & (1 << 3)) && !(cfg_b & (1 << 5)))
sio_data->has_fanin |= (1 << 6); /* FANIN6 */
/* Check which fan outputs are wired */
sio_data->has_fanout = (1 << 0); /* FANOUT0 */
if (cfg_b & (1 << 0))
sio_data->has_fanout |= (1 << 3); /* FANOUT3 */
cfg = superio_inb(sioaddr, SIOREG_CFC);
if (!(cfg & (1 << 4))) {
if (cfg_b & (1 << 1))
sio_data->has_fanout |= (1 << 1); /* FANOUT1 */
if (cfg_b & (1 << 2))
sio_data->has_fanout |= (1 << 2); /* FANOUT2 */
}
/* FANOUT1 and FANOUT2 can each be routed to 2 different pins */
cfg = superio_inb(sioaddr, SIOREG_CF5);
if (cfg & (1 << 6))
sio_data->has_fanout |= (1 << 1); /* FANOUT1 */
if (cfg & (1 << 5))
sio_data->has_fanout |= (1 << 2); /* FANOUT2 */
exit:
superio_exit(sioaddr);
return err;
}
static int __init pc87427_init(void)
{
int err;
struct pc87427_sio_data sio_data;
if (pc87427_find(0x2e, &sio_data)
&& pc87427_find(0x4e, &sio_data))
return -ENODEV;
err = platform_driver_register(&pc87427_driver);
if (err)
goto exit;
/* Sets global pdev as a side effect */
err = pc87427_device_add(&sio_data);
if (err)
goto exit_driver;
return 0;
exit_driver:
platform_driver_unregister(&pc87427_driver);
exit:
return err;
}
static void __exit pc87427_exit(void)
{
platform_device_unregister(pdev);
platform_driver_unregister(&pc87427_driver);
}
MODULE_AUTHOR("Jean Delvare <khali@linux-fr.org>");
MODULE_DESCRIPTION("PC87427 hardware monitoring driver");
MODULE_LICENSE("GPL");
module_init(pc87427_init);
module_exit(pc87427_exit);
| gpl-2.0 |
erikcas/kernel-tianchi | drivers/net/wireless/bcmdhd/siutils.c | 2155 | 56361 | /*
* Misc utility routines for accessing chip-specific features
* of the SiliconBackplane-based Broadcom chips.
*
* Copyright (C) 1999-2012, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
* $Id: siutils.c 328733 2012-04-20 14:49:55Z $
*/
#include <bcm_cfg.h>
#include <typedefs.h>
#include <bcmdefs.h>
#include <osl.h>
#include <bcmutils.h>
#include <siutils.h>
#include <bcmdevs.h>
#include <hndsoc.h>
#include <sbchipc.h>
#include <pcicfg.h>
#include <sbpcmcia.h>
#include <sbsocram.h>
#include <bcmsdh.h>
#include <sdio.h>
#include <sbsdio.h>
#include <sbhnddma.h>
#include <sbsdpcmdev.h>
#include <bcmsdpcm.h>
#include <hndpmu.h>
#include "siutils_priv.h"
/* local prototypes */
static si_info_t *si_doattach(si_info_t *sii, uint devid, osl_t *osh, void *regs,
uint bustype, void *sdh, char **vars, uint *varsz);
static bool si_buscore_prep(si_info_t *sii, uint bustype, uint devid, void *sdh);
static bool si_buscore_setup(si_info_t *sii, chipcregs_t *cc, uint bustype, uint32 savewin,
uint *origidx, void *regs);
/* global variable to indicate reservation/release of gpio's */
static uint32 si_gpioreservation = 0;
/* global flag to prevent shared resources from being initialized multiple times in si_attach() */
int do_4360_pcie2_war = 0;
/*
* Allocate a si handle.
* devid - pci device id (used to determine chip#)
* osh - opaque OS handle
* regs - virtual address of initial core registers
* bustype - pci/pcmcia/sb/sdio/etc
* vars - pointer to a pointer area for "environment" variables
* varsz - pointer to int to return the size of the vars
*/
si_t *
si_attach(uint devid, osl_t *osh, void *regs,
uint bustype, void *sdh, char **vars, uint *varsz)
{
si_info_t *sii;
/* alloc si_info_t */
if ((sii = MALLOC(osh, sizeof (si_info_t))) == NULL) {
SI_ERROR(("si_attach: malloc failed! malloced %d bytes\n", MALLOCED(osh)));
return (NULL);
}
if (si_doattach(sii, devid, osh, regs, bustype, sdh, vars, varsz) == NULL) {
MFREE(osh, sii, sizeof(si_info_t));
return (NULL);
}
sii->vars = vars ? *vars : NULL;
sii->varsz = varsz ? *varsz : 0;
return (si_t *)sii;
}
/* global kernel resource */
static si_info_t ksii;
static uint32 wd_msticks; /* watchdog timer ticks normalized to ms */
/* generic kernel variant of si_attach() */
si_t *
si_kattach(osl_t *osh)
{
static bool ksii_attached = FALSE;
if (!ksii_attached) {
void *regs;
regs = REG_MAP(SI_ENUM_BASE, SI_CORE_SIZE);
if (si_doattach(&ksii, BCM4710_DEVICE_ID, osh, regs,
SI_BUS, NULL,
osh != SI_OSH ? &ksii.vars : NULL,
osh != SI_OSH ? &ksii.varsz : NULL) == NULL) {
SI_ERROR(("si_kattach: si_doattach failed\n"));
REG_UNMAP(regs);
return NULL;
}
REG_UNMAP(regs);
/* save ticks normalized to ms for si_watchdog_ms() */
if (PMUCTL_ENAB(&ksii.pub)) {
/* based on 32KHz ILP clock */
wd_msticks = 32;
} else {
wd_msticks = ALP_CLOCK / 1000;
}
ksii_attached = TRUE;
SI_MSG(("si_kattach done. ccrev = %d, wd_msticks = %d\n",
ksii.pub.ccrev, wd_msticks));
}
return &ksii.pub;
}
static bool
si_buscore_prep(si_info_t *sii, uint bustype, uint devid, void *sdh)
{
/* need to set memseg flag for CF card first before any sb registers access */
if (BUSTYPE(bustype) == PCMCIA_BUS)
sii->memseg = TRUE;
if (BUSTYPE(bustype) == SDIO_BUS) {
int err;
uint8 clkset;
/* Try forcing SDIO core to do ALPAvail request only */
clkset = SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_ALP_AVAIL_REQ;
bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, clkset, &err);
if (!err) {
uint8 clkval;
/* If register supported, wait for ALPAvail and then force ALP */
clkval = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, NULL);
if ((clkval & ~SBSDIO_AVBITS) == clkset) {
SPINWAIT(((clkval = bcmsdh_cfg_read(sdh, SDIO_FUNC_1,
SBSDIO_FUNC1_CHIPCLKCSR, NULL)), !SBSDIO_ALPAV(clkval)),
PMU_MAX_TRANSITION_DLY);
if (!SBSDIO_ALPAV(clkval)) {
SI_ERROR(("timeout on ALPAV wait, clkval 0x%02x\n",
clkval));
return FALSE;
}
clkset = SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_FORCE_ALP;
bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR,
clkset, &err);
OSL_DELAY(65);
}
}
/* Also, disable the extra SDIO pull-ups */
bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SDIOPULLUP, 0, NULL);
}
return TRUE;
}
static bool
si_buscore_setup(si_info_t *sii, chipcregs_t *cc, uint bustype, uint32 savewin,
uint *origidx, void *regs)
{
bool pci, pcie, pcie_gen2 = FALSE;
uint i;
uint pciidx, pcieidx, pcirev, pcierev;
cc = si_setcoreidx(&sii->pub, SI_CC_IDX);
ASSERT((uintptr)cc);
/* get chipcommon rev */
sii->pub.ccrev = (int)si_corerev(&sii->pub);
/* get chipcommon chipstatus */
if (sii->pub.ccrev >= 11)
sii->pub.chipst = R_REG(sii->osh, &cc->chipstatus);
/* get chipcommon capabilites */
sii->pub.cccaps = R_REG(sii->osh, &cc->capabilities);
/* get chipcommon extended capabilities */
if (sii->pub.ccrev >= 35)
sii->pub.cccaps_ext = R_REG(sii->osh, &cc->capabilities_ext);
/* get pmu rev and caps */
if (sii->pub.cccaps & CC_CAP_PMU) {
sii->pub.pmucaps = R_REG(sii->osh, &cc->pmucapabilities);
sii->pub.pmurev = sii->pub.pmucaps & PCAP_REV_MASK;
}
SI_MSG(("Chipc: rev %d, caps 0x%x, chipst 0x%x pmurev %d, pmucaps 0x%x\n",
sii->pub.ccrev, sii->pub.cccaps, sii->pub.chipst, sii->pub.pmurev,
sii->pub.pmucaps));
/* figure out bus/orignal core idx */
sii->pub.buscoretype = NODEV_CORE_ID;
sii->pub.buscorerev = (uint)NOREV;
sii->pub.buscoreidx = BADIDX;
pci = pcie = FALSE;
pcirev = pcierev = (uint)NOREV;
pciidx = pcieidx = BADIDX;
for (i = 0; i < sii->numcores; i++) {
uint cid, crev;
si_setcoreidx(&sii->pub, i);
cid = si_coreid(&sii->pub);
crev = si_corerev(&sii->pub);
/* Display cores found */
SI_VMSG(("CORE[%d]: id 0x%x rev %d base 0x%x regs 0x%p\n",
i, cid, crev, sii->coresba[i], sii->regs[i]));
if (BUSTYPE(bustype) == PCI_BUS) {
if (cid == PCI_CORE_ID) {
pciidx = i;
pcirev = crev;
pci = TRUE;
} else if ((cid == PCIE_CORE_ID) || (cid == PCIE2_CORE_ID)) {
pcieidx = i;
pcierev = crev;
pcie = TRUE;
if (cid == PCIE2_CORE_ID)
pcie_gen2 = TRUE;
}
} else if ((BUSTYPE(bustype) == PCMCIA_BUS) &&
(cid == PCMCIA_CORE_ID)) {
sii->pub.buscorerev = crev;
sii->pub.buscoretype = cid;
sii->pub.buscoreidx = i;
}
else if (((BUSTYPE(bustype) == SDIO_BUS) ||
(BUSTYPE(bustype) == SPI_BUS)) &&
((cid == PCMCIA_CORE_ID) ||
(cid == SDIOD_CORE_ID))) {
sii->pub.buscorerev = crev;
sii->pub.buscoretype = cid;
sii->pub.buscoreidx = i;
}
/* find the core idx before entering this func. */
if ((savewin && (savewin == sii->coresba[i])) ||
(regs == sii->regs[i]))
*origidx = i;
}
if (pci) {
sii->pub.buscoretype = PCI_CORE_ID;
sii->pub.buscorerev = pcirev;
sii->pub.buscoreidx = pciidx;
} else if (pcie) {
if (pcie_gen2)
sii->pub.buscoretype = PCIE2_CORE_ID;
else
sii->pub.buscoretype = PCIE_CORE_ID;
sii->pub.buscorerev = pcierev;
sii->pub.buscoreidx = pcieidx;
}
SI_VMSG(("Buscore id/type/rev %d/0x%x/%d\n", sii->pub.buscoreidx, sii->pub.buscoretype,
sii->pub.buscorerev));
if (BUSTYPE(sii->pub.bustype) == SI_BUS && (CHIPID(sii->pub.chip) == BCM4712_CHIP_ID) &&
(sii->pub.chippkg != BCM4712LARGE_PKG_ID) && (CHIPREV(sii->pub.chiprev) <= 3))
OR_REG(sii->osh, &cc->slow_clk_ctl, SCC_SS_XTAL);
/* Make sure any on-chip ARM is off (in case strapping is wrong), or downloaded code was
* already running.
*/
if ((BUSTYPE(bustype) == SDIO_BUS) || (BUSTYPE(bustype) == SPI_BUS)) {
if (si_setcore(&sii->pub, ARM7S_CORE_ID, 0) ||
si_setcore(&sii->pub, ARMCM3_CORE_ID, 0))
si_core_disable(&sii->pub, 0);
}
/* return to the original core */
si_setcoreidx(&sii->pub, *origidx);
return TRUE;
}
static si_info_t *
si_doattach(si_info_t *sii, uint devid, osl_t *osh, void *regs,
uint bustype, void *sdh, char **vars, uint *varsz)
{
struct si_pub *sih = &sii->pub;
uint32 w, savewin;
chipcregs_t *cc;
char *pvars = NULL;
uint origidx;
ASSERT(GOODREGS(regs));
bzero((uchar*)sii, sizeof(si_info_t));
savewin = 0;
sih->buscoreidx = BADIDX;
sii->curmap = regs;
sii->sdh = sdh;
sii->osh = osh;
/* find Chipcommon address */
if (bustype == PCI_BUS) {
savewin = OSL_PCI_READ_CONFIG(sii->osh, PCI_BAR0_WIN, sizeof(uint32));
if (!GOODCOREADDR(savewin, SI_ENUM_BASE))
savewin = SI_ENUM_BASE;
OSL_PCI_WRITE_CONFIG(sii->osh, PCI_BAR0_WIN, 4, SI_ENUM_BASE);
if (!regs)
return NULL;
cc = (chipcregs_t *)regs;
} else if ((bustype == SDIO_BUS) || (bustype == SPI_BUS)) {
cc = (chipcregs_t *)sii->curmap;
} else {
cc = (chipcregs_t *)REG_MAP(SI_ENUM_BASE, SI_CORE_SIZE);
}
sih->bustype = bustype;
if (bustype != BUSTYPE(bustype)) {
SI_ERROR(("si_doattach: bus type %d does not match configured bus type %d\n",
bustype, BUSTYPE(bustype)));
return NULL;
}
/* bus/core/clk setup for register access */
if (!si_buscore_prep(sii, bustype, devid, sdh)) {
SI_ERROR(("si_doattach: si_core_clk_prep failed %d\n", bustype));
return NULL;
}
/* ChipID recognition.
* We assume we can read chipid at offset 0 from the regs arg.
* If we add other chiptypes (or if we need to support old sdio hosts w/o chipcommon),
* some way of recognizing them needs to be added here.
*/
if (!cc) {
SI_ERROR(("%s: chipcommon register space is null \n", __FUNCTION__));
return NULL;
}
w = R_REG(osh, &cc->chipid);
sih->socitype = (w & CID_TYPE_MASK) >> CID_TYPE_SHIFT;
/* Might as wll fill in chip id rev & pkg */
sih->chip = w & CID_ID_MASK;
sih->chiprev = (w & CID_REV_MASK) >> CID_REV_SHIFT;
sih->chippkg = (w & CID_PKG_MASK) >> CID_PKG_SHIFT;
if ((CHIPID(sih->chip) == BCM4329_CHIP_ID) && (sih->chiprev == 0) &&
(sih->chippkg != BCM4329_289PIN_PKG_ID)) {
sih->chippkg = BCM4329_182PIN_PKG_ID;
}
sih->issim = IS_SIM(sih->chippkg);
/* scan for cores */
if (CHIPTYPE(sii->pub.socitype) == SOCI_SB) {
SI_MSG(("Found chip type SB (0x%08x)\n", w));
sb_scan(&sii->pub, regs, devid);
} else if (CHIPTYPE(sii->pub.socitype) == SOCI_AI) {
SI_MSG(("Found chip type AI (0x%08x)\n", w));
/* pass chipc address instead of original core base */
ai_scan(&sii->pub, (void *)(uintptr)cc, devid);
} else if (CHIPTYPE(sii->pub.socitype) == SOCI_UBUS) {
SI_MSG(("Found chip type UBUS (0x%08x), chip id = 0x%4x\n", w, sih->chip));
/* pass chipc address instead of original core base */
ub_scan(&sii->pub, (void *)(uintptr)cc, devid);
} else {
SI_ERROR(("Found chip of unknown type (0x%08x)\n", w));
return NULL;
}
/* no cores found, bail out */
if (sii->numcores == 0) {
SI_ERROR(("si_doattach: could not find any cores\n"));
return NULL;
}
/* bus/core/clk setup */
origidx = SI_CC_IDX;
if (!si_buscore_setup(sii, cc, bustype, savewin, &origidx, regs)) {
SI_ERROR(("si_doattach: si_buscore_setup failed\n"));
goto exit;
}
if (CHIPID(sih->chip) == BCM4322_CHIP_ID && (((sih->chipst & CST4322_SPROM_OTP_SEL_MASK)
>> CST4322_SPROM_OTP_SEL_SHIFT) == (CST4322_OTP_PRESENT |
CST4322_SPROM_PRESENT))) {
SI_ERROR(("%s: Invalid setting: both SPROM and OTP strapped.\n", __FUNCTION__));
return NULL;
}
/* assume current core is CC */
if ((sii->pub.ccrev == 0x25) && ((CHIPID(sih->chip) == BCM43236_CHIP_ID ||
CHIPID(sih->chip) == BCM43235_CHIP_ID ||
CHIPID(sih->chip) == BCM43234_CHIP_ID ||
CHIPID(sih->chip) == BCM43238_CHIP_ID) &&
(CHIPREV(sii->pub.chiprev) <= 2))) {
if ((cc->chipstatus & CST43236_BP_CLK) != 0) {
uint clkdiv;
clkdiv = R_REG(osh, &cc->clkdiv);
/* otp_clk_div is even number, 120/14 < 9mhz */
clkdiv = (clkdiv & ~CLKD_OTP) | (14 << CLKD_OTP_SHIFT);
W_REG(osh, &cc->clkdiv, clkdiv);
SI_ERROR(("%s: set clkdiv to %x\n", __FUNCTION__, clkdiv));
}
OSL_DELAY(10);
}
if (bustype == PCI_BUS) {
}
pvars = NULL;
BCM_REFERENCE(pvars);
if (sii->pub.ccrev >= 20) {
uint32 gpiopullup = 0, gpiopulldown = 0;
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
ASSERT(cc != NULL);
/* 4314/43142 has pin muxing, don't clear gpio bits */
if ((CHIPID(sih->chip) == BCM4314_CHIP_ID) ||
(CHIPID(sih->chip) == BCM43142_CHIP_ID)) {
gpiopullup |= 0x402e0;
gpiopulldown |= 0x20500;
}
W_REG(osh, &cc->gpiopullup, gpiopullup);
W_REG(osh, &cc->gpiopulldown, gpiopulldown);
si_setcoreidx(sih, origidx);
}
/* clear any previous epidiag-induced target abort */
ASSERT(!si_taclear(sih, FALSE));
return (sii);
exit:
return NULL;
}
/* may be called with core in reset */
void
si_detach(si_t *sih)
{
si_info_t *sii;
uint idx;
sii = SI_INFO(sih);
if (sii == NULL)
return;
if (BUSTYPE(sih->bustype) == SI_BUS)
for (idx = 0; idx < SI_MAXCORES; idx++)
if (sii->regs[idx]) {
REG_UNMAP(sii->regs[idx]);
sii->regs[idx] = NULL;
}
#if !defined(BCMBUSTYPE) || (BCMBUSTYPE == SI_BUS)
if (sii != &ksii)
#endif /* !BCMBUSTYPE || (BCMBUSTYPE == SI_BUS) */
MFREE(sii->osh, sii, sizeof(si_info_t));
}
void *
si_osh(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
return sii->osh;
}
void
si_setosh(si_t *sih, osl_t *osh)
{
si_info_t *sii;
sii = SI_INFO(sih);
if (sii->osh != NULL) {
SI_ERROR(("osh is already set....\n"));
ASSERT(!sii->osh);
}
sii->osh = osh;
}
/* register driver interrupt disabling and restoring callback functions */
void
si_register_intr_callback(si_t *sih, void *intrsoff_fn, void *intrsrestore_fn,
void *intrsenabled_fn, void *intr_arg)
{
si_info_t *sii;
sii = SI_INFO(sih);
sii->intr_arg = intr_arg;
sii->intrsoff_fn = (si_intrsoff_t)intrsoff_fn;
sii->intrsrestore_fn = (si_intrsrestore_t)intrsrestore_fn;
sii->intrsenabled_fn = (si_intrsenabled_t)intrsenabled_fn;
/* save current core id. when this function called, the current core
* must be the core which provides driver functions(il, et, wl, etc.)
*/
sii->dev_coreid = sii->coreid[sii->curidx];
}
void
si_deregister_intr_callback(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
sii->intrsoff_fn = NULL;
}
uint
si_intflag(si_t *sih)
{
si_info_t *sii = SI_INFO(sih);
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_intflag(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return R_REG(sii->osh, ((uint32 *)(uintptr)
(sii->oob_router + OOB_STATUSA)));
else {
ASSERT(0);
return 0;
}
}
uint
si_flag(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_flag(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_flag(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
return ub_flag(sih);
else {
ASSERT(0);
return 0;
}
}
void
si_setint(si_t *sih, int siflag)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_setint(sih, siflag);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
ai_setint(sih, siflag);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
ub_setint(sih, siflag);
else
ASSERT(0);
}
uint
si_coreid(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
return sii->coreid[sii->curidx];
}
uint
si_coreidx(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
return sii->curidx;
}
/* return the core-type instantiation # of the current core */
uint
si_coreunit(si_t *sih)
{
si_info_t *sii;
uint idx;
uint coreid;
uint coreunit;
uint i;
sii = SI_INFO(sih);
coreunit = 0;
idx = sii->curidx;
ASSERT(GOODREGS(sii->curmap));
coreid = si_coreid(sih);
/* count the cores of our type */
for (i = 0; i < idx; i++)
if (sii->coreid[i] == coreid)
coreunit++;
return (coreunit);
}
uint
si_corevendor(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_corevendor(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_corevendor(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
return ub_corevendor(sih);
else {
ASSERT(0);
return 0;
}
}
bool
si_backplane64(si_t *sih)
{
return ((sih->cccaps & CC_CAP_BKPLN64) != 0);
}
uint
si_corerev(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_corerev(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_corerev(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
return ub_corerev(sih);
else {
ASSERT(0);
return 0;
}
}
/* return index of coreid or BADIDX if not found */
uint
si_findcoreidx(si_t *sih, uint coreid, uint coreunit)
{
si_info_t *sii;
uint found;
uint i;
sii = SI_INFO(sih);
found = 0;
for (i = 0; i < sii->numcores; i++)
if (sii->coreid[i] == coreid) {
if (found == coreunit)
return (i);
found++;
}
return (BADIDX);
}
/* return list of found cores */
uint
si_corelist(si_t *sih, uint coreid[])
{
si_info_t *sii;
sii = SI_INFO(sih);
bcopy((uchar*)sii->coreid, (uchar*)coreid, (sii->numcores * sizeof(uint)));
return (sii->numcores);
}
/* return current register mapping */
void *
si_coreregs(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
ASSERT(GOODREGS(sii->curmap));
return (sii->curmap);
}
/*
* This function changes logical "focus" to the indicated core;
* must be called with interrupts off.
* Moreover, callers should keep interrupts off during switching out of and back to d11 core
*/
void *
si_setcore(si_t *sih, uint coreid, uint coreunit)
{
uint idx;
idx = si_findcoreidx(sih, coreid, coreunit);
if (!GOODIDX(idx))
return (NULL);
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_setcoreidx(sih, idx);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_setcoreidx(sih, idx);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
return ub_setcoreidx(sih, idx);
else {
ASSERT(0);
return NULL;
}
}
void *
si_setcoreidx(si_t *sih, uint coreidx)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_setcoreidx(sih, coreidx);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_setcoreidx(sih, coreidx);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
return ub_setcoreidx(sih, coreidx);
else {
ASSERT(0);
return NULL;
}
}
/* Turn off interrupt as required by sb_setcore, before switch core */
void *
si_switch_core(si_t *sih, uint coreid, uint *origidx, uint *intr_val)
{
void *cc;
si_info_t *sii;
sii = SI_INFO(sih);
if (SI_FAST(sii)) {
/* Overloading the origidx variable to remember the coreid,
* this works because the core ids cannot be confused with
* core indices.
*/
*origidx = coreid;
if (coreid == CC_CORE_ID)
return (void *)CCREGS_FAST(sii);
else if (coreid == sih->buscoretype)
return (void *)PCIEREGS(sii);
}
INTR_OFF(sii, *intr_val);
*origidx = sii->curidx;
cc = si_setcore(sih, coreid, 0);
ASSERT(cc != NULL);
return cc;
}
/* restore coreidx and restore interrupt */
void
si_restore_core(si_t *sih, uint coreid, uint intr_val)
{
si_info_t *sii;
sii = SI_INFO(sih);
if (SI_FAST(sii) && ((coreid == CC_CORE_ID) || (coreid == sih->buscoretype)))
return;
si_setcoreidx(sih, coreid);
INTR_RESTORE(sii, intr_val);
}
int
si_numaddrspaces(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_numaddrspaces(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_numaddrspaces(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
return ub_numaddrspaces(sih);
else {
ASSERT(0);
return 0;
}
}
uint32
si_addrspace(si_t *sih, uint asidx)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_addrspace(sih, asidx);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_addrspace(sih, asidx);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
return ub_addrspace(sih, asidx);
else {
ASSERT(0);
return 0;
}
}
uint32
si_addrspacesize(si_t *sih, uint asidx)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_addrspacesize(sih, asidx);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_addrspacesize(sih, asidx);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
return ub_addrspacesize(sih, asidx);
else {
ASSERT(0);
return 0;
}
}
void
si_coreaddrspaceX(si_t *sih, uint asidx, uint32 *addr, uint32 *size)
{
/* Only supported for SOCI_AI */
if (CHIPTYPE(sih->socitype) == SOCI_AI)
ai_coreaddrspaceX(sih, asidx, addr, size);
else
*size = 0;
}
uint32
si_core_cflags(si_t *sih, uint32 mask, uint32 val)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_core_cflags(sih, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_core_cflags(sih, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
return ub_core_cflags(sih, mask, val);
else {
ASSERT(0);
return 0;
}
}
void
si_core_cflags_wo(si_t *sih, uint32 mask, uint32 val)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_core_cflags_wo(sih, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
ai_core_cflags_wo(sih, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
ub_core_cflags_wo(sih, mask, val);
else
ASSERT(0);
}
uint32
si_core_sflags(si_t *sih, uint32 mask, uint32 val)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_core_sflags(sih, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_core_sflags(sih, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
return ub_core_sflags(sih, mask, val);
else {
ASSERT(0);
return 0;
}
}
bool
si_iscoreup(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_iscoreup(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_iscoreup(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
return ub_iscoreup(sih);
else {
ASSERT(0);
return FALSE;
}
}
uint
si_wrapperreg(si_t *sih, uint32 offset, uint32 mask, uint32 val)
{
/* only for AI back plane chips */
if (CHIPTYPE(sih->socitype) == SOCI_AI)
return (ai_wrap_reg(sih, offset, mask, val));
return 0;
}
uint
si_corereg(si_t *sih, uint coreidx, uint regoff, uint mask, uint val)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_corereg(sih, coreidx, regoff, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_corereg(sih, coreidx, regoff, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
return ub_corereg(sih, coreidx, regoff, mask, val);
else {
ASSERT(0);
return 0;
}
}
void
si_core_disable(si_t *sih, uint32 bits)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_core_disable(sih, bits);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
ai_core_disable(sih, bits);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
ub_core_disable(sih, bits);
}
void
si_core_reset(si_t *sih, uint32 bits, uint32 resetbits)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_core_reset(sih, bits, resetbits);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
ai_core_reset(sih, bits, resetbits);
else if (CHIPTYPE(sih->socitype) == SOCI_UBUS)
ub_core_reset(sih, bits, resetbits);
}
/* Run bist on current core. Caller needs to take care of core-specific bist hazards */
int
si_corebist(si_t *sih)
{
uint32 cflags;
int result = 0;
/* Read core control flags */
cflags = si_core_cflags(sih, 0, 0);
/* Set bist & fgc */
si_core_cflags(sih, ~0, (SICF_BIST_EN | SICF_FGC));
/* Wait for bist done */
SPINWAIT(((si_core_sflags(sih, 0, 0) & SISF_BIST_DONE) == 0), 100000);
if (si_core_sflags(sih, 0, 0) & SISF_BIST_ERROR)
result = BCME_ERROR;
/* Reset core control flags */
si_core_cflags(sih, 0xffff, cflags);
return result;
}
static uint32
factor6(uint32 x)
{
switch (x) {
case CC_F6_2: return 2;
case CC_F6_3: return 3;
case CC_F6_4: return 4;
case CC_F6_5: return 5;
case CC_F6_6: return 6;
case CC_F6_7: return 7;
default: return 0;
}
}
/* calculate the speed the SI would run at given a set of clockcontrol values */
uint32
si_clock_rate(uint32 pll_type, uint32 n, uint32 m)
{
uint32 n1, n2, clock, m1, m2, m3, mc;
n1 = n & CN_N1_MASK;
n2 = (n & CN_N2_MASK) >> CN_N2_SHIFT;
if (pll_type == PLL_TYPE6) {
if (m & CC_T6_MMASK)
return CC_T6_M1;
else
return CC_T6_M0;
} else if ((pll_type == PLL_TYPE1) ||
(pll_type == PLL_TYPE3) ||
(pll_type == PLL_TYPE4) ||
(pll_type == PLL_TYPE7)) {
n1 = factor6(n1);
n2 += CC_F5_BIAS;
} else if (pll_type == PLL_TYPE2) {
n1 += CC_T2_BIAS;
n2 += CC_T2_BIAS;
ASSERT((n1 >= 2) && (n1 <= 7));
ASSERT((n2 >= 5) && (n2 <= 23));
} else if (pll_type == PLL_TYPE5) {
return (100000000);
} else
ASSERT(0);
/* PLL types 3 and 7 use BASE2 (25Mhz) */
if ((pll_type == PLL_TYPE3) ||
(pll_type == PLL_TYPE7)) {
clock = CC_CLOCK_BASE2 * n1 * n2;
} else
clock = CC_CLOCK_BASE1 * n1 * n2;
if (clock == 0)
return 0;
m1 = m & CC_M1_MASK;
m2 = (m & CC_M2_MASK) >> CC_M2_SHIFT;
m3 = (m & CC_M3_MASK) >> CC_M3_SHIFT;
mc = (m & CC_MC_MASK) >> CC_MC_SHIFT;
if ((pll_type == PLL_TYPE1) ||
(pll_type == PLL_TYPE3) ||
(pll_type == PLL_TYPE4) ||
(pll_type == PLL_TYPE7)) {
m1 = factor6(m1);
if ((pll_type == PLL_TYPE1) || (pll_type == PLL_TYPE3))
m2 += CC_F5_BIAS;
else
m2 = factor6(m2);
m3 = factor6(m3);
switch (mc) {
case CC_MC_BYPASS: return (clock);
case CC_MC_M1: return (clock / m1);
case CC_MC_M1M2: return (clock / (m1 * m2));
case CC_MC_M1M2M3: return (clock / (m1 * m2 * m3));
case CC_MC_M1M3: return (clock / (m1 * m3));
default: return (0);
}
} else {
ASSERT(pll_type == PLL_TYPE2);
m1 += CC_T2_BIAS;
m2 += CC_T2M2_BIAS;
m3 += CC_T2_BIAS;
ASSERT((m1 >= 2) && (m1 <= 7));
ASSERT((m2 >= 3) && (m2 <= 10));
ASSERT((m3 >= 2) && (m3 <= 7));
if ((mc & CC_T2MC_M1BYP) == 0)
clock /= m1;
if ((mc & CC_T2MC_M2BYP) == 0)
clock /= m2;
if ((mc & CC_T2MC_M3BYP) == 0)
clock /= m3;
return (clock);
}
}
/* set chip watchdog reset timer to fire in 'ticks' */
void
si_watchdog(si_t *sih, uint ticks)
{
uint nb, maxt;
if (PMUCTL_ENAB(sih)) {
if ((CHIPID(sih->chip) == BCM4319_CHIP_ID) &&
(CHIPREV(sih->chiprev) == 0) && (ticks != 0)) {
si_corereg(sih, SI_CC_IDX, OFFSETOF(chipcregs_t, clk_ctl_st), ~0, 0x2);
si_setcore(sih, USB20D_CORE_ID, 0);
si_core_disable(sih, 1);
si_setcore(sih, CC_CORE_ID, 0);
}
nb = (sih->ccrev < 26) ? 16 : ((sih->ccrev >= 37) ? 32 : 24);
/* The mips compiler uses the sllv instruction,
* so we specially handle the 32-bit case.
*/
if (nb == 32)
maxt = 0xffffffff;
else
maxt = ((1 << nb) - 1);
if (ticks == 1)
ticks = 2;
else if (ticks > maxt)
ticks = maxt;
si_corereg(sih, SI_CC_IDX, OFFSETOF(chipcregs_t, pmuwatchdog), ~0, ticks);
} else {
maxt = (1 << 28) - 1;
if (ticks > maxt)
ticks = maxt;
si_corereg(sih, SI_CC_IDX, OFFSETOF(chipcregs_t, watchdog), ~0, ticks);
}
}
/* trigger watchdog reset after ms milliseconds */
void
si_watchdog_ms(si_t *sih, uint32 ms)
{
si_watchdog(sih, wd_msticks * ms);
}
uint32 si_watchdog_msticks(void)
{
return wd_msticks;
}
bool
si_taclear(si_t *sih, bool details)
{
return FALSE;
}
/* return the slow clock source - LPO, XTAL, or PCI */
static uint
si_slowclk_src(si_info_t *sii)
{
chipcregs_t *cc;
ASSERT(SI_FAST(sii) || si_coreid(&sii->pub) == CC_CORE_ID);
if (sii->pub.ccrev < 6) {
if ((BUSTYPE(sii->pub.bustype) == PCI_BUS) &&
(OSL_PCI_READ_CONFIG(sii->osh, PCI_GPIO_OUT, sizeof(uint32)) &
PCI_CFG_GPIO_SCS))
return (SCC_SS_PCI);
else
return (SCC_SS_XTAL);
} else if (sii->pub.ccrev < 10) {
cc = (chipcregs_t *)si_setcoreidx(&sii->pub, sii->curidx);
return (R_REG(sii->osh, &cc->slow_clk_ctl) & SCC_SS_MASK);
} else /* Insta-clock */
return (SCC_SS_XTAL);
}
/* return the ILP (slowclock) min or max frequency */
static uint
si_slowclk_freq(si_info_t *sii, bool max_freq, chipcregs_t *cc)
{
uint32 slowclk;
uint div;
ASSERT(SI_FAST(sii) || si_coreid(&sii->pub) == CC_CORE_ID);
/* shouldn't be here unless we've established the chip has dynamic clk control */
ASSERT(R_REG(sii->osh, &cc->capabilities) & CC_CAP_PWR_CTL);
slowclk = si_slowclk_src(sii);
if (sii->pub.ccrev < 6) {
if (slowclk == SCC_SS_PCI)
return (max_freq ? (PCIMAXFREQ / 64) : (PCIMINFREQ / 64));
else
return (max_freq ? (XTALMAXFREQ / 32) : (XTALMINFREQ / 32));
} else if (sii->pub.ccrev < 10) {
div = 4 *
(((R_REG(sii->osh, &cc->slow_clk_ctl) & SCC_CD_MASK) >> SCC_CD_SHIFT) + 1);
if (slowclk == SCC_SS_LPO)
return (max_freq ? LPOMAXFREQ : LPOMINFREQ);
else if (slowclk == SCC_SS_XTAL)
return (max_freq ? (XTALMAXFREQ / div) : (XTALMINFREQ / div));
else if (slowclk == SCC_SS_PCI)
return (max_freq ? (PCIMAXFREQ / div) : (PCIMINFREQ / div));
else
ASSERT(0);
} else {
/* Chipc rev 10 is InstaClock */
div = R_REG(sii->osh, &cc->system_clk_ctl) >> SYCC_CD_SHIFT;
div = 4 * (div + 1);
return (max_freq ? XTALMAXFREQ : (XTALMINFREQ / div));
}
return (0);
}
static void
si_clkctl_setdelay(si_info_t *sii, void *chipcregs)
{
chipcregs_t *cc = (chipcregs_t *)chipcregs;
uint slowmaxfreq, pll_delay, slowclk;
uint pll_on_delay, fref_sel_delay;
pll_delay = PLL_DELAY;
/* If the slow clock is not sourced by the xtal then add the xtal_on_delay
* since the xtal will also be powered down by dynamic clk control logic.
*/
slowclk = si_slowclk_src(sii);
if (slowclk != SCC_SS_XTAL)
pll_delay += XTAL_ON_DELAY;
/* Starting with 4318 it is ILP that is used for the delays */
slowmaxfreq = si_slowclk_freq(sii, (sii->pub.ccrev >= 10) ? FALSE : TRUE, cc);
pll_on_delay = ((slowmaxfreq * pll_delay) + 999999) / 1000000;
fref_sel_delay = ((slowmaxfreq * FREF_DELAY) + 999999) / 1000000;
W_REG(sii->osh, &cc->pll_on_delay, pll_on_delay);
W_REG(sii->osh, &cc->fref_sel_delay, fref_sel_delay);
}
/* initialize power control delay registers */
void
si_clkctl_init(si_t *sih)
{
si_info_t *sii;
uint origidx = 0;
chipcregs_t *cc;
bool fast;
if (!CCCTL_ENAB(sih))
return;
sii = SI_INFO(sih);
fast = SI_FAST(sii);
if (!fast) {
origidx = sii->curidx;
if ((cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0)) == NULL)
return;
} else if ((cc = (chipcregs_t *)CCREGS_FAST(sii)) == NULL)
return;
ASSERT(cc != NULL);
/* set all Instaclk chip ILP to 1 MHz */
if (sih->ccrev >= 10)
SET_REG(sii->osh, &cc->system_clk_ctl, SYCC_CD_MASK,
(ILP_DIV_1MHZ << SYCC_CD_SHIFT));
si_clkctl_setdelay(sii, (void *)(uintptr)cc);
if (!fast)
si_setcoreidx(sih, origidx);
}
/* change logical "focus" to the gpio core for optimized access */
void *
si_gpiosetcore(si_t *sih)
{
return (si_setcoreidx(sih, SI_CC_IDX));
}
/*
* mask & set gpiocontrol bits.
* If a gpiocontrol bit is set to 0, chipcommon controls the corresponding GPIO pin.
* If a gpiocontrol bit is set to 1, the GPIO pin is no longer a GPIO and becomes dedicated
* to some chip-specific purpose.
*/
uint32
si_gpiocontrol(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
uint regoff;
regoff = 0;
/* gpios could be shared on router platforms
* ignore reservation if it's high priority (e.g., test apps)
*/
if ((priority != GPIO_HI_PRIORITY) &&
(BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpiocontrol);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* mask&set gpio output enable bits */
uint32
si_gpioouten(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
uint regoff;
regoff = 0;
/* gpios could be shared on router platforms
* ignore reservation if it's high priority (e.g., test apps)
*/
if ((priority != GPIO_HI_PRIORITY) &&
(BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpioouten);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* mask&set gpio output bits */
uint32
si_gpioout(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
uint regoff;
regoff = 0;
/* gpios could be shared on router platforms
* ignore reservation if it's high priority (e.g., test apps)
*/
if ((priority != GPIO_HI_PRIORITY) &&
(BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpioout);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* reserve one gpio */
uint32
si_gpioreserve(si_t *sih, uint32 gpio_bitmask, uint8 priority)
{
/* only cores on SI_BUS share GPIO's and only applcation users need to
* reserve/release GPIO
*/
if ((BUSTYPE(sih->bustype) != SI_BUS) || (!priority)) {
ASSERT((BUSTYPE(sih->bustype) == SI_BUS) && (priority));
return 0xffffffff;
}
/* make sure only one bit is set */
if ((!gpio_bitmask) || ((gpio_bitmask) & (gpio_bitmask - 1))) {
ASSERT((gpio_bitmask) && !((gpio_bitmask) & (gpio_bitmask - 1)));
return 0xffffffff;
}
/* already reserved */
if (si_gpioreservation & gpio_bitmask)
return 0xffffffff;
/* set reservation */
si_gpioreservation |= gpio_bitmask;
return si_gpioreservation;
}
/* release one gpio */
/*
* releasing the gpio doesn't change the current value on the GPIO last write value
* persists till some one overwrites it
*/
uint32
si_gpiorelease(si_t *sih, uint32 gpio_bitmask, uint8 priority)
{
/* only cores on SI_BUS share GPIO's and only applcation users need to
* reserve/release GPIO
*/
if ((BUSTYPE(sih->bustype) != SI_BUS) || (!priority)) {
ASSERT((BUSTYPE(sih->bustype) == SI_BUS) && (priority));
return 0xffffffff;
}
/* make sure only one bit is set */
if ((!gpio_bitmask) || ((gpio_bitmask) & (gpio_bitmask - 1))) {
ASSERT((gpio_bitmask) && !((gpio_bitmask) & (gpio_bitmask - 1)));
return 0xffffffff;
}
/* already released */
if (!(si_gpioreservation & gpio_bitmask))
return 0xffffffff;
/* clear reservation */
si_gpioreservation &= ~gpio_bitmask;
return si_gpioreservation;
}
/* return the current gpioin register value */
uint32
si_gpioin(si_t *sih)
{
uint regoff;
regoff = OFFSETOF(chipcregs_t, gpioin);
return (si_corereg(sih, SI_CC_IDX, regoff, 0, 0));
}
/* mask&set gpio interrupt polarity bits */
uint32
si_gpiointpolarity(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
uint regoff;
/* gpios could be shared on router platforms */
if ((BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpiointpolarity);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* mask&set gpio interrupt mask bits */
uint32
si_gpiointmask(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
uint regoff;
/* gpios could be shared on router platforms */
if ((BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpiointmask);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* assign the gpio to an led */
uint32
si_gpioled(si_t *sih, uint32 mask, uint32 val)
{
if (sih->ccrev < 16)
return 0xffffffff;
/* gpio led powersave reg */
return (si_corereg(sih, SI_CC_IDX, OFFSETOF(chipcregs_t, gpiotimeroutmask), mask, val));
}
/* mask&set gpio timer val */
uint32
si_gpiotimerval(si_t *sih, uint32 mask, uint32 gpiotimerval)
{
if (sih->ccrev < 16)
return 0xffffffff;
return (si_corereg(sih, SI_CC_IDX,
OFFSETOF(chipcregs_t, gpiotimerval), mask, gpiotimerval));
}
uint32
si_gpiopull(si_t *sih, bool updown, uint32 mask, uint32 val)
{
uint offs;
if (sih->ccrev < 20)
return 0xffffffff;
offs = (updown ? OFFSETOF(chipcregs_t, gpiopulldown) : OFFSETOF(chipcregs_t, gpiopullup));
return (si_corereg(sih, SI_CC_IDX, offs, mask, val));
}
uint32
si_gpioevent(si_t *sih, uint regtype, uint32 mask, uint32 val)
{
uint offs;
if (sih->ccrev < 11)
return 0xffffffff;
if (regtype == GPIO_REGEVT)
offs = OFFSETOF(chipcregs_t, gpioevent);
else if (regtype == GPIO_REGEVT_INTMSK)
offs = OFFSETOF(chipcregs_t, gpioeventintmask);
else if (regtype == GPIO_REGEVT_INTPOL)
offs = OFFSETOF(chipcregs_t, gpioeventintpolarity);
else
return 0xffffffff;
return (si_corereg(sih, SI_CC_IDX, offs, mask, val));
}
void *
si_gpio_handler_register(si_t *sih, uint32 event,
bool level, gpio_handler_t cb, void *arg)
{
si_info_t *sii;
gpioh_item_t *gi;
ASSERT(event);
ASSERT(cb != NULL);
sii = SI_INFO(sih);
if (sih->ccrev < 11)
return NULL;
if ((gi = MALLOC(sii->osh, sizeof(gpioh_item_t))) == NULL)
return NULL;
bzero(gi, sizeof(gpioh_item_t));
gi->event = event;
gi->handler = cb;
gi->arg = arg;
gi->level = level;
gi->next = sii->gpioh_head;
sii->gpioh_head = gi;
return (void *)(gi);
}
void
si_gpio_handler_unregister(si_t *sih, void *gpioh)
{
si_info_t *sii;
gpioh_item_t *p, *n;
sii = SI_INFO(sih);
if (sih->ccrev < 11)
return;
ASSERT(sii->gpioh_head != NULL);
if ((void*)sii->gpioh_head == gpioh) {
sii->gpioh_head = sii->gpioh_head->next;
MFREE(sii->osh, gpioh, sizeof(gpioh_item_t));
return;
} else {
p = sii->gpioh_head;
n = p->next;
while (n) {
if ((void*)n == gpioh) {
p->next = n->next;
MFREE(sii->osh, gpioh, sizeof(gpioh_item_t));
return;
}
p = n;
n = n->next;
}
}
ASSERT(0); /* Not found in list */
}
void
si_gpio_handler_process(si_t *sih)
{
si_info_t *sii;
gpioh_item_t *h;
uint32 level = si_gpioin(sih);
uint32 levelp = si_gpiointpolarity(sih, 0, 0, 0);
uint32 edge = si_gpioevent(sih, GPIO_REGEVT, 0, 0);
uint32 edgep = si_gpioevent(sih, GPIO_REGEVT_INTPOL, 0, 0);
sii = SI_INFO(sih);
for (h = sii->gpioh_head; h != NULL; h = h->next) {
if (h->handler) {
uint32 status = (h->level ? level : edge) & h->event;
uint32 polarity = (h->level ? levelp : edgep) & h->event;
/* polarity bitval is opposite of status bitval */
if (status ^ polarity)
h->handler(status, h->arg);
}
}
si_gpioevent(sih, GPIO_REGEVT, edge, edge); /* clear edge-trigger status */
}
uint32
si_gpio_int_enable(si_t *sih, bool enable)
{
uint offs;
if (sih->ccrev < 11)
return 0xffffffff;
offs = OFFSETOF(chipcregs_t, intmask);
return (si_corereg(sih, SI_CC_IDX, offs, CI_GPIO, (enable ? CI_GPIO : 0)));
}
/* Return the size of the specified SOCRAM bank */
static uint
socram_banksize(si_info_t *sii, sbsocramregs_t *regs, uint8 idx, uint8 mem_type)
{
uint banksize, bankinfo;
uint bankidx = idx | (mem_type << SOCRAM_BANKIDX_MEMTYPE_SHIFT);
ASSERT(mem_type <= SOCRAM_MEMTYPE_DEVRAM);
W_REG(sii->osh, ®s->bankidx, bankidx);
bankinfo = R_REG(sii->osh, ®s->bankinfo);
banksize = SOCRAM_BANKINFO_SZBASE * ((bankinfo & SOCRAM_BANKINFO_SZMASK) + 1);
return banksize;
}
void
si_socdevram(si_t *sih, bool set, uint8 *enable, uint8 *protect, uint8 *remap)
{
si_info_t *sii;
uint origidx;
uint intr_val = 0;
sbsocramregs_t *regs;
bool wasup;
uint corerev;
sii = SI_INFO(sih);
/* Block ints and save current core */
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
if (!set)
*enable = *protect = *remap = 0;
/* Switch to SOCRAM core */
if (!(regs = si_setcore(sih, SOCRAM_CORE_ID, 0)))
goto done;
/* Get info for determining size */
if (!(wasup = si_iscoreup(sih)))
si_core_reset(sih, 0, 0);
corerev = si_corerev(sih);
if (corerev >= 10) {
uint32 extcinfo;
uint8 nb;
uint8 i;
uint32 bankidx, bankinfo;
extcinfo = R_REG(sii->osh, ®s->extracoreinfo);
nb = ((extcinfo & SOCRAM_DEVRAMBANK_MASK) >> SOCRAM_DEVRAMBANK_SHIFT);
for (i = 0; i < nb; i++) {
bankidx = i | (SOCRAM_MEMTYPE_DEVRAM << SOCRAM_BANKIDX_MEMTYPE_SHIFT);
W_REG(sii->osh, ®s->bankidx, bankidx);
bankinfo = R_REG(sii->osh, ®s->bankinfo);
if (set) {
bankinfo &= ~SOCRAM_BANKINFO_DEVRAMSEL_MASK;
bankinfo &= ~SOCRAM_BANKINFO_DEVRAMPRO_MASK;
bankinfo &= ~SOCRAM_BANKINFO_DEVRAMREMAP_MASK;
if (*enable) {
bankinfo |= (1 << SOCRAM_BANKINFO_DEVRAMSEL_SHIFT);
if (*protect)
bankinfo |= (1 << SOCRAM_BANKINFO_DEVRAMPRO_SHIFT);
if ((corerev >= 16) && *remap)
bankinfo |=
(1 << SOCRAM_BANKINFO_DEVRAMREMAP_SHIFT);
}
W_REG(sii->osh, ®s->bankinfo, bankinfo);
}
else if (i == 0) {
if (bankinfo & SOCRAM_BANKINFO_DEVRAMSEL_MASK) {
*enable = 1;
if (bankinfo & SOCRAM_BANKINFO_DEVRAMPRO_MASK)
*protect = 1;
if (bankinfo & SOCRAM_BANKINFO_DEVRAMREMAP_MASK)
*remap = 1;
}
}
}
}
/* Return to previous state and core */
if (!wasup)
si_core_disable(sih, 0);
si_setcoreidx(sih, origidx);
done:
INTR_RESTORE(sii, intr_val);
}
bool
si_socdevram_remap_isenb(si_t *sih)
{
si_info_t *sii;
uint origidx;
uint intr_val = 0;
sbsocramregs_t *regs;
bool wasup, remap = FALSE;
uint corerev;
uint32 extcinfo;
uint8 nb;
uint8 i;
uint32 bankidx, bankinfo;
sii = SI_INFO(sih);
/* Block ints and save current core */
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
/* Switch to SOCRAM core */
if (!(regs = si_setcore(sih, SOCRAM_CORE_ID, 0)))
goto done;
/* Get info for determining size */
if (!(wasup = si_iscoreup(sih)))
si_core_reset(sih, 0, 0);
corerev = si_corerev(sih);
if (corerev >= 16) {
extcinfo = R_REG(sii->osh, ®s->extracoreinfo);
nb = ((extcinfo & SOCRAM_DEVRAMBANK_MASK) >> SOCRAM_DEVRAMBANK_SHIFT);
for (i = 0; i < nb; i++) {
bankidx = i | (SOCRAM_MEMTYPE_DEVRAM << SOCRAM_BANKIDX_MEMTYPE_SHIFT);
W_REG(sii->osh, ®s->bankidx, bankidx);
bankinfo = R_REG(sii->osh, ®s->bankinfo);
if (bankinfo & SOCRAM_BANKINFO_DEVRAMREMAP_MASK) {
remap = TRUE;
break;
}
}
}
/* Return to previous state and core */
if (!wasup)
si_core_disable(sih, 0);
si_setcoreidx(sih, origidx);
done:
INTR_RESTORE(sii, intr_val);
return remap;
}
bool
si_socdevram_pkg(si_t *sih)
{
if (si_socdevram_size(sih) > 0)
return TRUE;
else
return FALSE;
}
uint32
si_socdevram_size(si_t *sih)
{
si_info_t *sii;
uint origidx;
uint intr_val = 0;
uint32 memsize = 0;
sbsocramregs_t *regs;
bool wasup;
uint corerev;
sii = SI_INFO(sih);
/* Block ints and save current core */
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
/* Switch to SOCRAM core */
if (!(regs = si_setcore(sih, SOCRAM_CORE_ID, 0)))
goto done;
/* Get info for determining size */
if (!(wasup = si_iscoreup(sih)))
si_core_reset(sih, 0, 0);
corerev = si_corerev(sih);
if (corerev >= 10) {
uint32 extcinfo;
uint8 nb;
uint8 i;
extcinfo = R_REG(sii->osh, ®s->extracoreinfo);
nb = (((extcinfo & SOCRAM_DEVRAMBANK_MASK) >> SOCRAM_DEVRAMBANK_SHIFT));
for (i = 0; i < nb; i++)
memsize += socram_banksize(sii, regs, i, SOCRAM_MEMTYPE_DEVRAM);
}
/* Return to previous state and core */
if (!wasup)
si_core_disable(sih, 0);
si_setcoreidx(sih, origidx);
done:
INTR_RESTORE(sii, intr_val);
return memsize;
}
uint32
si_socdevram_remap_size(si_t *sih)
{
si_info_t *sii;
uint origidx;
uint intr_val = 0;
uint32 memsize = 0, banksz;
sbsocramregs_t *regs;
bool wasup;
uint corerev;
uint32 extcinfo;
uint8 nb;
uint8 i;
uint32 bankidx, bankinfo;
sii = SI_INFO(sih);
/* Block ints and save current core */
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
/* Switch to SOCRAM core */
if (!(regs = si_setcore(sih, SOCRAM_CORE_ID, 0)))
goto done;
/* Get info for determining size */
if (!(wasup = si_iscoreup(sih)))
si_core_reset(sih, 0, 0);
corerev = si_corerev(sih);
if (corerev >= 16) {
extcinfo = R_REG(sii->osh, ®s->extracoreinfo);
nb = (((extcinfo & SOCRAM_DEVRAMBANK_MASK) >> SOCRAM_DEVRAMBANK_SHIFT));
/*
* FIX: A0 Issue: Max addressable is 512KB, instead 640KB
* Only four banks are accessible to ARM
*/
if ((corerev == 16) && (nb == 5))
nb = 4;
for (i = 0; i < nb; i++) {
bankidx = i | (SOCRAM_MEMTYPE_DEVRAM << SOCRAM_BANKIDX_MEMTYPE_SHIFT);
W_REG(sii->osh, ®s->bankidx, bankidx);
bankinfo = R_REG(sii->osh, ®s->bankinfo);
if (bankinfo & SOCRAM_BANKINFO_DEVRAMREMAP_MASK) {
banksz = socram_banksize(sii, regs, i, SOCRAM_MEMTYPE_DEVRAM);
memsize += banksz;
} else {
/* Account only consecutive banks for now */
break;
}
}
}
/* Return to previous state and core */
if (!wasup)
si_core_disable(sih, 0);
si_setcoreidx(sih, origidx);
done:
INTR_RESTORE(sii, intr_val);
return memsize;
}
/* Return the RAM size of the SOCRAM core */
uint32
si_socram_size(si_t *sih)
{
si_info_t *sii;
uint origidx;
uint intr_val = 0;
sbsocramregs_t *regs;
bool wasup;
uint corerev;
uint32 coreinfo;
uint memsize = 0;
sii = SI_INFO(sih);
/* Block ints and save current core */
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
/* Switch to SOCRAM core */
if (!(regs = si_setcore(sih, SOCRAM_CORE_ID, 0)))
goto done;
/* Get info for determining size */
if (!(wasup = si_iscoreup(sih)))
si_core_reset(sih, 0, 0);
corerev = si_corerev(sih);
coreinfo = R_REG(sii->osh, ®s->coreinfo);
/* Calculate size from coreinfo based on rev */
if (corerev == 0)
memsize = 1 << (16 + (coreinfo & SRCI_MS0_MASK));
else if (corerev < 3) {
memsize = 1 << (SR_BSZ_BASE + (coreinfo & SRCI_SRBSZ_MASK));
memsize *= (coreinfo & SRCI_SRNB_MASK) >> SRCI_SRNB_SHIFT;
} else if ((corerev <= 7) || (corerev == 12)) {
uint nb = (coreinfo & SRCI_SRNB_MASK) >> SRCI_SRNB_SHIFT;
uint bsz = (coreinfo & SRCI_SRBSZ_MASK);
uint lss = (coreinfo & SRCI_LSS_MASK) >> SRCI_LSS_SHIFT;
if (lss != 0)
nb --;
memsize = nb * (1 << (bsz + SR_BSZ_BASE));
if (lss != 0)
memsize += (1 << ((lss - 1) + SR_BSZ_BASE));
} else {
uint8 i;
uint nb = (coreinfo & SRCI_SRNB_MASK) >> SRCI_SRNB_SHIFT;
for (i = 0; i < nb; i++)
memsize += socram_banksize(sii, regs, i, SOCRAM_MEMTYPE_RAM);
}
/* Return to previous state and core */
if (!wasup)
si_core_disable(sih, 0);
si_setcoreidx(sih, origidx);
done:
INTR_RESTORE(sii, intr_val);
return memsize;
}
uint32
si_socram_srmem_size(si_t *sih)
{
si_info_t *sii;
uint origidx;
uint intr_val = 0;
sbsocramregs_t *regs;
bool wasup;
uint corerev;
uint32 coreinfo;
uint memsize = 0;
if ((CHIPID(sih->chip) == BCM4334_CHIP_ID) && (CHIPREV(sih->chiprev) < 2)) {
return (32 * 1024);
}
sii = SI_INFO(sih);
/* Block ints and save current core */
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
/* Switch to SOCRAM core */
if (!(regs = si_setcore(sih, SOCRAM_CORE_ID, 0)))
goto done;
/* Get info for determining size */
if (!(wasup = si_iscoreup(sih)))
si_core_reset(sih, 0, 0);
corerev = si_corerev(sih);
coreinfo = R_REG(sii->osh, ®s->coreinfo);
/* Calculate size from coreinfo based on rev */
if (corerev >= 16) {
uint8 i;
uint nb = (coreinfo & SRCI_SRNB_MASK) >> SRCI_SRNB_SHIFT;
for (i = 0; i < nb; i++) {
W_REG(sii->osh, ®s->bankidx, i);
if (R_REG(sii->osh, ®s->bankinfo) & SOCRAM_BANKINFO_RETNTRAM_MASK)
memsize += socram_banksize(sii, regs, i, SOCRAM_MEMTYPE_RAM);
}
}
/* Return to previous state and core */
if (!wasup)
si_core_disable(sih, 0);
si_setcoreidx(sih, origidx);
done:
INTR_RESTORE(sii, intr_val);
return memsize;
}
void
si_btcgpiowar(si_t *sih)
{
si_info_t *sii;
uint origidx;
uint intr_val = 0;
chipcregs_t *cc;
sii = SI_INFO(sih);
/* Make sure that there is ChipCommon core present &&
* UART_TX is strapped to 1
*/
if (!(sih->cccaps & CC_CAP_UARTGPIO))
return;
/* si_corereg cannot be used as we have to guarantee 8-bit read/writes */
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
ASSERT(cc != NULL);
W_REG(sii->osh, &cc->uart0mcr, R_REG(sii->osh, &cc->uart0mcr) | 0x04);
/* restore the original index */
si_setcoreidx(sih, origidx);
INTR_RESTORE(sii, intr_val);
}
void
si_chipcontrl_btshd0_4331(si_t *sih, bool on)
{
si_info_t *sii;
chipcregs_t *cc;
uint origidx;
uint32 val;
uint intr_val = 0;
sii = SI_INFO(sih);
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
val = R_REG(sii->osh, &cc->chipcontrol);
/* bt_shd0 controls are same for 4331 chiprevs 0 and 1, packages 12x9 and 12x12 */
if (on) {
/* Enable bt_shd0 on gpio4: */
val |= (CCTRL4331_BT_SHD0_ON_GPIO4);
W_REG(sii->osh, &cc->chipcontrol, val);
} else {
val &= ~(CCTRL4331_BT_SHD0_ON_GPIO4);
W_REG(sii->osh, &cc->chipcontrol, val);
}
/* restore the original index */
si_setcoreidx(sih, origidx);
INTR_RESTORE(sii, intr_val);
}
void
si_chipcontrl_restore(si_t *sih, uint32 val)
{
si_info_t *sii;
chipcregs_t *cc;
uint origidx;
sii = SI_INFO(sih);
origidx = si_coreidx(sih);
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
W_REG(sii->osh, &cc->chipcontrol, val);
si_setcoreidx(sih, origidx);
}
uint32
si_chipcontrl_read(si_t *sih)
{
si_info_t *sii;
chipcregs_t *cc;
uint origidx;
uint32 val;
sii = SI_INFO(sih);
origidx = si_coreidx(sih);
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
val = R_REG(sii->osh, &cc->chipcontrol);
si_setcoreidx(sih, origidx);
return val;
}
void
si_chipcontrl_epa4331(si_t *sih, bool on)
{
si_info_t *sii;
chipcregs_t *cc;
uint origidx;
uint32 val;
sii = SI_INFO(sih);
origidx = si_coreidx(sih);
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
val = R_REG(sii->osh, &cc->chipcontrol);
if (on) {
if (sih->chippkg == 9 || sih->chippkg == 0xb) {
val |= (CCTRL4331_EXTPA_EN | CCTRL4331_EXTPA_ON_GPIO2_5);
/* Ext PA Controls for 4331 12x9 Package */
W_REG(sii->osh, &cc->chipcontrol, val);
} else {
/* Ext PA Controls for 4331 12x12 Package */
if (sih->chiprev > 0) {
W_REG(sii->osh, &cc->chipcontrol, val |
(CCTRL4331_EXTPA_EN) | (CCTRL4331_EXTPA_EN2));
} else {
W_REG(sii->osh, &cc->chipcontrol, val | (CCTRL4331_EXTPA_EN));
}
}
} else {
val &= ~(CCTRL4331_EXTPA_EN | CCTRL4331_EXTPA_EN2 | CCTRL4331_EXTPA_ON_GPIO2_5);
W_REG(sii->osh, &cc->chipcontrol, val);
}
si_setcoreidx(sih, origidx);
}
/* switch muxed pins, on: SROM, off: FEMCTRL */
void
si_chipcontrl_srom4360(si_t *sih, bool on)
{
si_info_t *sii;
chipcregs_t *cc;
uint origidx;
uint32 val;
sii = SI_INFO(sih);
origidx = si_coreidx(sih);
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
val = R_REG(sii->osh, &cc->chipcontrol);
if (on) {
val &= ~(CCTRL4360_SECI_MODE |
CCTRL4360_BTSWCTRL_MODE |
CCTRL4360_EXTRA_FEMCTRL_MODE |
CCTRL4360_BT_LGCY_MODE |
CCTRL4360_CORE2FEMCTRL4_ON);
W_REG(sii->osh, &cc->chipcontrol, val);
} else {
}
si_setcoreidx(sih, origidx);
}
void
si_chipcontrl_epa4331_wowl(si_t *sih, bool enter_wowl)
{
si_info_t *sii;
chipcregs_t *cc;
uint origidx;
uint32 val;
bool sel_chip;
sel_chip = (CHIPID(sih->chip) == BCM4331_CHIP_ID) ||
(CHIPID(sih->chip) == BCM43431_CHIP_ID);
sel_chip &= ((sih->chippkg == 9 || sih->chippkg == 0xb));
if (!sel_chip)
return;
sii = SI_INFO(sih);
origidx = si_coreidx(sih);
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
val = R_REG(sii->osh, &cc->chipcontrol);
if (enter_wowl) {
val |= CCTRL4331_EXTPA_EN;
W_REG(sii->osh, &cc->chipcontrol, val);
} else {
val |= (CCTRL4331_EXTPA_EN | CCTRL4331_EXTPA_ON_GPIO2_5);
W_REG(sii->osh, &cc->chipcontrol, val);
}
si_setcoreidx(sih, origidx);
}
uint
si_pll_reset(si_t *sih)
{
uint err = 0;
return (err);
}
/* Enable BT-COEX & Ex-PA for 4313 */
void
si_epa_4313war(si_t *sih)
{
si_info_t *sii;
chipcregs_t *cc;
uint origidx;
sii = SI_INFO(sih);
origidx = si_coreidx(sih);
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
/* EPA Fix */
W_REG(sii->osh, &cc->gpiocontrol,
R_REG(sii->osh, &cc->gpiocontrol) | GPIO_CTRL_EPA_EN_MASK);
si_setcoreidx(sih, origidx);
}
void
si_clk_pmu_htavail_set(si_t *sih, bool set_clear)
{
}
/* WL/BT control for 4313 btcombo boards >= P250 */
void
si_btcombo_p250_4313_war(si_t *sih)
{
si_info_t *sii;
chipcregs_t *cc;
uint origidx;
sii = SI_INFO(sih);
origidx = si_coreidx(sih);
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
W_REG(sii->osh, &cc->gpiocontrol,
R_REG(sii->osh, &cc->gpiocontrol) | GPIO_CTRL_5_6_EN_MASK);
W_REG(sii->osh, &cc->gpioouten,
R_REG(sii->osh, &cc->gpioouten) | GPIO_CTRL_5_6_EN_MASK);
si_setcoreidx(sih, origidx);
}
void
si_btc_enable_chipcontrol(si_t *sih)
{
si_info_t *sii;
chipcregs_t *cc;
uint origidx;
sii = SI_INFO(sih);
origidx = si_coreidx(sih);
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
/* BT fix */
W_REG(sii->osh, &cc->chipcontrol,
R_REG(sii->osh, &cc->chipcontrol) | CC_BTCOEX_EN_MASK);
si_setcoreidx(sih, origidx);
}
void
si_btcombo_43228_war(si_t *sih)
{
si_info_t *sii;
chipcregs_t *cc;
uint origidx;
sii = SI_INFO(sih);
origidx = si_coreidx(sih);
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
W_REG(sii->osh, &cc->gpioouten, GPIO_CTRL_7_6_EN_MASK);
W_REG(sii->osh, &cc->gpioout, GPIO_OUT_7_EN_MASK);
si_setcoreidx(sih, origidx);
}
/* check if the device is removed */
bool
si_deviceremoved(si_t *sih)
{
uint32 w;
si_info_t *sii;
sii = SI_INFO(sih);
switch (BUSTYPE(sih->bustype)) {
case PCI_BUS:
ASSERT(sii->osh != NULL);
w = OSL_PCI_READ_CONFIG(sii->osh, PCI_CFG_VID, sizeof(uint32));
if ((w & 0xFFFF) != VENDOR_BROADCOM)
return TRUE;
break;
}
return FALSE;
}
bool
si_is_sprom_available(si_t *sih)
{
if (sih->ccrev >= 31) {
si_info_t *sii;
uint origidx;
chipcregs_t *cc;
uint32 sromctrl;
if ((sih->cccaps & CC_CAP_SROM) == 0)
return FALSE;
sii = SI_INFO(sih);
origidx = sii->curidx;
cc = si_setcoreidx(sih, SI_CC_IDX);
sromctrl = R_REG(sii->osh, &cc->sromcontrol);
si_setcoreidx(sih, origidx);
return (sromctrl & SRC_PRESENT);
}
switch (CHIPID(sih->chip)) {
case BCM4312_CHIP_ID:
return ((sih->chipst & CST4312_SPROM_OTP_SEL_MASK) != CST4312_OTP_SEL);
case BCM4325_CHIP_ID:
return (sih->chipst & CST4325_SPROM_SEL) != 0;
case BCM4322_CHIP_ID: case BCM43221_CHIP_ID: case BCM43231_CHIP_ID:
case BCM43222_CHIP_ID: case BCM43111_CHIP_ID: case BCM43112_CHIP_ID:
case BCM4342_CHIP_ID: {
uint32 spromotp;
spromotp = (sih->chipst & CST4322_SPROM_OTP_SEL_MASK) >>
CST4322_SPROM_OTP_SEL_SHIFT;
return (spromotp & CST4322_SPROM_PRESENT) != 0;
}
case BCM4329_CHIP_ID:
return (sih->chipst & CST4329_SPROM_SEL) != 0;
case BCM4315_CHIP_ID:
return (sih->chipst & CST4315_SPROM_SEL) != 0;
case BCM4319_CHIP_ID:
return (sih->chipst & CST4319_SPROM_SEL) != 0;
case BCM4336_CHIP_ID:
case BCM43362_CHIP_ID:
return (sih->chipst & CST4336_SPROM_PRESENT) != 0;
case BCM4330_CHIP_ID:
return (sih->chipst & CST4330_SPROM_PRESENT) != 0;
case BCM4313_CHIP_ID:
return (sih->chipst & CST4313_SPROM_PRESENT) != 0;
case BCM4331_CHIP_ID:
case BCM43431_CHIP_ID:
return (sih->chipst & CST4331_SPROM_PRESENT) != 0;
case BCM43239_CHIP_ID:
return ((sih->chipst & CST43239_SPROM_MASK) &&
!(sih->chipst & CST43239_SFLASH_MASK));
case BCM4324_CHIP_ID:
return ((sih->chipst & CST4324_SPROM_MASK) &&
!(sih->chipst & CST4324_SFLASH_MASK));
case BCM43131_CHIP_ID:
case BCM43217_CHIP_ID:
case BCM43227_CHIP_ID:
case BCM43228_CHIP_ID:
case BCM43428_CHIP_ID:
return (sih->chipst & CST43228_OTP_PRESENT) != CST43228_OTP_PRESENT;
default:
return TRUE;
}
}
| gpl-2.0 |
AlmightyMegadeth00/kernel_tegra | drivers/mfd/ezx-pcap.c | 2155 | 13112 | /*
* Driver for Motorola PCAP2 as present in EZX phones
*
* Copyright (C) 2006 Harald Welte <laforge@openezx.org>
* Copyright (C) 2009 Daniel Ribeiro <drwyrm@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/mfd/ezx-pcap.h>
#include <linux/spi/spi.h>
#include <linux/gpio.h>
#include <linux/slab.h>
#define PCAP_ADC_MAXQ 8
struct pcap_adc_request {
u8 bank;
u8 ch[2];
u32 flags;
void (*callback)(void *, u16[]);
void *data;
};
struct pcap_adc_sync_request {
u16 res[2];
struct completion completion;
};
struct pcap_chip {
struct spi_device *spi;
/* IO */
u32 buf;
struct mutex io_mutex;
/* IRQ */
unsigned int irq_base;
u32 msr;
struct work_struct isr_work;
struct work_struct msr_work;
struct workqueue_struct *workqueue;
/* ADC */
struct pcap_adc_request *adc_queue[PCAP_ADC_MAXQ];
u8 adc_head;
u8 adc_tail;
struct mutex adc_mutex;
};
/* IO */
static int ezx_pcap_putget(struct pcap_chip *pcap, u32 *data)
{
struct spi_transfer t;
struct spi_message m;
int status;
memset(&t, 0, sizeof t);
spi_message_init(&m);
t.len = sizeof(u32);
spi_message_add_tail(&t, &m);
pcap->buf = *data;
t.tx_buf = (u8 *) &pcap->buf;
t.rx_buf = (u8 *) &pcap->buf;
status = spi_sync(pcap->spi, &m);
if (status == 0)
*data = pcap->buf;
return status;
}
int ezx_pcap_write(struct pcap_chip *pcap, u8 reg_num, u32 value)
{
int ret;
mutex_lock(&pcap->io_mutex);
value &= PCAP_REGISTER_VALUE_MASK;
value |= PCAP_REGISTER_WRITE_OP_BIT
| (reg_num << PCAP_REGISTER_ADDRESS_SHIFT);
ret = ezx_pcap_putget(pcap, &value);
mutex_unlock(&pcap->io_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(ezx_pcap_write);
int ezx_pcap_read(struct pcap_chip *pcap, u8 reg_num, u32 *value)
{
int ret;
mutex_lock(&pcap->io_mutex);
*value = PCAP_REGISTER_READ_OP_BIT
| (reg_num << PCAP_REGISTER_ADDRESS_SHIFT);
ret = ezx_pcap_putget(pcap, value);
mutex_unlock(&pcap->io_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(ezx_pcap_read);
int ezx_pcap_set_bits(struct pcap_chip *pcap, u8 reg_num, u32 mask, u32 val)
{
int ret;
u32 tmp = PCAP_REGISTER_READ_OP_BIT |
(reg_num << PCAP_REGISTER_ADDRESS_SHIFT);
mutex_lock(&pcap->io_mutex);
ret = ezx_pcap_putget(pcap, &tmp);
if (ret)
goto out_unlock;
tmp &= (PCAP_REGISTER_VALUE_MASK & ~mask);
tmp |= (val & mask) | PCAP_REGISTER_WRITE_OP_BIT |
(reg_num << PCAP_REGISTER_ADDRESS_SHIFT);
ret = ezx_pcap_putget(pcap, &tmp);
out_unlock:
mutex_unlock(&pcap->io_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(ezx_pcap_set_bits);
/* IRQ */
int irq_to_pcap(struct pcap_chip *pcap, int irq)
{
return irq - pcap->irq_base;
}
EXPORT_SYMBOL_GPL(irq_to_pcap);
int pcap_to_irq(struct pcap_chip *pcap, int irq)
{
return pcap->irq_base + irq;
}
EXPORT_SYMBOL_GPL(pcap_to_irq);
static void pcap_mask_irq(struct irq_data *d)
{
struct pcap_chip *pcap = irq_data_get_irq_chip_data(d);
pcap->msr |= 1 << irq_to_pcap(pcap, d->irq);
queue_work(pcap->workqueue, &pcap->msr_work);
}
static void pcap_unmask_irq(struct irq_data *d)
{
struct pcap_chip *pcap = irq_data_get_irq_chip_data(d);
pcap->msr &= ~(1 << irq_to_pcap(pcap, d->irq));
queue_work(pcap->workqueue, &pcap->msr_work);
}
static struct irq_chip pcap_irq_chip = {
.name = "pcap",
.irq_disable = pcap_mask_irq,
.irq_mask = pcap_mask_irq,
.irq_unmask = pcap_unmask_irq,
};
static void pcap_msr_work(struct work_struct *work)
{
struct pcap_chip *pcap = container_of(work, struct pcap_chip, msr_work);
ezx_pcap_write(pcap, PCAP_REG_MSR, pcap->msr);
}
static void pcap_isr_work(struct work_struct *work)
{
struct pcap_chip *pcap = container_of(work, struct pcap_chip, isr_work);
struct pcap_platform_data *pdata = pcap->spi->dev.platform_data;
u32 msr, isr, int_sel, service;
int irq;
do {
ezx_pcap_read(pcap, PCAP_REG_MSR, &msr);
ezx_pcap_read(pcap, PCAP_REG_ISR, &isr);
/* We can't service/ack irqs that are assigned to port 2 */
if (!(pdata->config & PCAP_SECOND_PORT)) {
ezx_pcap_read(pcap, PCAP_REG_INT_SEL, &int_sel);
isr &= ~int_sel;
}
ezx_pcap_write(pcap, PCAP_REG_MSR, isr | msr);
ezx_pcap_write(pcap, PCAP_REG_ISR, isr);
local_irq_disable();
service = isr & ~msr;
for (irq = pcap->irq_base; service; service >>= 1, irq++) {
if (service & 1)
generic_handle_irq(irq);
}
local_irq_enable();
ezx_pcap_write(pcap, PCAP_REG_MSR, pcap->msr);
} while (gpio_get_value(pdata->gpio));
}
static void pcap_irq_handler(unsigned int irq, struct irq_desc *desc)
{
struct pcap_chip *pcap = irq_get_handler_data(irq);
desc->irq_data.chip->irq_ack(&desc->irq_data);
queue_work(pcap->workqueue, &pcap->isr_work);
return;
}
/* ADC */
void pcap_set_ts_bits(struct pcap_chip *pcap, u32 bits)
{
u32 tmp;
mutex_lock(&pcap->adc_mutex);
ezx_pcap_read(pcap, PCAP_REG_ADC, &tmp);
tmp &= ~(PCAP_ADC_TS_M_MASK | PCAP_ADC_TS_REF_LOWPWR);
tmp |= bits & (PCAP_ADC_TS_M_MASK | PCAP_ADC_TS_REF_LOWPWR);
ezx_pcap_write(pcap, PCAP_REG_ADC, tmp);
mutex_unlock(&pcap->adc_mutex);
}
EXPORT_SYMBOL_GPL(pcap_set_ts_bits);
static void pcap_disable_adc(struct pcap_chip *pcap)
{
u32 tmp;
ezx_pcap_read(pcap, PCAP_REG_ADC, &tmp);
tmp &= ~(PCAP_ADC_ADEN|PCAP_ADC_BATT_I_ADC|PCAP_ADC_BATT_I_POLARITY);
ezx_pcap_write(pcap, PCAP_REG_ADC, tmp);
}
static void pcap_adc_trigger(struct pcap_chip *pcap)
{
u32 tmp;
u8 head;
mutex_lock(&pcap->adc_mutex);
head = pcap->adc_head;
if (!pcap->adc_queue[head]) {
/* queue is empty, save power */
pcap_disable_adc(pcap);
mutex_unlock(&pcap->adc_mutex);
return;
}
/* start conversion on requested bank, save TS_M bits */
ezx_pcap_read(pcap, PCAP_REG_ADC, &tmp);
tmp &= (PCAP_ADC_TS_M_MASK | PCAP_ADC_TS_REF_LOWPWR);
tmp |= pcap->adc_queue[head]->flags | PCAP_ADC_ADEN;
if (pcap->adc_queue[head]->bank == PCAP_ADC_BANK_1)
tmp |= PCAP_ADC_AD_SEL1;
ezx_pcap_write(pcap, PCAP_REG_ADC, tmp);
mutex_unlock(&pcap->adc_mutex);
ezx_pcap_write(pcap, PCAP_REG_ADR, PCAP_ADR_ASC);
}
static irqreturn_t pcap_adc_irq(int irq, void *_pcap)
{
struct pcap_chip *pcap = _pcap;
struct pcap_adc_request *req;
u16 res[2];
u32 tmp;
mutex_lock(&pcap->adc_mutex);
req = pcap->adc_queue[pcap->adc_head];
if (WARN(!req, "adc irq without pending request\n")) {
mutex_unlock(&pcap->adc_mutex);
return IRQ_HANDLED;
}
/* read requested channels results */
ezx_pcap_read(pcap, PCAP_REG_ADC, &tmp);
tmp &= ~(PCAP_ADC_ADA1_MASK | PCAP_ADC_ADA2_MASK);
tmp |= (req->ch[0] << PCAP_ADC_ADA1_SHIFT);
tmp |= (req->ch[1] << PCAP_ADC_ADA2_SHIFT);
ezx_pcap_write(pcap, PCAP_REG_ADC, tmp);
ezx_pcap_read(pcap, PCAP_REG_ADR, &tmp);
res[0] = (tmp & PCAP_ADR_ADD1_MASK) >> PCAP_ADR_ADD1_SHIFT;
res[1] = (tmp & PCAP_ADR_ADD2_MASK) >> PCAP_ADR_ADD2_SHIFT;
pcap->adc_queue[pcap->adc_head] = NULL;
pcap->adc_head = (pcap->adc_head + 1) & (PCAP_ADC_MAXQ - 1);
mutex_unlock(&pcap->adc_mutex);
/* pass the results and release memory */
req->callback(req->data, res);
kfree(req);
/* trigger next conversion (if any) on queue */
pcap_adc_trigger(pcap);
return IRQ_HANDLED;
}
int pcap_adc_async(struct pcap_chip *pcap, u8 bank, u32 flags, u8 ch[],
void *callback, void *data)
{
struct pcap_adc_request *req;
/* This will be freed after we have a result */
req = kmalloc(sizeof(struct pcap_adc_request), GFP_KERNEL);
if (!req)
return -ENOMEM;
req->bank = bank;
req->flags = flags;
req->ch[0] = ch[0];
req->ch[1] = ch[1];
req->callback = callback;
req->data = data;
mutex_lock(&pcap->adc_mutex);
if (pcap->adc_queue[pcap->adc_tail]) {
mutex_unlock(&pcap->adc_mutex);
kfree(req);
return -EBUSY;
}
pcap->adc_queue[pcap->adc_tail] = req;
pcap->adc_tail = (pcap->adc_tail + 1) & (PCAP_ADC_MAXQ - 1);
mutex_unlock(&pcap->adc_mutex);
/* start conversion */
pcap_adc_trigger(pcap);
return 0;
}
EXPORT_SYMBOL_GPL(pcap_adc_async);
static void pcap_adc_sync_cb(void *param, u16 res[])
{
struct pcap_adc_sync_request *req = param;
req->res[0] = res[0];
req->res[1] = res[1];
complete(&req->completion);
}
int pcap_adc_sync(struct pcap_chip *pcap, u8 bank, u32 flags, u8 ch[],
u16 res[])
{
struct pcap_adc_sync_request sync_data;
int ret;
init_completion(&sync_data.completion);
ret = pcap_adc_async(pcap, bank, flags, ch, pcap_adc_sync_cb,
&sync_data);
if (ret)
return ret;
wait_for_completion(&sync_data.completion);
res[0] = sync_data.res[0];
res[1] = sync_data.res[1];
return 0;
}
EXPORT_SYMBOL_GPL(pcap_adc_sync);
/* subdevs */
static int pcap_remove_subdev(struct device *dev, void *unused)
{
platform_device_unregister(to_platform_device(dev));
return 0;
}
static int pcap_add_subdev(struct pcap_chip *pcap,
struct pcap_subdev *subdev)
{
struct platform_device *pdev;
int ret;
pdev = platform_device_alloc(subdev->name, subdev->id);
if (!pdev)
return -ENOMEM;
pdev->dev.parent = &pcap->spi->dev;
pdev->dev.platform_data = subdev->platform_data;
ret = platform_device_add(pdev);
if (ret)
platform_device_put(pdev);
return ret;
}
static int ezx_pcap_remove(struct spi_device *spi)
{
struct pcap_chip *pcap = spi_get_drvdata(spi);
struct pcap_platform_data *pdata = spi->dev.platform_data;
int i, adc_irq;
/* remove all registered subdevs */
device_for_each_child(&spi->dev, NULL, pcap_remove_subdev);
/* cleanup ADC */
adc_irq = pcap_to_irq(pcap, (pdata->config & PCAP_SECOND_PORT) ?
PCAP_IRQ_ADCDONE2 : PCAP_IRQ_ADCDONE);
devm_free_irq(&spi->dev, adc_irq, pcap);
mutex_lock(&pcap->adc_mutex);
for (i = 0; i < PCAP_ADC_MAXQ; i++)
kfree(pcap->adc_queue[i]);
mutex_unlock(&pcap->adc_mutex);
/* cleanup irqchip */
for (i = pcap->irq_base; i < (pcap->irq_base + PCAP_NIRQS); i++)
irq_set_chip_and_handler(i, NULL, NULL);
destroy_workqueue(pcap->workqueue);
return 0;
}
static int ezx_pcap_probe(struct spi_device *spi)
{
struct pcap_platform_data *pdata = spi->dev.platform_data;
struct pcap_chip *pcap;
int i, adc_irq;
int ret = -ENODEV;
/* platform data is required */
if (!pdata)
goto ret;
pcap = devm_kzalloc(&spi->dev, sizeof(*pcap), GFP_KERNEL);
if (!pcap) {
ret = -ENOMEM;
goto ret;
}
mutex_init(&pcap->io_mutex);
mutex_init(&pcap->adc_mutex);
INIT_WORK(&pcap->isr_work, pcap_isr_work);
INIT_WORK(&pcap->msr_work, pcap_msr_work);
spi_set_drvdata(spi, pcap);
/* setup spi */
spi->bits_per_word = 32;
spi->mode = SPI_MODE_0 | (pdata->config & PCAP_CS_AH ? SPI_CS_HIGH : 0);
ret = spi_setup(spi);
if (ret)
goto ret;
pcap->spi = spi;
/* setup irq */
pcap->irq_base = pdata->irq_base;
pcap->workqueue = create_singlethread_workqueue("pcapd");
if (!pcap->workqueue) {
ret = -ENOMEM;
dev_err(&spi->dev, "can't create pcap thread\n");
goto ret;
}
/* redirect interrupts to AP, except adcdone2 */
if (!(pdata->config & PCAP_SECOND_PORT))
ezx_pcap_write(pcap, PCAP_REG_INT_SEL,
(1 << PCAP_IRQ_ADCDONE2));
/* setup irq chip */
for (i = pcap->irq_base; i < (pcap->irq_base + PCAP_NIRQS); i++) {
irq_set_chip_and_handler(i, &pcap_irq_chip, handle_simple_irq);
irq_set_chip_data(i, pcap);
#ifdef CONFIG_ARM
set_irq_flags(i, IRQF_VALID);
#else
irq_set_noprobe(i);
#endif
}
/* mask/ack all PCAP interrupts */
ezx_pcap_write(pcap, PCAP_REG_MSR, PCAP_MASK_ALL_INTERRUPT);
ezx_pcap_write(pcap, PCAP_REG_ISR, PCAP_CLEAR_INTERRUPT_REGISTER);
pcap->msr = PCAP_MASK_ALL_INTERRUPT;
irq_set_irq_type(spi->irq, IRQ_TYPE_EDGE_RISING);
irq_set_handler_data(spi->irq, pcap);
irq_set_chained_handler(spi->irq, pcap_irq_handler);
irq_set_irq_wake(spi->irq, 1);
/* ADC */
adc_irq = pcap_to_irq(pcap, (pdata->config & PCAP_SECOND_PORT) ?
PCAP_IRQ_ADCDONE2 : PCAP_IRQ_ADCDONE);
ret = devm_request_irq(&spi->dev, adc_irq, pcap_adc_irq, 0, "ADC",
pcap);
if (ret)
goto free_irqchip;
/* setup subdevs */
for (i = 0; i < pdata->num_subdevs; i++) {
ret = pcap_add_subdev(pcap, &pdata->subdevs[i]);
if (ret)
goto remove_subdevs;
}
/* board specific quirks */
if (pdata->init)
pdata->init(pcap);
return 0;
remove_subdevs:
device_for_each_child(&spi->dev, NULL, pcap_remove_subdev);
/* free_adc: */
devm_free_irq(&spi->dev, adc_irq, pcap);
free_irqchip:
for (i = pcap->irq_base; i < (pcap->irq_base + PCAP_NIRQS); i++)
irq_set_chip_and_handler(i, NULL, NULL);
/* destroy_workqueue: */
destroy_workqueue(pcap->workqueue);
ret:
return ret;
}
static struct spi_driver ezxpcap_driver = {
.probe = ezx_pcap_probe,
.remove = ezx_pcap_remove,
.driver = {
.name = "ezx-pcap",
.owner = THIS_MODULE,
},
};
static int __init ezx_pcap_init(void)
{
return spi_register_driver(&ezxpcap_driver);
}
static void __exit ezx_pcap_exit(void)
{
spi_unregister_driver(&ezxpcap_driver);
}
subsys_initcall(ezx_pcap_init);
module_exit(ezx_pcap_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Daniel Ribeiro / Harald Welte");
MODULE_DESCRIPTION("Motorola PCAP2 ASIC Driver");
MODULE_ALIAS("spi:ezx-pcap");
| gpl-2.0 |
mcrosson/samsung_kernel_comanche | net/netfilter/ipset/ip_set_hash_netport.c | 2411 | 14173 | /* Copyright (C) 2003-2011 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* Kernel module implementing an IP set type: the hash:net,port type */
#include <linux/jhash.h>
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/skbuff.h>
#include <linux/errno.h>
#include <linux/random.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/netlink.h>
#include <linux/netfilter.h>
#include <linux/netfilter/ipset/pfxlen.h>
#include <linux/netfilter/ipset/ip_set.h>
#include <linux/netfilter/ipset/ip_set_timeout.h>
#include <linux/netfilter/ipset/ip_set_getport.h>
#include <linux/netfilter/ipset/ip_set_hash.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
MODULE_DESCRIPTION("hash:net,port type of IP sets");
MODULE_ALIAS("ip_set_hash:net,port");
/* Type specific function prefix */
#define TYPE hash_netport
static bool
hash_netport_same_set(const struct ip_set *a, const struct ip_set *b);
#define hash_netport4_same_set hash_netport_same_set
#define hash_netport6_same_set hash_netport_same_set
/* The type variant functions: IPv4 */
/* Member elements without timeout */
struct hash_netport4_elem {
__be32 ip;
__be16 port;
u8 proto;
u8 cidr;
};
/* Member elements with timeout support */
struct hash_netport4_telem {
__be32 ip;
__be16 port;
u8 proto;
u8 cidr;
unsigned long timeout;
};
static inline bool
hash_netport4_data_equal(const struct hash_netport4_elem *ip1,
const struct hash_netport4_elem *ip2)
{
return ip1->ip == ip2->ip &&
ip1->port == ip2->port &&
ip1->proto == ip2->proto &&
ip1->cidr == ip2->cidr;
}
static inline bool
hash_netport4_data_isnull(const struct hash_netport4_elem *elem)
{
return elem->proto == 0;
}
static inline void
hash_netport4_data_copy(struct hash_netport4_elem *dst,
const struct hash_netport4_elem *src)
{
dst->ip = src->ip;
dst->port = src->port;
dst->proto = src->proto;
dst->cidr = src->cidr;
}
static inline void
hash_netport4_data_netmask(struct hash_netport4_elem *elem, u8 cidr)
{
elem->ip &= ip_set_netmask(cidr);
elem->cidr = cidr;
}
static inline void
hash_netport4_data_zero_out(struct hash_netport4_elem *elem)
{
elem->proto = 0;
}
static bool
hash_netport4_data_list(struct sk_buff *skb,
const struct hash_netport4_elem *data)
{
NLA_PUT_IPADDR4(skb, IPSET_ATTR_IP, data->ip);
NLA_PUT_NET16(skb, IPSET_ATTR_PORT, data->port);
NLA_PUT_U8(skb, IPSET_ATTR_CIDR, data->cidr);
NLA_PUT_U8(skb, IPSET_ATTR_PROTO, data->proto);
return 0;
nla_put_failure:
return 1;
}
static bool
hash_netport4_data_tlist(struct sk_buff *skb,
const struct hash_netport4_elem *data)
{
const struct hash_netport4_telem *tdata =
(const struct hash_netport4_telem *)data;
NLA_PUT_IPADDR4(skb, IPSET_ATTR_IP, tdata->ip);
NLA_PUT_NET16(skb, IPSET_ATTR_PORT, tdata->port);
NLA_PUT_U8(skb, IPSET_ATTR_CIDR, data->cidr);
NLA_PUT_U8(skb, IPSET_ATTR_PROTO, data->proto);
NLA_PUT_NET32(skb, IPSET_ATTR_TIMEOUT,
htonl(ip_set_timeout_get(tdata->timeout)));
return 0;
nla_put_failure:
return 1;
}
#define IP_SET_HASH_WITH_PROTO
#define IP_SET_HASH_WITH_NETS
#define PF 4
#define HOST_MASK 32
#include <linux/netfilter/ipset/ip_set_ahash.h>
static int
hash_netport4_kadt(struct ip_set *set, const struct sk_buff *skb,
enum ipset_adt adt, u8 pf, u8 dim, u8 flags)
{
const struct ip_set_hash *h = set->data;
ipset_adtfn adtfn = set->variant->adt[adt];
struct hash_netport4_elem data = {
.cidr = h->nets[0].cidr ? h->nets[0].cidr : HOST_MASK
};
if (data.cidr == 0)
return -EINVAL;
if (adt == IPSET_TEST)
data.cidr = HOST_MASK;
if (!ip_set_get_ip4_port(skb, flags & IPSET_DIM_TWO_SRC,
&data.port, &data.proto))
return -EINVAL;
ip4addrptr(skb, flags & IPSET_DIM_ONE_SRC, &data.ip);
data.ip &= ip_set_netmask(data.cidr);
return adtfn(set, &data, h->timeout);
}
static int
hash_netport4_uadt(struct ip_set *set, struct nlattr *tb[],
enum ipset_adt adt, u32 *lineno, u32 flags)
{
const struct ip_set_hash *h = set->data;
ipset_adtfn adtfn = set->variant->adt[adt];
struct hash_netport4_elem data = { .cidr = HOST_MASK };
u32 port, port_to;
u32 timeout = h->timeout;
bool with_ports = false;
int ret;
if (unlikely(!tb[IPSET_ATTR_IP] ||
!ip_set_attr_netorder(tb, IPSET_ATTR_PORT) ||
!ip_set_optattr_netorder(tb, IPSET_ATTR_PORT_TO) ||
!ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT)))
return -IPSET_ERR_PROTOCOL;
if (tb[IPSET_ATTR_LINENO])
*lineno = nla_get_u32(tb[IPSET_ATTR_LINENO]);
ret = ip_set_get_ipaddr4(tb[IPSET_ATTR_IP], &data.ip);
if (ret)
return ret;
if (tb[IPSET_ATTR_CIDR])
data.cidr = nla_get_u8(tb[IPSET_ATTR_CIDR]);
if (!data.cidr)
return -IPSET_ERR_INVALID_CIDR;
data.ip &= ip_set_netmask(data.cidr);
if (tb[IPSET_ATTR_PORT])
data.port = nla_get_be16(tb[IPSET_ATTR_PORT]);
else
return -IPSET_ERR_PROTOCOL;
if (tb[IPSET_ATTR_PROTO]) {
data.proto = nla_get_u8(tb[IPSET_ATTR_PROTO]);
with_ports = ip_set_proto_with_ports(data.proto);
if (data.proto == 0)
return -IPSET_ERR_INVALID_PROTO;
} else
return -IPSET_ERR_MISSING_PROTO;
if (!(with_ports || data.proto == IPPROTO_ICMP))
data.port = 0;
if (tb[IPSET_ATTR_TIMEOUT]) {
if (!with_timeout(h->timeout))
return -IPSET_ERR_TIMEOUT;
timeout = ip_set_timeout_uget(tb[IPSET_ATTR_TIMEOUT]);
}
if (adt == IPSET_TEST || !with_ports || !tb[IPSET_ATTR_PORT_TO]) {
ret = adtfn(set, &data, timeout);
return ip_set_eexist(ret, flags) ? 0 : ret;
}
port = ntohs(data.port);
port_to = ip_set_get_h16(tb[IPSET_ATTR_PORT_TO]);
if (port > port_to)
swap(port, port_to);
for (; port <= port_to; port++) {
data.port = htons(port);
ret = adtfn(set, &data, timeout);
if (ret && !ip_set_eexist(ret, flags))
return ret;
else
ret = 0;
}
return ret;
}
static bool
hash_netport_same_set(const struct ip_set *a, const struct ip_set *b)
{
const struct ip_set_hash *x = a->data;
const struct ip_set_hash *y = b->data;
/* Resizing changes htable_bits, so we ignore it */
return x->maxelem == y->maxelem &&
x->timeout == y->timeout;
}
/* The type variant functions: IPv6 */
struct hash_netport6_elem {
union nf_inet_addr ip;
__be16 port;
u8 proto;
u8 cidr;
};
struct hash_netport6_telem {
union nf_inet_addr ip;
__be16 port;
u8 proto;
u8 cidr;
unsigned long timeout;
};
static inline bool
hash_netport6_data_equal(const struct hash_netport6_elem *ip1,
const struct hash_netport6_elem *ip2)
{
return ipv6_addr_cmp(&ip1->ip.in6, &ip2->ip.in6) == 0 &&
ip1->port == ip2->port &&
ip1->proto == ip2->proto &&
ip1->cidr == ip2->cidr;
}
static inline bool
hash_netport6_data_isnull(const struct hash_netport6_elem *elem)
{
return elem->proto == 0;
}
static inline void
hash_netport6_data_copy(struct hash_netport6_elem *dst,
const struct hash_netport6_elem *src)
{
memcpy(dst, src, sizeof(*dst));
}
static inline void
hash_netport6_data_zero_out(struct hash_netport6_elem *elem)
{
elem->proto = 0;
}
static inline void
ip6_netmask(union nf_inet_addr *ip, u8 prefix)
{
ip->ip6[0] &= ip_set_netmask6(prefix)[0];
ip->ip6[1] &= ip_set_netmask6(prefix)[1];
ip->ip6[2] &= ip_set_netmask6(prefix)[2];
ip->ip6[3] &= ip_set_netmask6(prefix)[3];
}
static inline void
hash_netport6_data_netmask(struct hash_netport6_elem *elem, u8 cidr)
{
ip6_netmask(&elem->ip, cidr);
elem->cidr = cidr;
}
static bool
hash_netport6_data_list(struct sk_buff *skb,
const struct hash_netport6_elem *data)
{
NLA_PUT_IPADDR6(skb, IPSET_ATTR_IP, &data->ip);
NLA_PUT_NET16(skb, IPSET_ATTR_PORT, data->port);
NLA_PUT_U8(skb, IPSET_ATTR_CIDR, data->cidr);
NLA_PUT_U8(skb, IPSET_ATTR_PROTO, data->proto);
return 0;
nla_put_failure:
return 1;
}
static bool
hash_netport6_data_tlist(struct sk_buff *skb,
const struct hash_netport6_elem *data)
{
const struct hash_netport6_telem *e =
(const struct hash_netport6_telem *)data;
NLA_PUT_IPADDR6(skb, IPSET_ATTR_IP, &e->ip);
NLA_PUT_NET16(skb, IPSET_ATTR_PORT, data->port);
NLA_PUT_U8(skb, IPSET_ATTR_CIDR, data->cidr);
NLA_PUT_U8(skb, IPSET_ATTR_PROTO, data->proto);
NLA_PUT_NET32(skb, IPSET_ATTR_TIMEOUT,
htonl(ip_set_timeout_get(e->timeout)));
return 0;
nla_put_failure:
return 1;
}
#undef PF
#undef HOST_MASK
#define PF 6
#define HOST_MASK 128
#include <linux/netfilter/ipset/ip_set_ahash.h>
static int
hash_netport6_kadt(struct ip_set *set, const struct sk_buff *skb,
enum ipset_adt adt, u8 pf, u8 dim, u8 flags)
{
const struct ip_set_hash *h = set->data;
ipset_adtfn adtfn = set->variant->adt[adt];
struct hash_netport6_elem data = {
.cidr = h->nets[0].cidr ? h->nets[0].cidr : HOST_MASK
};
if (data.cidr == 0)
return -EINVAL;
if (adt == IPSET_TEST)
data.cidr = HOST_MASK;
if (!ip_set_get_ip6_port(skb, flags & IPSET_DIM_TWO_SRC,
&data.port, &data.proto))
return -EINVAL;
ip6addrptr(skb, flags & IPSET_DIM_ONE_SRC, &data.ip.in6);
ip6_netmask(&data.ip, data.cidr);
return adtfn(set, &data, h->timeout);
}
static int
hash_netport6_uadt(struct ip_set *set, struct nlattr *tb[],
enum ipset_adt adt, u32 *lineno, u32 flags)
{
const struct ip_set_hash *h = set->data;
ipset_adtfn adtfn = set->variant->adt[adt];
struct hash_netport6_elem data = { .cidr = HOST_MASK };
u32 port, port_to;
u32 timeout = h->timeout;
bool with_ports = false;
int ret;
if (unlikely(!tb[IPSET_ATTR_IP] ||
!ip_set_attr_netorder(tb, IPSET_ATTR_PORT) ||
!ip_set_optattr_netorder(tb, IPSET_ATTR_PORT_TO) ||
!ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT)))
return -IPSET_ERR_PROTOCOL;
if (tb[IPSET_ATTR_LINENO])
*lineno = nla_get_u32(tb[IPSET_ATTR_LINENO]);
ret = ip_set_get_ipaddr6(tb[IPSET_ATTR_IP], &data.ip);
if (ret)
return ret;
if (tb[IPSET_ATTR_CIDR])
data.cidr = nla_get_u8(tb[IPSET_ATTR_CIDR]);
if (!data.cidr)
return -IPSET_ERR_INVALID_CIDR;
ip6_netmask(&data.ip, data.cidr);
if (tb[IPSET_ATTR_PORT])
data.port = nla_get_be16(tb[IPSET_ATTR_PORT]);
else
return -IPSET_ERR_PROTOCOL;
if (tb[IPSET_ATTR_PROTO]) {
data.proto = nla_get_u8(tb[IPSET_ATTR_PROTO]);
with_ports = ip_set_proto_with_ports(data.proto);
if (data.proto == 0)
return -IPSET_ERR_INVALID_PROTO;
} else
return -IPSET_ERR_MISSING_PROTO;
if (!(with_ports || data.proto == IPPROTO_ICMPV6))
data.port = 0;
if (tb[IPSET_ATTR_TIMEOUT]) {
if (!with_timeout(h->timeout))
return -IPSET_ERR_TIMEOUT;
timeout = ip_set_timeout_uget(tb[IPSET_ATTR_TIMEOUT]);
}
if (adt == IPSET_TEST || !with_ports || !tb[IPSET_ATTR_PORT_TO]) {
ret = adtfn(set, &data, timeout);
return ip_set_eexist(ret, flags) ? 0 : ret;
}
port = ntohs(data.port);
port_to = ip_set_get_h16(tb[IPSET_ATTR_PORT_TO]);
if (port > port_to)
swap(port, port_to);
for (; port <= port_to; port++) {
data.port = htons(port);
ret = adtfn(set, &data, timeout);
if (ret && !ip_set_eexist(ret, flags))
return ret;
else
ret = 0;
}
return ret;
}
/* Create hash:ip type of sets */
static int
hash_netport_create(struct ip_set *set, struct nlattr *tb[], u32 flags)
{
struct ip_set_hash *h;
u32 hashsize = IPSET_DEFAULT_HASHSIZE, maxelem = IPSET_DEFAULT_MAXELEM;
u8 hbits;
if (!(set->family == AF_INET || set->family == AF_INET6))
return -IPSET_ERR_INVALID_FAMILY;
if (unlikely(!ip_set_optattr_netorder(tb, IPSET_ATTR_HASHSIZE) ||
!ip_set_optattr_netorder(tb, IPSET_ATTR_MAXELEM) ||
!ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT)))
return -IPSET_ERR_PROTOCOL;
if (tb[IPSET_ATTR_HASHSIZE]) {
hashsize = ip_set_get_h32(tb[IPSET_ATTR_HASHSIZE]);
if (hashsize < IPSET_MIMINAL_HASHSIZE)
hashsize = IPSET_MIMINAL_HASHSIZE;
}
if (tb[IPSET_ATTR_MAXELEM])
maxelem = ip_set_get_h32(tb[IPSET_ATTR_MAXELEM]);
h = kzalloc(sizeof(*h)
+ sizeof(struct ip_set_hash_nets)
* (set->family == AF_INET ? 32 : 128), GFP_KERNEL);
if (!h)
return -ENOMEM;
h->maxelem = maxelem;
get_random_bytes(&h->initval, sizeof(h->initval));
h->timeout = IPSET_NO_TIMEOUT;
hbits = htable_bits(hashsize);
h->table = ip_set_alloc(
sizeof(struct htable)
+ jhash_size(hbits) * sizeof(struct hbucket));
if (!h->table) {
kfree(h);
return -ENOMEM;
}
h->table->htable_bits = hbits;
set->data = h;
if (tb[IPSET_ATTR_TIMEOUT]) {
h->timeout = ip_set_timeout_uget(tb[IPSET_ATTR_TIMEOUT]);
set->variant = set->family == AF_INET
? &hash_netport4_tvariant : &hash_netport6_tvariant;
if (set->family == AF_INET)
hash_netport4_gc_init(set);
else
hash_netport6_gc_init(set);
} else {
set->variant = set->family == AF_INET
? &hash_netport4_variant : &hash_netport6_variant;
}
pr_debug("create %s hashsize %u (%u) maxelem %u: %p(%p)\n",
set->name, jhash_size(h->table->htable_bits),
h->table->htable_bits, h->maxelem, set->data, h->table);
return 0;
}
static struct ip_set_type hash_netport_type __read_mostly = {
.name = "hash:net,port",
.protocol = IPSET_PROTOCOL,
.features = IPSET_TYPE_IP | IPSET_TYPE_PORT,
.dimension = IPSET_DIM_TWO,
.family = AF_UNSPEC,
.revision = 1,
.create = hash_netport_create,
.create_policy = {
[IPSET_ATTR_HASHSIZE] = { .type = NLA_U32 },
[IPSET_ATTR_MAXELEM] = { .type = NLA_U32 },
[IPSET_ATTR_PROBES] = { .type = NLA_U8 },
[IPSET_ATTR_RESIZE] = { .type = NLA_U8 },
[IPSET_ATTR_PROTO] = { .type = NLA_U8 },
[IPSET_ATTR_TIMEOUT] = { .type = NLA_U32 },
},
.adt_policy = {
[IPSET_ATTR_IP] = { .type = NLA_NESTED },
[IPSET_ATTR_PORT] = { .type = NLA_U16 },
[IPSET_ATTR_PORT_TO] = { .type = NLA_U16 },
[IPSET_ATTR_PROTO] = { .type = NLA_U8 },
[IPSET_ATTR_CIDR] = { .type = NLA_U8 },
[IPSET_ATTR_TIMEOUT] = { .type = NLA_U32 },
[IPSET_ATTR_LINENO] = { .type = NLA_U32 },
},
.me = THIS_MODULE,
};
static int __init
hash_netport_init(void)
{
return ip_set_type_register(&hash_netport_type);
}
static void __exit
hash_netport_fini(void)
{
ip_set_type_unregister(&hash_netport_type);
}
module_init(hash_netport_init);
module_exit(hash_netport_fini);
| gpl-2.0 |
krachlatte/Sony-Xperia-Go-ST27i-ICS | arch/arm/mach-orion5x/rd88f6183ap-ge-setup.c | 2667 | 3253 | /*
* arch/arm/mach-orion5x/rd88f6183-ap-ge-setup.c
*
* Marvell Orion-1-90 AP GE Reference Design 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/pci.h>
#include <linux/irq.h>
#include <linux/mtd/physmap.h>
#include <linux/mv643xx_eth.h>
#include <linux/spi/spi.h>
#include <linux/spi/orion_spi.h>
#include <linux/spi/flash.h>
#include <linux/ethtool.h>
#include <net/dsa.h>
#include <asm/mach-types.h>
#include <asm/gpio.h>
#include <asm/leds.h>
#include <asm/mach/arch.h>
#include <asm/mach/pci.h>
#include <mach/orion5x.h>
#include "common.h"
static struct mv643xx_eth_platform_data rd88f6183ap_ge_eth_data = {
.phy_addr = -1,
.speed = SPEED_1000,
.duplex = DUPLEX_FULL,
};
static struct dsa_chip_data rd88f6183ap_ge_switch_chip_data = {
.port_names[0] = "lan1",
.port_names[1] = "lan2",
.port_names[2] = "lan3",
.port_names[3] = "lan4",
.port_names[4] = "wan",
.port_names[5] = "cpu",
};
static struct dsa_platform_data rd88f6183ap_ge_switch_plat_data = {
.nr_chips = 1,
.chip = &rd88f6183ap_ge_switch_chip_data,
};
static struct mtd_partition rd88f6183ap_ge_partitions[] = {
{
.name = "kernel",
.offset = 0x00000000,
.size = 0x00200000,
}, {
.name = "rootfs",
.offset = 0x00200000,
.size = 0x00500000,
}, {
.name = "nvram",
.offset = 0x00700000,
.size = 0x00080000,
},
};
static struct flash_platform_data rd88f6183ap_ge_spi_slave_data = {
.type = "m25p64",
.nr_parts = ARRAY_SIZE(rd88f6183ap_ge_partitions),
.parts = rd88f6183ap_ge_partitions,
};
static struct spi_board_info __initdata rd88f6183ap_ge_spi_slave_info[] = {
{
.modalias = "m25p80",
.platform_data = &rd88f6183ap_ge_spi_slave_data,
.irq = NO_IRQ,
.max_speed_hz = 20000000,
.bus_num = 0,
.chip_select = 0,
},
};
static void __init rd88f6183ap_ge_init(void)
{
/*
* Setup basic Orion functions. Need to be called early.
*/
orion5x_init();
/*
* Configure peripherals.
*/
orion5x_ehci0_init();
orion5x_eth_init(&rd88f6183ap_ge_eth_data);
orion5x_eth_switch_init(&rd88f6183ap_ge_switch_plat_data,
gpio_to_irq(3));
spi_register_board_info(rd88f6183ap_ge_spi_slave_info,
ARRAY_SIZE(rd88f6183ap_ge_spi_slave_info));
orion5x_spi_init();
orion5x_uart0_init();
}
static struct hw_pci rd88f6183ap_ge_pci __initdata = {
.nr_controllers = 2,
.swizzle = pci_std_swizzle,
.setup = orion5x_pci_sys_setup,
.scan = orion5x_pci_sys_scan_bus,
.map_irq = orion5x_pci_map_irq,
};
static int __init rd88f6183ap_ge_pci_init(void)
{
if (machine_is_rd88f6183ap_ge()) {
orion5x_pci_disable();
pci_common_init(&rd88f6183ap_ge_pci);
}
return 0;
}
subsys_initcall(rd88f6183ap_ge_pci_init);
MACHINE_START(RD88F6183AP_GE, "Marvell Orion-1-90 AP GE Reference Design")
/* Maintainer: Lennert Buytenhek <buytenh@marvell.com> */
.boot_params = 0x00000100,
.init_machine = rd88f6183ap_ge_init,
.map_io = orion5x_map_io,
.init_early = orion5x_init_early,
.init_irq = orion5x_init_irq,
.timer = &orion5x_timer,
.fixup = tag_fixup_mem32,
MACHINE_END
| gpl-2.0 |
jjm2473/AMLOGIC_M8 | sound/pci/au88x0/au88x0_a3d.c | 2923 | 25221 | /***************************************************************************
* au88x0_a3d.c
*
* Fri Jul 18 14:16:22 2003
* Copyright 2003 mjander
* mjander@users.sourceforge.net
*
* A3D. You may think i'm crazy, but this may work someday. Who knows...
****************************************************************************/
/*
* 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 Library 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 "au88x0_a3d.h"
#include "au88x0_a3ddata.c"
#include "au88x0_xtalk.h"
#include "au88x0.h"
static void
a3dsrc_SetTimeConsts(a3dsrc_t * a, short HrtfTrack, short ItdTrack,
short GTrack, short CTrack)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfTrackTC), HrtfTrack);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_ITDTrackTC), ItdTrack);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_GainTrackTC), GTrack);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_CoeffTrackTC), CTrack);
}
#if 0
static void
a3dsrc_GetTimeConsts(a3dsrc_t * a, short *HrtfTrack, short *ItdTrack,
short *GTrack, short *CTrack)
{
// stub!
}
#endif
/* Atmospheric absorption. */
static void
a3dsrc_SetAtmosTarget(a3dsrc_t * a, short aa, short b, short c, short d,
short e)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_A21Target),
(e << 0x10) | d);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B10Target),
(b << 0x10) | aa);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B2Target), c);
}
static void
a3dsrc_SetAtmosCurrent(a3dsrc_t * a, short aa, short b, short c, short d,
short e)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_A12Current),
(e << 0x10) | d);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B01Current),
(b << 0x10) | aa);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B2Current), c);
}
static void
a3dsrc_SetAtmosState(a3dsrc_t * a, short x1, short x2, short y1, short y2)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, a3d_addrA(a->slice, a->source, A3D_A_x1), x1);
hwwrite(vortex->mmio, a3d_addrA(a->slice, a->source, A3D_A_x2), x2);
hwwrite(vortex->mmio, a3d_addrA(a->slice, a->source, A3D_A_y1), y1);
hwwrite(vortex->mmio, a3d_addrA(a->slice, a->source, A3D_A_y2), y2);
}
#if 0
static void
a3dsrc_GetAtmosTarget(a3dsrc_t * a, short *aa, short *b, short *c,
short *d, short *e)
{
}
static void
a3dsrc_GetAtmosCurrent(a3dsrc_t * a, short *bb01, short *ab01, short *b2,
short *aa12, short *ba12)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*aa12 =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_A12Current));
*ba12 =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_A12Current));
*ab01 =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_B01Current));
*bb01 =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B01Current));
*b2 =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_B2Current));
}
static void
a3dsrc_GetAtmosState(a3dsrc_t * a, short *x1, short *x2, short *y1, short *y2)
{
}
#endif
/* HRTF */
static void
a3dsrc_SetHrtfTarget(a3dsrc_t * a, a3d_Hrtf_t const aa, a3d_Hrtf_t const b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfTarget) + (i << 2),
(b[i] << 0x10) | aa[i]);
}
static void
a3dsrc_SetHrtfCurrent(a3dsrc_t * a, a3d_Hrtf_t const aa, a3d_Hrtf_t const b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfCurrent) + (i << 2),
(b[i] << 0x10) | aa[i]);
}
static void
a3dsrc_SetHrtfState(a3dsrc_t * a, a3d_Hrtf_t const aa, a3d_Hrtf_t const b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfDelayLine) + (i << 2),
(b[i] << 0x10) | aa[i]);
}
static void a3dsrc_SetHrtfOutput(a3dsrc_t * a, short left, short right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfOutL), left);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfOutR), right);
}
#if 0
static void a3dsrc_GetHrtfTarget(a3dsrc_t * a, a3d_Hrtf_t aa, a3d_Hrtf_t b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
aa[i] =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_HrtfTarget + (i << 2)));
for (i = 0; i < HRTF_SZ; i++)
b[i] =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfTarget + (i << 2)));
}
static void a3dsrc_GetHrtfCurrent(a3dsrc_t * a, a3d_Hrtf_t aa, a3d_Hrtf_t b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
aa[i] =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_HrtfCurrent + (i << 2)));
for (i = 0; i < HRTF_SZ; i++)
b[i] =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfCurrent + (i << 2)));
}
static void a3dsrc_GetHrtfState(a3dsrc_t * a, a3d_Hrtf_t aa, a3d_Hrtf_t b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
// FIXME: verify this!
for (i = 0; i < HRTF_SZ; i++)
aa[i] =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_HrtfDelayLine + (i << 2)));
for (i = 0; i < HRTF_SZ; i++)
b[i] =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfDelayLine + (i << 2)));
}
static void a3dsrc_GetHrtfOutput(a3dsrc_t * a, short *left, short *right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*left =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfOutL));
*right =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfOutR));
}
#endif
/* Interaural Time Difference.
* "The other main clue that humans use to locate sounds, is called
* Interaural Time Difference (ITD). The differences in distance from
* the sound source to a listeners ears means that the sound will
* reach one ear slightly before the other....", found somewhere with google.*/
static void a3dsrc_SetItdTarget(a3dsrc_t * a, short litd, short ritd)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
if (litd < 0)
litd = 0;
if (litd > 0x57FF)
litd = 0x57FF;
if (ritd < 0)
ritd = 0;
if (ritd > 0x57FF)
ritd = 0x57FF;
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_ITDTarget),
(ritd << 0x10) | litd);
//hwwrite(vortex->mmio, addr(0x191DF+5, this04, this08), (ritd<<0x10)|litd);
}
static void a3dsrc_SetItdCurrent(a3dsrc_t * a, short litd, short ritd)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
if (litd < 0)
litd = 0;
if (litd > 0x57FF)
litd = 0x57FF;
if (ritd < 0)
ritd = 0;
if (ritd > 0x57FF)
ritd = 0x57FF;
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_ITDCurrent),
(ritd << 0x10) | litd);
//hwwrite(vortex->mmio, addr(0x191DF+1, this04, this08), (ritd<<0x10)|litd);
}
static void a3dsrc_SetItdDline(a3dsrc_t * a, a3d_ItdDline_t const dline)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
/* 45 != 40 -> Check this ! */
for (i = 0; i < DLINE_SZ; i++)
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_ITDDelayLine) + (i << 2), dline[i]);
}
#if 0
static void a3dsrc_GetItdTarget(a3dsrc_t * a, short *litd, short *ritd)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*ritd =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_ITDTarget));
*litd =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_ITDTarget));
}
static void a3dsrc_GetItdCurrent(a3dsrc_t * a, short *litd, short *ritd)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*ritd =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_ITDCurrent));
*litd =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_ITDCurrent));
}
static void a3dsrc_GetItdDline(a3dsrc_t * a, a3d_ItdDline_t dline)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < DLINE_SZ; i++)
dline[i] =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_ITDDelayLine + (i << 2)));
}
#endif
/* This is may be used for ILD Interaural Level Difference. */
static void a3dsrc_SetGainTarget(a3dsrc_t * a, short left, short right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_GainTarget),
(right << 0x10) | left);
}
static void a3dsrc_SetGainCurrent(a3dsrc_t * a, short left, short right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_GainCurrent),
(right << 0x10) | left);
}
#if 0
static void a3dsrc_GetGainTarget(a3dsrc_t * a, short *left, short *right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*right =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_GainTarget));
*left =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_GainTarget));
}
static void a3dsrc_GetGainCurrent(a3dsrc_t * a, short *left, short *right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*right =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_GainCurrent));
*left =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_GainCurrent));
}
/* CA3dIO this func seems to be inlined all over this place. */
static void CA3dIO_WriteReg(a3dsrc_t * a, unsigned long addr, short aa, short b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, addr, (aa << 0x10) | b);
}
#endif
/* Generic A3D stuff */
static void a3dsrc_SetA3DSampleRate(a3dsrc_t * a, int sr)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int esp0 = 0;
esp0 = (((esp0 & 0x7fffffff) | 0xB8000000) & 0x7) | ((sr & 0x1f) << 3);
hwwrite(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd), esp0);
//hwwrite(vortex->mmio, 0x19C38 + (this08<<0xd), esp0);
}
static void a3dsrc_EnableA3D(a3dsrc_t * a)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd),
0xF0000001);
//hwwrite(vortex->mmio, 0x19C38 + (this08<<0xd), 0xF0000001);
}
static void a3dsrc_DisableA3D(a3dsrc_t * a)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd),
0xF0000000);
}
static void a3dsrc_SetA3DControlReg(a3dsrc_t * a, unsigned long ctrl)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd), ctrl);
}
static void a3dsrc_SetA3DPointerReg(a3dsrc_t * a, unsigned long ptr)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, A3D_SLICE_Pointers + ((a->slice) << 0xd), ptr);
}
#if 0
static void a3dsrc_GetA3DSampleRate(a3dsrc_t * a, int *sr)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*sr = ((hwread(vortex->mmio, A3D_SLICE_Control + (a->slice << 0xd))
>> 3) & 0x1f);
//*sr = ((hwread(vortex->mmio, 0x19C38 + (this08<<0xd))>>3)&0x1f);
}
static void a3dsrc_GetA3DControlReg(a3dsrc_t * a, unsigned long *ctrl)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*ctrl = hwread(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd));
}
static void a3dsrc_GetA3DPointerReg(a3dsrc_t * a, unsigned long *ptr)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*ptr = hwread(vortex->mmio, A3D_SLICE_Pointers + ((a->slice) << 0xd));
}
#endif
static void a3dsrc_ZeroSliceIO(a3dsrc_t * a)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < 8; i++)
hwwrite(vortex->mmio,
A3D_SLICE_VDBDest +
((((a->slice) << 0xb) + i) << 2), 0);
for (i = 0; i < 4; i++)
hwwrite(vortex->mmio,
A3D_SLICE_VDBSource +
((((a->slice) << 0xb) + i) << 2), 0);
}
/* Reset Single A3D source. */
static void a3dsrc_ZeroState(a3dsrc_t * a)
{
/*
printk(KERN_DEBUG "vortex: ZeroState slice: %d, source %d\n",
a->slice, a->source);
*/
a3dsrc_SetAtmosState(a, 0, 0, 0, 0);
a3dsrc_SetHrtfState(a, A3dHrirZeros, A3dHrirZeros);
a3dsrc_SetItdDline(a, A3dItdDlineZeros);
a3dsrc_SetHrtfOutput(a, 0, 0);
a3dsrc_SetTimeConsts(a, 0, 0, 0, 0);
a3dsrc_SetAtmosCurrent(a, 0, 0, 0, 0, 0);
a3dsrc_SetAtmosTarget(a, 0, 0, 0, 0, 0);
a3dsrc_SetItdCurrent(a, 0, 0);
a3dsrc_SetItdTarget(a, 0, 0);
a3dsrc_SetGainCurrent(a, 0, 0);
a3dsrc_SetGainTarget(a, 0, 0);
a3dsrc_SetHrtfCurrent(a, A3dHrirZeros, A3dHrirZeros);
a3dsrc_SetHrtfTarget(a, A3dHrirZeros, A3dHrirZeros);
}
/* Reset entire A3D engine */
static void a3dsrc_ZeroStateA3D(a3dsrc_t * a)
{
int i, var, var2;
if ((a->vortex) == NULL) {
printk(KERN_ERR "vortex: ZeroStateA3D: ERROR: a->vortex is NULL\n");
return;
}
a3dsrc_SetA3DControlReg(a, 0);
a3dsrc_SetA3DPointerReg(a, 0);
var = a->slice;
var2 = a->source;
for (i = 0; i < 4; i++) {
a->slice = i;
a3dsrc_ZeroSliceIO(a);
//a3dsrc_ZeroState(a);
}
a->source = var2;
a->slice = var;
}
/* Program A3D block as pass through */
static void a3dsrc_ProgramPipe(a3dsrc_t * a)
{
a3dsrc_SetTimeConsts(a, 0, 0, 0, 0);
a3dsrc_SetAtmosCurrent(a, 0, 0x4000, 0, 0, 0);
a3dsrc_SetAtmosTarget(a, 0x4000, 0, 0, 0, 0);
a3dsrc_SetItdCurrent(a, 0, 0);
a3dsrc_SetItdTarget(a, 0, 0);
a3dsrc_SetGainCurrent(a, 0x7fff, 0x7fff);
a3dsrc_SetGainTarget(a, 0x7fff, 0x7fff);
/* SET HRTF HERE */
/* Single spike leads to identity transfer function. */
a3dsrc_SetHrtfCurrent(a, A3dHrirImpulse, A3dHrirImpulse);
a3dsrc_SetHrtfTarget(a, A3dHrirImpulse, A3dHrirImpulse);
/* Test: Sounds saturated. */
//a3dsrc_SetHrtfCurrent(a, A3dHrirSatTest, A3dHrirSatTest);
//a3dsrc_SetHrtfTarget(a, A3dHrirSatTest, A3dHrirSatTest);
}
/* VDB = Vortex audio Dataflow Bus */
#if 0
static void a3dsrc_ClearVDBData(a3dsrc_t * a, unsigned long aa)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
// ((aa >> 2) << 8) - (aa >> 2)
hwwrite(vortex->mmio,
a3d_addrS(a->slice, A3D_SLICE_VDBDest) + (a->source << 2), 0);
hwwrite(vortex->mmio,
a3d_addrS(a->slice,
A3D_SLICE_VDBDest + 4) + (a->source << 2), 0);
/*
hwwrite(vortex->mmio, 0x19c00 + (((aa>>2)*255*4)+aa)*8, 0);
hwwrite(vortex->mmio, 0x19c04 + (((aa>>2)*255*4)+aa)*8, 0);
*/
}
#endif
/* A3D HwSource stuff. */
static void vortex_A3dSourceHw_Initialize(vortex_t * v, int source, int slice)
{
a3dsrc_t *a3dsrc = &(v->a3d[source + (slice * 4)]);
//a3dsrc_t *a3dsrc = &(v->a3d[source + (slice*4)]);
a3dsrc->vortex = (void *)v;
a3dsrc->source = source; /* source */
a3dsrc->slice = slice; /* slice */
a3dsrc_ZeroState(a3dsrc);
/* Added by me. */
a3dsrc_SetA3DSampleRate(a3dsrc, 0x11);
}
static int Vort3DRend_Initialize(vortex_t * v, unsigned short mode)
{
v->xt_mode = mode; /* this_14 */
vortex_XtalkHw_init(v);
vortex_XtalkHw_SetGainsAllChan(v);
switch (v->xt_mode) {
case XT_SPEAKER0:
vortex_XtalkHw_ProgramXtalkNarrow(v);
break;
case XT_SPEAKER1:
vortex_XtalkHw_ProgramXtalkWide(v);
break;
default:
case XT_HEADPHONE:
vortex_XtalkHw_ProgramPipe(v);
break;
case XT_DIAMOND:
vortex_XtalkHw_ProgramDiamondXtalk(v);
break;
}
vortex_XtalkHw_SetSampleRate(v, 0x11);
vortex_XtalkHw_Enable(v);
return 0;
}
/* 3D Sound entry points. */
static int vortex_a3d_register_controls(vortex_t * vortex);
static void vortex_a3d_unregister_controls(vortex_t * vortex);
/* A3D base support init/shudown */
static void vortex_Vort3D_enable(vortex_t *v)
{
int i;
Vort3DRend_Initialize(v, XT_HEADPHONE);
for (i = 0; i < NR_A3D; i++) {
vortex_A3dSourceHw_Initialize(v, i % 4, i >> 2);
a3dsrc_ZeroStateA3D(&(v->a3d[0]));
}
/* Register ALSA controls */
vortex_a3d_register_controls(v);
}
static void vortex_Vort3D_disable(vortex_t * v)
{
vortex_XtalkHw_Disable(v);
vortex_a3d_unregister_controls(v);
}
/* Make A3D subsystem connections. */
static void vortex_Vort3D_connect(vortex_t * v, int en)
{
int i;
// Disable AU8810 routes, since they seem to be wrong (in au8810.h).
#ifdef CHIP_AU8810
return;
#endif
#if 1
/* Alloc Xtalk mixin resources */
v->mixxtlk[0] =
vortex_adb_checkinout(v, v->fixed_res, en, VORTEX_RESOURCE_MIXIN);
if (v->mixxtlk[0] < 0) {
printk
("vortex: vortex_Vort3D: ERROR: not enough free mixer resources.\n");
return;
}
v->mixxtlk[1] =
vortex_adb_checkinout(v, v->fixed_res, en, VORTEX_RESOURCE_MIXIN);
if (v->mixxtlk[1] < 0) {
printk
("vortex: vortex_Vort3D: ERROR: not enough free mixer resources.\n");
return;
}
#endif
/* Connect A3D -> XTALK */
for (i = 0; i < 4; i++) {
// 2 outputs per each A3D slice.
vortex_route(v, en, 0x11, ADB_A3DOUT(i * 2), ADB_XTALKIN(i));
vortex_route(v, en, 0x11, ADB_A3DOUT(i * 2) + 1, ADB_XTALKIN(5 + i));
}
#if 0
vortex_route(v, en, 0x11, ADB_XTALKOUT(0), ADB_EQIN(2));
vortex_route(v, en, 0x11, ADB_XTALKOUT(1), ADB_EQIN(3));
#else
/* Connect XTalk -> mixer */
vortex_route(v, en, 0x11, ADB_XTALKOUT(0), ADB_MIXIN(v->mixxtlk[0]));
vortex_route(v, en, 0x11, ADB_XTALKOUT(1), ADB_MIXIN(v->mixxtlk[1]));
vortex_connection_mixin_mix(v, en, v->mixxtlk[0], v->mixplayb[0], 0);
vortex_connection_mixin_mix(v, en, v->mixxtlk[1], v->mixplayb[1], 0);
vortex_mix_setinputvolumebyte(v, v->mixplayb[0], v->mixxtlk[0],
en ? MIX_DEFIGAIN : VOL_MIN);
vortex_mix_setinputvolumebyte(v, v->mixplayb[1], v->mixxtlk[1],
en ? MIX_DEFIGAIN : VOL_MIN);
if (VORTEX_IS_QUAD(v)) {
vortex_connection_mixin_mix(v, en, v->mixxtlk[0],
v->mixplayb[2], 0);
vortex_connection_mixin_mix(v, en, v->mixxtlk[1],
v->mixplayb[3], 0);
vortex_mix_setinputvolumebyte(v, v->mixplayb[2],
v->mixxtlk[0],
en ? MIX_DEFIGAIN : VOL_MIN);
vortex_mix_setinputvolumebyte(v, v->mixplayb[3],
v->mixxtlk[1],
en ? MIX_DEFIGAIN : VOL_MIN);
}
#endif
}
/* Initialize one single A3D source. */
static void vortex_Vort3D_InitializeSource(a3dsrc_t * a, int en)
{
if (a->vortex == NULL) {
printk
("vortex: Vort3D_InitializeSource: A3D source not initialized\n");
return;
}
if (en) {
a3dsrc_ProgramPipe(a);
a3dsrc_SetA3DSampleRate(a, 0x11);
a3dsrc_SetTimeConsts(a, HrtfTCDefault,
ItdTCDefault, GainTCDefault,
CoefTCDefault);
/* Remark: zero gain is muted. */
//a3dsrc_SetGainTarget(a,0,0);
//a3dsrc_SetGainCurrent(a,0,0);
a3dsrc_EnableA3D(a);
} else {
a3dsrc_DisableA3D(a);
a3dsrc_ZeroState(a);
}
}
/* Conversion of coordinates into 3D parameters. */
static void vortex_a3d_coord2hrtf(a3d_Hrtf_t hrtf, int *coord)
{
/* FIXME: implement this. */
}
static void vortex_a3d_coord2itd(a3d_Itd_t itd, int *coord)
{
/* FIXME: implement this. */
}
static void vortex_a3d_coord2ild(a3d_LRGains_t ild, int left, int right)
{
/* FIXME: implement this. */
}
static void vortex_a3d_translate_filter(a3d_atmos_t filter, int *params)
{
/* FIXME: implement this. */
}
/* ALSA control interface. */
static int
snd_vortex_a3d_hrtf_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 6;
uinfo->value.integer.min = 0x00000000;
uinfo->value.integer.max = 0xffffffff;
return 0;
}
static int
snd_vortex_a3d_itd_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0x00000000;
uinfo->value.integer.max = 0xffffffff;
return 0;
}
static int
snd_vortex_a3d_ild_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0x00000000;
uinfo->value.integer.max = 0xffffffff;
return 0;
}
static int
snd_vortex_a3d_filter_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 4;
uinfo->value.integer.min = 0x00000000;
uinfo->value.integer.max = 0xffffffff;
return 0;
}
static int
snd_vortex_a3d_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
//a3dsrc_t *a = kcontrol->private_data;
/* No read yet. Would this be really useable/needed ? */
return 0;
}
static int
snd_vortex_a3d_hrtf_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
a3dsrc_t *a = kcontrol->private_data;
int changed = 1, i;
int coord[6];
for (i = 0; i < 6; i++)
coord[i] = ucontrol->value.integer.value[i];
/* Translate orientation coordinates to a3d params. */
vortex_a3d_coord2hrtf(a->hrtf[0], coord);
vortex_a3d_coord2hrtf(a->hrtf[1], coord);
a3dsrc_SetHrtfTarget(a, a->hrtf[0], a->hrtf[1]);
a3dsrc_SetHrtfCurrent(a, a->hrtf[0], a->hrtf[1]);
return changed;
}
static int
snd_vortex_a3d_itd_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
a3dsrc_t *a = kcontrol->private_data;
int coord[6];
int i, changed = 1;
for (i = 0; i < 6; i++)
coord[i] = ucontrol->value.integer.value[i];
/* Translate orientation coordinates to a3d params. */
vortex_a3d_coord2itd(a->hrtf[0], coord);
vortex_a3d_coord2itd(a->hrtf[1], coord);
/* Inter aural time difference. */
a3dsrc_SetItdTarget(a, a->itd[0], a->itd[1]);
a3dsrc_SetItdCurrent(a, a->itd[0], a->itd[1]);
a3dsrc_SetItdDline(a, a->dline);
return changed;
}
static int
snd_vortex_a3d_ild_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
a3dsrc_t *a = kcontrol->private_data;
int changed = 1;
int l, r;
/* There may be some scale tranlation needed here. */
l = ucontrol->value.integer.value[0];
r = ucontrol->value.integer.value[1];
vortex_a3d_coord2ild(a->ild, l, r);
/* Left Right panning. */
a3dsrc_SetGainTarget(a, l, r);
a3dsrc_SetGainCurrent(a, l, r);
return changed;
}
static int
snd_vortex_a3d_filter_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
a3dsrc_t *a = kcontrol->private_data;
int i, changed = 1;
int params[6];
for (i = 0; i < 6; i++)
params[i] = ucontrol->value.integer.value[i];
/* Translate generic filter params to a3d filter params. */
vortex_a3d_translate_filter(a->filter, params);
/* Atmospheric absorption and filtering. */
a3dsrc_SetAtmosTarget(a, a->filter[0],
a->filter[1], a->filter[2],
a->filter[3], a->filter[4]);
a3dsrc_SetAtmosCurrent(a, a->filter[0],
a->filter[1], a->filter[2],
a->filter[3], a->filter[4]);
return changed;
}
static struct snd_kcontrol_new vortex_a3d_kcontrol = {
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = "Playback PCM advanced processing",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_vortex_a3d_hrtf_info,
.get = snd_vortex_a3d_get,
.put = snd_vortex_a3d_hrtf_put,
};
/* Control (un)registration. */
static int vortex_a3d_register_controls(vortex_t *vortex)
{
struct snd_kcontrol *kcontrol;
int err, i;
/* HRTF controls. */
for (i = 0; i < NR_A3D; i++) {
if ((kcontrol =
snd_ctl_new1(&vortex_a3d_kcontrol, &vortex->a3d[i])) == NULL)
return -ENOMEM;
kcontrol->id.numid = CTRLID_HRTF;
kcontrol->info = snd_vortex_a3d_hrtf_info;
kcontrol->put = snd_vortex_a3d_hrtf_put;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
}
/* ITD controls. */
for (i = 0; i < NR_A3D; i++) {
if ((kcontrol =
snd_ctl_new1(&vortex_a3d_kcontrol, &vortex->a3d[i])) == NULL)
return -ENOMEM;
kcontrol->id.numid = CTRLID_ITD;
kcontrol->info = snd_vortex_a3d_itd_info;
kcontrol->put = snd_vortex_a3d_itd_put;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
}
/* ILD (gains) controls. */
for (i = 0; i < NR_A3D; i++) {
if ((kcontrol =
snd_ctl_new1(&vortex_a3d_kcontrol, &vortex->a3d[i])) == NULL)
return -ENOMEM;
kcontrol->id.numid = CTRLID_GAINS;
kcontrol->info = snd_vortex_a3d_ild_info;
kcontrol->put = snd_vortex_a3d_ild_put;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
}
/* Filter controls. */
for (i = 0; i < NR_A3D; i++) {
if ((kcontrol =
snd_ctl_new1(&vortex_a3d_kcontrol, &vortex->a3d[i])) == NULL)
return -ENOMEM;
kcontrol->id.numid = CTRLID_FILTER;
kcontrol->info = snd_vortex_a3d_filter_info;
kcontrol->put = snd_vortex_a3d_filter_put;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
}
return 0;
}
static void vortex_a3d_unregister_controls(vortex_t * vortex)
{
}
/* End of File*/
| gpl-2.0 |
pst1337/cm11_mkc_boeffla | drivers/hwmon/s3c-hwmon.c | 2923 | 10714 | /* linux/drivers/hwmon/s3c-hwmon.c
*
* Copyright (C) 2005, 2008, 2009 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* S3C24XX/S3C64XX ADC hwmon support
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* 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/slab.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <plat/adc.h>
#include <plat/hwmon.h>
struct s3c_hwmon_attr {
struct sensor_device_attribute in;
struct sensor_device_attribute label;
char in_name[12];
char label_name[12];
};
/**
* struct s3c_hwmon - ADC hwmon client information
* @lock: Access lock to serialise the conversions.
* @client: The client we registered with the S3C ADC core.
* @hwmon_dev: The hwmon device we created.
* @attr: The holders for the channel attributes.
*/
struct s3c_hwmon {
struct mutex lock;
struct s3c_adc_client *client;
struct device *hwmon_dev;
struct s3c_hwmon_attr attrs[8];
};
/**
* s3c_hwmon_read_ch - read a value from a given adc channel.
* @dev: The device.
* @hwmon: Our state.
* @channel: The channel we're reading from.
*
* Read a value from the @channel with the proper locking and sleep until
* either the read completes or we timeout awaiting the ADC core to get
* back to us.
*/
static int s3c_hwmon_read_ch(struct device *dev,
struct s3c_hwmon *hwmon, int channel)
{
int ret;
ret = mutex_lock_interruptible(&hwmon->lock);
if (ret < 0)
return ret;
dev_dbg(dev, "reading channel %d\n", channel);
ret = s3c_adc_read(hwmon->client, channel);
mutex_unlock(&hwmon->lock);
return ret;
}
#ifdef CONFIG_SENSORS_S3C_RAW
/**
* s3c_hwmon_show_raw - show a conversion from the raw channel number.
* @dev: The device that the attribute belongs to.
* @attr: The attribute being read.
* @buf: The result buffer.
*
* This show deals with the raw attribute, registered for each possible
* ADC channel. This does a conversion and returns the raw (un-scaled)
* value returned from the hardware.
*/
static ssize_t s3c_hwmon_show_raw(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct s3c_hwmon *adc = platform_get_drvdata(to_platform_device(dev));
struct sensor_device_attribute *sa = to_sensor_dev_attr(attr);
int ret;
ret = s3c_hwmon_read_ch(dev, adc, sa->index);
return (ret < 0) ? ret : snprintf(buf, PAGE_SIZE, "%d\n", ret);
}
#define DEF_ADC_ATTR(x) \
static SENSOR_DEVICE_ATTR(adc##x##_raw, S_IRUGO, s3c_hwmon_show_raw, NULL, x)
DEF_ADC_ATTR(0);
DEF_ADC_ATTR(1);
DEF_ADC_ATTR(2);
DEF_ADC_ATTR(3);
DEF_ADC_ATTR(4);
DEF_ADC_ATTR(5);
DEF_ADC_ATTR(6);
DEF_ADC_ATTR(7);
static struct attribute *s3c_hwmon_attrs[9] = {
&sensor_dev_attr_adc0_raw.dev_attr.attr,
&sensor_dev_attr_adc1_raw.dev_attr.attr,
&sensor_dev_attr_adc2_raw.dev_attr.attr,
&sensor_dev_attr_adc3_raw.dev_attr.attr,
&sensor_dev_attr_adc4_raw.dev_attr.attr,
&sensor_dev_attr_adc5_raw.dev_attr.attr,
&sensor_dev_attr_adc6_raw.dev_attr.attr,
&sensor_dev_attr_adc7_raw.dev_attr.attr,
NULL,
};
static struct attribute_group s3c_hwmon_attrgroup = {
.attrs = s3c_hwmon_attrs,
};
static inline int s3c_hwmon_add_raw(struct device *dev)
{
return sysfs_create_group(&dev->kobj, &s3c_hwmon_attrgroup);
}
static inline void s3c_hwmon_remove_raw(struct device *dev)
{
sysfs_remove_group(&dev->kobj, &s3c_hwmon_attrgroup);
}
#else
static inline int s3c_hwmon_add_raw(struct device *dev) { return 0; }
static inline void s3c_hwmon_remove_raw(struct device *dev) { }
#endif /* CONFIG_SENSORS_S3C_RAW */
/**
* s3c_hwmon_ch_show - show value of a given channel
* @dev: The device that the attribute belongs to.
* @attr: The attribute being read.
* @buf: The result buffer.
*
* Read a value from the ADC and scale it before returning it to the
* caller. The scale factor is gained from the channel configuration
* passed via the platform data when the device was registered.
*/
static ssize_t s3c_hwmon_ch_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sen_attr = to_sensor_dev_attr(attr);
struct s3c_hwmon *hwmon = platform_get_drvdata(to_platform_device(dev));
struct s3c_hwmon_pdata *pdata = dev->platform_data;
struct s3c_hwmon_chcfg *cfg;
int ret;
cfg = pdata->in[sen_attr->index];
ret = s3c_hwmon_read_ch(dev, hwmon, sen_attr->index);
if (ret < 0)
return ret;
ret *= cfg->mult;
ret = DIV_ROUND_CLOSEST(ret, cfg->div);
return snprintf(buf, PAGE_SIZE, "%d\n", ret);
}
/**
* s3c_hwmon_label_show - show label name of the given channel.
* @dev: The device that the attribute belongs to.
* @attr: The attribute being read.
* @buf: The result buffer.
*
* Return the label name of a given channel
*/
static ssize_t s3c_hwmon_label_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sen_attr = to_sensor_dev_attr(attr);
struct s3c_hwmon_pdata *pdata = dev->platform_data;
struct s3c_hwmon_chcfg *cfg;
cfg = pdata->in[sen_attr->index];
return snprintf(buf, PAGE_SIZE, "%s\n", cfg->name);
}
/**
* s3c_hwmon_create_attr - create hwmon attribute for given channel.
* @dev: The device to create the attribute on.
* @cfg: The channel configuration passed from the platform data.
* @channel: The ADC channel number to process.
*
* Create the scaled attribute for use with hwmon from the specified
* platform data in @pdata. The sysfs entry is handled by the routine
* s3c_hwmon_ch_show().
*
* The attribute name is taken from the configuration data if present
* otherwise the name is taken by concatenating in_ with the channel
* number.
*/
static int s3c_hwmon_create_attr(struct device *dev,
struct s3c_hwmon_chcfg *cfg,
struct s3c_hwmon_attr *attrs,
int channel)
{
struct sensor_device_attribute *attr;
int ret;
snprintf(attrs->in_name, sizeof(attrs->in_name), "in%d_input", channel);
attr = &attrs->in;
attr->index = channel;
sysfs_attr_init(&attr->dev_attr.attr);
attr->dev_attr.attr.name = attrs->in_name;
attr->dev_attr.attr.mode = S_IRUGO;
attr->dev_attr.show = s3c_hwmon_ch_show;
ret = device_create_file(dev, &attr->dev_attr);
if (ret < 0) {
dev_err(dev, "failed to create input attribute\n");
return ret;
}
/* if this has a name, add a label */
if (cfg->name) {
snprintf(attrs->label_name, sizeof(attrs->label_name),
"in%d_label", channel);
attr = &attrs->label;
attr->index = channel;
sysfs_attr_init(&attr->dev_attr.attr);
attr->dev_attr.attr.name = attrs->label_name;
attr->dev_attr.attr.mode = S_IRUGO;
attr->dev_attr.show = s3c_hwmon_label_show;
ret = device_create_file(dev, &attr->dev_attr);
if (ret < 0) {
device_remove_file(dev, &attrs->in.dev_attr);
dev_err(dev, "failed to create label attribute\n");
}
}
return ret;
}
static void s3c_hwmon_remove_attr(struct device *dev,
struct s3c_hwmon_attr *attrs)
{
device_remove_file(dev, &attrs->in.dev_attr);
device_remove_file(dev, &attrs->label.dev_attr);
}
/**
* s3c_hwmon_probe - device probe entry.
* @dev: The device being probed.
*/
static int __devinit s3c_hwmon_probe(struct platform_device *dev)
{
struct s3c_hwmon_pdata *pdata = dev->dev.platform_data;
struct s3c_hwmon *hwmon;
int ret = 0;
int i;
if (!pdata) {
dev_err(&dev->dev, "no platform data supplied\n");
return -EINVAL;
}
hwmon = kzalloc(sizeof(struct s3c_hwmon), GFP_KERNEL);
if (hwmon == NULL) {
dev_err(&dev->dev, "no memory\n");
return -ENOMEM;
}
platform_set_drvdata(dev, hwmon);
mutex_init(&hwmon->lock);
/* Register with the core ADC driver. */
hwmon->client = s3c_adc_register(dev, NULL, NULL, 0);
if (IS_ERR(hwmon->client)) {
dev_err(&dev->dev, "cannot register adc\n");
ret = PTR_ERR(hwmon->client);
goto err_mem;
}
/* add attributes for our adc devices. */
ret = s3c_hwmon_add_raw(&dev->dev);
if (ret)
goto err_registered;
/* register with the hwmon core */
hwmon->hwmon_dev = hwmon_device_register(&dev->dev);
if (IS_ERR(hwmon->hwmon_dev)) {
dev_err(&dev->dev, "error registering with hwmon\n");
ret = PTR_ERR(hwmon->hwmon_dev);
goto err_raw_attribute;
}
for (i = 0; i < ARRAY_SIZE(pdata->in); i++) {
struct s3c_hwmon_chcfg *cfg = pdata->in[i];
if (!cfg)
continue;
if (cfg->mult >= 0x10000)
dev_warn(&dev->dev,
"channel %d multiplier too large\n",
i);
if (cfg->div == 0) {
dev_err(&dev->dev, "channel %d divider zero\n", i);
continue;
}
ret = s3c_hwmon_create_attr(&dev->dev, pdata->in[i],
&hwmon->attrs[i], i);
if (ret) {
dev_err(&dev->dev,
"error creating channel %d\n", i);
for (i--; i >= 0; i--)
s3c_hwmon_remove_attr(&dev->dev,
&hwmon->attrs[i]);
goto err_hwmon_register;
}
}
return 0;
err_hwmon_register:
hwmon_device_unregister(hwmon->hwmon_dev);
err_raw_attribute:
s3c_hwmon_remove_raw(&dev->dev);
err_registered:
s3c_adc_release(hwmon->client);
err_mem:
kfree(hwmon);
return ret;
}
static int __devexit s3c_hwmon_remove(struct platform_device *dev)
{
struct s3c_hwmon *hwmon = platform_get_drvdata(dev);
int i;
s3c_hwmon_remove_raw(&dev->dev);
for (i = 0; i < ARRAY_SIZE(hwmon->attrs); i++)
s3c_hwmon_remove_attr(&dev->dev, &hwmon->attrs[i]);
hwmon_device_unregister(hwmon->hwmon_dev);
s3c_adc_release(hwmon->client);
return 0;
}
static struct platform_driver s3c_hwmon_driver = {
.driver = {
.name = "s3c-hwmon",
.owner = THIS_MODULE,
},
.probe = s3c_hwmon_probe,
.remove = __devexit_p(s3c_hwmon_remove),
};
static int __init s3c_hwmon_init(void)
{
return platform_driver_register(&s3c_hwmon_driver);
}
static void __exit s3c_hwmon_exit(void)
{
platform_driver_unregister(&s3c_hwmon_driver);
}
module_init(s3c_hwmon_init);
module_exit(s3c_hwmon_exit);
MODULE_AUTHOR("Ben Dooks <ben@simtec.co.uk>");
MODULE_DESCRIPTION("S3C ADC HWMon driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:s3c-hwmon");
| gpl-2.0 |
zoobab/vzkernel | sound/pci/au88x0/au88x0_a3d.c | 2923 | 25221 | /***************************************************************************
* au88x0_a3d.c
*
* Fri Jul 18 14:16:22 2003
* Copyright 2003 mjander
* mjander@users.sourceforge.net
*
* A3D. You may think i'm crazy, but this may work someday. Who knows...
****************************************************************************/
/*
* 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 Library 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 "au88x0_a3d.h"
#include "au88x0_a3ddata.c"
#include "au88x0_xtalk.h"
#include "au88x0.h"
static void
a3dsrc_SetTimeConsts(a3dsrc_t * a, short HrtfTrack, short ItdTrack,
short GTrack, short CTrack)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfTrackTC), HrtfTrack);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_ITDTrackTC), ItdTrack);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_GainTrackTC), GTrack);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_CoeffTrackTC), CTrack);
}
#if 0
static void
a3dsrc_GetTimeConsts(a3dsrc_t * a, short *HrtfTrack, short *ItdTrack,
short *GTrack, short *CTrack)
{
// stub!
}
#endif
/* Atmospheric absorption. */
static void
a3dsrc_SetAtmosTarget(a3dsrc_t * a, short aa, short b, short c, short d,
short e)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_A21Target),
(e << 0x10) | d);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B10Target),
(b << 0x10) | aa);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B2Target), c);
}
static void
a3dsrc_SetAtmosCurrent(a3dsrc_t * a, short aa, short b, short c, short d,
short e)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_A12Current),
(e << 0x10) | d);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B01Current),
(b << 0x10) | aa);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B2Current), c);
}
static void
a3dsrc_SetAtmosState(a3dsrc_t * a, short x1, short x2, short y1, short y2)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, a3d_addrA(a->slice, a->source, A3D_A_x1), x1);
hwwrite(vortex->mmio, a3d_addrA(a->slice, a->source, A3D_A_x2), x2);
hwwrite(vortex->mmio, a3d_addrA(a->slice, a->source, A3D_A_y1), y1);
hwwrite(vortex->mmio, a3d_addrA(a->slice, a->source, A3D_A_y2), y2);
}
#if 0
static void
a3dsrc_GetAtmosTarget(a3dsrc_t * a, short *aa, short *b, short *c,
short *d, short *e)
{
}
static void
a3dsrc_GetAtmosCurrent(a3dsrc_t * a, short *bb01, short *ab01, short *b2,
short *aa12, short *ba12)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*aa12 =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_A12Current));
*ba12 =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_A12Current));
*ab01 =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_B01Current));
*bb01 =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B01Current));
*b2 =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_B2Current));
}
static void
a3dsrc_GetAtmosState(a3dsrc_t * a, short *x1, short *x2, short *y1, short *y2)
{
}
#endif
/* HRTF */
static void
a3dsrc_SetHrtfTarget(a3dsrc_t * a, a3d_Hrtf_t const aa, a3d_Hrtf_t const b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfTarget) + (i << 2),
(b[i] << 0x10) | aa[i]);
}
static void
a3dsrc_SetHrtfCurrent(a3dsrc_t * a, a3d_Hrtf_t const aa, a3d_Hrtf_t const b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfCurrent) + (i << 2),
(b[i] << 0x10) | aa[i]);
}
static void
a3dsrc_SetHrtfState(a3dsrc_t * a, a3d_Hrtf_t const aa, a3d_Hrtf_t const b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfDelayLine) + (i << 2),
(b[i] << 0x10) | aa[i]);
}
static void a3dsrc_SetHrtfOutput(a3dsrc_t * a, short left, short right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfOutL), left);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfOutR), right);
}
#if 0
static void a3dsrc_GetHrtfTarget(a3dsrc_t * a, a3d_Hrtf_t aa, a3d_Hrtf_t b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
aa[i] =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_HrtfTarget + (i << 2)));
for (i = 0; i < HRTF_SZ; i++)
b[i] =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfTarget + (i << 2)));
}
static void a3dsrc_GetHrtfCurrent(a3dsrc_t * a, a3d_Hrtf_t aa, a3d_Hrtf_t b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
aa[i] =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_HrtfCurrent + (i << 2)));
for (i = 0; i < HRTF_SZ; i++)
b[i] =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfCurrent + (i << 2)));
}
static void a3dsrc_GetHrtfState(a3dsrc_t * a, a3d_Hrtf_t aa, a3d_Hrtf_t b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
// FIXME: verify this!
for (i = 0; i < HRTF_SZ; i++)
aa[i] =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_HrtfDelayLine + (i << 2)));
for (i = 0; i < HRTF_SZ; i++)
b[i] =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfDelayLine + (i << 2)));
}
static void a3dsrc_GetHrtfOutput(a3dsrc_t * a, short *left, short *right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*left =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfOutL));
*right =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfOutR));
}
#endif
/* Interaural Time Difference.
* "The other main clue that humans use to locate sounds, is called
* Interaural Time Difference (ITD). The differences in distance from
* the sound source to a listeners ears means that the sound will
* reach one ear slightly before the other....", found somewhere with google.*/
static void a3dsrc_SetItdTarget(a3dsrc_t * a, short litd, short ritd)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
if (litd < 0)
litd = 0;
if (litd > 0x57FF)
litd = 0x57FF;
if (ritd < 0)
ritd = 0;
if (ritd > 0x57FF)
ritd = 0x57FF;
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_ITDTarget),
(ritd << 0x10) | litd);
//hwwrite(vortex->mmio, addr(0x191DF+5, this04, this08), (ritd<<0x10)|litd);
}
static void a3dsrc_SetItdCurrent(a3dsrc_t * a, short litd, short ritd)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
if (litd < 0)
litd = 0;
if (litd > 0x57FF)
litd = 0x57FF;
if (ritd < 0)
ritd = 0;
if (ritd > 0x57FF)
ritd = 0x57FF;
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_ITDCurrent),
(ritd << 0x10) | litd);
//hwwrite(vortex->mmio, addr(0x191DF+1, this04, this08), (ritd<<0x10)|litd);
}
static void a3dsrc_SetItdDline(a3dsrc_t * a, a3d_ItdDline_t const dline)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
/* 45 != 40 -> Check this ! */
for (i = 0; i < DLINE_SZ; i++)
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_ITDDelayLine) + (i << 2), dline[i]);
}
#if 0
static void a3dsrc_GetItdTarget(a3dsrc_t * a, short *litd, short *ritd)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*ritd =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_ITDTarget));
*litd =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_ITDTarget));
}
static void a3dsrc_GetItdCurrent(a3dsrc_t * a, short *litd, short *ritd)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*ritd =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_ITDCurrent));
*litd =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_ITDCurrent));
}
static void a3dsrc_GetItdDline(a3dsrc_t * a, a3d_ItdDline_t dline)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < DLINE_SZ; i++)
dline[i] =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_ITDDelayLine + (i << 2)));
}
#endif
/* This is may be used for ILD Interaural Level Difference. */
static void a3dsrc_SetGainTarget(a3dsrc_t * a, short left, short right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_GainTarget),
(right << 0x10) | left);
}
static void a3dsrc_SetGainCurrent(a3dsrc_t * a, short left, short right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_GainCurrent),
(right << 0x10) | left);
}
#if 0
static void a3dsrc_GetGainTarget(a3dsrc_t * a, short *left, short *right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*right =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_GainTarget));
*left =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_GainTarget));
}
static void a3dsrc_GetGainCurrent(a3dsrc_t * a, short *left, short *right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*right =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_GainCurrent));
*left =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_GainCurrent));
}
/* CA3dIO this func seems to be inlined all over this place. */
static void CA3dIO_WriteReg(a3dsrc_t * a, unsigned long addr, short aa, short b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, addr, (aa << 0x10) | b);
}
#endif
/* Generic A3D stuff */
static void a3dsrc_SetA3DSampleRate(a3dsrc_t * a, int sr)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int esp0 = 0;
esp0 = (((esp0 & 0x7fffffff) | 0xB8000000) & 0x7) | ((sr & 0x1f) << 3);
hwwrite(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd), esp0);
//hwwrite(vortex->mmio, 0x19C38 + (this08<<0xd), esp0);
}
static void a3dsrc_EnableA3D(a3dsrc_t * a)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd),
0xF0000001);
//hwwrite(vortex->mmio, 0x19C38 + (this08<<0xd), 0xF0000001);
}
static void a3dsrc_DisableA3D(a3dsrc_t * a)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd),
0xF0000000);
}
static void a3dsrc_SetA3DControlReg(a3dsrc_t * a, unsigned long ctrl)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd), ctrl);
}
static void a3dsrc_SetA3DPointerReg(a3dsrc_t * a, unsigned long ptr)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, A3D_SLICE_Pointers + ((a->slice) << 0xd), ptr);
}
#if 0
static void a3dsrc_GetA3DSampleRate(a3dsrc_t * a, int *sr)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*sr = ((hwread(vortex->mmio, A3D_SLICE_Control + (a->slice << 0xd))
>> 3) & 0x1f);
//*sr = ((hwread(vortex->mmio, 0x19C38 + (this08<<0xd))>>3)&0x1f);
}
static void a3dsrc_GetA3DControlReg(a3dsrc_t * a, unsigned long *ctrl)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*ctrl = hwread(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd));
}
static void a3dsrc_GetA3DPointerReg(a3dsrc_t * a, unsigned long *ptr)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*ptr = hwread(vortex->mmio, A3D_SLICE_Pointers + ((a->slice) << 0xd));
}
#endif
static void a3dsrc_ZeroSliceIO(a3dsrc_t * a)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < 8; i++)
hwwrite(vortex->mmio,
A3D_SLICE_VDBDest +
((((a->slice) << 0xb) + i) << 2), 0);
for (i = 0; i < 4; i++)
hwwrite(vortex->mmio,
A3D_SLICE_VDBSource +
((((a->slice) << 0xb) + i) << 2), 0);
}
/* Reset Single A3D source. */
static void a3dsrc_ZeroState(a3dsrc_t * a)
{
/*
printk(KERN_DEBUG "vortex: ZeroState slice: %d, source %d\n",
a->slice, a->source);
*/
a3dsrc_SetAtmosState(a, 0, 0, 0, 0);
a3dsrc_SetHrtfState(a, A3dHrirZeros, A3dHrirZeros);
a3dsrc_SetItdDline(a, A3dItdDlineZeros);
a3dsrc_SetHrtfOutput(a, 0, 0);
a3dsrc_SetTimeConsts(a, 0, 0, 0, 0);
a3dsrc_SetAtmosCurrent(a, 0, 0, 0, 0, 0);
a3dsrc_SetAtmosTarget(a, 0, 0, 0, 0, 0);
a3dsrc_SetItdCurrent(a, 0, 0);
a3dsrc_SetItdTarget(a, 0, 0);
a3dsrc_SetGainCurrent(a, 0, 0);
a3dsrc_SetGainTarget(a, 0, 0);
a3dsrc_SetHrtfCurrent(a, A3dHrirZeros, A3dHrirZeros);
a3dsrc_SetHrtfTarget(a, A3dHrirZeros, A3dHrirZeros);
}
/* Reset entire A3D engine */
static void a3dsrc_ZeroStateA3D(a3dsrc_t * a)
{
int i, var, var2;
if ((a->vortex) == NULL) {
printk(KERN_ERR "vortex: ZeroStateA3D: ERROR: a->vortex is NULL\n");
return;
}
a3dsrc_SetA3DControlReg(a, 0);
a3dsrc_SetA3DPointerReg(a, 0);
var = a->slice;
var2 = a->source;
for (i = 0; i < 4; i++) {
a->slice = i;
a3dsrc_ZeroSliceIO(a);
//a3dsrc_ZeroState(a);
}
a->source = var2;
a->slice = var;
}
/* Program A3D block as pass through */
static void a3dsrc_ProgramPipe(a3dsrc_t * a)
{
a3dsrc_SetTimeConsts(a, 0, 0, 0, 0);
a3dsrc_SetAtmosCurrent(a, 0, 0x4000, 0, 0, 0);
a3dsrc_SetAtmosTarget(a, 0x4000, 0, 0, 0, 0);
a3dsrc_SetItdCurrent(a, 0, 0);
a3dsrc_SetItdTarget(a, 0, 0);
a3dsrc_SetGainCurrent(a, 0x7fff, 0x7fff);
a3dsrc_SetGainTarget(a, 0x7fff, 0x7fff);
/* SET HRTF HERE */
/* Single spike leads to identity transfer function. */
a3dsrc_SetHrtfCurrent(a, A3dHrirImpulse, A3dHrirImpulse);
a3dsrc_SetHrtfTarget(a, A3dHrirImpulse, A3dHrirImpulse);
/* Test: Sounds saturated. */
//a3dsrc_SetHrtfCurrent(a, A3dHrirSatTest, A3dHrirSatTest);
//a3dsrc_SetHrtfTarget(a, A3dHrirSatTest, A3dHrirSatTest);
}
/* VDB = Vortex audio Dataflow Bus */
#if 0
static void a3dsrc_ClearVDBData(a3dsrc_t * a, unsigned long aa)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
// ((aa >> 2) << 8) - (aa >> 2)
hwwrite(vortex->mmio,
a3d_addrS(a->slice, A3D_SLICE_VDBDest) + (a->source << 2), 0);
hwwrite(vortex->mmio,
a3d_addrS(a->slice,
A3D_SLICE_VDBDest + 4) + (a->source << 2), 0);
/*
hwwrite(vortex->mmio, 0x19c00 + (((aa>>2)*255*4)+aa)*8, 0);
hwwrite(vortex->mmio, 0x19c04 + (((aa>>2)*255*4)+aa)*8, 0);
*/
}
#endif
/* A3D HwSource stuff. */
static void vortex_A3dSourceHw_Initialize(vortex_t * v, int source, int slice)
{
a3dsrc_t *a3dsrc = &(v->a3d[source + (slice * 4)]);
//a3dsrc_t *a3dsrc = &(v->a3d[source + (slice*4)]);
a3dsrc->vortex = (void *)v;
a3dsrc->source = source; /* source */
a3dsrc->slice = slice; /* slice */
a3dsrc_ZeroState(a3dsrc);
/* Added by me. */
a3dsrc_SetA3DSampleRate(a3dsrc, 0x11);
}
static int Vort3DRend_Initialize(vortex_t * v, unsigned short mode)
{
v->xt_mode = mode; /* this_14 */
vortex_XtalkHw_init(v);
vortex_XtalkHw_SetGainsAllChan(v);
switch (v->xt_mode) {
case XT_SPEAKER0:
vortex_XtalkHw_ProgramXtalkNarrow(v);
break;
case XT_SPEAKER1:
vortex_XtalkHw_ProgramXtalkWide(v);
break;
default:
case XT_HEADPHONE:
vortex_XtalkHw_ProgramPipe(v);
break;
case XT_DIAMOND:
vortex_XtalkHw_ProgramDiamondXtalk(v);
break;
}
vortex_XtalkHw_SetSampleRate(v, 0x11);
vortex_XtalkHw_Enable(v);
return 0;
}
/* 3D Sound entry points. */
static int vortex_a3d_register_controls(vortex_t * vortex);
static void vortex_a3d_unregister_controls(vortex_t * vortex);
/* A3D base support init/shudown */
static void vortex_Vort3D_enable(vortex_t *v)
{
int i;
Vort3DRend_Initialize(v, XT_HEADPHONE);
for (i = 0; i < NR_A3D; i++) {
vortex_A3dSourceHw_Initialize(v, i % 4, i >> 2);
a3dsrc_ZeroStateA3D(&(v->a3d[0]));
}
/* Register ALSA controls */
vortex_a3d_register_controls(v);
}
static void vortex_Vort3D_disable(vortex_t * v)
{
vortex_XtalkHw_Disable(v);
vortex_a3d_unregister_controls(v);
}
/* Make A3D subsystem connections. */
static void vortex_Vort3D_connect(vortex_t * v, int en)
{
int i;
// Disable AU8810 routes, since they seem to be wrong (in au8810.h).
#ifdef CHIP_AU8810
return;
#endif
#if 1
/* Alloc Xtalk mixin resources */
v->mixxtlk[0] =
vortex_adb_checkinout(v, v->fixed_res, en, VORTEX_RESOURCE_MIXIN);
if (v->mixxtlk[0] < 0) {
printk
("vortex: vortex_Vort3D: ERROR: not enough free mixer resources.\n");
return;
}
v->mixxtlk[1] =
vortex_adb_checkinout(v, v->fixed_res, en, VORTEX_RESOURCE_MIXIN);
if (v->mixxtlk[1] < 0) {
printk
("vortex: vortex_Vort3D: ERROR: not enough free mixer resources.\n");
return;
}
#endif
/* Connect A3D -> XTALK */
for (i = 0; i < 4; i++) {
// 2 outputs per each A3D slice.
vortex_route(v, en, 0x11, ADB_A3DOUT(i * 2), ADB_XTALKIN(i));
vortex_route(v, en, 0x11, ADB_A3DOUT(i * 2) + 1, ADB_XTALKIN(5 + i));
}
#if 0
vortex_route(v, en, 0x11, ADB_XTALKOUT(0), ADB_EQIN(2));
vortex_route(v, en, 0x11, ADB_XTALKOUT(1), ADB_EQIN(3));
#else
/* Connect XTalk -> mixer */
vortex_route(v, en, 0x11, ADB_XTALKOUT(0), ADB_MIXIN(v->mixxtlk[0]));
vortex_route(v, en, 0x11, ADB_XTALKOUT(1), ADB_MIXIN(v->mixxtlk[1]));
vortex_connection_mixin_mix(v, en, v->mixxtlk[0], v->mixplayb[0], 0);
vortex_connection_mixin_mix(v, en, v->mixxtlk[1], v->mixplayb[1], 0);
vortex_mix_setinputvolumebyte(v, v->mixplayb[0], v->mixxtlk[0],
en ? MIX_DEFIGAIN : VOL_MIN);
vortex_mix_setinputvolumebyte(v, v->mixplayb[1], v->mixxtlk[1],
en ? MIX_DEFIGAIN : VOL_MIN);
if (VORTEX_IS_QUAD(v)) {
vortex_connection_mixin_mix(v, en, v->mixxtlk[0],
v->mixplayb[2], 0);
vortex_connection_mixin_mix(v, en, v->mixxtlk[1],
v->mixplayb[3], 0);
vortex_mix_setinputvolumebyte(v, v->mixplayb[2],
v->mixxtlk[0],
en ? MIX_DEFIGAIN : VOL_MIN);
vortex_mix_setinputvolumebyte(v, v->mixplayb[3],
v->mixxtlk[1],
en ? MIX_DEFIGAIN : VOL_MIN);
}
#endif
}
/* Initialize one single A3D source. */
static void vortex_Vort3D_InitializeSource(a3dsrc_t * a, int en)
{
if (a->vortex == NULL) {
printk
("vortex: Vort3D_InitializeSource: A3D source not initialized\n");
return;
}
if (en) {
a3dsrc_ProgramPipe(a);
a3dsrc_SetA3DSampleRate(a, 0x11);
a3dsrc_SetTimeConsts(a, HrtfTCDefault,
ItdTCDefault, GainTCDefault,
CoefTCDefault);
/* Remark: zero gain is muted. */
//a3dsrc_SetGainTarget(a,0,0);
//a3dsrc_SetGainCurrent(a,0,0);
a3dsrc_EnableA3D(a);
} else {
a3dsrc_DisableA3D(a);
a3dsrc_ZeroState(a);
}
}
/* Conversion of coordinates into 3D parameters. */
static void vortex_a3d_coord2hrtf(a3d_Hrtf_t hrtf, int *coord)
{
/* FIXME: implement this. */
}
static void vortex_a3d_coord2itd(a3d_Itd_t itd, int *coord)
{
/* FIXME: implement this. */
}
static void vortex_a3d_coord2ild(a3d_LRGains_t ild, int left, int right)
{
/* FIXME: implement this. */
}
static void vortex_a3d_translate_filter(a3d_atmos_t filter, int *params)
{
/* FIXME: implement this. */
}
/* ALSA control interface. */
static int
snd_vortex_a3d_hrtf_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 6;
uinfo->value.integer.min = 0x00000000;
uinfo->value.integer.max = 0xffffffff;
return 0;
}
static int
snd_vortex_a3d_itd_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0x00000000;
uinfo->value.integer.max = 0xffffffff;
return 0;
}
static int
snd_vortex_a3d_ild_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0x00000000;
uinfo->value.integer.max = 0xffffffff;
return 0;
}
static int
snd_vortex_a3d_filter_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 4;
uinfo->value.integer.min = 0x00000000;
uinfo->value.integer.max = 0xffffffff;
return 0;
}
static int
snd_vortex_a3d_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
//a3dsrc_t *a = kcontrol->private_data;
/* No read yet. Would this be really useable/needed ? */
return 0;
}
static int
snd_vortex_a3d_hrtf_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
a3dsrc_t *a = kcontrol->private_data;
int changed = 1, i;
int coord[6];
for (i = 0; i < 6; i++)
coord[i] = ucontrol->value.integer.value[i];
/* Translate orientation coordinates to a3d params. */
vortex_a3d_coord2hrtf(a->hrtf[0], coord);
vortex_a3d_coord2hrtf(a->hrtf[1], coord);
a3dsrc_SetHrtfTarget(a, a->hrtf[0], a->hrtf[1]);
a3dsrc_SetHrtfCurrent(a, a->hrtf[0], a->hrtf[1]);
return changed;
}
static int
snd_vortex_a3d_itd_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
a3dsrc_t *a = kcontrol->private_data;
int coord[6];
int i, changed = 1;
for (i = 0; i < 6; i++)
coord[i] = ucontrol->value.integer.value[i];
/* Translate orientation coordinates to a3d params. */
vortex_a3d_coord2itd(a->hrtf[0], coord);
vortex_a3d_coord2itd(a->hrtf[1], coord);
/* Inter aural time difference. */
a3dsrc_SetItdTarget(a, a->itd[0], a->itd[1]);
a3dsrc_SetItdCurrent(a, a->itd[0], a->itd[1]);
a3dsrc_SetItdDline(a, a->dline);
return changed;
}
static int
snd_vortex_a3d_ild_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
a3dsrc_t *a = kcontrol->private_data;
int changed = 1;
int l, r;
/* There may be some scale tranlation needed here. */
l = ucontrol->value.integer.value[0];
r = ucontrol->value.integer.value[1];
vortex_a3d_coord2ild(a->ild, l, r);
/* Left Right panning. */
a3dsrc_SetGainTarget(a, l, r);
a3dsrc_SetGainCurrent(a, l, r);
return changed;
}
static int
snd_vortex_a3d_filter_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
a3dsrc_t *a = kcontrol->private_data;
int i, changed = 1;
int params[6];
for (i = 0; i < 6; i++)
params[i] = ucontrol->value.integer.value[i];
/* Translate generic filter params to a3d filter params. */
vortex_a3d_translate_filter(a->filter, params);
/* Atmospheric absorption and filtering. */
a3dsrc_SetAtmosTarget(a, a->filter[0],
a->filter[1], a->filter[2],
a->filter[3], a->filter[4]);
a3dsrc_SetAtmosCurrent(a, a->filter[0],
a->filter[1], a->filter[2],
a->filter[3], a->filter[4]);
return changed;
}
static struct snd_kcontrol_new vortex_a3d_kcontrol = {
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = "Playback PCM advanced processing",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_vortex_a3d_hrtf_info,
.get = snd_vortex_a3d_get,
.put = snd_vortex_a3d_hrtf_put,
};
/* Control (un)registration. */
static int vortex_a3d_register_controls(vortex_t *vortex)
{
struct snd_kcontrol *kcontrol;
int err, i;
/* HRTF controls. */
for (i = 0; i < NR_A3D; i++) {
if ((kcontrol =
snd_ctl_new1(&vortex_a3d_kcontrol, &vortex->a3d[i])) == NULL)
return -ENOMEM;
kcontrol->id.numid = CTRLID_HRTF;
kcontrol->info = snd_vortex_a3d_hrtf_info;
kcontrol->put = snd_vortex_a3d_hrtf_put;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
}
/* ITD controls. */
for (i = 0; i < NR_A3D; i++) {
if ((kcontrol =
snd_ctl_new1(&vortex_a3d_kcontrol, &vortex->a3d[i])) == NULL)
return -ENOMEM;
kcontrol->id.numid = CTRLID_ITD;
kcontrol->info = snd_vortex_a3d_itd_info;
kcontrol->put = snd_vortex_a3d_itd_put;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
}
/* ILD (gains) controls. */
for (i = 0; i < NR_A3D; i++) {
if ((kcontrol =
snd_ctl_new1(&vortex_a3d_kcontrol, &vortex->a3d[i])) == NULL)
return -ENOMEM;
kcontrol->id.numid = CTRLID_GAINS;
kcontrol->info = snd_vortex_a3d_ild_info;
kcontrol->put = snd_vortex_a3d_ild_put;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
}
/* Filter controls. */
for (i = 0; i < NR_A3D; i++) {
if ((kcontrol =
snd_ctl_new1(&vortex_a3d_kcontrol, &vortex->a3d[i])) == NULL)
return -ENOMEM;
kcontrol->id.numid = CTRLID_FILTER;
kcontrol->info = snd_vortex_a3d_filter_info;
kcontrol->put = snd_vortex_a3d_filter_put;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
}
return 0;
}
static void vortex_a3d_unregister_controls(vortex_t * vortex)
{
}
/* End of File*/
| gpl-2.0 |
djmax81/Hani_Kernel_Exynos5433 | drivers/tty/serial/8250/8250_gsc.c | 3947 | 3869 | /*
* Serial Device Initialisation for Lasi/Asp/Wax/Dino
*
* (c) Copyright Matthew Wilcox <willy@debian.org> 2001-2002
*
* 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/errno.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/module.h>
#include <linux/serial_core.h>
#include <linux/signal.h>
#include <linux/types.h>
#include <asm/hardware.h>
#include <asm/parisc-device.h>
#include <asm/io.h>
#include "8250.h"
static int __init serial_init_chip(struct parisc_device *dev)
{
struct uart_8250_port uart;
unsigned long address;
int err;
#ifdef CONFIG_64BIT
if (!dev->irq && (dev->id.sversion == 0xad))
dev->irq = iosapic_serial_irq(dev);
#endif
if (!dev->irq) {
/* We find some unattached serial ports by walking native
* busses. These should be silently ignored. Otherwise,
* what we have here is a missing parent device, so tell
* the user what they're missing.
*/
if (parisc_parent(dev)->id.hw_type != HPHW_IOA)
printk(KERN_INFO
"Serial: device 0x%llx not configured.\n"
"Enable support for Wax, Lasi, Asp or Dino.\n",
(unsigned long long)dev->hpa.start);
return -ENODEV;
}
address = dev->hpa.start;
if (dev->id.sversion != 0x8d)
address += 0x800;
memset(&uart, 0, sizeof(uart));
uart.port.iotype = UPIO_MEM;
/* 7.272727MHz on Lasi. Assumed the same for Dino, Wax and Timi. */
uart.port.uartclk = (dev->id.sversion != 0xad) ?
7272727 : 1843200;
uart.port.mapbase = address;
uart.port.membase = ioremap_nocache(address, 16);
uart.port.irq = dev->irq;
uart.port.flags = UPF_BOOT_AUTOCONF;
uart.port.dev = &dev->dev;
err = serial8250_register_8250_port(&uart);
if (err < 0) {
printk(KERN_WARNING
"serial8250_register_8250_port returned error %d\n", err);
iounmap(uart.port.membase);
return err;
}
return 0;
}
static struct parisc_device_id serial_tbl[] = {
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x00075 },
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0008c },
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0008d },
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x000ad },
{ 0 }
};
/* Hack. Some machines have SERIAL_0 attached to Lasi and SERIAL_1
* attached to Dino. Unfortunately, Dino appears before Lasi in the device
* tree. To ensure that ttyS0 == SERIAL_0, we register two drivers; one
* which only knows about Lasi and then a second which will find all the
* other serial ports. HPUX ignores this problem.
*/
static struct parisc_device_id lasi_tbl[] = {
{ HPHW_FIO, HVERSION_REV_ANY_ID, 0x03B, 0x0008C }, /* C1xx/C1xxL */
{ HPHW_FIO, HVERSION_REV_ANY_ID, 0x03C, 0x0008C }, /* B132L */
{ HPHW_FIO, HVERSION_REV_ANY_ID, 0x03D, 0x0008C }, /* B160L */
{ HPHW_FIO, HVERSION_REV_ANY_ID, 0x03E, 0x0008C }, /* B132L+ */
{ HPHW_FIO, HVERSION_REV_ANY_ID, 0x03F, 0x0008C }, /* B180L+ */
{ HPHW_FIO, HVERSION_REV_ANY_ID, 0x046, 0x0008C }, /* Rocky2 120 */
{ HPHW_FIO, HVERSION_REV_ANY_ID, 0x047, 0x0008C }, /* Rocky2 150 */
{ HPHW_FIO, HVERSION_REV_ANY_ID, 0x04E, 0x0008C }, /* Kiji L2 132 */
{ HPHW_FIO, HVERSION_REV_ANY_ID, 0x056, 0x0008C }, /* Raven+ */
{ 0 }
};
MODULE_DEVICE_TABLE(parisc, serial_tbl);
static struct parisc_driver lasi_driver = {
.name = "serial_1",
.id_table = lasi_tbl,
.probe = serial_init_chip,
};
static struct parisc_driver serial_driver = {
.name = "serial",
.id_table = serial_tbl,
.probe = serial_init_chip,
};
static int __init probe_serial_gsc(void)
{
register_parisc_driver(&lasi_driver);
register_parisc_driver(&serial_driver);
return 0;
}
module_init(probe_serial_gsc);
MODULE_LICENSE("GPL");
| gpl-2.0 |
savoca/kernel-msm | drivers/net/can/sja1000/sja1000_platform.c | 4971 | 4678 | /*
* Copyright (C) 2005 Sascha Hauer, Pengutronix
* Copyright (C) 2007 Wolfgang Grandegger <wg@grandegger.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the version 2 of the GNU General Public License
* as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/netdevice.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/platform_device.h>
#include <linux/irq.h>
#include <linux/can/dev.h>
#include <linux/can/platform/sja1000.h>
#include <linux/io.h>
#include "sja1000.h"
#define DRV_NAME "sja1000_platform"
MODULE_AUTHOR("Sascha Hauer <s.hauer@pengutronix.de>");
MODULE_DESCRIPTION("Socket-CAN driver for SJA1000 on the platform bus");
MODULE_LICENSE("GPL v2");
static u8 sp_read_reg8(const struct sja1000_priv *priv, int reg)
{
return ioread8(priv->reg_base + reg);
}
static void sp_write_reg8(const struct sja1000_priv *priv, int reg, u8 val)
{
iowrite8(val, priv->reg_base + reg);
}
static u8 sp_read_reg16(const struct sja1000_priv *priv, int reg)
{
return ioread8(priv->reg_base + reg * 2);
}
static void sp_write_reg16(const struct sja1000_priv *priv, int reg, u8 val)
{
iowrite8(val, priv->reg_base + reg * 2);
}
static u8 sp_read_reg32(const struct sja1000_priv *priv, int reg)
{
return ioread8(priv->reg_base + reg * 4);
}
static void sp_write_reg32(const struct sja1000_priv *priv, int reg, u8 val)
{
iowrite8(val, priv->reg_base + reg * 4);
}
static int sp_probe(struct platform_device *pdev)
{
int err;
void __iomem *addr;
struct net_device *dev;
struct sja1000_priv *priv;
struct resource *res_mem, *res_irq;
struct sja1000_platform_data *pdata;
pdata = pdev->dev.platform_data;
if (!pdata) {
dev_err(&pdev->dev, "No platform data provided!\n");
err = -ENODEV;
goto exit;
}
res_mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
res_irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!res_mem || !res_irq) {
err = -ENODEV;
goto exit;
}
if (!request_mem_region(res_mem->start, resource_size(res_mem),
DRV_NAME)) {
err = -EBUSY;
goto exit;
}
addr = ioremap_nocache(res_mem->start, resource_size(res_mem));
if (!addr) {
err = -ENOMEM;
goto exit_release;
}
dev = alloc_sja1000dev(0);
if (!dev) {
err = -ENOMEM;
goto exit_iounmap;
}
priv = netdev_priv(dev);
dev->irq = res_irq->start;
priv->irq_flags = res_irq->flags & (IRQF_TRIGGER_MASK | IRQF_SHARED);
priv->reg_base = addr;
/* The CAN clock frequency is half the oscillator clock frequency */
priv->can.clock.freq = pdata->osc_freq / 2;
priv->ocr = pdata->ocr;
priv->cdr = pdata->cdr;
switch (res_mem->flags & IORESOURCE_MEM_TYPE_MASK) {
case IORESOURCE_MEM_32BIT:
priv->read_reg = sp_read_reg32;
priv->write_reg = sp_write_reg32;
break;
case IORESOURCE_MEM_16BIT:
priv->read_reg = sp_read_reg16;
priv->write_reg = sp_write_reg16;
break;
case IORESOURCE_MEM_8BIT:
default:
priv->read_reg = sp_read_reg8;
priv->write_reg = sp_write_reg8;
break;
}
dev_set_drvdata(&pdev->dev, dev);
SET_NETDEV_DEV(dev, &pdev->dev);
err = register_sja1000dev(dev);
if (err) {
dev_err(&pdev->dev, "registering %s failed (err=%d)\n",
DRV_NAME, err);
goto exit_free;
}
dev_info(&pdev->dev, "%s device registered (reg_base=%p, irq=%d)\n",
DRV_NAME, priv->reg_base, dev->irq);
return 0;
exit_free:
free_sja1000dev(dev);
exit_iounmap:
iounmap(addr);
exit_release:
release_mem_region(res_mem->start, resource_size(res_mem));
exit:
return err;
}
static int sp_remove(struct platform_device *pdev)
{
struct net_device *dev = dev_get_drvdata(&pdev->dev);
struct sja1000_priv *priv = netdev_priv(dev);
struct resource *res;
unregister_sja1000dev(dev);
dev_set_drvdata(&pdev->dev, NULL);
if (priv->reg_base)
iounmap(priv->reg_base);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, resource_size(res));
free_sja1000dev(dev);
return 0;
}
static struct platform_driver sp_driver = {
.probe = sp_probe,
.remove = sp_remove,
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
};
module_platform_driver(sp_driver);
| gpl-2.0 |
ltelg/kernel_lge_geeb-cm10.1 | arch/powerpc/platforms/ps3/spu.c | 7019 | 15518 | /*
* PS3 Platform spu routines.
*
* Copyright (C) 2006 Sony Computer Entertainment Inc.
* Copyright 2006 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/mmzone.h>
#include <linux/export.h>
#include <linux/io.h>
#include <linux/mm.h>
#include <asm/spu.h>
#include <asm/spu_priv1.h>
#include <asm/lv1call.h>
#include <asm/ps3.h>
#include "../cell/spufs/spufs.h"
#include "platform.h"
/* spu_management_ops */
/**
* enum spe_type - Type of spe to create.
* @spe_type_logical: Standard logical spe.
*
* For use with lv1_construct_logical_spe(). The current HV does not support
* any types other than those listed.
*/
enum spe_type {
SPE_TYPE_LOGICAL = 0,
};
/**
* struct spe_shadow - logical spe shadow register area.
*
* Read-only shadow of spe registers.
*/
struct spe_shadow {
u8 padding_0140[0x0140];
u64 int_status_class0_RW; /* 0x0140 */
u64 int_status_class1_RW; /* 0x0148 */
u64 int_status_class2_RW; /* 0x0150 */
u8 padding_0158[0x0610-0x0158];
u64 mfc_dsisr_RW; /* 0x0610 */
u8 padding_0618[0x0620-0x0618];
u64 mfc_dar_RW; /* 0x0620 */
u8 padding_0628[0x0800-0x0628];
u64 mfc_dsipr_R; /* 0x0800 */
u8 padding_0808[0x0810-0x0808];
u64 mfc_lscrr_R; /* 0x0810 */
u8 padding_0818[0x0c00-0x0818];
u64 mfc_cer_R; /* 0x0c00 */
u8 padding_0c08[0x0f00-0x0c08];
u64 spe_execution_status; /* 0x0f00 */
u8 padding_0f08[0x1000-0x0f08];
};
/**
* enum spe_ex_state - Logical spe execution state.
* @spe_ex_state_unexecutable: Uninitialized.
* @spe_ex_state_executable: Enabled, not ready.
* @spe_ex_state_executed: Ready for use.
*
* The execution state (status) of the logical spe as reported in
* struct spe_shadow:spe_execution_status.
*/
enum spe_ex_state {
SPE_EX_STATE_UNEXECUTABLE = 0,
SPE_EX_STATE_EXECUTABLE = 2,
SPE_EX_STATE_EXECUTED = 3,
};
/**
* struct priv1_cache - Cached values of priv1 registers.
* @masks[]: Array of cached spe interrupt masks, indexed by class.
* @sr1: Cached mfc_sr1 register.
* @tclass_id: Cached mfc_tclass_id register.
*/
struct priv1_cache {
u64 masks[3];
u64 sr1;
u64 tclass_id;
};
/**
* struct spu_pdata - Platform state variables.
* @spe_id: HV spe id returned by lv1_construct_logical_spe().
* @resource_id: HV spe resource id returned by
* ps3_repository_read_spe_resource_id().
* @priv2_addr: lpar address of spe priv2 area returned by
* lv1_construct_logical_spe().
* @shadow_addr: lpar address of spe register shadow area returned by
* lv1_construct_logical_spe().
* @shadow: Virtual (ioremap) address of spe register shadow area.
* @cache: Cached values of priv1 registers.
*/
struct spu_pdata {
u64 spe_id;
u64 resource_id;
u64 priv2_addr;
u64 shadow_addr;
struct spe_shadow __iomem *shadow;
struct priv1_cache cache;
};
static struct spu_pdata *spu_pdata(struct spu *spu)
{
return spu->pdata;
}
#define dump_areas(_a, _b, _c, _d, _e) \
_dump_areas(_a, _b, _c, _d, _e, __func__, __LINE__)
static void _dump_areas(unsigned int spe_id, unsigned long priv2,
unsigned long problem, unsigned long ls, unsigned long shadow,
const char* func, int line)
{
pr_debug("%s:%d: spe_id: %xh (%u)\n", func, line, spe_id, spe_id);
pr_debug("%s:%d: priv2: %lxh\n", func, line, priv2);
pr_debug("%s:%d: problem: %lxh\n", func, line, problem);
pr_debug("%s:%d: ls: %lxh\n", func, line, ls);
pr_debug("%s:%d: shadow: %lxh\n", func, line, shadow);
}
inline u64 ps3_get_spe_id(void *arg)
{
return spu_pdata(arg)->spe_id;
}
EXPORT_SYMBOL_GPL(ps3_get_spe_id);
static unsigned long get_vas_id(void)
{
u64 id;
lv1_get_logical_ppe_id(&id);
lv1_get_virtual_address_space_id_of_ppe(&id);
return id;
}
static int __init construct_spu(struct spu *spu)
{
int result;
u64 unused;
u64 problem_phys;
u64 local_store_phys;
result = lv1_construct_logical_spe(PAGE_SHIFT, PAGE_SHIFT, PAGE_SHIFT,
PAGE_SHIFT, PAGE_SHIFT, get_vas_id(), SPE_TYPE_LOGICAL,
&spu_pdata(spu)->priv2_addr, &problem_phys,
&local_store_phys, &unused,
&spu_pdata(spu)->shadow_addr,
&spu_pdata(spu)->spe_id);
spu->problem_phys = problem_phys;
spu->local_store_phys = local_store_phys;
if (result) {
pr_debug("%s:%d: lv1_construct_logical_spe failed: %s\n",
__func__, __LINE__, ps3_result(result));
return result;
}
return result;
}
static void spu_unmap(struct spu *spu)
{
iounmap(spu->priv2);
iounmap(spu->problem);
iounmap((__force u8 __iomem *)spu->local_store);
iounmap(spu_pdata(spu)->shadow);
}
/**
* setup_areas - Map the spu regions into the address space.
*
* The current HV requires the spu shadow regs to be mapped with the
* PTE page protection bits set as read-only (PP=3). This implementation
* uses the low level __ioremap() to bypass the page protection settings
* inforced by ioremap_prot() to get the needed PTE bits set for the
* shadow regs.
*/
static int __init setup_areas(struct spu *spu)
{
struct table {char* name; unsigned long addr; unsigned long size;};
static const unsigned long shadow_flags = _PAGE_NO_CACHE | 3;
spu_pdata(spu)->shadow = __ioremap(spu_pdata(spu)->shadow_addr,
sizeof(struct spe_shadow),
shadow_flags);
if (!spu_pdata(spu)->shadow) {
pr_debug("%s:%d: ioremap shadow failed\n", __func__, __LINE__);
goto fail_ioremap;
}
spu->local_store = (__force void *)ioremap_prot(spu->local_store_phys,
LS_SIZE, _PAGE_NO_CACHE);
if (!spu->local_store) {
pr_debug("%s:%d: ioremap local_store failed\n",
__func__, __LINE__);
goto fail_ioremap;
}
spu->problem = ioremap(spu->problem_phys,
sizeof(struct spu_problem));
if (!spu->problem) {
pr_debug("%s:%d: ioremap problem failed\n", __func__, __LINE__);
goto fail_ioremap;
}
spu->priv2 = ioremap(spu_pdata(spu)->priv2_addr,
sizeof(struct spu_priv2));
if (!spu->priv2) {
pr_debug("%s:%d: ioremap priv2 failed\n", __func__, __LINE__);
goto fail_ioremap;
}
dump_areas(spu_pdata(spu)->spe_id, spu_pdata(spu)->priv2_addr,
spu->problem_phys, spu->local_store_phys,
spu_pdata(spu)->shadow_addr);
dump_areas(spu_pdata(spu)->spe_id, (unsigned long)spu->priv2,
(unsigned long)spu->problem, (unsigned long)spu->local_store,
(unsigned long)spu_pdata(spu)->shadow);
return 0;
fail_ioremap:
spu_unmap(spu);
return -ENOMEM;
}
static int __init setup_interrupts(struct spu *spu)
{
int result;
result = ps3_spe_irq_setup(PS3_BINDING_CPU_ANY, spu_pdata(spu)->spe_id,
0, &spu->irqs[0]);
if (result)
goto fail_alloc_0;
result = ps3_spe_irq_setup(PS3_BINDING_CPU_ANY, spu_pdata(spu)->spe_id,
1, &spu->irqs[1]);
if (result)
goto fail_alloc_1;
result = ps3_spe_irq_setup(PS3_BINDING_CPU_ANY, spu_pdata(spu)->spe_id,
2, &spu->irqs[2]);
if (result)
goto fail_alloc_2;
return result;
fail_alloc_2:
ps3_spe_irq_destroy(spu->irqs[1]);
fail_alloc_1:
ps3_spe_irq_destroy(spu->irqs[0]);
fail_alloc_0:
spu->irqs[0] = spu->irqs[1] = spu->irqs[2] = NO_IRQ;
return result;
}
static int __init enable_spu(struct spu *spu)
{
int result;
result = lv1_enable_logical_spe(spu_pdata(spu)->spe_id,
spu_pdata(spu)->resource_id);
if (result) {
pr_debug("%s:%d: lv1_enable_logical_spe failed: %s\n",
__func__, __LINE__, ps3_result(result));
goto fail_enable;
}
result = setup_areas(spu);
if (result)
goto fail_areas;
result = setup_interrupts(spu);
if (result)
goto fail_interrupts;
return 0;
fail_interrupts:
spu_unmap(spu);
fail_areas:
lv1_disable_logical_spe(spu_pdata(spu)->spe_id, 0);
fail_enable:
return result;
}
static int ps3_destroy_spu(struct spu *spu)
{
int result;
pr_debug("%s:%d spu_%d\n", __func__, __LINE__, spu->number);
result = lv1_disable_logical_spe(spu_pdata(spu)->spe_id, 0);
BUG_ON(result);
ps3_spe_irq_destroy(spu->irqs[2]);
ps3_spe_irq_destroy(spu->irqs[1]);
ps3_spe_irq_destroy(spu->irqs[0]);
spu->irqs[0] = spu->irqs[1] = spu->irqs[2] = NO_IRQ;
spu_unmap(spu);
result = lv1_destruct_logical_spe(spu_pdata(spu)->spe_id);
BUG_ON(result);
kfree(spu->pdata);
spu->pdata = NULL;
return 0;
}
static int __init ps3_create_spu(struct spu *spu, void *data)
{
int result;
pr_debug("%s:%d spu_%d\n", __func__, __LINE__, spu->number);
spu->pdata = kzalloc(sizeof(struct spu_pdata),
GFP_KERNEL);
if (!spu->pdata) {
result = -ENOMEM;
goto fail_malloc;
}
spu_pdata(spu)->resource_id = (unsigned long)data;
/* Init cached reg values to HV defaults. */
spu_pdata(spu)->cache.sr1 = 0x33;
result = construct_spu(spu);
if (result)
goto fail_construct;
/* For now, just go ahead and enable it. */
result = enable_spu(spu);
if (result)
goto fail_enable;
/* Make sure the spu is in SPE_EX_STATE_EXECUTED. */
/* need something better here!!! */
while (in_be64(&spu_pdata(spu)->shadow->spe_execution_status)
!= SPE_EX_STATE_EXECUTED)
(void)0;
return result;
fail_enable:
fail_construct:
ps3_destroy_spu(spu);
fail_malloc:
return result;
}
static int __init ps3_enumerate_spus(int (*fn)(void *data))
{
int result;
unsigned int num_resource_id;
unsigned int i;
result = ps3_repository_read_num_spu_resource_id(&num_resource_id);
pr_debug("%s:%d: num_resource_id %u\n", __func__, __LINE__,
num_resource_id);
/*
* For now, just create logical spus equal to the number
* of physical spus reserved for the partition.
*/
for (i = 0; i < num_resource_id; i++) {
enum ps3_spu_resource_type resource_type;
unsigned int resource_id;
result = ps3_repository_read_spu_resource_id(i,
&resource_type, &resource_id);
if (result)
break;
if (resource_type == PS3_SPU_RESOURCE_TYPE_EXCLUSIVE) {
result = fn((void*)(unsigned long)resource_id);
if (result)
break;
}
}
if (result) {
printk(KERN_WARNING "%s:%d: Error initializing spus\n",
__func__, __LINE__);
return result;
}
return num_resource_id;
}
static int ps3_init_affinity(void)
{
return 0;
}
/**
* ps3_enable_spu - Enable SPU run control.
*
* An outstanding enhancement for the PS3 would be to add a guard to check
* for incorrect access to the spu problem state when the spu context is
* disabled. This check could be implemented with a flag added to the spu
* context that would inhibit mapping problem state pages, and a routine
* to unmap spu problem state pages. When the spu is enabled with
* ps3_enable_spu() the flag would be set allowing pages to be mapped,
* and when the spu is disabled with ps3_disable_spu() the flag would be
* cleared and the mapped problem state pages would be unmapped.
*/
static void ps3_enable_spu(struct spu_context *ctx)
{
}
static void ps3_disable_spu(struct spu_context *ctx)
{
ctx->ops->runcntl_stop(ctx);
}
const struct spu_management_ops spu_management_ps3_ops = {
.enumerate_spus = ps3_enumerate_spus,
.create_spu = ps3_create_spu,
.destroy_spu = ps3_destroy_spu,
.enable_spu = ps3_enable_spu,
.disable_spu = ps3_disable_spu,
.init_affinity = ps3_init_affinity,
};
/* spu_priv1_ops */
static void int_mask_and(struct spu *spu, int class, u64 mask)
{
u64 old_mask;
/* are these serialized by caller??? */
old_mask = spu_int_mask_get(spu, class);
spu_int_mask_set(spu, class, old_mask & mask);
}
static void int_mask_or(struct spu *spu, int class, u64 mask)
{
u64 old_mask;
old_mask = spu_int_mask_get(spu, class);
spu_int_mask_set(spu, class, old_mask | mask);
}
static void int_mask_set(struct spu *spu, int class, u64 mask)
{
spu_pdata(spu)->cache.masks[class] = mask;
lv1_set_spe_interrupt_mask(spu_pdata(spu)->spe_id, class,
spu_pdata(spu)->cache.masks[class]);
}
static u64 int_mask_get(struct spu *spu, int class)
{
return spu_pdata(spu)->cache.masks[class];
}
static void int_stat_clear(struct spu *spu, int class, u64 stat)
{
/* Note that MFC_DSISR will be cleared when class1[MF] is set. */
lv1_clear_spe_interrupt_status(spu_pdata(spu)->spe_id, class,
stat, 0);
}
static u64 int_stat_get(struct spu *spu, int class)
{
u64 stat;
lv1_get_spe_interrupt_status(spu_pdata(spu)->spe_id, class, &stat);
return stat;
}
static void cpu_affinity_set(struct spu *spu, int cpu)
{
/* No support. */
}
static u64 mfc_dar_get(struct spu *spu)
{
return in_be64(&spu_pdata(spu)->shadow->mfc_dar_RW);
}
static void mfc_dsisr_set(struct spu *spu, u64 dsisr)
{
/* Nothing to do, cleared in int_stat_clear(). */
}
static u64 mfc_dsisr_get(struct spu *spu)
{
return in_be64(&spu_pdata(spu)->shadow->mfc_dsisr_RW);
}
static void mfc_sdr_setup(struct spu *spu)
{
/* Nothing to do. */
}
static void mfc_sr1_set(struct spu *spu, u64 sr1)
{
/* Check bits allowed by HV. */
static const u64 allowed = ~(MFC_STATE1_LOCAL_STORAGE_DECODE_MASK
| MFC_STATE1_PROBLEM_STATE_MASK);
BUG_ON((sr1 & allowed) != (spu_pdata(spu)->cache.sr1 & allowed));
spu_pdata(spu)->cache.sr1 = sr1;
lv1_set_spe_privilege_state_area_1_register(
spu_pdata(spu)->spe_id,
offsetof(struct spu_priv1, mfc_sr1_RW),
spu_pdata(spu)->cache.sr1);
}
static u64 mfc_sr1_get(struct spu *spu)
{
return spu_pdata(spu)->cache.sr1;
}
static void mfc_tclass_id_set(struct spu *spu, u64 tclass_id)
{
spu_pdata(spu)->cache.tclass_id = tclass_id;
lv1_set_spe_privilege_state_area_1_register(
spu_pdata(spu)->spe_id,
offsetof(struct spu_priv1, mfc_tclass_id_RW),
spu_pdata(spu)->cache.tclass_id);
}
static u64 mfc_tclass_id_get(struct spu *spu)
{
return spu_pdata(spu)->cache.tclass_id;
}
static void tlb_invalidate(struct spu *spu)
{
/* Nothing to do. */
}
static void resource_allocation_groupID_set(struct spu *spu, u64 id)
{
/* No support. */
}
static u64 resource_allocation_groupID_get(struct spu *spu)
{
return 0; /* No support. */
}
static void resource_allocation_enable_set(struct spu *spu, u64 enable)
{
/* No support. */
}
static u64 resource_allocation_enable_get(struct spu *spu)
{
return 0; /* No support. */
}
const struct spu_priv1_ops spu_priv1_ps3_ops = {
.int_mask_and = int_mask_and,
.int_mask_or = int_mask_or,
.int_mask_set = int_mask_set,
.int_mask_get = int_mask_get,
.int_stat_clear = int_stat_clear,
.int_stat_get = int_stat_get,
.cpu_affinity_set = cpu_affinity_set,
.mfc_dar_get = mfc_dar_get,
.mfc_dsisr_set = mfc_dsisr_set,
.mfc_dsisr_get = mfc_dsisr_get,
.mfc_sdr_setup = mfc_sdr_setup,
.mfc_sr1_set = mfc_sr1_set,
.mfc_sr1_get = mfc_sr1_get,
.mfc_tclass_id_set = mfc_tclass_id_set,
.mfc_tclass_id_get = mfc_tclass_id_get,
.tlb_invalidate = tlb_invalidate,
.resource_allocation_groupID_set = resource_allocation_groupID_set,
.resource_allocation_groupID_get = resource_allocation_groupID_get,
.resource_allocation_enable_set = resource_allocation_enable_set,
.resource_allocation_enable_get = resource_allocation_enable_get,
};
void ps3_spu_set_platform(void)
{
spu_priv1_ops = &spu_priv1_ps3_ops;
spu_management_ops = &spu_management_ps3_ops;
}
| gpl-2.0 |
espenfjo/android_kernel_samsung_n8000 | arch/blackfin/mach-bf518/ints-priority.c | 13675 | 3242 | /*
* Set up the interrupt priorities
*
* Copyright 2008 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/module.h>
#include <linux/irq.h>
#include <asm/blackfin.h>
void __init program_IAR(void)
{
/* Program the IAR0 Register with the configured priority */
bfin_write_SIC_IAR0(((CONFIG_IRQ_PLL_WAKEUP - 7) << IRQ_PLL_WAKEUP_POS) |
((CONFIG_IRQ_DMA0_ERROR - 7) << IRQ_DMA0_ERROR_POS) |
((CONFIG_IRQ_DMAR0_BLK - 7) << IRQ_DMAR0_BLK_POS) |
((CONFIG_IRQ_DMAR1_BLK - 7) << IRQ_DMAR1_BLK_POS) |
((CONFIG_IRQ_DMAR0_OVR - 7) << IRQ_DMAR0_OVR_POS) |
((CONFIG_IRQ_DMAR1_OVR - 7) << IRQ_DMAR1_OVR_POS) |
((CONFIG_IRQ_PPI_ERROR - 7) << IRQ_PPI_ERROR_POS) |
((CONFIG_IRQ_MAC_ERROR - 7) << IRQ_MAC_ERROR_POS));
bfin_write_SIC_IAR1(((CONFIG_IRQ_SPORT0_ERROR - 7) << IRQ_SPORT0_ERROR_POS) |
((CONFIG_IRQ_SPORT1_ERROR - 7) << IRQ_SPORT1_ERROR_POS) |
((CONFIG_IRQ_PTP_ERROR - 7) << IRQ_PTP_ERROR_POS) |
((CONFIG_IRQ_UART0_ERROR - 7) << IRQ_UART0_ERROR_POS) |
((CONFIG_IRQ_UART1_ERROR - 7) << IRQ_UART1_ERROR_POS) |
((CONFIG_IRQ_RTC - 7) << IRQ_RTC_POS) |
((CONFIG_IRQ_PPI - 7) << IRQ_PPI_POS));
bfin_write_SIC_IAR2(((CONFIG_IRQ_SPORT0_RX - 7) << IRQ_SPORT0_RX_POS) |
((CONFIG_IRQ_SPORT0_TX - 7) << IRQ_SPORT0_TX_POS) |
((CONFIG_IRQ_SPORT1_RX - 7) << IRQ_SPORT1_RX_POS) |
((CONFIG_IRQ_SPORT1_TX - 7) << IRQ_SPORT1_TX_POS) |
((CONFIG_IRQ_TWI - 7) << IRQ_TWI_POS) |
((CONFIG_IRQ_SPI0 - 7) << IRQ_SPI0_POS) |
((CONFIG_IRQ_UART0_RX - 7) << IRQ_UART0_RX_POS) |
((CONFIG_IRQ_UART0_TX - 7) << IRQ_UART0_TX_POS));
bfin_write_SIC_IAR3(((CONFIG_IRQ_UART1_RX - 7) << IRQ_UART1_RX_POS) |
((CONFIG_IRQ_UART1_TX - 7) << IRQ_UART1_TX_POS) |
((CONFIG_IRQ_OPTSEC - 7) << IRQ_OPTSEC_POS) |
((CONFIG_IRQ_CNT - 7) << IRQ_CNT_POS) |
((CONFIG_IRQ_MAC_RX - 7) << IRQ_MAC_RX_POS) |
((CONFIG_IRQ_PORTH_INTA - 7) << IRQ_PORTH_INTA_POS) |
((CONFIG_IRQ_MAC_TX - 7) << IRQ_MAC_TX_POS) |
((CONFIG_IRQ_PORTH_INTB - 7) << IRQ_PORTH_INTB_POS));
bfin_write_SIC_IAR4(((CONFIG_IRQ_TIMER0 - 7) << IRQ_TIMER0_POS) |
((CONFIG_IRQ_TIMER1 - 7) << IRQ_TIMER1_POS) |
((CONFIG_IRQ_TIMER2 - 7) << IRQ_TIMER2_POS) |
((CONFIG_IRQ_TIMER3 - 7) << IRQ_TIMER3_POS) |
((CONFIG_IRQ_TIMER4 - 7) << IRQ_TIMER4_POS) |
((CONFIG_IRQ_TIMER5 - 7) << IRQ_TIMER5_POS) |
((CONFIG_IRQ_TIMER6 - 7) << IRQ_TIMER6_POS) |
((CONFIG_IRQ_TIMER7 - 7) << IRQ_TIMER7_POS));
bfin_write_SIC_IAR5(((CONFIG_IRQ_PORTG_INTA - 7) << IRQ_PORTG_INTA_POS) |
((CONFIG_IRQ_PORTG_INTB - 7) << IRQ_PORTG_INTB_POS) |
((CONFIG_IRQ_MEM_DMA0 - 7) << IRQ_MEM_DMA0_POS) |
((CONFIG_IRQ_MEM_DMA1 - 7) << IRQ_MEM_DMA1_POS) |
((CONFIG_IRQ_WATCH - 7) << IRQ_WATCH_POS) |
((CONFIG_IRQ_PORTF_INTA - 7) << IRQ_PORTF_INTA_POS) |
((CONFIG_IRQ_PORTF_INTB - 7) << IRQ_PORTF_INTB_POS) |
((CONFIG_IRQ_SPI0_ERROR - 7) << IRQ_SPI0_ERROR_POS));
bfin_write_SIC_IAR6(((CONFIG_IRQ_SPI1_ERROR - 7) << IRQ_SPI1_ERROR_POS) |
((CONFIG_IRQ_RSI_INT0 - 7) << IRQ_RSI_INT0_POS) |
((CONFIG_IRQ_RSI_INT1 - 7) << IRQ_RSI_INT1_POS) |
((CONFIG_IRQ_PWM_TRIP - 7) << IRQ_PWM_TRIP_POS) |
((CONFIG_IRQ_PWM_SYNC - 7) << IRQ_PWM_SYNC_POS) |
((CONFIG_IRQ_PTP_STAT - 7) << IRQ_PTP_STAT_POS));
SSYNC();
}
| gpl-2.0 |
unless/android_kernel_huawei_u8818 | drivers/net/cxgb3/cxgb3_main.c | 108 | 89246 | /*
* Copyright (c) 2003-2008 Chelsio, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_vlan.h>
#include <linux/mdio.h>
#include <linux/sockios.h>
#include <linux/workqueue.h>
#include <linux/proc_fs.h>
#include <linux/rtnetlink.h>
#include <linux/firmware.h>
#include <linux/log2.h>
#include <linux/stringify.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include "common.h"
#include "cxgb3_ioctl.h"
#include "regs.h"
#include "cxgb3_offload.h"
#include "version.h"
#include "cxgb3_ctl_defs.h"
#include "t3_cpl.h"
#include "firmware_exports.h"
enum {
MAX_TXQ_ENTRIES = 16384,
MAX_CTRL_TXQ_ENTRIES = 1024,
MAX_RSPQ_ENTRIES = 16384,
MAX_RX_BUFFERS = 16384,
MAX_RX_JUMBO_BUFFERS = 16384,
MIN_TXQ_ENTRIES = 4,
MIN_CTRL_TXQ_ENTRIES = 4,
MIN_RSPQ_ENTRIES = 32,
MIN_FL_ENTRIES = 32
};
#define PORT_MASK ((1 << MAX_NPORTS) - 1)
#define DFLT_MSG_ENABLE (NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK | \
NETIF_MSG_TIMER | NETIF_MSG_IFDOWN | NETIF_MSG_IFUP |\
NETIF_MSG_RX_ERR | NETIF_MSG_TX_ERR)
#define EEPROM_MAGIC 0x38E2F10C
#define CH_DEVICE(devid, idx) \
{ PCI_VENDOR_ID_CHELSIO, devid, PCI_ANY_ID, PCI_ANY_ID, 0, 0, idx }
static DEFINE_PCI_DEVICE_TABLE(cxgb3_pci_tbl) = {
CH_DEVICE(0x20, 0), /* PE9000 */
CH_DEVICE(0x21, 1), /* T302E */
CH_DEVICE(0x22, 2), /* T310E */
CH_DEVICE(0x23, 3), /* T320X */
CH_DEVICE(0x24, 1), /* T302X */
CH_DEVICE(0x25, 3), /* T320E */
CH_DEVICE(0x26, 2), /* T310X */
CH_DEVICE(0x30, 2), /* T3B10 */
CH_DEVICE(0x31, 3), /* T3B20 */
CH_DEVICE(0x32, 1), /* T3B02 */
CH_DEVICE(0x35, 6), /* T3C20-derived T3C10 */
CH_DEVICE(0x36, 3), /* S320E-CR */
CH_DEVICE(0x37, 7), /* N320E-G2 */
{0,}
};
MODULE_DESCRIPTION(DRV_DESC);
MODULE_AUTHOR("Chelsio Communications");
MODULE_LICENSE("Dual BSD/GPL");
MODULE_VERSION(DRV_VERSION);
MODULE_DEVICE_TABLE(pci, cxgb3_pci_tbl);
static int dflt_msg_enable = DFLT_MSG_ENABLE;
module_param(dflt_msg_enable, int, 0644);
MODULE_PARM_DESC(dflt_msg_enable, "Chelsio T3 default message enable bitmap");
/*
* The driver uses the best interrupt scheme available on a platform in the
* order MSI-X, MSI, legacy pin interrupts. This parameter determines which
* of these schemes the driver may consider as follows:
*
* msi = 2: choose from among all three options
* msi = 1: only consider MSI and pin interrupts
* msi = 0: force pin interrupts
*/
static int msi = 2;
module_param(msi, int, 0644);
MODULE_PARM_DESC(msi, "whether to use MSI or MSI-X");
/*
* The driver enables offload as a default.
* To disable it, use ofld_disable = 1.
*/
static int ofld_disable = 0;
module_param(ofld_disable, int, 0644);
MODULE_PARM_DESC(ofld_disable, "whether to enable offload at init time or not");
/*
* We have work elements that we need to cancel when an interface is taken
* down. Normally the work elements would be executed by keventd but that
* can deadlock because of linkwatch. If our close method takes the rtnl
* lock and linkwatch is ahead of our work elements in keventd, linkwatch
* will block keventd as it needs the rtnl lock, and we'll deadlock waiting
* for our work to complete. Get our own work queue to solve this.
*/
struct workqueue_struct *cxgb3_wq;
/**
* link_report - show link status and link speed/duplex
* @p: the port whose settings are to be reported
*
* Shows the link status, speed, and duplex of a port.
*/
static void link_report(struct net_device *dev)
{
if (!netif_carrier_ok(dev))
printk(KERN_INFO "%s: link down\n", dev->name);
else {
const char *s = "10Mbps";
const struct port_info *p = netdev_priv(dev);
switch (p->link_config.speed) {
case SPEED_10000:
s = "10Gbps";
break;
case SPEED_1000:
s = "1000Mbps";
break;
case SPEED_100:
s = "100Mbps";
break;
}
printk(KERN_INFO "%s: link up, %s, %s-duplex\n", dev->name, s,
p->link_config.duplex == DUPLEX_FULL ? "full" : "half");
}
}
static void enable_tx_fifo_drain(struct adapter *adapter,
struct port_info *pi)
{
t3_set_reg_field(adapter, A_XGM_TXFIFO_CFG + pi->mac.offset, 0,
F_ENDROPPKT);
t3_write_reg(adapter, A_XGM_RX_CTRL + pi->mac.offset, 0);
t3_write_reg(adapter, A_XGM_TX_CTRL + pi->mac.offset, F_TXEN);
t3_write_reg(adapter, A_XGM_RX_CTRL + pi->mac.offset, F_RXEN);
}
static void disable_tx_fifo_drain(struct adapter *adapter,
struct port_info *pi)
{
t3_set_reg_field(adapter, A_XGM_TXFIFO_CFG + pi->mac.offset,
F_ENDROPPKT, 0);
}
void t3_os_link_fault(struct adapter *adap, int port_id, int state)
{
struct net_device *dev = adap->port[port_id];
struct port_info *pi = netdev_priv(dev);
if (state == netif_carrier_ok(dev))
return;
if (state) {
struct cmac *mac = &pi->mac;
netif_carrier_on(dev);
disable_tx_fifo_drain(adap, pi);
/* Clear local faults */
t3_xgm_intr_disable(adap, pi->port_id);
t3_read_reg(adap, A_XGM_INT_STATUS +
pi->mac.offset);
t3_write_reg(adap,
A_XGM_INT_CAUSE + pi->mac.offset,
F_XGM_INT);
t3_set_reg_field(adap,
A_XGM_INT_ENABLE +
pi->mac.offset,
F_XGM_INT, F_XGM_INT);
t3_xgm_intr_enable(adap, pi->port_id);
t3_mac_enable(mac, MAC_DIRECTION_TX);
} else {
netif_carrier_off(dev);
/* Flush TX FIFO */
enable_tx_fifo_drain(adap, pi);
}
link_report(dev);
}
/**
* t3_os_link_changed - handle link status changes
* @adapter: the adapter associated with the link change
* @port_id: the port index whose limk status has changed
* @link_stat: the new status of the link
* @speed: the new speed setting
* @duplex: the new duplex setting
* @pause: the new flow-control setting
*
* This is the OS-dependent handler for link status changes. The OS
* neutral handler takes care of most of the processing for these events,
* then calls this handler for any OS-specific processing.
*/
void t3_os_link_changed(struct adapter *adapter, int port_id, int link_stat,
int speed, int duplex, int pause)
{
struct net_device *dev = adapter->port[port_id];
struct port_info *pi = netdev_priv(dev);
struct cmac *mac = &pi->mac;
/* Skip changes from disabled ports. */
if (!netif_running(dev))
return;
if (link_stat != netif_carrier_ok(dev)) {
if (link_stat) {
disable_tx_fifo_drain(adapter, pi);
t3_mac_enable(mac, MAC_DIRECTION_RX);
/* Clear local faults */
t3_xgm_intr_disable(adapter, pi->port_id);
t3_read_reg(adapter, A_XGM_INT_STATUS +
pi->mac.offset);
t3_write_reg(adapter,
A_XGM_INT_CAUSE + pi->mac.offset,
F_XGM_INT);
t3_set_reg_field(adapter,
A_XGM_INT_ENABLE + pi->mac.offset,
F_XGM_INT, F_XGM_INT);
t3_xgm_intr_enable(adapter, pi->port_id);
netif_carrier_on(dev);
} else {
netif_carrier_off(dev);
t3_xgm_intr_disable(adapter, pi->port_id);
t3_read_reg(adapter, A_XGM_INT_STATUS + pi->mac.offset);
t3_set_reg_field(adapter,
A_XGM_INT_ENABLE + pi->mac.offset,
F_XGM_INT, 0);
if (is_10G(adapter))
pi->phy.ops->power_down(&pi->phy, 1);
t3_read_reg(adapter, A_XGM_INT_STATUS + pi->mac.offset);
t3_mac_disable(mac, MAC_DIRECTION_RX);
t3_link_start(&pi->phy, mac, &pi->link_config);
/* Flush TX FIFO */
enable_tx_fifo_drain(adapter, pi);
}
link_report(dev);
}
}
/**
* t3_os_phymod_changed - handle PHY module changes
* @phy: the PHY reporting the module change
* @mod_type: new module type
*
* This is the OS-dependent handler for PHY module changes. It is
* invoked when a PHY module is removed or inserted for any OS-specific
* processing.
*/
void t3_os_phymod_changed(struct adapter *adap, int port_id)
{
static const char *mod_str[] = {
NULL, "SR", "LR", "LRM", "TWINAX", "TWINAX", "unknown"
};
const struct net_device *dev = adap->port[port_id];
const struct port_info *pi = netdev_priv(dev);
if (pi->phy.modtype == phy_modtype_none)
printk(KERN_INFO "%s: PHY module unplugged\n", dev->name);
else
printk(KERN_INFO "%s: %s PHY module inserted\n", dev->name,
mod_str[pi->phy.modtype]);
}
static void cxgb_set_rxmode(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
t3_mac_set_rx_mode(&pi->mac, dev);
}
/**
* link_start - enable a port
* @dev: the device to enable
*
* Performs the MAC and PHY actions needed to enable a port.
*/
static void link_start(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct cmac *mac = &pi->mac;
t3_mac_reset(mac);
t3_mac_set_num_ucast(mac, MAX_MAC_IDX);
t3_mac_set_mtu(mac, dev->mtu);
t3_mac_set_address(mac, LAN_MAC_IDX, dev->dev_addr);
t3_mac_set_address(mac, SAN_MAC_IDX, pi->iscsic.mac_addr);
t3_mac_set_rx_mode(mac, dev);
t3_link_start(&pi->phy, mac, &pi->link_config);
t3_mac_enable(mac, MAC_DIRECTION_RX | MAC_DIRECTION_TX);
}
static inline void cxgb_disable_msi(struct adapter *adapter)
{
if (adapter->flags & USING_MSIX) {
pci_disable_msix(adapter->pdev);
adapter->flags &= ~USING_MSIX;
} else if (adapter->flags & USING_MSI) {
pci_disable_msi(adapter->pdev);
adapter->flags &= ~USING_MSI;
}
}
/*
* Interrupt handler for asynchronous events used with MSI-X.
*/
static irqreturn_t t3_async_intr_handler(int irq, void *cookie)
{
t3_slow_intr_handler(cookie);
return IRQ_HANDLED;
}
/*
* Name the MSI-X interrupts.
*/
static void name_msix_vecs(struct adapter *adap)
{
int i, j, msi_idx = 1, n = sizeof(adap->msix_info[0].desc) - 1;
snprintf(adap->msix_info[0].desc, n, "%s", adap->name);
adap->msix_info[0].desc[n] = 0;
for_each_port(adap, j) {
struct net_device *d = adap->port[j];
const struct port_info *pi = netdev_priv(d);
for (i = 0; i < pi->nqsets; i++, msi_idx++) {
snprintf(adap->msix_info[msi_idx].desc, n,
"%s-%d", d->name, pi->first_qset + i);
adap->msix_info[msi_idx].desc[n] = 0;
}
}
}
static int request_msix_data_irqs(struct adapter *adap)
{
int i, j, err, qidx = 0;
for_each_port(adap, i) {
int nqsets = adap2pinfo(adap, i)->nqsets;
for (j = 0; j < nqsets; ++j) {
err = request_irq(adap->msix_info[qidx + 1].vec,
t3_intr_handler(adap,
adap->sge.qs[qidx].
rspq.polling), 0,
adap->msix_info[qidx + 1].desc,
&adap->sge.qs[qidx]);
if (err) {
while (--qidx >= 0)
free_irq(adap->msix_info[qidx + 1].vec,
&adap->sge.qs[qidx]);
return err;
}
qidx++;
}
}
return 0;
}
static void free_irq_resources(struct adapter *adapter)
{
if (adapter->flags & USING_MSIX) {
int i, n = 0;
free_irq(adapter->msix_info[0].vec, adapter);
for_each_port(adapter, i)
n += adap2pinfo(adapter, i)->nqsets;
for (i = 0; i < n; ++i)
free_irq(adapter->msix_info[i + 1].vec,
&adapter->sge.qs[i]);
} else
free_irq(adapter->pdev->irq, adapter);
}
static int await_mgmt_replies(struct adapter *adap, unsigned long init_cnt,
unsigned long n)
{
int attempts = 10;
while (adap->sge.qs[0].rspq.offload_pkts < init_cnt + n) {
if (!--attempts)
return -ETIMEDOUT;
msleep(10);
}
return 0;
}
static int init_tp_parity(struct adapter *adap)
{
int i;
struct sk_buff *skb;
struct cpl_set_tcb_field *greq;
unsigned long cnt = adap->sge.qs[0].rspq.offload_pkts;
t3_tp_set_offload_mode(adap, 1);
for (i = 0; i < 16; i++) {
struct cpl_smt_write_req *req;
skb = alloc_skb(sizeof(*req), GFP_KERNEL);
if (!skb)
skb = adap->nofail_skb;
if (!skb)
goto alloc_skb_fail;
req = (struct cpl_smt_write_req *)__skb_put(skb, sizeof(*req));
memset(req, 0, sizeof(*req));
req->wr.wr_hi = htonl(V_WR_OP(FW_WROPCODE_FORWARD));
OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_SMT_WRITE_REQ, i));
req->mtu_idx = NMTUS - 1;
req->iff = i;
t3_mgmt_tx(adap, skb);
if (skb == adap->nofail_skb) {
await_mgmt_replies(adap, cnt, i + 1);
adap->nofail_skb = alloc_skb(sizeof(*greq), GFP_KERNEL);
if (!adap->nofail_skb)
goto alloc_skb_fail;
}
}
for (i = 0; i < 2048; i++) {
struct cpl_l2t_write_req *req;
skb = alloc_skb(sizeof(*req), GFP_KERNEL);
if (!skb)
skb = adap->nofail_skb;
if (!skb)
goto alloc_skb_fail;
req = (struct cpl_l2t_write_req *)__skb_put(skb, sizeof(*req));
memset(req, 0, sizeof(*req));
req->wr.wr_hi = htonl(V_WR_OP(FW_WROPCODE_FORWARD));
OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_L2T_WRITE_REQ, i));
req->params = htonl(V_L2T_W_IDX(i));
t3_mgmt_tx(adap, skb);
if (skb == adap->nofail_skb) {
await_mgmt_replies(adap, cnt, 16 + i + 1);
adap->nofail_skb = alloc_skb(sizeof(*greq), GFP_KERNEL);
if (!adap->nofail_skb)
goto alloc_skb_fail;
}
}
for (i = 0; i < 2048; i++) {
struct cpl_rte_write_req *req;
skb = alloc_skb(sizeof(*req), GFP_KERNEL);
if (!skb)
skb = adap->nofail_skb;
if (!skb)
goto alloc_skb_fail;
req = (struct cpl_rte_write_req *)__skb_put(skb, sizeof(*req));
memset(req, 0, sizeof(*req));
req->wr.wr_hi = htonl(V_WR_OP(FW_WROPCODE_FORWARD));
OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_RTE_WRITE_REQ, i));
req->l2t_idx = htonl(V_L2T_W_IDX(i));
t3_mgmt_tx(adap, skb);
if (skb == adap->nofail_skb) {
await_mgmt_replies(adap, cnt, 16 + 2048 + i + 1);
adap->nofail_skb = alloc_skb(sizeof(*greq), GFP_KERNEL);
if (!adap->nofail_skb)
goto alloc_skb_fail;
}
}
skb = alloc_skb(sizeof(*greq), GFP_KERNEL);
if (!skb)
skb = adap->nofail_skb;
if (!skb)
goto alloc_skb_fail;
greq = (struct cpl_set_tcb_field *)__skb_put(skb, sizeof(*greq));
memset(greq, 0, sizeof(*greq));
greq->wr.wr_hi = htonl(V_WR_OP(FW_WROPCODE_FORWARD));
OPCODE_TID(greq) = htonl(MK_OPCODE_TID(CPL_SET_TCB_FIELD, 0));
greq->mask = cpu_to_be64(1);
t3_mgmt_tx(adap, skb);
i = await_mgmt_replies(adap, cnt, 16 + 2048 + 2048 + 1);
if (skb == adap->nofail_skb) {
i = await_mgmt_replies(adap, cnt, 16 + 2048 + 2048 + 1);
adap->nofail_skb = alloc_skb(sizeof(*greq), GFP_KERNEL);
}
t3_tp_set_offload_mode(adap, 0);
return i;
alloc_skb_fail:
t3_tp_set_offload_mode(adap, 0);
return -ENOMEM;
}
/**
* setup_rss - configure RSS
* @adap: the adapter
*
* Sets up RSS to distribute packets to multiple receive queues. We
* configure the RSS CPU lookup table to distribute to the number of HW
* receive queues, and the response queue lookup table to narrow that
* down to the response queues actually configured for each port.
* We always configure the RSS mapping for two ports since the mapping
* table has plenty of entries.
*/
static void setup_rss(struct adapter *adap)
{
int i;
unsigned int nq0 = adap2pinfo(adap, 0)->nqsets;
unsigned int nq1 = adap->port[1] ? adap2pinfo(adap, 1)->nqsets : 1;
u8 cpus[SGE_QSETS + 1];
u16 rspq_map[RSS_TABLE_SIZE];
for (i = 0; i < SGE_QSETS; ++i)
cpus[i] = i;
cpus[SGE_QSETS] = 0xff; /* terminator */
for (i = 0; i < RSS_TABLE_SIZE / 2; ++i) {
rspq_map[i] = i % nq0;
rspq_map[i + RSS_TABLE_SIZE / 2] = (i % nq1) + nq0;
}
t3_config_rss(adap, F_RQFEEDBACKENABLE | F_TNLLKPEN | F_TNLMAPEN |
F_TNLPRTEN | F_TNL2TUPEN | F_TNL4TUPEN |
V_RRCPLCPUSIZE(6) | F_HASHTOEPLITZ, cpus, rspq_map);
}
static void ring_dbs(struct adapter *adap)
{
int i, j;
for (i = 0; i < SGE_QSETS; i++) {
struct sge_qset *qs = &adap->sge.qs[i];
if (qs->adap)
for (j = 0; j < SGE_TXQ_PER_SET; j++)
t3_write_reg(adap, A_SG_KDOORBELL, F_SELEGRCNTX | V_EGRCNTX(qs->txq[j].cntxt_id));
}
}
static void init_napi(struct adapter *adap)
{
int i;
for (i = 0; i < SGE_QSETS; i++) {
struct sge_qset *qs = &adap->sge.qs[i];
if (qs->adap)
netif_napi_add(qs->netdev, &qs->napi, qs->napi.poll,
64);
}
/*
* netif_napi_add() can be called only once per napi_struct because it
* adds each new napi_struct to a list. Be careful not to call it a
* second time, e.g., during EEH recovery, by making a note of it.
*/
adap->flags |= NAPI_INIT;
}
/*
* Wait until all NAPI handlers are descheduled. This includes the handlers of
* both netdevices representing interfaces and the dummy ones for the extra
* queues.
*/
static void quiesce_rx(struct adapter *adap)
{
int i;
for (i = 0; i < SGE_QSETS; i++)
if (adap->sge.qs[i].adap)
napi_disable(&adap->sge.qs[i].napi);
}
static void enable_all_napi(struct adapter *adap)
{
int i;
for (i = 0; i < SGE_QSETS; i++)
if (adap->sge.qs[i].adap)
napi_enable(&adap->sge.qs[i].napi);
}
/**
* set_qset_lro - Turn a queue set's LRO capability on and off
* @dev: the device the qset is attached to
* @qset_idx: the queue set index
* @val: the LRO switch
*
* Sets LRO on or off for a particular queue set.
* the device's features flag is updated to reflect the LRO
* capability when all queues belonging to the device are
* in the same state.
*/
static void set_qset_lro(struct net_device *dev, int qset_idx, int val)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
adapter->params.sge.qset[qset_idx].lro = !!val;
adapter->sge.qs[qset_idx].lro_enabled = !!val;
}
/**
* setup_sge_qsets - configure SGE Tx/Rx/response queues
* @adap: the adapter
*
* Determines how many sets of SGE queues to use and initializes them.
* We support multiple queue sets per port if we have MSI-X, otherwise
* just one queue set per port.
*/
static int setup_sge_qsets(struct adapter *adap)
{
int i, j, err, irq_idx = 0, qset_idx = 0;
unsigned int ntxq = SGE_TXQ_PER_SET;
if (adap->params.rev > 0 && !(adap->flags & USING_MSI))
irq_idx = -1;
for_each_port(adap, i) {
struct net_device *dev = adap->port[i];
struct port_info *pi = netdev_priv(dev);
pi->qs = &adap->sge.qs[pi->first_qset];
for (j = 0; j < pi->nqsets; ++j, ++qset_idx) {
set_qset_lro(dev, qset_idx, pi->rx_offload & T3_LRO);
err = t3_sge_alloc_qset(adap, qset_idx, 1,
(adap->flags & USING_MSIX) ? qset_idx + 1 :
irq_idx,
&adap->params.sge.qset[qset_idx], ntxq, dev,
netdev_get_tx_queue(dev, j));
if (err) {
t3_free_sge_resources(adap);
return err;
}
}
}
return 0;
}
static ssize_t attr_show(struct device *d, char *buf,
ssize_t(*format) (struct net_device *, char *))
{
ssize_t len;
/* Synchronize with ioctls that may shut down the device */
rtnl_lock();
len = (*format) (to_net_dev(d), buf);
rtnl_unlock();
return len;
}
static ssize_t attr_store(struct device *d,
const char *buf, size_t len,
ssize_t(*set) (struct net_device *, unsigned int),
unsigned int min_val, unsigned int max_val)
{
char *endp;
ssize_t ret;
unsigned int val;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
val = simple_strtoul(buf, &endp, 0);
if (endp == buf || val < min_val || val > max_val)
return -EINVAL;
rtnl_lock();
ret = (*set) (to_net_dev(d), val);
if (!ret)
ret = len;
rtnl_unlock();
return ret;
}
#define CXGB3_SHOW(name, val_expr) \
static ssize_t format_##name(struct net_device *dev, char *buf) \
{ \
struct port_info *pi = netdev_priv(dev); \
struct adapter *adap = pi->adapter; \
return sprintf(buf, "%u\n", val_expr); \
} \
static ssize_t show_##name(struct device *d, struct device_attribute *attr, \
char *buf) \
{ \
return attr_show(d, buf, format_##name); \
}
static ssize_t set_nfilters(struct net_device *dev, unsigned int val)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adap = pi->adapter;
int min_tids = is_offload(adap) ? MC5_MIN_TIDS : 0;
if (adap->flags & FULL_INIT_DONE)
return -EBUSY;
if (val && adap->params.rev == 0)
return -EINVAL;
if (val > t3_mc5_size(&adap->mc5) - adap->params.mc5.nservers -
min_tids)
return -EINVAL;
adap->params.mc5.nfilters = val;
return 0;
}
static ssize_t store_nfilters(struct device *d, struct device_attribute *attr,
const char *buf, size_t len)
{
return attr_store(d, buf, len, set_nfilters, 0, ~0);
}
static ssize_t set_nservers(struct net_device *dev, unsigned int val)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adap = pi->adapter;
if (adap->flags & FULL_INIT_DONE)
return -EBUSY;
if (val > t3_mc5_size(&adap->mc5) - adap->params.mc5.nfilters -
MC5_MIN_TIDS)
return -EINVAL;
adap->params.mc5.nservers = val;
return 0;
}
static ssize_t store_nservers(struct device *d, struct device_attribute *attr,
const char *buf, size_t len)
{
return attr_store(d, buf, len, set_nservers, 0, ~0);
}
#define CXGB3_ATTR_R(name, val_expr) \
CXGB3_SHOW(name, val_expr) \
static DEVICE_ATTR(name, S_IRUGO, show_##name, NULL)
#define CXGB3_ATTR_RW(name, val_expr, store_method) \
CXGB3_SHOW(name, val_expr) \
static DEVICE_ATTR(name, S_IRUGO | S_IWUSR, show_##name, store_method)
CXGB3_ATTR_R(cam_size, t3_mc5_size(&adap->mc5));
CXGB3_ATTR_RW(nfilters, adap->params.mc5.nfilters, store_nfilters);
CXGB3_ATTR_RW(nservers, adap->params.mc5.nservers, store_nservers);
static struct attribute *cxgb3_attrs[] = {
&dev_attr_cam_size.attr,
&dev_attr_nfilters.attr,
&dev_attr_nservers.attr,
NULL
};
static struct attribute_group cxgb3_attr_group = {.attrs = cxgb3_attrs };
static ssize_t tm_attr_show(struct device *d,
char *buf, int sched)
{
struct port_info *pi = netdev_priv(to_net_dev(d));
struct adapter *adap = pi->adapter;
unsigned int v, addr, bpt, cpt;
ssize_t len;
addr = A_TP_TX_MOD_Q1_Q0_RATE_LIMIT - sched / 2;
rtnl_lock();
t3_write_reg(adap, A_TP_TM_PIO_ADDR, addr);
v = t3_read_reg(adap, A_TP_TM_PIO_DATA);
if (sched & 1)
v >>= 16;
bpt = (v >> 8) & 0xff;
cpt = v & 0xff;
if (!cpt)
len = sprintf(buf, "disabled\n");
else {
v = (adap->params.vpd.cclk * 1000) / cpt;
len = sprintf(buf, "%u Kbps\n", (v * bpt) / 125);
}
rtnl_unlock();
return len;
}
static ssize_t tm_attr_store(struct device *d,
const char *buf, size_t len, int sched)
{
struct port_info *pi = netdev_priv(to_net_dev(d));
struct adapter *adap = pi->adapter;
unsigned int val;
char *endp;
ssize_t ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
val = simple_strtoul(buf, &endp, 0);
if (endp == buf || val > 10000000)
return -EINVAL;
rtnl_lock();
ret = t3_config_sched(adap, val, sched);
if (!ret)
ret = len;
rtnl_unlock();
return ret;
}
#define TM_ATTR(name, sched) \
static ssize_t show_##name(struct device *d, struct device_attribute *attr, \
char *buf) \
{ \
return tm_attr_show(d, buf, sched); \
} \
static ssize_t store_##name(struct device *d, struct device_attribute *attr, \
const char *buf, size_t len) \
{ \
return tm_attr_store(d, buf, len, sched); \
} \
static DEVICE_ATTR(name, S_IRUGO | S_IWUSR, show_##name, store_##name)
TM_ATTR(sched0, 0);
TM_ATTR(sched1, 1);
TM_ATTR(sched2, 2);
TM_ATTR(sched3, 3);
TM_ATTR(sched4, 4);
TM_ATTR(sched5, 5);
TM_ATTR(sched6, 6);
TM_ATTR(sched7, 7);
static struct attribute *offload_attrs[] = {
&dev_attr_sched0.attr,
&dev_attr_sched1.attr,
&dev_attr_sched2.attr,
&dev_attr_sched3.attr,
&dev_attr_sched4.attr,
&dev_attr_sched5.attr,
&dev_attr_sched6.attr,
&dev_attr_sched7.attr,
NULL
};
static struct attribute_group offload_attr_group = {.attrs = offload_attrs };
/*
* Sends an sk_buff to an offload queue driver
* after dealing with any active network taps.
*/
static inline int offload_tx(struct t3cdev *tdev, struct sk_buff *skb)
{
int ret;
local_bh_disable();
ret = t3_offload_tx(tdev, skb);
local_bh_enable();
return ret;
}
static int write_smt_entry(struct adapter *adapter, int idx)
{
struct cpl_smt_write_req *req;
struct port_info *pi = netdev_priv(adapter->port[idx]);
struct sk_buff *skb = alloc_skb(sizeof(*req), GFP_KERNEL);
if (!skb)
return -ENOMEM;
req = (struct cpl_smt_write_req *)__skb_put(skb, sizeof(*req));
req->wr.wr_hi = htonl(V_WR_OP(FW_WROPCODE_FORWARD));
OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_SMT_WRITE_REQ, idx));
req->mtu_idx = NMTUS - 1; /* should be 0 but there's a T3 bug */
req->iff = idx;
memcpy(req->src_mac0, adapter->port[idx]->dev_addr, ETH_ALEN);
memcpy(req->src_mac1, pi->iscsic.mac_addr, ETH_ALEN);
skb->priority = 1;
offload_tx(&adapter->tdev, skb);
return 0;
}
static int init_smt(struct adapter *adapter)
{
int i;
for_each_port(adapter, i)
write_smt_entry(adapter, i);
return 0;
}
static void init_port_mtus(struct adapter *adapter)
{
unsigned int mtus = adapter->port[0]->mtu;
if (adapter->port[1])
mtus |= adapter->port[1]->mtu << 16;
t3_write_reg(adapter, A_TP_MTU_PORT_TABLE, mtus);
}
static int send_pktsched_cmd(struct adapter *adap, int sched, int qidx, int lo,
int hi, int port)
{
struct sk_buff *skb;
struct mngt_pktsched_wr *req;
int ret;
skb = alloc_skb(sizeof(*req), GFP_KERNEL);
if (!skb)
skb = adap->nofail_skb;
if (!skb)
return -ENOMEM;
req = (struct mngt_pktsched_wr *)skb_put(skb, sizeof(*req));
req->wr_hi = htonl(V_WR_OP(FW_WROPCODE_MNGT));
req->mngt_opcode = FW_MNGTOPCODE_PKTSCHED_SET;
req->sched = sched;
req->idx = qidx;
req->min = lo;
req->max = hi;
req->binding = port;
ret = t3_mgmt_tx(adap, skb);
if (skb == adap->nofail_skb) {
adap->nofail_skb = alloc_skb(sizeof(struct cpl_set_tcb_field),
GFP_KERNEL);
if (!adap->nofail_skb)
ret = -ENOMEM;
}
return ret;
}
static int bind_qsets(struct adapter *adap)
{
int i, j, err = 0;
for_each_port(adap, i) {
const struct port_info *pi = adap2pinfo(adap, i);
for (j = 0; j < pi->nqsets; ++j) {
int ret = send_pktsched_cmd(adap, 1,
pi->first_qset + j, -1,
-1, i);
if (ret)
err = ret;
}
}
return err;
}
#define FW_VERSION __stringify(FW_VERSION_MAJOR) "." \
__stringify(FW_VERSION_MINOR) "." __stringify(FW_VERSION_MICRO)
#define FW_FNAME "cxgb3/t3fw-" FW_VERSION ".bin"
#define TPSRAM_VERSION __stringify(TP_VERSION_MAJOR) "." \
__stringify(TP_VERSION_MINOR) "." __stringify(TP_VERSION_MICRO)
#define TPSRAM_NAME "cxgb3/t3%c_psram-" TPSRAM_VERSION ".bin"
#define AEL2005_OPT_EDC_NAME "cxgb3/ael2005_opt_edc.bin"
#define AEL2005_TWX_EDC_NAME "cxgb3/ael2005_twx_edc.bin"
#define AEL2020_TWX_EDC_NAME "cxgb3/ael2020_twx_edc.bin"
MODULE_FIRMWARE(FW_FNAME);
MODULE_FIRMWARE("cxgb3/t3b_psram-" TPSRAM_VERSION ".bin");
MODULE_FIRMWARE("cxgb3/t3c_psram-" TPSRAM_VERSION ".bin");
MODULE_FIRMWARE(AEL2005_OPT_EDC_NAME);
MODULE_FIRMWARE(AEL2005_TWX_EDC_NAME);
MODULE_FIRMWARE(AEL2020_TWX_EDC_NAME);
static inline const char *get_edc_fw_name(int edc_idx)
{
const char *fw_name = NULL;
switch (edc_idx) {
case EDC_OPT_AEL2005:
fw_name = AEL2005_OPT_EDC_NAME;
break;
case EDC_TWX_AEL2005:
fw_name = AEL2005_TWX_EDC_NAME;
break;
case EDC_TWX_AEL2020:
fw_name = AEL2020_TWX_EDC_NAME;
break;
}
return fw_name;
}
int t3_get_edc_fw(struct cphy *phy, int edc_idx, int size)
{
struct adapter *adapter = phy->adapter;
const struct firmware *fw;
char buf[64];
u32 csum;
const __be32 *p;
u16 *cache = phy->phy_cache;
int i, ret;
snprintf(buf, sizeof(buf), get_edc_fw_name(edc_idx));
ret = request_firmware(&fw, buf, &adapter->pdev->dev);
if (ret < 0) {
dev_err(&adapter->pdev->dev,
"could not upgrade firmware: unable to load %s\n",
buf);
return ret;
}
/* check size, take checksum in account */
if (fw->size > size + 4) {
CH_ERR(adapter, "firmware image too large %u, expected %d\n",
(unsigned int)fw->size, size + 4);
ret = -EINVAL;
}
/* compute checksum */
p = (const __be32 *)fw->data;
for (csum = 0, i = 0; i < fw->size / sizeof(csum); i++)
csum += ntohl(p[i]);
if (csum != 0xffffffff) {
CH_ERR(adapter, "corrupted firmware image, checksum %u\n",
csum);
ret = -EINVAL;
}
for (i = 0; i < size / 4 ; i++) {
*cache++ = (be32_to_cpu(p[i]) & 0xffff0000) >> 16;
*cache++ = be32_to_cpu(p[i]) & 0xffff;
}
release_firmware(fw);
return ret;
}
static int upgrade_fw(struct adapter *adap)
{
int ret;
const struct firmware *fw;
struct device *dev = &adap->pdev->dev;
ret = request_firmware(&fw, FW_FNAME, dev);
if (ret < 0) {
dev_err(dev, "could not upgrade firmware: unable to load %s\n",
FW_FNAME);
return ret;
}
ret = t3_load_fw(adap, fw->data, fw->size);
release_firmware(fw);
if (ret == 0)
dev_info(dev, "successful upgrade to firmware %d.%d.%d\n",
FW_VERSION_MAJOR, FW_VERSION_MINOR, FW_VERSION_MICRO);
else
dev_err(dev, "failed to upgrade to firmware %d.%d.%d\n",
FW_VERSION_MAJOR, FW_VERSION_MINOR, FW_VERSION_MICRO);
return ret;
}
static inline char t3rev2char(struct adapter *adapter)
{
char rev = 0;
switch(adapter->params.rev) {
case T3_REV_B:
case T3_REV_B2:
rev = 'b';
break;
case T3_REV_C:
rev = 'c';
break;
}
return rev;
}
static int update_tpsram(struct adapter *adap)
{
const struct firmware *tpsram;
char buf[64];
struct device *dev = &adap->pdev->dev;
int ret;
char rev;
rev = t3rev2char(adap);
if (!rev)
return 0;
snprintf(buf, sizeof(buf), TPSRAM_NAME, rev);
ret = request_firmware(&tpsram, buf, dev);
if (ret < 0) {
dev_err(dev, "could not load TP SRAM: unable to load %s\n",
buf);
return ret;
}
ret = t3_check_tpsram(adap, tpsram->data, tpsram->size);
if (ret)
goto release_tpsram;
ret = t3_set_proto_sram(adap, tpsram->data);
if (ret == 0)
dev_info(dev,
"successful update of protocol engine "
"to %d.%d.%d\n",
TP_VERSION_MAJOR, TP_VERSION_MINOR, TP_VERSION_MICRO);
else
dev_err(dev, "failed to update of protocol engine %d.%d.%d\n",
TP_VERSION_MAJOR, TP_VERSION_MINOR, TP_VERSION_MICRO);
if (ret)
dev_err(dev, "loading protocol SRAM failed\n");
release_tpsram:
release_firmware(tpsram);
return ret;
}
/**
* cxgb_up - enable the adapter
* @adapter: adapter being enabled
*
* Called when the first port is enabled, this function performs the
* actions necessary to make an adapter operational, such as completing
* the initialization of HW modules, and enabling interrupts.
*
* Must be called with the rtnl lock held.
*/
static int cxgb_up(struct adapter *adap)
{
int err;
if (!(adap->flags & FULL_INIT_DONE)) {
err = t3_check_fw_version(adap);
if (err == -EINVAL) {
err = upgrade_fw(adap);
CH_WARN(adap, "FW upgrade to %d.%d.%d %s\n",
FW_VERSION_MAJOR, FW_VERSION_MINOR,
FW_VERSION_MICRO, err ? "failed" : "succeeded");
}
err = t3_check_tpsram_version(adap);
if (err == -EINVAL) {
err = update_tpsram(adap);
CH_WARN(adap, "TP upgrade to %d.%d.%d %s\n",
TP_VERSION_MAJOR, TP_VERSION_MINOR,
TP_VERSION_MICRO, err ? "failed" : "succeeded");
}
/*
* Clear interrupts now to catch errors if t3_init_hw fails.
* We clear them again later as initialization may trigger
* conditions that can interrupt.
*/
t3_intr_clear(adap);
err = t3_init_hw(adap, 0);
if (err)
goto out;
t3_set_reg_field(adap, A_TP_PARA_REG5, 0, F_RXDDPOFFINIT);
t3_write_reg(adap, A_ULPRX_TDDP_PSZ, V_HPZ0(PAGE_SHIFT - 12));
err = setup_sge_qsets(adap);
if (err)
goto out;
setup_rss(adap);
if (!(adap->flags & NAPI_INIT))
init_napi(adap);
t3_start_sge_timers(adap);
adap->flags |= FULL_INIT_DONE;
}
t3_intr_clear(adap);
if (adap->flags & USING_MSIX) {
name_msix_vecs(adap);
err = request_irq(adap->msix_info[0].vec,
t3_async_intr_handler, 0,
adap->msix_info[0].desc, adap);
if (err)
goto irq_err;
err = request_msix_data_irqs(adap);
if (err) {
free_irq(adap->msix_info[0].vec, adap);
goto irq_err;
}
} else if ((err = request_irq(adap->pdev->irq,
t3_intr_handler(adap,
adap->sge.qs[0].rspq.
polling),
(adap->flags & USING_MSI) ?
0 : IRQF_SHARED,
adap->name, adap)))
goto irq_err;
enable_all_napi(adap);
t3_sge_start(adap);
t3_intr_enable(adap);
if (adap->params.rev >= T3_REV_C && !(adap->flags & TP_PARITY_INIT) &&
is_offload(adap) && init_tp_parity(adap) == 0)
adap->flags |= TP_PARITY_INIT;
if (adap->flags & TP_PARITY_INIT) {
t3_write_reg(adap, A_TP_INT_CAUSE,
F_CMCACHEPERR | F_ARPLUTPERR);
t3_write_reg(adap, A_TP_INT_ENABLE, 0x7fbfffff);
}
if (!(adap->flags & QUEUES_BOUND)) {
int ret = bind_qsets(adap);
if (ret < 0) {
CH_ERR(adap, "failed to bind qsets, err %d\n", ret);
t3_intr_disable(adap);
free_irq_resources(adap);
err = ret;
goto out;
}
adap->flags |= QUEUES_BOUND;
}
out:
return err;
irq_err:
CH_ERR(adap, "request_irq failed, err %d\n", err);
goto out;
}
/*
* Release resources when all the ports and offloading have been stopped.
*/
static void cxgb_down(struct adapter *adapter, int on_wq)
{
t3_sge_stop(adapter);
spin_lock_irq(&adapter->work_lock); /* sync with PHY intr task */
t3_intr_disable(adapter);
spin_unlock_irq(&adapter->work_lock);
free_irq_resources(adapter);
quiesce_rx(adapter);
t3_sge_stop(adapter);
if (!on_wq)
flush_workqueue(cxgb3_wq);/* wait for external IRQ handler */
}
static void schedule_chk_task(struct adapter *adap)
{
unsigned int timeo;
timeo = adap->params.linkpoll_period ?
(HZ * adap->params.linkpoll_period) / 10 :
adap->params.stats_update_period * HZ;
if (timeo)
queue_delayed_work(cxgb3_wq, &adap->adap_check_task, timeo);
}
static int offload_open(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
struct t3cdev *tdev = dev2t3cdev(dev);
int adap_up = adapter->open_device_map & PORT_MASK;
int err;
if (test_and_set_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map))
return 0;
if (!adap_up && (err = cxgb_up(adapter)) < 0)
goto out;
t3_tp_set_offload_mode(adapter, 1);
tdev->lldev = adapter->port[0];
err = cxgb3_offload_activate(adapter);
if (err)
goto out;
init_port_mtus(adapter);
t3_load_mtus(adapter, adapter->params.mtus, adapter->params.a_wnd,
adapter->params.b_wnd,
adapter->params.rev == 0 ?
adapter->port[0]->mtu : 0xffff);
init_smt(adapter);
if (sysfs_create_group(&tdev->lldev->dev.kobj, &offload_attr_group))
dev_dbg(&dev->dev, "cannot create sysfs group\n");
/* Call back all registered clients */
cxgb3_add_clients(tdev);
out:
/* restore them in case the offload module has changed them */
if (err) {
t3_tp_set_offload_mode(adapter, 0);
clear_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map);
cxgb3_set_dummy_ops(tdev);
}
return err;
}
static int offload_close(struct t3cdev *tdev)
{
struct adapter *adapter = tdev2adap(tdev);
struct t3c_data *td = T3C_DATA(tdev);
if (!test_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map))
return 0;
/* Call back all registered clients */
cxgb3_remove_clients(tdev);
sysfs_remove_group(&tdev->lldev->dev.kobj, &offload_attr_group);
/* Flush work scheduled while releasing TIDs */
flush_work_sync(&td->tid_release_task);
tdev->lldev = NULL;
cxgb3_set_dummy_ops(tdev);
t3_tp_set_offload_mode(adapter, 0);
clear_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map);
if (!adapter->open_device_map)
cxgb_down(adapter, 0);
cxgb3_offload_deactivate(adapter);
return 0;
}
static int cxgb_open(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
int other_ports = adapter->open_device_map & PORT_MASK;
int err;
if (!adapter->open_device_map && (err = cxgb_up(adapter)) < 0)
return err;
set_bit(pi->port_id, &adapter->open_device_map);
if (is_offload(adapter) && !ofld_disable) {
err = offload_open(dev);
if (err)
printk(KERN_WARNING
"Could not initialize offload capabilities\n");
}
netif_set_real_num_tx_queues(dev, pi->nqsets);
err = netif_set_real_num_rx_queues(dev, pi->nqsets);
if (err)
return err;
link_start(dev);
t3_port_intr_enable(adapter, pi->port_id);
netif_tx_start_all_queues(dev);
if (!other_ports)
schedule_chk_task(adapter);
cxgb3_event_notify(&adapter->tdev, OFFLOAD_PORT_UP, pi->port_id);
return 0;
}
static int __cxgb_close(struct net_device *dev, int on_wq)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
if (!adapter->open_device_map)
return 0;
/* Stop link fault interrupts */
t3_xgm_intr_disable(adapter, pi->port_id);
t3_read_reg(adapter, A_XGM_INT_STATUS + pi->mac.offset);
t3_port_intr_disable(adapter, pi->port_id);
netif_tx_stop_all_queues(dev);
pi->phy.ops->power_down(&pi->phy, 1);
netif_carrier_off(dev);
t3_mac_disable(&pi->mac, MAC_DIRECTION_TX | MAC_DIRECTION_RX);
spin_lock_irq(&adapter->work_lock); /* sync with update task */
clear_bit(pi->port_id, &adapter->open_device_map);
spin_unlock_irq(&adapter->work_lock);
if (!(adapter->open_device_map & PORT_MASK))
cancel_delayed_work_sync(&adapter->adap_check_task);
if (!adapter->open_device_map)
cxgb_down(adapter, on_wq);
cxgb3_event_notify(&adapter->tdev, OFFLOAD_PORT_DOWN, pi->port_id);
return 0;
}
static int cxgb_close(struct net_device *dev)
{
return __cxgb_close(dev, 0);
}
static struct net_device_stats *cxgb_get_stats(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
struct net_device_stats *ns = &pi->netstats;
const struct mac_stats *pstats;
spin_lock(&adapter->stats_lock);
pstats = t3_mac_update_stats(&pi->mac);
spin_unlock(&adapter->stats_lock);
ns->tx_bytes = pstats->tx_octets;
ns->tx_packets = pstats->tx_frames;
ns->rx_bytes = pstats->rx_octets;
ns->rx_packets = pstats->rx_frames;
ns->multicast = pstats->rx_mcast_frames;
ns->tx_errors = pstats->tx_underrun;
ns->rx_errors = pstats->rx_symbol_errs + pstats->rx_fcs_errs +
pstats->rx_too_long + pstats->rx_jabber + pstats->rx_short +
pstats->rx_fifo_ovfl;
/* detailed rx_errors */
ns->rx_length_errors = pstats->rx_jabber + pstats->rx_too_long;
ns->rx_over_errors = 0;
ns->rx_crc_errors = pstats->rx_fcs_errs;
ns->rx_frame_errors = pstats->rx_symbol_errs;
ns->rx_fifo_errors = pstats->rx_fifo_ovfl;
ns->rx_missed_errors = pstats->rx_cong_drops;
/* detailed tx_errors */
ns->tx_aborted_errors = 0;
ns->tx_carrier_errors = 0;
ns->tx_fifo_errors = pstats->tx_underrun;
ns->tx_heartbeat_errors = 0;
ns->tx_window_errors = 0;
return ns;
}
static u32 get_msglevel(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
return adapter->msg_enable;
}
static void set_msglevel(struct net_device *dev, u32 val)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
adapter->msg_enable = val;
}
static char stats_strings[][ETH_GSTRING_LEN] = {
"TxOctetsOK ",
"TxFramesOK ",
"TxMulticastFramesOK",
"TxBroadcastFramesOK",
"TxPauseFrames ",
"TxUnderrun ",
"TxExtUnderrun ",
"TxFrames64 ",
"TxFrames65To127 ",
"TxFrames128To255 ",
"TxFrames256To511 ",
"TxFrames512To1023 ",
"TxFrames1024To1518 ",
"TxFrames1519ToMax ",
"RxOctetsOK ",
"RxFramesOK ",
"RxMulticastFramesOK",
"RxBroadcastFramesOK",
"RxPauseFrames ",
"RxFCSErrors ",
"RxSymbolErrors ",
"RxShortErrors ",
"RxJabberErrors ",
"RxLengthErrors ",
"RxFIFOoverflow ",
"RxFrames64 ",
"RxFrames65To127 ",
"RxFrames128To255 ",
"RxFrames256To511 ",
"RxFrames512To1023 ",
"RxFrames1024To1518 ",
"RxFrames1519ToMax ",
"PhyFIFOErrors ",
"TSO ",
"VLANextractions ",
"VLANinsertions ",
"TxCsumOffload ",
"RxCsumGood ",
"LroAggregated ",
"LroFlushed ",
"LroNoDesc ",
"RxDrops ",
"CheckTXEnToggled ",
"CheckResets ",
"LinkFaults ",
};
static int get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(stats_strings);
default:
return -EOPNOTSUPP;
}
}
#define T3_REGMAP_SIZE (3 * 1024)
static int get_regs_len(struct net_device *dev)
{
return T3_REGMAP_SIZE;
}
static int get_eeprom_len(struct net_device *dev)
{
return EEPROMSIZE;
}
static void get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
u32 fw_vers = 0;
u32 tp_vers = 0;
spin_lock(&adapter->stats_lock);
t3_get_fw_version(adapter, &fw_vers);
t3_get_tp_version(adapter, &tp_vers);
spin_unlock(&adapter->stats_lock);
strcpy(info->driver, DRV_NAME);
strcpy(info->version, DRV_VERSION);
strcpy(info->bus_info, pci_name(adapter->pdev));
if (!fw_vers)
strcpy(info->fw_version, "N/A");
else {
snprintf(info->fw_version, sizeof(info->fw_version),
"%s %u.%u.%u TP %u.%u.%u",
G_FW_VERSION_TYPE(fw_vers) ? "T" : "N",
G_FW_VERSION_MAJOR(fw_vers),
G_FW_VERSION_MINOR(fw_vers),
G_FW_VERSION_MICRO(fw_vers),
G_TP_VERSION_MAJOR(tp_vers),
G_TP_VERSION_MINOR(tp_vers),
G_TP_VERSION_MICRO(tp_vers));
}
}
static void get_strings(struct net_device *dev, u32 stringset, u8 * data)
{
if (stringset == ETH_SS_STATS)
memcpy(data, stats_strings, sizeof(stats_strings));
}
static unsigned long collect_sge_port_stats(struct adapter *adapter,
struct port_info *p, int idx)
{
int i;
unsigned long tot = 0;
for (i = p->first_qset; i < p->first_qset + p->nqsets; ++i)
tot += adapter->sge.qs[i].port_stats[idx];
return tot;
}
static void get_stats(struct net_device *dev, struct ethtool_stats *stats,
u64 *data)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
const struct mac_stats *s;
spin_lock(&adapter->stats_lock);
s = t3_mac_update_stats(&pi->mac);
spin_unlock(&adapter->stats_lock);
*data++ = s->tx_octets;
*data++ = s->tx_frames;
*data++ = s->tx_mcast_frames;
*data++ = s->tx_bcast_frames;
*data++ = s->tx_pause;
*data++ = s->tx_underrun;
*data++ = s->tx_fifo_urun;
*data++ = s->tx_frames_64;
*data++ = s->tx_frames_65_127;
*data++ = s->tx_frames_128_255;
*data++ = s->tx_frames_256_511;
*data++ = s->tx_frames_512_1023;
*data++ = s->tx_frames_1024_1518;
*data++ = s->tx_frames_1519_max;
*data++ = s->rx_octets;
*data++ = s->rx_frames;
*data++ = s->rx_mcast_frames;
*data++ = s->rx_bcast_frames;
*data++ = s->rx_pause;
*data++ = s->rx_fcs_errs;
*data++ = s->rx_symbol_errs;
*data++ = s->rx_short;
*data++ = s->rx_jabber;
*data++ = s->rx_too_long;
*data++ = s->rx_fifo_ovfl;
*data++ = s->rx_frames_64;
*data++ = s->rx_frames_65_127;
*data++ = s->rx_frames_128_255;
*data++ = s->rx_frames_256_511;
*data++ = s->rx_frames_512_1023;
*data++ = s->rx_frames_1024_1518;
*data++ = s->rx_frames_1519_max;
*data++ = pi->phy.fifo_errors;
*data++ = collect_sge_port_stats(adapter, pi, SGE_PSTAT_TSO);
*data++ = collect_sge_port_stats(adapter, pi, SGE_PSTAT_VLANEX);
*data++ = collect_sge_port_stats(adapter, pi, SGE_PSTAT_VLANINS);
*data++ = collect_sge_port_stats(adapter, pi, SGE_PSTAT_TX_CSUM);
*data++ = collect_sge_port_stats(adapter, pi, SGE_PSTAT_RX_CSUM_GOOD);
*data++ = 0;
*data++ = 0;
*data++ = 0;
*data++ = s->rx_cong_drops;
*data++ = s->num_toggled;
*data++ = s->num_resets;
*data++ = s->link_faults;
}
static inline void reg_block_dump(struct adapter *ap, void *buf,
unsigned int start, unsigned int end)
{
u32 *p = buf + start;
for (; start <= end; start += sizeof(u32))
*p++ = t3_read_reg(ap, start);
}
static void get_regs(struct net_device *dev, struct ethtool_regs *regs,
void *buf)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *ap = pi->adapter;
/*
* Version scheme:
* bits 0..9: chip version
* bits 10..15: chip revision
* bit 31: set for PCIe cards
*/
regs->version = 3 | (ap->params.rev << 10) | (is_pcie(ap) << 31);
/*
* We skip the MAC statistics registers because they are clear-on-read.
* Also reading multi-register stats would need to synchronize with the
* periodic mac stats accumulation. Hard to justify the complexity.
*/
memset(buf, 0, T3_REGMAP_SIZE);
reg_block_dump(ap, buf, 0, A_SG_RSPQ_CREDIT_RETURN);
reg_block_dump(ap, buf, A_SG_HI_DRB_HI_THRSH, A_ULPRX_PBL_ULIMIT);
reg_block_dump(ap, buf, A_ULPTX_CONFIG, A_MPS_INT_CAUSE);
reg_block_dump(ap, buf, A_CPL_SWITCH_CNTRL, A_CPL_MAP_TBL_DATA);
reg_block_dump(ap, buf, A_SMB_GLOBAL_TIME_CFG, A_XGM_SERDES_STAT3);
reg_block_dump(ap, buf, A_XGM_SERDES_STATUS0,
XGM_REG(A_XGM_SERDES_STAT3, 1));
reg_block_dump(ap, buf, XGM_REG(A_XGM_SERDES_STATUS0, 1),
XGM_REG(A_XGM_RX_SPI4_SOP_EOP_CNT, 1));
}
static int restart_autoneg(struct net_device *dev)
{
struct port_info *p = netdev_priv(dev);
if (!netif_running(dev))
return -EAGAIN;
if (p->link_config.autoneg != AUTONEG_ENABLE)
return -EINVAL;
p->phy.ops->autoneg_restart(&p->phy);
return 0;
}
static int cxgb3_phys_id(struct net_device *dev, u32 data)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
int i;
if (data == 0)
data = 2;
for (i = 0; i < data * 2; i++) {
t3_set_reg_field(adapter, A_T3DBG_GPIO_EN, F_GPIO0_OUT_VAL,
(i & 1) ? F_GPIO0_OUT_VAL : 0);
if (msleep_interruptible(500))
break;
}
t3_set_reg_field(adapter, A_T3DBG_GPIO_EN, F_GPIO0_OUT_VAL,
F_GPIO0_OUT_VAL);
return 0;
}
static int get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct port_info *p = netdev_priv(dev);
cmd->supported = p->link_config.supported;
cmd->advertising = p->link_config.advertising;
if (netif_carrier_ok(dev)) {
cmd->speed = p->link_config.speed;
cmd->duplex = p->link_config.duplex;
} else {
cmd->speed = -1;
cmd->duplex = -1;
}
cmd->port = (cmd->supported & SUPPORTED_TP) ? PORT_TP : PORT_FIBRE;
cmd->phy_address = p->phy.mdio.prtad;
cmd->transceiver = XCVR_EXTERNAL;
cmd->autoneg = p->link_config.autoneg;
cmd->maxtxpkt = 0;
cmd->maxrxpkt = 0;
return 0;
}
static int speed_duplex_to_caps(int speed, int duplex)
{
int cap = 0;
switch (speed) {
case SPEED_10:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_10baseT_Full;
else
cap = SUPPORTED_10baseT_Half;
break;
case SPEED_100:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_100baseT_Full;
else
cap = SUPPORTED_100baseT_Half;
break;
case SPEED_1000:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_1000baseT_Full;
else
cap = SUPPORTED_1000baseT_Half;
break;
case SPEED_10000:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_10000baseT_Full;
}
return cap;
}
#define ADVERTISED_MASK (ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | \
ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | \
ADVERTISED_1000baseT_Half | ADVERTISED_1000baseT_Full | \
ADVERTISED_10000baseT_Full)
static int set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct port_info *p = netdev_priv(dev);
struct link_config *lc = &p->link_config;
if (!(lc->supported & SUPPORTED_Autoneg)) {
/*
* PHY offers a single speed/duplex. See if that's what's
* being requested.
*/
if (cmd->autoneg == AUTONEG_DISABLE) {
int cap = speed_duplex_to_caps(cmd->speed, cmd->duplex);
if (lc->supported & cap)
return 0;
}
return -EINVAL;
}
if (cmd->autoneg == AUTONEG_DISABLE) {
int cap = speed_duplex_to_caps(cmd->speed, cmd->duplex);
if (!(lc->supported & cap) || cmd->speed == SPEED_1000)
return -EINVAL;
lc->requested_speed = cmd->speed;
lc->requested_duplex = cmd->duplex;
lc->advertising = 0;
} else {
cmd->advertising &= ADVERTISED_MASK;
cmd->advertising &= lc->supported;
if (!cmd->advertising)
return -EINVAL;
lc->requested_speed = SPEED_INVALID;
lc->requested_duplex = DUPLEX_INVALID;
lc->advertising = cmd->advertising | ADVERTISED_Autoneg;
}
lc->autoneg = cmd->autoneg;
if (netif_running(dev))
t3_link_start(&p->phy, &p->mac, lc);
return 0;
}
static void get_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct port_info *p = netdev_priv(dev);
epause->autoneg = (p->link_config.requested_fc & PAUSE_AUTONEG) != 0;
epause->rx_pause = (p->link_config.fc & PAUSE_RX) != 0;
epause->tx_pause = (p->link_config.fc & PAUSE_TX) != 0;
}
static int set_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct port_info *p = netdev_priv(dev);
struct link_config *lc = &p->link_config;
if (epause->autoneg == AUTONEG_DISABLE)
lc->requested_fc = 0;
else if (lc->supported & SUPPORTED_Autoneg)
lc->requested_fc = PAUSE_AUTONEG;
else
return -EINVAL;
if (epause->rx_pause)
lc->requested_fc |= PAUSE_RX;
if (epause->tx_pause)
lc->requested_fc |= PAUSE_TX;
if (lc->autoneg == AUTONEG_ENABLE) {
if (netif_running(dev))
t3_link_start(&p->phy, &p->mac, lc);
} else {
lc->fc = lc->requested_fc & (PAUSE_RX | PAUSE_TX);
if (netif_running(dev))
t3_mac_set_speed_duplex_fc(&p->mac, -1, -1, lc->fc);
}
return 0;
}
static u32 get_rx_csum(struct net_device *dev)
{
struct port_info *p = netdev_priv(dev);
return p->rx_offload & T3_RX_CSUM;
}
static int set_rx_csum(struct net_device *dev, u32 data)
{
struct port_info *p = netdev_priv(dev);
if (data) {
p->rx_offload |= T3_RX_CSUM;
} else {
int i;
p->rx_offload &= ~(T3_RX_CSUM | T3_LRO);
for (i = p->first_qset; i < p->first_qset + p->nqsets; i++)
set_qset_lro(dev, i, 0);
}
return 0;
}
static void get_sge_param(struct net_device *dev, struct ethtool_ringparam *e)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
const struct qset_params *q = &adapter->params.sge.qset[pi->first_qset];
e->rx_max_pending = MAX_RX_BUFFERS;
e->rx_mini_max_pending = 0;
e->rx_jumbo_max_pending = MAX_RX_JUMBO_BUFFERS;
e->tx_max_pending = MAX_TXQ_ENTRIES;
e->rx_pending = q->fl_size;
e->rx_mini_pending = q->rspq_size;
e->rx_jumbo_pending = q->jumbo_size;
e->tx_pending = q->txq_size[0];
}
static int set_sge_param(struct net_device *dev, struct ethtool_ringparam *e)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
struct qset_params *q;
int i;
if (e->rx_pending > MAX_RX_BUFFERS ||
e->rx_jumbo_pending > MAX_RX_JUMBO_BUFFERS ||
e->tx_pending > MAX_TXQ_ENTRIES ||
e->rx_mini_pending > MAX_RSPQ_ENTRIES ||
e->rx_mini_pending < MIN_RSPQ_ENTRIES ||
e->rx_pending < MIN_FL_ENTRIES ||
e->rx_jumbo_pending < MIN_FL_ENTRIES ||
e->tx_pending < adapter->params.nports * MIN_TXQ_ENTRIES)
return -EINVAL;
if (adapter->flags & FULL_INIT_DONE)
return -EBUSY;
q = &adapter->params.sge.qset[pi->first_qset];
for (i = 0; i < pi->nqsets; ++i, ++q) {
q->rspq_size = e->rx_mini_pending;
q->fl_size = e->rx_pending;
q->jumbo_size = e->rx_jumbo_pending;
q->txq_size[0] = e->tx_pending;
q->txq_size[1] = e->tx_pending;
q->txq_size[2] = e->tx_pending;
}
return 0;
}
static int set_coalesce(struct net_device *dev, struct ethtool_coalesce *c)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
struct qset_params *qsp = &adapter->params.sge.qset[0];
struct sge_qset *qs = &adapter->sge.qs[0];
if (c->rx_coalesce_usecs * 10 > M_NEWTIMER)
return -EINVAL;
qsp->coalesce_usecs = c->rx_coalesce_usecs;
t3_update_qset_coalesce(qs, qsp);
return 0;
}
static int get_coalesce(struct net_device *dev, struct ethtool_coalesce *c)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
struct qset_params *q = adapter->params.sge.qset;
c->rx_coalesce_usecs = q->coalesce_usecs;
return 0;
}
static int get_eeprom(struct net_device *dev, struct ethtool_eeprom *e,
u8 * data)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
int i, err = 0;
u8 *buf = kmalloc(EEPROMSIZE, GFP_KERNEL);
if (!buf)
return -ENOMEM;
e->magic = EEPROM_MAGIC;
for (i = e->offset & ~3; !err && i < e->offset + e->len; i += 4)
err = t3_seeprom_read(adapter, i, (__le32 *) & buf[i]);
if (!err)
memcpy(data, buf + e->offset, e->len);
kfree(buf);
return err;
}
static int set_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom,
u8 * data)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
u32 aligned_offset, aligned_len;
__le32 *p;
u8 *buf;
int err;
if (eeprom->magic != EEPROM_MAGIC)
return -EINVAL;
aligned_offset = eeprom->offset & ~3;
aligned_len = (eeprom->len + (eeprom->offset & 3) + 3) & ~3;
if (aligned_offset != eeprom->offset || aligned_len != eeprom->len) {
buf = kmalloc(aligned_len, GFP_KERNEL);
if (!buf)
return -ENOMEM;
err = t3_seeprom_read(adapter, aligned_offset, (__le32 *) buf);
if (!err && aligned_len > 4)
err = t3_seeprom_read(adapter,
aligned_offset + aligned_len - 4,
(__le32 *) & buf[aligned_len - 4]);
if (err)
goto out;
memcpy(buf + (eeprom->offset & 3), data, eeprom->len);
} else
buf = data;
err = t3_seeprom_wp(adapter, 0);
if (err)
goto out;
for (p = (__le32 *) buf; !err && aligned_len; aligned_len -= 4, p++) {
err = t3_seeprom_write(adapter, aligned_offset, *p);
aligned_offset += 4;
}
if (!err)
err = t3_seeprom_wp(adapter, 1);
out:
if (buf != data)
kfree(buf);
return err;
}
static void get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
wol->supported = 0;
wol->wolopts = 0;
memset(&wol->sopass, 0, sizeof(wol->sopass));
}
static const struct ethtool_ops cxgb_ethtool_ops = {
.get_settings = get_settings,
.set_settings = set_settings,
.get_drvinfo = get_drvinfo,
.get_msglevel = get_msglevel,
.set_msglevel = set_msglevel,
.get_ringparam = get_sge_param,
.set_ringparam = set_sge_param,
.get_coalesce = get_coalesce,
.set_coalesce = set_coalesce,
.get_eeprom_len = get_eeprom_len,
.get_eeprom = get_eeprom,
.set_eeprom = set_eeprom,
.get_pauseparam = get_pauseparam,
.set_pauseparam = set_pauseparam,
.get_rx_csum = get_rx_csum,
.set_rx_csum = set_rx_csum,
.set_tx_csum = ethtool_op_set_tx_csum,
.set_sg = ethtool_op_set_sg,
.get_link = ethtool_op_get_link,
.get_strings = get_strings,
.phys_id = cxgb3_phys_id,
.nway_reset = restart_autoneg,
.get_sset_count = get_sset_count,
.get_ethtool_stats = get_stats,
.get_regs_len = get_regs_len,
.get_regs = get_regs,
.get_wol = get_wol,
.set_tso = ethtool_op_set_tso,
};
static int in_range(int val, int lo, int hi)
{
return val < 0 || (val <= hi && val >= lo);
}
static int cxgb_extension_ioctl(struct net_device *dev, void __user *useraddr)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
u32 cmd;
int ret;
if (copy_from_user(&cmd, useraddr, sizeof(cmd)))
return -EFAULT;
switch (cmd) {
case CHELSIO_SET_QSET_PARAMS:{
int i;
struct qset_params *q;
struct ch_qset_params t;
int q1 = pi->first_qset;
int nqsets = pi->nqsets;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&t, useraddr, sizeof(t)))
return -EFAULT;
if (t.qset_idx >= SGE_QSETS)
return -EINVAL;
if (!in_range(t.intr_lat, 0, M_NEWTIMER) ||
!in_range(t.cong_thres, 0, 255) ||
!in_range(t.txq_size[0], MIN_TXQ_ENTRIES,
MAX_TXQ_ENTRIES) ||
!in_range(t.txq_size[1], MIN_TXQ_ENTRIES,
MAX_TXQ_ENTRIES) ||
!in_range(t.txq_size[2], MIN_CTRL_TXQ_ENTRIES,
MAX_CTRL_TXQ_ENTRIES) ||
!in_range(t.fl_size[0], MIN_FL_ENTRIES,
MAX_RX_BUFFERS) ||
!in_range(t.fl_size[1], MIN_FL_ENTRIES,
MAX_RX_JUMBO_BUFFERS) ||
!in_range(t.rspq_size, MIN_RSPQ_ENTRIES,
MAX_RSPQ_ENTRIES))
return -EINVAL;
if ((adapter->flags & FULL_INIT_DONE) && t.lro > 0)
for_each_port(adapter, i) {
pi = adap2pinfo(adapter, i);
if (t.qset_idx >= pi->first_qset &&
t.qset_idx < pi->first_qset + pi->nqsets &&
!(pi->rx_offload & T3_RX_CSUM))
return -EINVAL;
}
if ((adapter->flags & FULL_INIT_DONE) &&
(t.rspq_size >= 0 || t.fl_size[0] >= 0 ||
t.fl_size[1] >= 0 || t.txq_size[0] >= 0 ||
t.txq_size[1] >= 0 || t.txq_size[2] >= 0 ||
t.polling >= 0 || t.cong_thres >= 0))
return -EBUSY;
/* Allow setting of any available qset when offload enabled */
if (test_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map)) {
q1 = 0;
for_each_port(adapter, i) {
pi = adap2pinfo(adapter, i);
nqsets += pi->first_qset + pi->nqsets;
}
}
if (t.qset_idx < q1)
return -EINVAL;
if (t.qset_idx > q1 + nqsets - 1)
return -EINVAL;
q = &adapter->params.sge.qset[t.qset_idx];
if (t.rspq_size >= 0)
q->rspq_size = t.rspq_size;
if (t.fl_size[0] >= 0)
q->fl_size = t.fl_size[0];
if (t.fl_size[1] >= 0)
q->jumbo_size = t.fl_size[1];
if (t.txq_size[0] >= 0)
q->txq_size[0] = t.txq_size[0];
if (t.txq_size[1] >= 0)
q->txq_size[1] = t.txq_size[1];
if (t.txq_size[2] >= 0)
q->txq_size[2] = t.txq_size[2];
if (t.cong_thres >= 0)
q->cong_thres = t.cong_thres;
if (t.intr_lat >= 0) {
struct sge_qset *qs =
&adapter->sge.qs[t.qset_idx];
q->coalesce_usecs = t.intr_lat;
t3_update_qset_coalesce(qs, q);
}
if (t.polling >= 0) {
if (adapter->flags & USING_MSIX)
q->polling = t.polling;
else {
/* No polling with INTx for T3A */
if (adapter->params.rev == 0 &&
!(adapter->flags & USING_MSI))
t.polling = 0;
for (i = 0; i < SGE_QSETS; i++) {
q = &adapter->params.sge.
qset[i];
q->polling = t.polling;
}
}
}
if (t.lro >= 0)
set_qset_lro(dev, t.qset_idx, t.lro);
break;
}
case CHELSIO_GET_QSET_PARAMS:{
struct qset_params *q;
struct ch_qset_params t;
int q1 = pi->first_qset;
int nqsets = pi->nqsets;
int i;
if (copy_from_user(&t, useraddr, sizeof(t)))
return -EFAULT;
/* Display qsets for all ports when offload enabled */
if (test_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map)) {
q1 = 0;
for_each_port(adapter, i) {
pi = adap2pinfo(adapter, i);
nqsets = pi->first_qset + pi->nqsets;
}
}
if (t.qset_idx >= nqsets)
return -EINVAL;
q = &adapter->params.sge.qset[q1 + t.qset_idx];
t.rspq_size = q->rspq_size;
t.txq_size[0] = q->txq_size[0];
t.txq_size[1] = q->txq_size[1];
t.txq_size[2] = q->txq_size[2];
t.fl_size[0] = q->fl_size;
t.fl_size[1] = q->jumbo_size;
t.polling = q->polling;
t.lro = q->lro;
t.intr_lat = q->coalesce_usecs;
t.cong_thres = q->cong_thres;
t.qnum = q1;
if (adapter->flags & USING_MSIX)
t.vector = adapter->msix_info[q1 + t.qset_idx + 1].vec;
else
t.vector = adapter->pdev->irq;
if (copy_to_user(useraddr, &t, sizeof(t)))
return -EFAULT;
break;
}
case CHELSIO_SET_QSET_NUM:{
struct ch_reg edata;
unsigned int i, first_qset = 0, other_qsets = 0;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (adapter->flags & FULL_INIT_DONE)
return -EBUSY;
if (copy_from_user(&edata, useraddr, sizeof(edata)))
return -EFAULT;
if (edata.val < 1 ||
(edata.val > 1 && !(adapter->flags & USING_MSIX)))
return -EINVAL;
for_each_port(adapter, i)
if (adapter->port[i] && adapter->port[i] != dev)
other_qsets += adap2pinfo(adapter, i)->nqsets;
if (edata.val + other_qsets > SGE_QSETS)
return -EINVAL;
pi->nqsets = edata.val;
for_each_port(adapter, i)
if (adapter->port[i]) {
pi = adap2pinfo(adapter, i);
pi->first_qset = first_qset;
first_qset += pi->nqsets;
}
break;
}
case CHELSIO_GET_QSET_NUM:{
struct ch_reg edata;
memset(&edata, 0, sizeof(struct ch_reg));
edata.cmd = CHELSIO_GET_QSET_NUM;
edata.val = pi->nqsets;
if (copy_to_user(useraddr, &edata, sizeof(edata)))
return -EFAULT;
break;
}
case CHELSIO_LOAD_FW:{
u8 *fw_data;
struct ch_mem_range t;
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
if (copy_from_user(&t, useraddr, sizeof(t)))
return -EFAULT;
/* Check t.len sanity ? */
fw_data = memdup_user(useraddr + sizeof(t), t.len);
if (IS_ERR(fw_data))
return PTR_ERR(fw_data);
ret = t3_load_fw(adapter, fw_data, t.len);
kfree(fw_data);
if (ret)
return ret;
break;
}
case CHELSIO_SETMTUTAB:{
struct ch_mtus m;
int i;
if (!is_offload(adapter))
return -EOPNOTSUPP;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (offload_running(adapter))
return -EBUSY;
if (copy_from_user(&m, useraddr, sizeof(m)))
return -EFAULT;
if (m.nmtus != NMTUS)
return -EINVAL;
if (m.mtus[0] < 81) /* accommodate SACK */
return -EINVAL;
/* MTUs must be in ascending order */
for (i = 1; i < NMTUS; ++i)
if (m.mtus[i] < m.mtus[i - 1])
return -EINVAL;
memcpy(adapter->params.mtus, m.mtus,
sizeof(adapter->params.mtus));
break;
}
case CHELSIO_GET_PM:{
struct tp_params *p = &adapter->params.tp;
struct ch_pm m = {.cmd = CHELSIO_GET_PM };
if (!is_offload(adapter))
return -EOPNOTSUPP;
m.tx_pg_sz = p->tx_pg_size;
m.tx_num_pg = p->tx_num_pgs;
m.rx_pg_sz = p->rx_pg_size;
m.rx_num_pg = p->rx_num_pgs;
m.pm_total = p->pmtx_size + p->chan_rx_size * p->nchan;
if (copy_to_user(useraddr, &m, sizeof(m)))
return -EFAULT;
break;
}
case CHELSIO_SET_PM:{
struct ch_pm m;
struct tp_params *p = &adapter->params.tp;
if (!is_offload(adapter))
return -EOPNOTSUPP;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (adapter->flags & FULL_INIT_DONE)
return -EBUSY;
if (copy_from_user(&m, useraddr, sizeof(m)))
return -EFAULT;
if (!is_power_of_2(m.rx_pg_sz) ||
!is_power_of_2(m.tx_pg_sz))
return -EINVAL; /* not power of 2 */
if (!(m.rx_pg_sz & 0x14000))
return -EINVAL; /* not 16KB or 64KB */
if (!(m.tx_pg_sz & 0x1554000))
return -EINVAL;
if (m.tx_num_pg == -1)
m.tx_num_pg = p->tx_num_pgs;
if (m.rx_num_pg == -1)
m.rx_num_pg = p->rx_num_pgs;
if (m.tx_num_pg % 24 || m.rx_num_pg % 24)
return -EINVAL;
if (m.rx_num_pg * m.rx_pg_sz > p->chan_rx_size ||
m.tx_num_pg * m.tx_pg_sz > p->chan_tx_size)
return -EINVAL;
p->rx_pg_size = m.rx_pg_sz;
p->tx_pg_size = m.tx_pg_sz;
p->rx_num_pgs = m.rx_num_pg;
p->tx_num_pgs = m.tx_num_pg;
break;
}
case CHELSIO_GET_MEM:{
struct ch_mem_range t;
struct mc7 *mem;
u64 buf[32];
if (!is_offload(adapter))
return -EOPNOTSUPP;
if (!(adapter->flags & FULL_INIT_DONE))
return -EIO; /* need the memory controllers */
if (copy_from_user(&t, useraddr, sizeof(t)))
return -EFAULT;
if ((t.addr & 7) || (t.len & 7))
return -EINVAL;
if (t.mem_id == MEM_CM)
mem = &adapter->cm;
else if (t.mem_id == MEM_PMRX)
mem = &adapter->pmrx;
else if (t.mem_id == MEM_PMTX)
mem = &adapter->pmtx;
else
return -EINVAL;
/*
* Version scheme:
* bits 0..9: chip version
* bits 10..15: chip revision
*/
t.version = 3 | (adapter->params.rev << 10);
if (copy_to_user(useraddr, &t, sizeof(t)))
return -EFAULT;
/*
* Read 256 bytes at a time as len can be large and we don't
* want to use huge intermediate buffers.
*/
useraddr += sizeof(t); /* advance to start of buffer */
while (t.len) {
unsigned int chunk =
min_t(unsigned int, t.len, sizeof(buf));
ret =
t3_mc7_bd_read(mem, t.addr / 8, chunk / 8,
buf);
if (ret)
return ret;
if (copy_to_user(useraddr, buf, chunk))
return -EFAULT;
useraddr += chunk;
t.addr += chunk;
t.len -= chunk;
}
break;
}
case CHELSIO_SET_TRACE_FILTER:{
struct ch_trace t;
const struct trace_params *tp;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (!offload_running(adapter))
return -EAGAIN;
if (copy_from_user(&t, useraddr, sizeof(t)))
return -EFAULT;
tp = (const struct trace_params *)&t.sip;
if (t.config_tx)
t3_config_trace_filter(adapter, tp, 0,
t.invert_match,
t.trace_tx);
if (t.config_rx)
t3_config_trace_filter(adapter, tp, 1,
t.invert_match,
t.trace_rx);
break;
}
default:
return -EOPNOTSUPP;
}
return 0;
}
static int cxgb_ioctl(struct net_device *dev, struct ifreq *req, int cmd)
{
struct mii_ioctl_data *data = if_mii(req);
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
switch (cmd) {
case SIOCGMIIREG:
case SIOCSMIIREG:
/* Convert phy_id from older PRTAD/DEVAD format */
if (is_10G(adapter) &&
!mdio_phy_id_is_c45(data->phy_id) &&
(data->phy_id & 0x1f00) &&
!(data->phy_id & 0xe0e0))
data->phy_id = mdio_phy_id_c45(data->phy_id >> 8,
data->phy_id & 0x1f);
/* FALLTHRU */
case SIOCGMIIPHY:
return mdio_mii_ioctl(&pi->phy.mdio, data, cmd);
case SIOCCHIOCTL:
return cxgb_extension_ioctl(dev, req->ifr_data);
default:
return -EOPNOTSUPP;
}
}
static int cxgb_change_mtu(struct net_device *dev, int new_mtu)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
int ret;
if (new_mtu < 81) /* accommodate SACK */
return -EINVAL;
if ((ret = t3_mac_set_mtu(&pi->mac, new_mtu)))
return ret;
dev->mtu = new_mtu;
init_port_mtus(adapter);
if (adapter->params.rev == 0 && offload_running(adapter))
t3_load_mtus(adapter, adapter->params.mtus,
adapter->params.a_wnd, adapter->params.b_wnd,
adapter->port[0]->mtu);
return 0;
}
static int cxgb_set_mac_addr(struct net_device *dev, void *p)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EINVAL;
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
t3_mac_set_address(&pi->mac, LAN_MAC_IDX, dev->dev_addr);
if (offload_running(adapter))
write_smt_entry(adapter, pi->port_id);
return 0;
}
/**
* t3_synchronize_rx - wait for current Rx processing on a port to complete
* @adap: the adapter
* @p: the port
*
* Ensures that current Rx processing on any of the queues associated with
* the given port completes before returning. We do this by acquiring and
* releasing the locks of the response queues associated with the port.
*/
static void t3_synchronize_rx(struct adapter *adap, const struct port_info *p)
{
int i;
for (i = p->first_qset; i < p->first_qset + p->nqsets; i++) {
struct sge_rspq *q = &adap->sge.qs[i].rspq;
spin_lock_irq(&q->lock);
spin_unlock_irq(&q->lock);
}
}
static void vlan_rx_register(struct net_device *dev, struct vlan_group *grp)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
pi->vlan_grp = grp;
if (adapter->params.rev > 0)
t3_set_vlan_accel(adapter, 1 << pi->port_id, grp != NULL);
else {
/* single control for all ports */
unsigned int i, have_vlans = 0;
for_each_port(adapter, i)
have_vlans |= adap2pinfo(adapter, i)->vlan_grp != NULL;
t3_set_vlan_accel(adapter, 1, have_vlans);
}
t3_synchronize_rx(adapter, pi);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void cxgb_netpoll(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
int qidx;
for (qidx = pi->first_qset; qidx < pi->first_qset + pi->nqsets; qidx++) {
struct sge_qset *qs = &adapter->sge.qs[qidx];
void *source;
if (adapter->flags & USING_MSIX)
source = qs;
else
source = adapter;
t3_intr_handler(adapter, qs->rspq.polling) (0, source);
}
}
#endif
/*
* Periodic accumulation of MAC statistics.
*/
static void mac_stats_update(struct adapter *adapter)
{
int i;
for_each_port(adapter, i) {
struct net_device *dev = adapter->port[i];
struct port_info *p = netdev_priv(dev);
if (netif_running(dev)) {
spin_lock(&adapter->stats_lock);
t3_mac_update_stats(&p->mac);
spin_unlock(&adapter->stats_lock);
}
}
}
static void check_link_status(struct adapter *adapter)
{
int i;
for_each_port(adapter, i) {
struct net_device *dev = adapter->port[i];
struct port_info *p = netdev_priv(dev);
int link_fault;
spin_lock_irq(&adapter->work_lock);
link_fault = p->link_fault;
spin_unlock_irq(&adapter->work_lock);
if (link_fault) {
t3_link_fault(adapter, i);
continue;
}
if (!(p->phy.caps & SUPPORTED_IRQ) && netif_running(dev)) {
t3_xgm_intr_disable(adapter, i);
t3_read_reg(adapter, A_XGM_INT_STATUS + p->mac.offset);
t3_link_changed(adapter, i);
t3_xgm_intr_enable(adapter, i);
}
}
}
static void check_t3b2_mac(struct adapter *adapter)
{
int i;
if (!rtnl_trylock()) /* synchronize with ifdown */
return;
for_each_port(adapter, i) {
struct net_device *dev = adapter->port[i];
struct port_info *p = netdev_priv(dev);
int status;
if (!netif_running(dev))
continue;
status = 0;
if (netif_running(dev) && netif_carrier_ok(dev))
status = t3b2_mac_watchdog_task(&p->mac);
if (status == 1)
p->mac.stats.num_toggled++;
else if (status == 2) {
struct cmac *mac = &p->mac;
t3_mac_set_mtu(mac, dev->mtu);
t3_mac_set_address(mac, LAN_MAC_IDX, dev->dev_addr);
cxgb_set_rxmode(dev);
t3_link_start(&p->phy, mac, &p->link_config);
t3_mac_enable(mac, MAC_DIRECTION_RX | MAC_DIRECTION_TX);
t3_port_intr_enable(adapter, p->port_id);
p->mac.stats.num_resets++;
}
}
rtnl_unlock();
}
static void t3_adap_check_task(struct work_struct *work)
{
struct adapter *adapter = container_of(work, struct adapter,
adap_check_task.work);
const struct adapter_params *p = &adapter->params;
int port;
unsigned int v, status, reset;
adapter->check_task_cnt++;
check_link_status(adapter);
/* Accumulate MAC stats if needed */
if (!p->linkpoll_period ||
(adapter->check_task_cnt * p->linkpoll_period) / 10 >=
p->stats_update_period) {
mac_stats_update(adapter);
adapter->check_task_cnt = 0;
}
if (p->rev == T3_REV_B2)
check_t3b2_mac(adapter);
/*
* Scan the XGMAC's to check for various conditions which we want to
* monitor in a periodic polling manner rather than via an interrupt
* condition. This is used for conditions which would otherwise flood
* the system with interrupts and we only really need to know that the
* conditions are "happening" ... For each condition we count the
* detection of the condition and reset it for the next polling loop.
*/
for_each_port(adapter, port) {
struct cmac *mac = &adap2pinfo(adapter, port)->mac;
u32 cause;
cause = t3_read_reg(adapter, A_XGM_INT_CAUSE + mac->offset);
reset = 0;
if (cause & F_RXFIFO_OVERFLOW) {
mac->stats.rx_fifo_ovfl++;
reset |= F_RXFIFO_OVERFLOW;
}
t3_write_reg(adapter, A_XGM_INT_CAUSE + mac->offset, reset);
}
/*
* We do the same as above for FL_EMPTY interrupts.
*/
status = t3_read_reg(adapter, A_SG_INT_CAUSE);
reset = 0;
if (status & F_FLEMPTY) {
struct sge_qset *qs = &adapter->sge.qs[0];
int i = 0;
reset |= F_FLEMPTY;
v = (t3_read_reg(adapter, A_SG_RSPQ_FL_STATUS) >> S_FL0EMPTY) &
0xffff;
while (v) {
qs->fl[i].empty += (v & 1);
if (i)
qs++;
i ^= 1;
v >>= 1;
}
}
t3_write_reg(adapter, A_SG_INT_CAUSE, reset);
/* Schedule the next check update if any port is active. */
spin_lock_irq(&adapter->work_lock);
if (adapter->open_device_map & PORT_MASK)
schedule_chk_task(adapter);
spin_unlock_irq(&adapter->work_lock);
}
static void db_full_task(struct work_struct *work)
{
struct adapter *adapter = container_of(work, struct adapter,
db_full_task);
cxgb3_event_notify(&adapter->tdev, OFFLOAD_DB_FULL, 0);
}
static void db_empty_task(struct work_struct *work)
{
struct adapter *adapter = container_of(work, struct adapter,
db_empty_task);
cxgb3_event_notify(&adapter->tdev, OFFLOAD_DB_EMPTY, 0);
}
static void db_drop_task(struct work_struct *work)
{
struct adapter *adapter = container_of(work, struct adapter,
db_drop_task);
unsigned long delay = 1000;
unsigned short r;
cxgb3_event_notify(&adapter->tdev, OFFLOAD_DB_DROP, 0);
/*
* Sleep a while before ringing the driver qset dbs.
* The delay is between 1000-2023 usecs.
*/
get_random_bytes(&r, 2);
delay += r & 1023;
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout(usecs_to_jiffies(delay));
ring_dbs(adapter);
}
/*
* Processes external (PHY) interrupts in process context.
*/
static void ext_intr_task(struct work_struct *work)
{
struct adapter *adapter = container_of(work, struct adapter,
ext_intr_handler_task);
int i;
/* Disable link fault interrupts */
for_each_port(adapter, i) {
struct net_device *dev = adapter->port[i];
struct port_info *p = netdev_priv(dev);
t3_xgm_intr_disable(adapter, i);
t3_read_reg(adapter, A_XGM_INT_STATUS + p->mac.offset);
}
/* Re-enable link fault interrupts */
t3_phy_intr_handler(adapter);
for_each_port(adapter, i)
t3_xgm_intr_enable(adapter, i);
/* Now reenable external interrupts */
spin_lock_irq(&adapter->work_lock);
if (adapter->slow_intr_mask) {
adapter->slow_intr_mask |= F_T3DBG;
t3_write_reg(adapter, A_PL_INT_CAUSE0, F_T3DBG);
t3_write_reg(adapter, A_PL_INT_ENABLE0,
adapter->slow_intr_mask);
}
spin_unlock_irq(&adapter->work_lock);
}
/*
* Interrupt-context handler for external (PHY) interrupts.
*/
void t3_os_ext_intr_handler(struct adapter *adapter)
{
/*
* Schedule a task to handle external interrupts as they may be slow
* and we use a mutex to protect MDIO registers. We disable PHY
* interrupts in the meantime and let the task reenable them when
* it's done.
*/
spin_lock(&adapter->work_lock);
if (adapter->slow_intr_mask) {
adapter->slow_intr_mask &= ~F_T3DBG;
t3_write_reg(adapter, A_PL_INT_ENABLE0,
adapter->slow_intr_mask);
queue_work(cxgb3_wq, &adapter->ext_intr_handler_task);
}
spin_unlock(&adapter->work_lock);
}
void t3_os_link_fault_handler(struct adapter *adapter, int port_id)
{
struct net_device *netdev = adapter->port[port_id];
struct port_info *pi = netdev_priv(netdev);
spin_lock(&adapter->work_lock);
pi->link_fault = 1;
spin_unlock(&adapter->work_lock);
}
static int t3_adapter_error(struct adapter *adapter, int reset, int on_wq)
{
int i, ret = 0;
if (is_offload(adapter) &&
test_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map)) {
cxgb3_event_notify(&adapter->tdev, OFFLOAD_STATUS_DOWN, 0);
offload_close(&adapter->tdev);
}
/* Stop all ports */
for_each_port(adapter, i) {
struct net_device *netdev = adapter->port[i];
if (netif_running(netdev))
__cxgb_close(netdev, on_wq);
}
/* Stop SGE timers */
t3_stop_sge_timers(adapter);
adapter->flags &= ~FULL_INIT_DONE;
if (reset)
ret = t3_reset_adapter(adapter);
pci_disable_device(adapter->pdev);
return ret;
}
static int t3_reenable_adapter(struct adapter *adapter)
{
if (pci_enable_device(adapter->pdev)) {
dev_err(&adapter->pdev->dev,
"Cannot re-enable PCI device after reset.\n");
goto err;
}
pci_set_master(adapter->pdev);
pci_restore_state(adapter->pdev);
pci_save_state(adapter->pdev);
/* Free sge resources */
t3_free_sge_resources(adapter);
if (t3_replay_prep_adapter(adapter))
goto err;
return 0;
err:
return -1;
}
static void t3_resume_ports(struct adapter *adapter)
{
int i;
/* Restart the ports */
for_each_port(adapter, i) {
struct net_device *netdev = adapter->port[i];
if (netif_running(netdev)) {
if (cxgb_open(netdev)) {
dev_err(&adapter->pdev->dev,
"can't bring device back up"
" after reset\n");
continue;
}
}
}
if (is_offload(adapter) && !ofld_disable)
cxgb3_event_notify(&adapter->tdev, OFFLOAD_STATUS_UP, 0);
}
/*
* processes a fatal error.
* Bring the ports down, reset the chip, bring the ports back up.
*/
static void fatal_error_task(struct work_struct *work)
{
struct adapter *adapter = container_of(work, struct adapter,
fatal_error_handler_task);
int err = 0;
rtnl_lock();
err = t3_adapter_error(adapter, 1, 1);
if (!err)
err = t3_reenable_adapter(adapter);
if (!err)
t3_resume_ports(adapter);
CH_ALERT(adapter, "adapter reset %s\n", err ? "failed" : "succeeded");
rtnl_unlock();
}
void t3_fatal_err(struct adapter *adapter)
{
unsigned int fw_status[4];
if (adapter->flags & FULL_INIT_DONE) {
t3_sge_stop(adapter);
t3_write_reg(adapter, A_XGM_TX_CTRL, 0);
t3_write_reg(adapter, A_XGM_RX_CTRL, 0);
t3_write_reg(adapter, XGM_REG(A_XGM_TX_CTRL, 1), 0);
t3_write_reg(adapter, XGM_REG(A_XGM_RX_CTRL, 1), 0);
spin_lock(&adapter->work_lock);
t3_intr_disable(adapter);
queue_work(cxgb3_wq, &adapter->fatal_error_handler_task);
spin_unlock(&adapter->work_lock);
}
CH_ALERT(adapter, "encountered fatal error, operation suspended\n");
if (!t3_cim_ctl_blk_read(adapter, 0xa0, 4, fw_status))
CH_ALERT(adapter, "FW status: 0x%x, 0x%x, 0x%x, 0x%x\n",
fw_status[0], fw_status[1],
fw_status[2], fw_status[3]);
}
/**
* t3_io_error_detected - called when PCI error is detected
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*
* This function is called after a PCI bus error affecting
* this device has been detected.
*/
static pci_ers_result_t t3_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct adapter *adapter = pci_get_drvdata(pdev);
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
t3_adapter_error(adapter, 0, 0);
/* Request a slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
/**
* t3_io_slot_reset - called after the pci bus has been reset.
* @pdev: Pointer to PCI device
*
* Restart the card from scratch, as if from a cold-boot.
*/
static pci_ers_result_t t3_io_slot_reset(struct pci_dev *pdev)
{
struct adapter *adapter = pci_get_drvdata(pdev);
if (!t3_reenable_adapter(adapter))
return PCI_ERS_RESULT_RECOVERED;
return PCI_ERS_RESULT_DISCONNECT;
}
/**
* t3_io_resume - called when traffic can start flowing again.
* @pdev: Pointer to PCI device
*
* This callback is called when the error recovery driver tells us that
* its OK to resume normal operation.
*/
static void t3_io_resume(struct pci_dev *pdev)
{
struct adapter *adapter = pci_get_drvdata(pdev);
CH_ALERT(adapter, "adapter recovering, PEX ERR 0x%x\n",
t3_read_reg(adapter, A_PCIE_PEX_ERR));
t3_resume_ports(adapter);
}
static struct pci_error_handlers t3_err_handler = {
.error_detected = t3_io_error_detected,
.slot_reset = t3_io_slot_reset,
.resume = t3_io_resume,
};
/*
* Set the number of qsets based on the number of CPUs and the number of ports,
* not to exceed the number of available qsets, assuming there are enough qsets
* per port in HW.
*/
static void set_nqsets(struct adapter *adap)
{
int i, j = 0;
int num_cpus = num_online_cpus();
int hwports = adap->params.nports;
int nqsets = adap->msix_nvectors - 1;
if (adap->params.rev > 0 && adap->flags & USING_MSIX) {
if (hwports == 2 &&
(hwports * nqsets > SGE_QSETS ||
num_cpus >= nqsets / hwports))
nqsets /= hwports;
if (nqsets > num_cpus)
nqsets = num_cpus;
if (nqsets < 1 || hwports == 4)
nqsets = 1;
} else
nqsets = 1;
for_each_port(adap, i) {
struct port_info *pi = adap2pinfo(adap, i);
pi->first_qset = j;
pi->nqsets = nqsets;
j = pi->first_qset + nqsets;
dev_info(&adap->pdev->dev,
"Port %d using %d queue sets.\n", i, nqsets);
}
}
static int __devinit cxgb_enable_msix(struct adapter *adap)
{
struct msix_entry entries[SGE_QSETS + 1];
int vectors;
int i, err;
vectors = ARRAY_SIZE(entries);
for (i = 0; i < vectors; ++i)
entries[i].entry = i;
while ((err = pci_enable_msix(adap->pdev, entries, vectors)) > 0)
vectors = err;
if (err < 0)
pci_disable_msix(adap->pdev);
if (!err && vectors < (adap->params.nports + 1)) {
pci_disable_msix(adap->pdev);
err = -1;
}
if (!err) {
for (i = 0; i < vectors; ++i)
adap->msix_info[i].vec = entries[i].vector;
adap->msix_nvectors = vectors;
}
return err;
}
static void __devinit print_port_info(struct adapter *adap,
const struct adapter_info *ai)
{
static const char *pci_variant[] = {
"PCI", "PCI-X", "PCI-X ECC", "PCI-X 266", "PCI Express"
};
int i;
char buf[80];
if (is_pcie(adap))
snprintf(buf, sizeof(buf), "%s x%d",
pci_variant[adap->params.pci.variant],
adap->params.pci.width);
else
snprintf(buf, sizeof(buf), "%s %dMHz/%d-bit",
pci_variant[adap->params.pci.variant],
adap->params.pci.speed, adap->params.pci.width);
for_each_port(adap, i) {
struct net_device *dev = adap->port[i];
const struct port_info *pi = netdev_priv(dev);
if (!test_bit(i, &adap->registered_device_map))
continue;
printk(KERN_INFO "%s: %s %s %sNIC (rev %d) %s%s\n",
dev->name, ai->desc, pi->phy.desc,
is_offload(adap) ? "R" : "", adap->params.rev, buf,
(adap->flags & USING_MSIX) ? " MSI-X" :
(adap->flags & USING_MSI) ? " MSI" : "");
if (adap->name == dev->name && adap->params.vpd.mclk)
printk(KERN_INFO
"%s: %uMB CM, %uMB PMTX, %uMB PMRX, S/N: %s\n",
adap->name, t3_mc7_size(&adap->cm) >> 20,
t3_mc7_size(&adap->pmtx) >> 20,
t3_mc7_size(&adap->pmrx) >> 20,
adap->params.vpd.sn);
}
}
static const struct net_device_ops cxgb_netdev_ops = {
.ndo_open = cxgb_open,
.ndo_stop = cxgb_close,
.ndo_start_xmit = t3_eth_xmit,
.ndo_get_stats = cxgb_get_stats,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_multicast_list = cxgb_set_rxmode,
.ndo_do_ioctl = cxgb_ioctl,
.ndo_change_mtu = cxgb_change_mtu,
.ndo_set_mac_address = cxgb_set_mac_addr,
.ndo_vlan_rx_register = vlan_rx_register,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = cxgb_netpoll,
#endif
};
static void __devinit cxgb3_init_iscsi_mac(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
memcpy(pi->iscsic.mac_addr, dev->dev_addr, ETH_ALEN);
pi->iscsic.mac_addr[3] |= 0x80;
}
static int __devinit init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
static int version_printed;
int i, err, pci_using_dac = 0;
resource_size_t mmio_start, mmio_len;
const struct adapter_info *ai;
struct adapter *adapter = NULL;
struct port_info *pi;
if (!version_printed) {
printk(KERN_INFO "%s - version %s\n", DRV_DESC, DRV_VERSION);
++version_printed;
}
if (!cxgb3_wq) {
cxgb3_wq = create_singlethread_workqueue(DRV_NAME);
if (!cxgb3_wq) {
printk(KERN_ERR DRV_NAME
": cannot initialize work queue\n");
return -ENOMEM;
}
}
err = pci_enable_device(pdev);
if (err) {
dev_err(&pdev->dev, "cannot enable PCI device\n");
goto out;
}
err = pci_request_regions(pdev, DRV_NAME);
if (err) {
/* Just info, some other driver may have claimed the device. */
dev_info(&pdev->dev, "cannot obtain PCI resources\n");
goto out_disable_device;
}
if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
pci_using_dac = 1;
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
if (err) {
dev_err(&pdev->dev, "unable to obtain 64-bit DMA for "
"coherent allocations\n");
goto out_release_regions;
}
} else if ((err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) != 0) {
dev_err(&pdev->dev, "no usable DMA configuration\n");
goto out_release_regions;
}
pci_set_master(pdev);
pci_save_state(pdev);
mmio_start = pci_resource_start(pdev, 0);
mmio_len = pci_resource_len(pdev, 0);
ai = t3_get_adapter_info(ent->driver_data);
adapter = kzalloc(sizeof(*adapter), GFP_KERNEL);
if (!adapter) {
err = -ENOMEM;
goto out_release_regions;
}
adapter->nofail_skb =
alloc_skb(sizeof(struct cpl_set_tcb_field), GFP_KERNEL);
if (!adapter->nofail_skb) {
dev_err(&pdev->dev, "cannot allocate nofail buffer\n");
err = -ENOMEM;
goto out_free_adapter;
}
adapter->regs = ioremap_nocache(mmio_start, mmio_len);
if (!adapter->regs) {
dev_err(&pdev->dev, "cannot map device registers\n");
err = -ENOMEM;
goto out_free_adapter;
}
adapter->pdev = pdev;
adapter->name = pci_name(pdev);
adapter->msg_enable = dflt_msg_enable;
adapter->mmio_len = mmio_len;
mutex_init(&adapter->mdio_lock);
spin_lock_init(&adapter->work_lock);
spin_lock_init(&adapter->stats_lock);
INIT_LIST_HEAD(&adapter->adapter_list);
INIT_WORK(&adapter->ext_intr_handler_task, ext_intr_task);
INIT_WORK(&adapter->fatal_error_handler_task, fatal_error_task);
INIT_WORK(&adapter->db_full_task, db_full_task);
INIT_WORK(&adapter->db_empty_task, db_empty_task);
INIT_WORK(&adapter->db_drop_task, db_drop_task);
INIT_DELAYED_WORK(&adapter->adap_check_task, t3_adap_check_task);
for (i = 0; i < ai->nports0 + ai->nports1; ++i) {
struct net_device *netdev;
netdev = alloc_etherdev_mq(sizeof(struct port_info), SGE_QSETS);
if (!netdev) {
err = -ENOMEM;
goto out_free_dev;
}
SET_NETDEV_DEV(netdev, &pdev->dev);
adapter->port[i] = netdev;
pi = netdev_priv(netdev);
pi->adapter = adapter;
pi->rx_offload = T3_RX_CSUM | T3_LRO;
pi->port_id = i;
netif_carrier_off(netdev);
netdev->irq = pdev->irq;
netdev->mem_start = mmio_start;
netdev->mem_end = mmio_start + mmio_len - 1;
netdev->features |= NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_TSO;
netdev->features |= NETIF_F_GRO;
if (pci_using_dac)
netdev->features |= NETIF_F_HIGHDMA;
netdev->features |= NETIF_F_HW_VLAN_TX | NETIF_F_HW_VLAN_RX;
netdev->netdev_ops = &cxgb_netdev_ops;
SET_ETHTOOL_OPS(netdev, &cxgb_ethtool_ops);
}
pci_set_drvdata(pdev, adapter);
if (t3_prep_adapter(adapter, ai, 1) < 0) {
err = -ENODEV;
goto out_free_dev;
}
/*
* The card is now ready to go. If any errors occur during device
* registration we do not fail the whole card but rather proceed only
* with the ports we manage to register successfully. However we must
* register at least one net device.
*/
for_each_port(adapter, i) {
err = register_netdev(adapter->port[i]);
if (err)
dev_warn(&pdev->dev,
"cannot register net device %s, skipping\n",
adapter->port[i]->name);
else {
/*
* Change the name we use for messages to the name of
* the first successfully registered interface.
*/
if (!adapter->registered_device_map)
adapter->name = adapter->port[i]->name;
__set_bit(i, &adapter->registered_device_map);
}
}
if (!adapter->registered_device_map) {
dev_err(&pdev->dev, "could not register any net devices\n");
goto out_free_dev;
}
for_each_port(adapter, i)
cxgb3_init_iscsi_mac(adapter->port[i]);
/* Driver's ready. Reflect it on LEDs */
t3_led_ready(adapter);
if (is_offload(adapter)) {
__set_bit(OFFLOAD_DEVMAP_BIT, &adapter->registered_device_map);
cxgb3_adapter_ofld(adapter);
}
/* See what interrupts we'll be using */
if (msi > 1 && cxgb_enable_msix(adapter) == 0)
adapter->flags |= USING_MSIX;
else if (msi > 0 && pci_enable_msi(pdev) == 0)
adapter->flags |= USING_MSI;
set_nqsets(adapter);
err = sysfs_create_group(&adapter->port[0]->dev.kobj,
&cxgb3_attr_group);
print_port_info(adapter, ai);
return 0;
out_free_dev:
iounmap(adapter->regs);
for (i = ai->nports0 + ai->nports1 - 1; i >= 0; --i)
if (adapter->port[i])
free_netdev(adapter->port[i]);
out_free_adapter:
kfree(adapter);
out_release_regions:
pci_release_regions(pdev);
out_disable_device:
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
out:
return err;
}
static void __devexit remove_one(struct pci_dev *pdev)
{
struct adapter *adapter = pci_get_drvdata(pdev);
if (adapter) {
int i;
t3_sge_stop(adapter);
sysfs_remove_group(&adapter->port[0]->dev.kobj,
&cxgb3_attr_group);
if (is_offload(adapter)) {
cxgb3_adapter_unofld(adapter);
if (test_bit(OFFLOAD_DEVMAP_BIT,
&adapter->open_device_map))
offload_close(&adapter->tdev);
}
for_each_port(adapter, i)
if (test_bit(i, &adapter->registered_device_map))
unregister_netdev(adapter->port[i]);
t3_stop_sge_timers(adapter);
t3_free_sge_resources(adapter);
cxgb_disable_msi(adapter);
for_each_port(adapter, i)
if (adapter->port[i])
free_netdev(adapter->port[i]);
iounmap(adapter->regs);
if (adapter->nofail_skb)
kfree_skb(adapter->nofail_skb);
kfree(adapter);
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
}
}
static struct pci_driver driver = {
.name = DRV_NAME,
.id_table = cxgb3_pci_tbl,
.probe = init_one,
.remove = __devexit_p(remove_one),
.err_handler = &t3_err_handler,
};
static int __init cxgb3_init_module(void)
{
int ret;
cxgb3_offload_init();
ret = pci_register_driver(&driver);
return ret;
}
static void __exit cxgb3_cleanup_module(void)
{
pci_unregister_driver(&driver);
if (cxgb3_wq)
destroy_workqueue(cxgb3_wq);
}
module_init(cxgb3_init_module);
module_exit(cxgb3_cleanup_module);
| gpl-2.0 |
friedrich420/S5-AEL-Kernel | sound/soc/soc-dapm.c | 108 | 89021 | /*
* 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/pm_runtime.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>
int soc_dpcm_runtime_update(struct snd_soc_dapm_widget *);
#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_adc] = 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_aif_in] = 8,
[snd_soc_dapm_aif_out] = 8,
[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_aif_in] = 1,
[snd_soc_dapm_aif_out] = 1,
[snd_soc_dapm_adc] = 5,
[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_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)
{
bool change;
unsigned int old, new;
int ret;
if (w->codec && w->codec->using_regmap) {
ret = regmap_update_bits_check(w->codec->control_data,
reg, mask, value, &change);
if (ret != 0)
return ret;
} else {
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, snd_soc_get_enum_text(e, 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, snd_soc_get_enum_text(e, 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, snd_soc_get_enum_text(e, 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_siggen:
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, snd_soc_get_enum_text(e, 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*)snd_soc_get_enum_text(e, 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;
}
/* 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;
}
}
/* 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;
}
/* add widget to list if it's not already in the list */
static int dapm_list_add_widget(struct snd_soc_dapm_widget_list **list,
struct snd_soc_dapm_widget *w)
{
struct snd_soc_dapm_widget_list *wlist;
int wlistsize, wlistentries, i;
if (*list == NULL)
return -EINVAL;
wlist = *list;
/* is this widget already in the list */
for (i = 0; i < wlist->num_widgets; i++) {
if (wlist->widgets[i] == w)
return 0;
}
/* allocate some new space */
wlistentries = wlist->num_widgets + 1;
wlistsize = sizeof(struct snd_soc_dapm_widget_list) +
wlistentries * sizeof(struct snd_soc_dapm_widget *);
*list = krealloc(wlist, wlistsize, GFP_KERNEL);
if (*list == NULL) {
dev_err(w->dapm->dev, "can't allocate widget list for %s\n",
w->name);
return -ENOMEM;
}
wlist = *list;
/* insert the widget */
dev_dbg(w->dapm->dev, "added %s in widget list pos %d\n",
w->name, wlist->num_widgets);
wlist->widgets[wlist->num_widgets] = w;
wlist->num_widgets++;
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_widget_list **list)
{
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;
dev_vdbg(widget->dapm->dev," %c : %s -> %s -> %s : %c\n",
path->sink && path->connect ? '*' : ' ',
widget->name, path->name, path->sink->name,
path->weak ? 'w': ' ');
if (path->sink && path->connect) {
path->walked = 1;
/* do we need to add this widget to the list ? */
if (list) {
int err;
err = dapm_list_add_widget(list, path->sink);
if (err < 0) {
dev_err(widget->dapm->dev, "could not add widget %s\n",
widget->name);
return con;
}
}
con += is_connected_output_ep(path->sink, list);
}
}
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_widget_list **list)
{
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;
}
/* signal generator */
if (widget->id == snd_soc_dapm_siggen) {
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->source)
dev_vdbg(widget->dapm->dev," %c : %s <- %s <- %s : %c\n",
path->source && path->connect ? '*' : ' ',
widget->name, path->name, path->source->name,
path->weak ? 'w': ' ');
if (path->weak)
continue;
if (path->walked)
continue;
if (path->source && path->connect) {
path->walked = 1;
/* do we need to add this widget to the list ? */
if (list) {
int err;
err = dapm_list_add_widget(list, path->sink);
if (err < 0) {
dev_err(widget->dapm->dev, "could not add widget %s\n",
widget->name);
return con;
}
}
con += is_connected_input_ep(path->source, list);
}
}
widget->inputs = con;
return con;
}
/* Get the DAPM AIF widget for thie DAI stream */
struct snd_soc_dapm_widget *snd_soc_get_codec_widget(struct snd_soc_card *card,
struct snd_soc_codec *codec, const char *name)
{
struct snd_soc_dapm_widget *w;
/* get stream root widget AIF from stream string and direction */
list_for_each_entry(w, &card->widgets, list) {
/* make sure the widget belongs the DAI codec or platform */
if (w->codec && w->codec != codec)
continue;
if (!strcmp(w->name, name))
return w;
}
dev_err(card->dapm.dev, "DAI AIF widget for %s not found\n", name);
return NULL;
}
EXPORT_SYMBOL_GPL(snd_soc_get_codec_widget);
struct snd_soc_dapm_widget *snd_soc_get_platform_widget(struct snd_soc_card *card,
struct snd_soc_platform *platform, const char *name)
{
struct snd_soc_dapm_widget *w;
/* get stream root widget AIF from stream string and direction */
list_for_each_entry(w, &card->widgets, list) {
/* make sure the widget belongs the DAI codec or platform */
if (w->platform && w->platform != platform)
continue;
if (!strcmp(w->name, name))
return w;
}
dev_err(card->dapm.dev, "DAI AIF widget for %s not found\n", name);
return NULL;
}
EXPORT_SYMBOL_GPL(snd_soc_get_platform_widget);
static int dapm_get_playback_paths(struct snd_soc_dapm_context *dapm,
struct snd_soc_dapm_widget *root,
struct snd_soc_dapm_widget_list **list)
{
int paths;
if (!root) {
dev_err(dapm->dev, "no root widget for path discovery\n");
return 0;
}
dev_dbg(dapm->dev, "Playback: checking paths from %s\n",root->name);
paths = is_connected_output_ep(root, list);
dev_dbg(dapm->dev, "Playback: found %d paths from %s\n", paths, root->name);
return paths;
}
int snd_soc_dapm_codec_dai_get_playback_connected_widgets(struct snd_soc_dai *dai,
struct snd_soc_dapm_widget_list **list)
{
struct snd_soc_dapm_widget *w;
struct snd_soc_dapm_widget *widget;
struct snd_soc_dapm_widget_list *wlist;
struct snd_soc_codec *codec = dai->codec;
struct snd_soc_card *card = dai->card;
const char *stream_name;
int paths;
stream_name = dai->driver->playback.stream_name;
list_for_each_entry(w, &card->widgets, list)
{
if (!w->sname || (w->dapm != &codec->dapm))
continue;
dev_dbg(dai->dev, "%s(): widget = %s. widget stream name = %s.\n",
__func__, w->name, w->sname);
if (!strstr(w->sname, stream_name)) {
dev_dbg(dai->dev, "%s(): NOT Found AIF widget with sname %s.\n"
" current AIF widget with stream name = %s.\n",
__func__, stream_name, w->sname);
continue;
}
dev_dbg(dai->dev, "%s(): Found AIF widget with stream name = %s.\n",
__func__, w->sname);
break;
}
wlist = kzalloc(sizeof(struct snd_soc_dapm_widget_list) +
sizeof(struct snd_soc_dapm_widget *), GFP_KERNEL);
if (wlist == NULL) {
dev_err(codec->dev, "%s(): can't allocate widget list for %s\n",
__func__,w->name);
return -ENOMEM;
}
memset(&card->dapm_stats, 0, sizeof(card->dapm_stats));
list_for_each_entry(widget, &card->widgets, list) {
widget->power_checked = false;
widget->inputs = -1;
widget->outputs = -1;
}
/* get number of valid DAI paths and their widgets */
paths = dapm_get_playback_paths(&card->dapm, w, &wlist);
dapm_clear_walk(&card->dapm);
dev_dbg(dai->dev, "%s(): found %d audio playback paths for codec dai: %s\n",
__func__, paths, dai->name);
*list = wlist;
return paths;
}
static int dapm_get_capture_paths(struct snd_soc_dapm_context *dapm,
struct snd_soc_dapm_widget *root,
struct snd_soc_dapm_widget_list **list)
{
int paths;
if (!root) {
dev_err(dapm->dev, "no root widget for path discovery\n");
return 0;
}
dev_dbg(dapm->dev, "Capture: checking paths from %s\n",root->name);
paths = is_connected_input_ep(root, list);
dev_dbg(dapm->dev, "Capture: found %d paths from %s\n", paths, root->name);
return paths;
}
/**
* snd_soc_dapm_get_connected_widgets - query audio path and it's widgets.
* @dai: the soc DAI.
* @stream: stream direction.
* @list: list of active widgets for this stream.
*
* Queries DAPM graph as to whether an valid audio stream path exists for
* the initial stream specified by name. This takes into account
* current mixer and mux kcontrol settings. Creates list of valid widgets.
*
* Returns the number of valid paths or negative error.
*/
int snd_soc_dapm_dai_get_connected_widgets(struct snd_soc_dai *dai, int stream,
struct snd_soc_dapm_widget_list **list)
{
struct snd_soc_card *card = dai->card;
struct snd_soc_dapm_widget *w;
int paths;
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;
}
if (stream == SNDRV_PCM_STREAM_PLAYBACK)
paths = dapm_get_playback_paths(&card->dapm, dai->playback_aif, list);
else
paths = dapm_get_capture_paths(&card->dapm, dai->capture_aif, list);
dapm_clear_walk(&card->dapm);
return paths;
}
/*
* 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, NULL);
dapm_clear_walk(w->dapm);
out = is_connected_output_ep(w, NULL);
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, NULL);
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, NULL);
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 (cur_dapm && !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 (cur_dapm && !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) {
if (d->dev)
pm_runtime_get_sync(d->dev);
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 (d->dev)
pm_runtime_put_sync(d->dev);
}
/* 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);
dev_dbg(w->dapm->dev,
"dapm: power up widget %s\n", w->name);
} else {
dapm_seq_insert(w, down_list, false);
dev_dbg(w->dapm->dev,
"dapm: power down widget %s\n", w->name);
}
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);
mutex_lock(&card->dapm_power_mutex);
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 && 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);
mutex_unlock(&card->dapm_power_mutex);
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, NULL);
dapm_clear_walk(w->dapm);
out = is_connected_output_ep(w, NULL);
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 soc_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 || !snd_soc_get_enum_text(e, mux))
continue;
found = 1;
/* we now need to match the string in the enum to the path */
if (!(strcmp(path->name, snd_soc_get_enum_text(e, 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 found;
}
int snd_soc_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_card *card = widget->dapm->card;
int ret;
mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_PCM);
ret = soc_dapm_mux_update_power(widget, kcontrol, change, mux, e);
mutex_unlock(&card->dapm_mutex);
if (ret > 0)
soc_dpcm_runtime_update(widget);
return ret;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_mux_update_power);
/* test and update the power status of a mixer or switch widget */
static int soc_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 found;
}
int snd_soc_dapm_mixer_update_power(struct snd_soc_dapm_widget *widget,
struct snd_kcontrol *kcontrol, int connect)
{
struct snd_soc_card *card = widget->dapm->card;
int ret;
mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_PCM);
ret = soc_dapm_mixer_update_power(widget, kcontrol, connect);
mutex_unlock(&card->dapm_mutex);
if (ret > 0)
soc_dpcm_runtime_update(widget);
return ret;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_mixer_update_power);
/* 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 = dev_get_drvdata(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)
{
int ret;
/*
* Suppress early reports (eg, jacks syncing their state) to avoid
* silly DAPM runs during card startup.
*/
if (!dapm->card || !dapm->card->instantiated)
return 0;
mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_PCM);
ret = dapm_power_widgets(dapm, SND_SOC_DAPM_STREAM_NOP);
mutex_unlock(&dapm->card->dapm_mutex);
return ret;
}
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_siggen:
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;
mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_INIT);
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++;
}
mutex_unlock(&dapm->card->dapm_mutex);
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;
mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_INIT);
for (i = 0; i < num; i++) {
err = snd_soc_dapm_weak_route(dapm, route);
if (err)
ret = err;
route++;
}
mutex_unlock(&dapm->card->dapm_mutex);
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;
mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_INIT);
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) {
mutex_unlock(&dapm->card->dapm_mutex);
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);
mutex_unlock(&dapm->card->dapm_mutex);
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 snd_soc_card *card = codec->card;
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_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_PCM);
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;
soc_dapm_mixer_update_power(widget, kcontrol, connect);
widget->dapm->update = NULL;
}
}
mutex_unlock(&card->dapm_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 snd_soc_card *card = codec->card;
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_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_PCM);
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;
soc_dapm_mux_update_power(widget, kcontrol, change, mux, e);
widget->dapm->update = NULL;
}
}
mutex_unlock(&card->dapm_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 snd_soc_card *card = codec->card;
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_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_PCM);
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];
soc_dapm_mux_update_power(widget, kcontrol, change,
widget->value, e);
}
}
mutex_unlock(&card->dapm_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 snd_soc_card *card = codec->card;
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_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_PCM);
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;
soc_dapm_mux_update_power(widget, kcontrol, change, mux, e);
widget->dapm->update = NULL;
}
}
mutex_unlock(&card->dapm_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_card *card = snd_kcontrol_chip(kcontrol);
const char *pin = (const char *)kcontrol->private_value;
mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_PCM);
ucontrol->value.integer.value[0] =
snd_soc_dapm_get_pin_status(&card->dapm, pin);
mutex_unlock(&card->dapm_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_card *card = snd_kcontrol_chip(kcontrol);
const char *pin = (const char *)kcontrol->private_value;
mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_PCM);
if (ucontrol->value.integer.value[0])
snd_soc_dapm_enable_pin(&card->dapm, pin);
else
snd_soc_dapm_disable_pin(&card->dapm, pin);
mutex_unlock(&card->dapm_mutex);
snd_soc_dapm_sync(&card->dapm);
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;
w->dai = dapm->dai;
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;
mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_INIT);
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++;
}
mutex_unlock(&dapm->card->dapm_mutex);
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;
if (!dapm)
return;
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);
}
static void widget_stream_event(struct snd_soc_dapm_context *dapm,
struct snd_soc_dapm_widget *w, int event)
{
if (!w)
return;
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);
}
void snd_soc_dapm_rtd_stream_event(struct snd_soc_pcm_runtime *rtd,
int stream, int event)
{
struct snd_soc_dapm_context *pdapm = &rtd->platform->dapm;
struct snd_soc_dapm_context *cdapm = &rtd->codec->dapm;
struct snd_soc_card *card = rtd->card;
dev_dbg(rtd->dev, "rtd stream %d event %d\n", stream, event);
mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME);
if (stream == SNDRV_PCM_STREAM_PLAYBACK) {
widget_stream_event(pdapm, rtd->cpu_dai->playback_aif, event);
widget_stream_event(cdapm, rtd->codec_dai->playback_aif, event);
} else {
widget_stream_event(pdapm, rtd->cpu_dai->capture_aif, event);
widget_stream_event(cdapm, rtd->codec_dai->capture_aif, event);
}
mutex_unlock(&card->dapm_mutex);
/* do we need to notify any clients that DAPM stream is complete */
if (pdapm->stream_event)
pdapm->stream_event(pdapm, event);
if (cdapm->stream_event)
cdapm->stream_event(cdapm, event);
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_rtd_stream_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_card *card = rtd->card;
struct snd_soc_codec *codec = rtd->codec;
if (stream == NULL)
return 0;
mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_PCM);
soc_dapm_stream_event(&codec->dapm, stream, event);
mutex_unlock(&card->dapm_mutex);
return 0;
}
void snd_soc_dapm_codec_stream_event(struct snd_soc_codec *codec,
const char *stream, int event)
{
// mutex_lock(&codec->card->dapm_mutex);
soc_dapm_stream_event(&codec->dapm, stream, event);
// mutex_unlock(&codec->card->dapm_mutex);
}
EXPORT_SYMBOL(snd_soc_dapm_codec_stream_event);
/**
* 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);
static bool snd_soc_dapm_widget_in_card_paths(struct snd_soc_card *card,
struct snd_soc_dapm_widget *w)
{
struct snd_soc_dapm_path *p;
list_for_each_entry(p, &card->paths, list) {
if ((p->source == w) || (p->sink == w)) {
dev_dbg(card->dev,
"... Path %s(id:%d dapm:%p) - %s(id:%d dapm:%p)\n",
p->source->name, p->source->id, p->source->dapm,
p->sink->name, p->sink->id, p->sink->dapm);
/* Connected to something other than the codec */
if (p->source->dapm != p->sink->dapm)
return true;
/*
* Loopback connection from codec external pin to
* codec external pin
*/
if (p->sink->id == snd_soc_dapm_input) {
switch (p->source->id) {
case snd_soc_dapm_output:
case snd_soc_dapm_micbias:
return true;
default:
break;
}
}
}
}
return false;
}
/**
* snd_soc_dapm_auto_nc_codec_pins - call snd_soc_dapm_nc_pin for unused pins
* @codec: The codec whose pins should be processed
*
* Automatically call snd_soc_dapm_nc_pin() for any external pins in the codec
* which are unused. Pins are used if they are connected externally to the
* codec, whether that be to some other device, or a loop-back connection to
* the codec itself.
*/
void snd_soc_dapm_auto_nc_codec_pins(struct snd_soc_codec *codec)
{
struct snd_soc_card *card = codec->card;
struct snd_soc_dapm_context *dapm = &codec->dapm;
struct snd_soc_dapm_widget *w;
dev_dbg(codec->dev, "Auto NC: DAPMs: card:%p codec:%p\n",
&card->dapm, &codec->dapm);
list_for_each_entry(w, &card->widgets, list) {
if (w->dapm != dapm)
continue;
switch (w->id) {
case snd_soc_dapm_input:
case snd_soc_dapm_output:
case snd_soc_dapm_micbias:
dev_dbg(codec->dev, "Auto NC: Checking widget %s\n",
w->name);
if (!snd_soc_dapm_widget_in_card_paths(card, w)) {
dev_dbg(codec->dev,
"... Not in map; disabling\n");
snd_soc_dapm_nc_pin(dapm, w->name);
}
break;
default:
break;
}
}
}
/**
* 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 |
OESF/linux-linaro-natty | drivers/media/video/cx88/cx88-cards.c | 108 | 92827 | /*
*
* device driver for Conexant 2388x based TV cards
* card-specific stuff.
*
* (c) 2003 Gerd Knorr <kraxel@bytesex.org> [SuSE Labs]
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include "cx88.h"
#include "tea5767.h"
static unsigned int tuner[] = {[0 ... (CX88_MAXBOARDS - 1)] = UNSET };
static unsigned int radio[] = {[0 ... (CX88_MAXBOARDS - 1)] = UNSET };
static unsigned int card[] = {[0 ... (CX88_MAXBOARDS - 1)] = UNSET };
module_param_array(tuner, int, NULL, 0444);
module_param_array(radio, int, NULL, 0444);
module_param_array(card, int, NULL, 0444);
MODULE_PARM_DESC(tuner,"tuner type");
MODULE_PARM_DESC(radio,"radio tuner type");
MODULE_PARM_DESC(card,"card type");
static unsigned int latency = UNSET;
module_param(latency,int,0444);
MODULE_PARM_DESC(latency,"pci latency timer");
static int disable_ir;
module_param(disable_ir, int, 0444);
MODULE_PARM_DESC(disable_ir, "Disable IR support");
#define info_printk(core, fmt, arg...) \
printk(KERN_INFO "%s: " fmt, core->name , ## arg)
#define warn_printk(core, fmt, arg...) \
printk(KERN_WARNING "%s: " fmt, core->name , ## arg)
#define err_printk(core, fmt, arg...) \
printk(KERN_ERR "%s: " fmt, core->name , ## arg)
/* ------------------------------------------------------------------ */
/* board config info */
/* If radio_type !=UNSET, radio_addr should be specified
*/
static const struct cx88_board cx88_boards[] = {
[CX88_BOARD_UNKNOWN] = {
.name = "UNKNOWN/GENERIC",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 0,
},{
.type = CX88_VMUX_COMPOSITE2,
.vmux = 1,
},{
.type = CX88_VMUX_COMPOSITE3,
.vmux = 2,
},{
.type = CX88_VMUX_COMPOSITE4,
.vmux = 3,
}},
},
[CX88_BOARD_HAUPPAUGE] = {
.name = "Hauppauge WinTV 34xxx models",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0xff00, // internal decoder
},{
.type = CX88_VMUX_DEBUG,
.vmux = 0,
.gpio0 = 0xff01, // mono from tuner chip
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0xff02,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0xff02,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0xff01,
},
},
[CX88_BOARD_GDI] = {
.name = "GDI Black Gold",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
}},
},
[CX88_BOARD_PIXELVIEW] = {
.name = "PixelView",
.tuner_type = TUNER_PHILIPS_PAL,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0xff00, // internal decoder
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0xff10,
},
},
[CX88_BOARD_ATI_WONDER_PRO] = {
.name = "ATI TV Wonder Pro",
.tuner_type = TUNER_PHILIPS_4IN1,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT | TDA9887_INTERCARRIER,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x03ff,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x03fe,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x03fe,
}},
},
[CX88_BOARD_WINFAST2000XP_EXPERT] = {
.name = "Leadtek Winfast 2000XP Expert",
.tuner_type = TUNER_PHILIPS_4IN1,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x00F5e700,
.gpio1 = 0x00003004,
.gpio2 = 0x00F5e700,
.gpio3 = 0x02000000,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x00F5c700,
.gpio1 = 0x00003004,
.gpio2 = 0x00F5c700,
.gpio3 = 0x02000000,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x00F5c700,
.gpio1 = 0x00003004,
.gpio2 = 0x00F5c700,
.gpio3 = 0x02000000,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x00F5d700,
.gpio1 = 0x00003004,
.gpio2 = 0x00F5d700,
.gpio3 = 0x02000000,
},
},
[CX88_BOARD_AVERTV_STUDIO_303] = {
.name = "AverTV Studio 303 (M126)",
.tuner_type = TUNER_PHILIPS_FM1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio1 = 0xe09f,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio1 = 0xe05f,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio1 = 0xe05f,
}},
.radio = {
.gpio1 = 0xe0df,
.type = CX88_RADIO,
},
},
[CX88_BOARD_MSI_TVANYWHERE_MASTER] = {
// added gpio values thanks to Michal
// values for PAL from DScaler
.name = "MSI TV-@nywhere Master",
.tuner_type = TUNER_MT2032,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT | TDA9887_INTERCARRIER_NTSC,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x000040bf,
.gpio1 = 0x000080c0,
.gpio2 = 0x0000ff40,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x000040bf,
.gpio1 = 0x000080c0,
.gpio2 = 0x0000ff40,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x000040bf,
.gpio1 = 0x000080c0,
.gpio2 = 0x0000ff40,
}},
.radio = {
.type = CX88_RADIO,
.vmux = 3,
.gpio0 = 0x000040bf,
.gpio1 = 0x000080c0,
.gpio2 = 0x0000ff20,
},
},
[CX88_BOARD_WINFAST_DV2000] = {
.name = "Leadtek Winfast DV2000",
.tuner_type = TUNER_PHILIPS_FM1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x0035e700,
.gpio1 = 0x00003004,
.gpio2 = 0x0035e700,
.gpio3 = 0x02000000,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x0035c700,
.gpio1 = 0x00003004,
.gpio2 = 0x0035c700,
.gpio3 = 0x02000000,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x0035c700,
.gpio1 = 0x0035c700,
.gpio2 = 0x02000000,
.gpio3 = 0x02000000,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x0035d700,
.gpio1 = 0x00007004,
.gpio2 = 0x0035d700,
.gpio3 = 0x02000000,
},
},
[CX88_BOARD_LEADTEK_PVR2000] = {
// gpio values for PAL version from regspy by DScaler
.name = "Leadtek PVR 2000",
.tuner_type = TUNER_PHILIPS_FM1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x0000bde2,
.audioroute = 1,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x0000bde6,
.audioroute = 1,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x0000bde6,
.audioroute = 1,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x0000bd62,
.audioroute = 1,
},
.mpeg = CX88_MPEG_BLACKBIRD,
},
[CX88_BOARD_IODATA_GVVCP3PCI] = {
.name = "IODATA GV-VCP3/PCI",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 0,
},{
.type = CX88_VMUX_COMPOSITE2,
.vmux = 1,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
}},
},
[CX88_BOARD_PROLINK_PLAYTVPVR] = {
.name = "Prolink PlayTV PVR",
.tuner_type = TUNER_PHILIPS_FM1236_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0xbff0,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0xbff3,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0xbff3,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0xbff0,
},
},
[CX88_BOARD_ASUS_PVR_416] = {
.name = "ASUS PVR-416",
.tuner_type = TUNER_PHILIPS_FM1236_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x0000fde6,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x0000fde6, // 0x0000fda6 L,R RCA audio in?
.audioroute = 1,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x0000fde2,
},
.mpeg = CX88_MPEG_BLACKBIRD,
},
[CX88_BOARD_MSI_TVANYWHERE] = {
.name = "MSI TV-@nywhere",
.tuner_type = TUNER_MT2032,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x00000fbf,
.gpio2 = 0x0000fc08,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x00000fbf,
.gpio2 = 0x0000fc68,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x00000fbf,
.gpio2 = 0x0000fc68,
}},
},
[CX88_BOARD_KWORLD_DVB_T] = {
.name = "KWorld/VStream XPert DVB-T",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x0700,
.gpio2 = 0x0101,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x0700,
.gpio2 = 0x0101,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_DVICO_FUSIONHDTV_DVB_T1] = {
.name = "DViCO FusionHDTV DVB-T1",
.tuner_type = TUNER_ABSENT, /* No analog tuner */
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x000027df,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x000027df,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_KWORLD_LTV883] = {
.name = "KWorld LTV883RF",
.tuner_type = TUNER_TNF_8831BGFF,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x07f8,
},{
.type = CX88_VMUX_DEBUG,
.vmux = 0,
.gpio0 = 0x07f9, // mono from tuner chip
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x000007fa,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x000007fa,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x000007f8,
},
},
[CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_Q] = {
.name = "DViCO FusionHDTV 3 Gold-Q",
.tuner_type = TUNER_MICROTUNE_4042FI5,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
/*
GPIO[0] resets DT3302 DTV receiver
0 - reset asserted
1 - normal operation
GPIO[1] mutes analog audio output connector
0 - enable selected source
1 - mute
GPIO[2] selects source for analog audio output connector
0 - analog audio input connector on tab
1 - analog DAC output from CX23881 chip
GPIO[3] selects RF input connector on tuner module
0 - RF connector labeled CABLE
1 - RF connector labeled ANT
GPIO[4] selects high RF for QAM256 mode
0 - normal RF
1 - high RF
*/
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x0f0d,
},{
.type = CX88_VMUX_CABLE,
.vmux = 0,
.gpio0 = 0x0f05,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x0f00,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x0f00,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_HAUPPAUGE_DVB_T1] = {
.name = "Hauppauge Nova-T DVB-T",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_CONEXANT_DVB_T1] = {
.name = "Conexant DVB-T reference design",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_PROVIDEO_PV259] = {
.name = "Provideo PV259",
.tuner_type = TUNER_PHILIPS_FQ1216ME,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.audioroute = 1,
}},
.mpeg = CX88_MPEG_BLACKBIRD,
},
[CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_PLUS] = {
.name = "DViCO FusionHDTV DVB-T Plus",
.tuner_type = TUNER_ABSENT, /* No analog tuner */
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x000027df,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x000027df,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_DNTV_LIVE_DVB_T] = {
.name = "digitalnow DNTV Live! DVB-T",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x00000700,
.gpio2 = 0x00000101,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x00000700,
.gpio2 = 0x00000101,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_PCHDTV_HD3000] = {
.name = "pcHDTV HD3000 HDTV",
.tuner_type = TUNER_THOMSON_DTT761X,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
/* GPIO[2] = audio source for analog audio out connector
* 0 = analog audio input connector
* 1 = CX88 audio DACs
*
* GPIO[7] = input to CX88's audio/chroma ADC
* 0 = FM 10.7 MHz IF
* 1 = Sound 4.5 MHz IF
*
* GPIO[1,5,6] = Oren 51132 pins 27,35,28 respectively
*
* GPIO[16] = Remote control input
*/
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x00008484,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x00008400,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x00008400,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x00008404,
},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_HAUPPAUGE_ROSLYN] = {
// entry added by Kaustubh D. Bhalerao <bhalerao.1@osu.edu>
// GPIO values obtained from regspy, courtesy Sean Covel
.name = "Hauppauge WinTV 28xxx (Roslyn) models",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0xed1a,
.gpio2 = 0x00ff,
},{
.type = CX88_VMUX_DEBUG,
.vmux = 0,
.gpio0 = 0xff01,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0xff02,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0xed92,
.gpio2 = 0x00ff,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0xed96,
.gpio2 = 0x00ff,
},
.mpeg = CX88_MPEG_BLACKBIRD,
},
[CX88_BOARD_DIGITALLOGIC_MEC] = {
.name = "Digital-Logic MICROSPACE Entertainment Center (MEC)",
.tuner_type = TUNER_PHILIPS_FM1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x00009d80,
.audioroute = 1,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x00009d76,
.audioroute = 1,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x00009d76,
.audioroute = 1,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x00009d00,
.audioroute = 1,
},
.mpeg = CX88_MPEG_BLACKBIRD,
},
[CX88_BOARD_IODATA_GVBCTV7E] = {
.name = "IODATA GV/BCTV7E",
.tuner_type = TUNER_PHILIPS_FQ1286,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 1,
.gpio1 = 0x0000e03f,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 2,
.gpio1 = 0x0000e07f,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 3,
.gpio1 = 0x0000e07f,
}}
},
[CX88_BOARD_PIXELVIEW_PLAYTV_ULTRA_PRO] = {
.name = "PixelView PlayTV Ultra Pro (Stereo)",
/* May be also TUNER_YMEC_TVF_5533MF for NTSC/M or PAL/M */
.tuner_type = TUNER_PHILIPS_FM1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
/* Some variants use a tda9874 and so need the tvaudio module. */
.audio_chip = V4L2_IDENT_TVAUDIO,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0xbf61, /* internal decoder */
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0xbf63,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0xbf63,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0xbf60,
},
},
[CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_T] = {
.name = "DViCO FusionHDTV 3 Gold-T",
.tuner_type = TUNER_THOMSON_DTT761X,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x97ed,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x97e9,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x97e9,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_ADSTECH_DVB_T_PCI] = {
.name = "ADS Tech Instant TV DVB-T PCI",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x0700,
.gpio2 = 0x0101,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x0700,
.gpio2 = 0x0101,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_TERRATEC_CINERGY_1400_DVB_T1] = {
.name = "TerraTec Cinergy 1400 DVB-T",
.tuner_type = TUNER_ABSENT,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 2,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_DVICO_FUSIONHDTV_5_GOLD] = {
.name = "DViCO FusionHDTV 5 Gold",
.tuner_type = TUNER_LG_TDVS_H06XF, /* TDVS-H062F */
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x87fd,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x87f9,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x87f9,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_AVERMEDIA_ULTRATV_MC_550] = {
.name = "AverMedia UltraTV Media Center PCI 550",
.tuner_type = TUNER_PHILIPS_FM1236_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 0,
.gpio0 = 0x0000cd73,
.audioroute = 1,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 1,
.gpio0 = 0x0000cd73,
.audioroute = 1,
},{
.type = CX88_VMUX_TELEVISION,
.vmux = 3,
.gpio0 = 0x0000cdb3,
.audioroute = 1,
}},
.radio = {
.type = CX88_RADIO,
.vmux = 2,
.gpio0 = 0x0000cdf3,
.audioroute = 1,
},
.mpeg = CX88_MPEG_BLACKBIRD,
},
[CX88_BOARD_KWORLD_VSTREAM_EXPERT_DVD] = {
/* Alexander Wold <awold@bigfoot.com> */
.name = "Kworld V-Stream Xpert DVD",
.tuner_type = UNSET,
.input = {{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x03000000,
.gpio1 = 0x01000000,
.gpio2 = 0x02000000,
.gpio3 = 0x00100000,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x03000000,
.gpio1 = 0x01000000,
.gpio2 = 0x02000000,
.gpio3 = 0x00100000,
}},
},
[CX88_BOARD_ATI_HDTVWONDER] = {
.name = "ATI HDTV Wonder",
.tuner_type = TUNER_PHILIPS_TUV1236D,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x00000ff7,
.gpio1 = 0x000000ff,
.gpio2 = 0x00000001,
.gpio3 = 0x00000000,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x00000ffe,
.gpio1 = 0x000000ff,
.gpio2 = 0x00000001,
.gpio3 = 0x00000000,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x00000ffe,
.gpio1 = 0x000000ff,
.gpio2 = 0x00000001,
.gpio3 = 0x00000000,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_WINFAST_DTV1000] = {
.name = "WinFast DTV1000-T",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_AVERTV_303] = {
.name = "AVerTV 303 (M126)",
.tuner_type = TUNER_PHILIPS_FM1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x00ff,
.gpio1 = 0xe09f,
.gpio2 = 0x0010,
.gpio3 = 0x0000,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x00ff,
.gpio1 = 0xe05f,
.gpio2 = 0x0010,
.gpio3 = 0x0000,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x00ff,
.gpio1 = 0xe05f,
.gpio2 = 0x0010,
.gpio3 = 0x0000,
}},
},
[CX88_BOARD_HAUPPAUGE_NOVASPLUS_S1] = {
.name = "Hauppauge Nova-S-Plus DVB-S",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.audio_chip = V4L2_IDENT_WM8775,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
/* 2: Line-In */
.audioroute = 2,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
/* 2: Line-In */
.audioroute = 2,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
/* 2: Line-In */
.audioroute = 2,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_HAUPPAUGE_NOVASE2_S1] = {
.name = "Hauppauge Nova-SE2 DVB-S",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_KWORLD_DVBS_100] = {
.name = "KWorld DVB-S 100",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.audio_chip = V4L2_IDENT_WM8775,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
/* 2: Line-In */
.audioroute = 2,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
/* 2: Line-In */
.audioroute = 2,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
/* 2: Line-In */
.audioroute = 2,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_HAUPPAUGE_HVR1100] = {
.name = "Hauppauge WinTV-HVR1100 DVB-T/Hybrid",
.tuner_type = TUNER_PHILIPS_FMD1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
}},
/* fixme: Add radio support */
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_HAUPPAUGE_HVR1100LP] = {
.name = "Hauppauge WinTV-HVR1100 DVB-T/Hybrid (Low Profile)",
.tuner_type = TUNER_PHILIPS_FMD1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
}},
/* fixme: Add radio support */
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_DNTV_LIVE_DVB_T_PRO] = {
.name = "digitalnow DNTV Live! DVB-T Pro",
.tuner_type = TUNER_PHILIPS_FMD1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT | TDA9887_PORT1_ACTIVE |
TDA9887_PORT2_ACTIVE,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0xf80808,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0xf80808,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0xf80808,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0xf80808,
},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_KWORLD_DVB_T_CX22702] = {
/* Kworld V-stream Xpert DVB-T with Thomson tuner */
/* DTT 7579 Conexant CX22702-19 Conexant CX2388x */
/* Manenti Marco <marco_manenti@colman.it> */
.name = "KWorld/VStream XPert DVB-T with cx22702",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x0700,
.gpio2 = 0x0101,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x0700,
.gpio2 = 0x0101,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_DUAL] = {
.name = "DViCO FusionHDTV DVB-T Dual Digital",
.tuner_type = TUNER_ABSENT, /* No analog tuner */
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x000067df,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x000067df,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_KWORLD_HARDWARE_MPEG_TV_XPERT] = {
.name = "KWorld HardwareMpegTV XPert",
.tuner_type = TUNER_PHILIPS_TDA8290,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x3de2,
.gpio2 = 0x00ff,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x3de6,
.audioroute = 1,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x3de6,
.audioroute = 1,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x3de6,
.gpio2 = 0x00ff,
},
.mpeg = CX88_MPEG_BLACKBIRD,
},
[CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_HYBRID] = {
.name = "DViCO FusionHDTV DVB-T Hybrid",
.tuner_type = TUNER_THOMSON_FE6600,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x0000a75f,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x0000a75b,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x0000a75b,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_PCHDTV_HD5500] = {
.name = "pcHDTV HD5500 HDTV",
.tuner_type = TUNER_LG_TDVS_H06XF, /* TDVS-H064F */
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x87fd,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x87f9,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x87f9,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_KWORLD_MCE200_DELUXE] = {
/* FIXME: tested TV input only, disabled composite,
svideo and radio until they can be tested also. */
.name = "Kworld MCE 200 Deluxe",
.tuner_type = TUNER_TENA_9533_DI,
.radio_type = UNSET,
.tda9887_conf = TDA9887_PRESENT,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x0000BDE6
}},
.mpeg = CX88_MPEG_BLACKBIRD,
},
[CX88_BOARD_PIXELVIEW_PLAYTV_P7000] = {
/* FIXME: SVideo, Composite and FM inputs are untested */
.name = "PixelView PlayTV P7000",
.tuner_type = TUNER_PHILIPS_FM1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT | TDA9887_PORT1_ACTIVE |
TDA9887_PORT2_ACTIVE,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x5da6,
}},
.mpeg = CX88_MPEG_BLACKBIRD,
},
[CX88_BOARD_NPGTECH_REALTV_TOP10FM] = {
.name = "NPG Tech Real TV FM Top 10",
.tuner_type = TUNER_TNF_5335MF, /* Actually a TNF9535 */
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x0788,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x078b,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x078b,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x074a,
},
},
[CX88_BOARD_WINFAST_DTV2000H] = {
.name = "WinFast DTV2000 H",
.tuner_type = TUNER_PHILIPS_FMD1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x00017304,
.gpio1 = 0x00008203,
.gpio2 = 0x00017304,
.gpio3 = 0x02000000,
}, {
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x0001d701,
.gpio1 = 0x0000b207,
.gpio2 = 0x0001d701,
.gpio3 = 0x02000000,
}, {
.type = CX88_VMUX_COMPOSITE2,
.vmux = 2,
.gpio0 = 0x0001d503,
.gpio1 = 0x0000b207,
.gpio2 = 0x0001d503,
.gpio3 = 0x02000000,
}, {
.type = CX88_VMUX_SVIDEO,
.vmux = 3,
.gpio0 = 0x0001d701,
.gpio1 = 0x0000b207,
.gpio2 = 0x0001d701,
.gpio3 = 0x02000000,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x00015702,
.gpio1 = 0x0000f207,
.gpio2 = 0x00015702,
.gpio3 = 0x02000000,
},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_WINFAST_DTV2000H_J] = {
.name = "WinFast DTV2000 H rev. J",
.tuner_type = TUNER_PHILIPS_FMD1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x00017300,
.gpio1 = 0x00008207,
.gpio2 = 0x00000000,
.gpio3 = 0x02000000,
},{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x00018300,
.gpio1 = 0x0000f207,
.gpio2 = 0x00017304,
.gpio3 = 0x02000000,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x00018301,
.gpio1 = 0x0000f207,
.gpio2 = 0x00017304,
.gpio3 = 0x02000000,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x00018301,
.gpio1 = 0x0000f207,
.gpio2 = 0x00017304,
.gpio3 = 0x02000000,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x00015702,
.gpio1 = 0x0000f207,
.gpio2 = 0x00015702,
.gpio3 = 0x02000000,
},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_GENIATECH_DVBS] = {
.name = "Geniatech DVB-S",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_HAUPPAUGE_HVR3000] = {
.name = "Hauppauge WinTV-HVR3000 TriMode Analog/DVB-S/DVB-T",
.tuner_type = TUNER_PHILIPS_FMD1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.audio_chip = V4L2_IDENT_WM8775,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x84bf,
/* 1: TV Audio / FM Mono */
.audioroute = 1,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x84bf,
/* 2: Line-In */
.audioroute = 2,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x84bf,
/* 2: Line-In */
.audioroute = 2,
}},
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x84bf,
/* 4: FM Stereo (untested) */
.audioroute = 8,
},
.mpeg = CX88_MPEG_DVB,
.num_frontends = 2,
},
[CX88_BOARD_NORWOOD_MICRO] = {
.name = "Norwood Micro TV Tuner",
.tuner_type = TUNER_TNF_5335MF,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x0709,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x070b,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x070b,
}},
},
[CX88_BOARD_TE_DTV_250_OEM_SWANN] = {
.name = "Shenzhen Tungsten Ages Tech TE-DTV-250 / Swann OEM",
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x003fffff,
.gpio1 = 0x00e00000,
.gpio2 = 0x003fffff,
.gpio3 = 0x02000000,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x003fffff,
.gpio1 = 0x00e00000,
.gpio2 = 0x003fffff,
.gpio3 = 0x02000000,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x003fffff,
.gpio1 = 0x00e00000,
.gpio2 = 0x003fffff,
.gpio3 = 0x02000000,
}},
},
[CX88_BOARD_HAUPPAUGE_HVR1300] = {
.name = "Hauppauge WinTV-HVR1300 DVB-T/Hybrid MPEG Encoder",
.tuner_type = TUNER_PHILIPS_FMD1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.audio_chip = V4L2_IDENT_WM8775,
/*
* gpio0 as reported by Mike Crash <mike AT mikecrash.com>
*/
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0xef88,
/* 1: TV Audio / FM Mono */
.audioroute = 1,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0xef88,
/* 2: Line-In */
.audioroute = 2,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0xef88,
/* 2: Line-In */
.audioroute = 2,
}},
.mpeg = CX88_MPEG_DVB | CX88_MPEG_BLACKBIRD,
.radio = {
.type = CX88_RADIO,
.gpio0 = 0xef88,
/* 4: FM Stereo (untested) */
.audioroute = 8,
},
},
[CX88_BOARD_SAMSUNG_SMT_7020] = {
.name = "Samsung SMT 7020 DVB-S",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = { {
.type = CX88_VMUX_DVB,
.vmux = 0,
} },
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_ADSTECH_PTV_390] = {
.name = "ADS Tech Instant Video PCI",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DEBUG,
.vmux = 3,
.gpio0 = 0x04ff,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x07fa,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x07fa,
}},
},
[CX88_BOARD_PINNACLE_PCTV_HD_800i] = {
.name = "Pinnacle PCTV HD 800i",
.tuner_type = TUNER_XC5000,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x04fb,
.gpio1 = 0x10ff,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x04fb,
.gpio1 = 0x10ef,
.audioroute = 1,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x04fb,
.gpio1 = 0x10ef,
.audioroute = 1,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_DVICO_FUSIONHDTV_5_PCI_NANO] = {
.name = "DViCO FusionHDTV 5 PCI nano",
/* xc3008 tuner, digital only for now */
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x000027df, /* Unconfirmed */
}, {
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x000027df, /* Unconfirmed */
.audioroute = 1,
}, {
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x000027df, /* Unconfirmed */
.audioroute = 1,
} },
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_PINNACLE_HYBRID_PCTV] = {
.name = "Pinnacle Hybrid PCTV",
.tuner_type = TUNER_XC2028,
.tuner_addr = 0x61,
.radio_type = TUNER_XC2028,
.radio_addr = 0x61,
.input = { {
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x004ff,
.gpio1 = 0x010ff,
.gpio2 = 0x00001,
}, {
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x004fb,
.gpio1 = 0x010ef,
.audioroute = 1,
}, {
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x004fb,
.gpio1 = 0x010ef,
.audioroute = 1,
} },
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x004ff,
.gpio1 = 0x010ff,
.gpio2 = 0x0ff,
},
.mpeg = CX88_MPEG_DVB,
},
/* Terry Wu <terrywu2009@gmail.com> */
/* TV Audio : set GPIO 2, 18, 19 value to 0, 1, 0 */
/* FM Audio : set GPIO 2, 18, 19 value to 0, 0, 0 */
/* Line-in Audio : set GPIO 2, 18, 19 value to 0, 1, 1 */
/* Mute Audio : set GPIO 2 value to 1 */
[CX88_BOARD_WINFAST_TV2000_XP_GLOBAL] = {
.name = "Leadtek TV2000 XP Global",
.tuner_type = TUNER_XC2028,
.tuner_addr = 0x61,
.radio_type = TUNER_XC2028,
.radio_addr = 0x61,
.input = { {
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x0400, /* pin 2 = 0 */
.gpio1 = 0x0000,
.gpio2 = 0x0C04, /* pin 18 = 1, pin 19 = 0 */
.gpio3 = 0x0000,
}, {
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x0400, /* pin 2 = 0 */
.gpio1 = 0x0000,
.gpio2 = 0x0C0C, /* pin 18 = 1, pin 19 = 1 */
.gpio3 = 0x0000,
}, {
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x0400, /* pin 2 = 0 */
.gpio1 = 0x0000,
.gpio2 = 0x0C0C, /* pin 18 = 1, pin 19 = 1 */
.gpio3 = 0x0000,
} },
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x0400, /* pin 2 = 0 */
.gpio1 = 0x0000,
.gpio2 = 0x0C00, /* pin 18 = 0, pin 19 = 0 */
.gpio3 = 0x0000,
},
},
[CX88_BOARD_POWERCOLOR_REAL_ANGEL] = {
.name = "PowerColor RA330", /* Long names may confuse LIRC. */
.tuner_type = TUNER_XC2028,
.tuner_addr = 0x61,
.input = { {
.type = CX88_VMUX_DEBUG,
.vmux = 3, /* Due to the way the cx88 driver is written, */
.gpio0 = 0x00ff, /* there is no way to deactivate audio pass- */
.gpio1 = 0xf39d, /* through without this entry. Furthermore, if */
.gpio3 = 0x0000, /* the TV mux entry is first, you get audio */
}, { /* from the tuner on boot for a little while. */
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x00ff,
.gpio1 = 0xf35d,
.gpio3 = 0x0000,
}, {
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x00ff,
.gpio1 = 0xf37d,
.gpio3 = 0x0000,
}, {
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x000ff,
.gpio1 = 0x0f37d,
.gpio3 = 0x00000,
} },
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x000ff,
.gpio1 = 0x0f35d,
.gpio3 = 0x00000,
},
},
[CX88_BOARD_GENIATECH_X8000_MT] = {
/* Also PowerColor Real Angel 330 and Geniatech X800 OEM */
.name = "Geniatech X8000-MT DVBT",
.tuner_type = TUNER_XC2028,
.tuner_addr = 0x61,
.input = { {
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x00000000,
.gpio1 = 0x00e3e341,
.gpio2 = 0x00000000,
.gpio3 = 0x00000000,
}, {
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x00000000,
.gpio1 = 0x00e3e361,
.gpio2 = 0x00000000,
.gpio3 = 0x00000000,
}, {
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x00000000,
.gpio1 = 0x00e3e361,
.gpio2 = 0x00000000,
.gpio3 = 0x00000000,
} },
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x00000000,
.gpio1 = 0x00e3e341,
.gpio2 = 0x00000000,
.gpio3 = 0x00000000,
},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_PRO] = {
.name = "DViCO FusionHDTV DVB-T PRO",
.tuner_type = TUNER_XC2028,
.tuner_addr = 0x61,
.radio_type = UNSET,
.radio_addr = ADDR_UNSET,
.input = { {
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x000067df,
}, {
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x000067df,
} },
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_DVICO_FUSIONHDTV_7_GOLD] = {
.name = "DViCO FusionHDTV 7 Gold",
.tuner_type = TUNER_XC5000,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x10df,
},{
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x16d9,
},{
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x16d9,
}},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_PROLINK_PV_8000GT] = {
.name = "Prolink Pixelview MPEG 8000GT",
.tuner_type = TUNER_XC2028,
.tuner_addr = 0x61,
.input = { {
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x0ff,
.gpio2 = 0x0cfb,
}, {
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio2 = 0x0cfb,
}, {
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio2 = 0x0cfb,
} },
.radio = {
.type = CX88_RADIO,
.gpio2 = 0x0cfb,
},
},
[CX88_BOARD_PROLINK_PV_GLOBAL_XTREME] = {
.name = "Prolink Pixelview Global Extreme",
.tuner_type = TUNER_XC2028,
.tuner_addr = 0x61,
.input = { {
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x04fb,
.gpio1 = 0x04080,
.gpio2 = 0x0cf7,
}, {
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x04fb,
.gpio1 = 0x04080,
.gpio2 = 0x0cfb,
}, {
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x04fb,
.gpio1 = 0x04080,
.gpio2 = 0x0cfb,
} },
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x04ff,
.gpio1 = 0x04080,
.gpio2 = 0x0cf7,
},
},
/* Both radio, analog and ATSC work with this board.
However, for analog to work, s5h1409 gate should be open,
otherwise, tuner-xc3028 won't be detected.
A proper fix require using the newer i2c methods to add
tuner-xc3028 without doing an i2c probe.
*/
[CX88_BOARD_KWORLD_ATSC_120] = {
.name = "Kworld PlusTV HD PCI 120 (ATSC 120)",
.tuner_type = TUNER_XC2028,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = { {
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x000000ff,
.gpio1 = 0x0000f35d,
.gpio2 = 0x00000000,
}, {
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x000000ff,
.gpio1 = 0x0000f37e,
.gpio2 = 0x00000000,
}, {
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x000000ff,
.gpio1 = 0x0000f37e,
.gpio2 = 0x00000000,
} },
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x000000ff,
.gpio1 = 0x0000f35d,
.gpio2 = 0x00000000,
},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_HAUPPAUGE_HVR4000] = {
.name = "Hauppauge WinTV-HVR4000 DVB-S/S2/T/Hybrid",
.tuner_type = TUNER_PHILIPS_FMD1216ME_MK3,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.tda9887_conf = TDA9887_PRESENT,
.audio_chip = V4L2_IDENT_WM8775,
/*
* GPIO0 (WINTV2000)
*
* Analogue SAT DVB-T
* Antenna 0xc4bf 0xc4bb
* Composite 0xc4bf 0xc4bb
* S-Video 0xc4bf 0xc4bb
* Composite1 0xc4ff 0xc4fb
* S-Video1 0xc4ff 0xc4fb
*
* BIT VALUE FUNCTION GP{x}_IO
* 0 1 I:?
* 1 1 I:?
* 2 1 O:MPEG PORT 0=DVB-T 1=DVB-S
* 3 1 I:?
* 4 1 I:?
* 5 1 I:?
* 6 0 O:INPUT SELECTOR 0=INTERNAL 1=EXPANSION
* 7 1 O:DVB-T DEMOD RESET LOW
*
* BIT VALUE FUNCTION GP{x}_OE
* 8 0 I
* 9 0 I
* a 1 O
* b 0 I
* c 0 I
* d 0 I
* e 1 O
* f 1 O
*
* WM8775 ADC
*
* 1: TV Audio / FM Mono
* 2: Line-In
* 3: Line-In Expansion
* 4: FM Stereo
*/
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0xc4bf,
/* 1: TV Audio / FM Mono */
.audioroute = 1,
}, {
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0xc4bf,
/* 2: Line-In */
.audioroute = 2,
}, {
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0xc4bf,
/* 2: Line-In */
.audioroute = 2,
} },
.radio = {
.type = CX88_RADIO,
.gpio0 = 0xc4bf,
/* 4: FM Stereo */
.audioroute = 8,
},
.mpeg = CX88_MPEG_DVB,
.num_frontends = 2,
},
[CX88_BOARD_HAUPPAUGE_HVR4000LITE] = {
.name = "Hauppauge WinTV-HVR4000(Lite) DVB-S/S2",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
} },
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_TEVII_S420] = {
.name = "TeVii S420 DVB-S",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
} },
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_TEVII_S460] = {
.name = "TeVii S460 DVB-S/S2",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
} },
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_OMICOM_SS4_PCI] = {
.name = "Omicom SS4 DVB-S/S2 PCI",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
} },
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_TBS_8910] = {
.name = "TBS 8910 DVB-S",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
} },
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_TBS_8920] = {
.name = "TBS 8920 DVB-S/S2",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
.gpio0 = 0x8080,
} },
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_PROF_6200] = {
.name = "Prof 6200 DVB-S",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
} },
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_PROF_7300] = {
.name = "PROF 7300 DVB-S/S2",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
} },
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_SATTRADE_ST4200] = {
.name = "SATTRADE ST4200 DVB-S/S2",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
} },
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_TERRATEC_CINERGY_HT_PCI_MKII] = {
.name = "Terratec Cinergy HT PCI MKII",
.tuner_type = TUNER_XC2028,
.tuner_addr = 0x61,
.radio_type = TUNER_XC2028,
.radio_addr = 0x61,
.input = { {
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x004ff,
.gpio1 = 0x010ff,
.gpio2 = 0x00001,
}, {
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x004fb,
.gpio1 = 0x010ef,
.audioroute = 1,
}, {
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x004fb,
.gpio1 = 0x010ef,
.audioroute = 1,
} },
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x004ff,
.gpio1 = 0x010ff,
.gpio2 = 0x0ff,
},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_HAUPPAUGE_IRONLY] = {
.name = "Hauppauge WinTV-IR Only",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
},
[CX88_BOARD_WINFAST_DTV1800H] = {
.name = "Leadtek WinFast DTV1800 Hybrid",
.tuner_type = TUNER_XC2028,
.radio_type = TUNER_XC2028,
.tuner_addr = 0x61,
.radio_addr = 0x61,
/*
* GPIO setting
*
* 2: mute (0=off,1=on)
* 12: tuner reset pin
* 13: audio source (0=tuner audio,1=line in)
* 14: FM (0=on,1=off ???)
*/
.input = {{
.type = CX88_VMUX_TELEVISION,
.vmux = 0,
.gpio0 = 0x0400, /* pin 2 = 0 */
.gpio1 = 0x6040, /* pin 13 = 0, pin 14 = 1 */
.gpio2 = 0x0000,
}, {
.type = CX88_VMUX_COMPOSITE1,
.vmux = 1,
.gpio0 = 0x0400, /* pin 2 = 0 */
.gpio1 = 0x6060, /* pin 13 = 1, pin 14 = 1 */
.gpio2 = 0x0000,
}, {
.type = CX88_VMUX_SVIDEO,
.vmux = 2,
.gpio0 = 0x0400, /* pin 2 = 0 */
.gpio1 = 0x6060, /* pin 13 = 1, pin 14 = 1 */
.gpio2 = 0x0000,
} },
.radio = {
.type = CX88_RADIO,
.gpio0 = 0x0400, /* pin 2 = 0 */
.gpio1 = 0x6000, /* pin 13 = 0, pin 14 = 0 */
.gpio2 = 0x0000,
},
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_PROF_7301] = {
.name = "Prof 7301 DVB-S/S2",
.tuner_type = UNSET,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = { {
.type = CX88_VMUX_DVB,
.vmux = 0,
} },
.mpeg = CX88_MPEG_DVB,
},
[CX88_BOARD_TWINHAN_VP1027_DVBS] = {
.name = "Twinhan VP-1027 DVB-S",
.tuner_type = TUNER_ABSENT,
.radio_type = UNSET,
.tuner_addr = ADDR_UNSET,
.radio_addr = ADDR_UNSET,
.input = {{
.type = CX88_VMUX_DVB,
.vmux = 0,
} },
.mpeg = CX88_MPEG_DVB,
},
};
/* ------------------------------------------------------------------ */
/* PCI subsystem IDs */
static const struct cx88_subid cx88_subids[] = {
{
.subvendor = 0x0070,
.subdevice = 0x3400,
.card = CX88_BOARD_HAUPPAUGE,
},{
.subvendor = 0x0070,
.subdevice = 0x3401,
.card = CX88_BOARD_HAUPPAUGE,
},{
.subvendor = 0x14c7,
.subdevice = 0x0106,
.card = CX88_BOARD_GDI,
},{
.subvendor = 0x14c7,
.subdevice = 0x0107, /* with mpeg encoder */
.card = CX88_BOARD_GDI,
},{
.subvendor = PCI_VENDOR_ID_ATI,
.subdevice = 0x00f8,
.card = CX88_BOARD_ATI_WONDER_PRO,
}, {
.subvendor = PCI_VENDOR_ID_ATI,
.subdevice = 0x00f9,
.card = CX88_BOARD_ATI_WONDER_PRO,
}, {
.subvendor = 0x107d,
.subdevice = 0x6611,
.card = CX88_BOARD_WINFAST2000XP_EXPERT,
},{
.subvendor = 0x107d,
.subdevice = 0x6613, /* NTSC */
.card = CX88_BOARD_WINFAST2000XP_EXPERT,
},{
.subvendor = 0x107d,
.subdevice = 0x6620,
.card = CX88_BOARD_WINFAST_DV2000,
},{
.subvendor = 0x107d,
.subdevice = 0x663b,
.card = CX88_BOARD_LEADTEK_PVR2000,
},{
.subvendor = 0x107d,
.subdevice = 0x663c,
.card = CX88_BOARD_LEADTEK_PVR2000,
},{
.subvendor = 0x1461,
.subdevice = 0x000b,
.card = CX88_BOARD_AVERTV_STUDIO_303,
},{
.subvendor = 0x1462,
.subdevice = 0x8606,
.card = CX88_BOARD_MSI_TVANYWHERE_MASTER,
},{
.subvendor = 0x10fc,
.subdevice = 0xd003,
.card = CX88_BOARD_IODATA_GVVCP3PCI,
},{
.subvendor = 0x1043,
.subdevice = 0x4823, /* with mpeg encoder */
.card = CX88_BOARD_ASUS_PVR_416,
},{
.subvendor = 0x17de,
.subdevice = 0x08a6,
.card = CX88_BOARD_KWORLD_DVB_T,
},{
.subvendor = 0x18ac,
.subdevice = 0xd810,
.card = CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_Q,
},{
.subvendor = 0x18ac,
.subdevice = 0xd820,
.card = CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_T,
},{
.subvendor = 0x18ac,
.subdevice = 0xdb00,
.card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T1,
},{
.subvendor = 0x0070,
.subdevice = 0x9002,
.card = CX88_BOARD_HAUPPAUGE_DVB_T1,
},{
.subvendor = 0x14f1,
.subdevice = 0x0187,
.card = CX88_BOARD_CONEXANT_DVB_T1,
},{
.subvendor = 0x1540,
.subdevice = 0x2580,
.card = CX88_BOARD_PROVIDEO_PV259,
},{
.subvendor = 0x18ac,
.subdevice = 0xdb10,
.card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_PLUS,
},{
.subvendor = 0x1554,
.subdevice = 0x4811,
.card = CX88_BOARD_PIXELVIEW,
},{
.subvendor = 0x7063,
.subdevice = 0x3000, /* HD-3000 card */
.card = CX88_BOARD_PCHDTV_HD3000,
},{
.subvendor = 0x17de,
.subdevice = 0xa8a6,
.card = CX88_BOARD_DNTV_LIVE_DVB_T,
},{
.subvendor = 0x0070,
.subdevice = 0x2801,
.card = CX88_BOARD_HAUPPAUGE_ROSLYN,
},{
.subvendor = 0x14f1,
.subdevice = 0x0342,
.card = CX88_BOARD_DIGITALLOGIC_MEC,
},{
.subvendor = 0x10fc,
.subdevice = 0xd035,
.card = CX88_BOARD_IODATA_GVBCTV7E,
},{
.subvendor = 0x1421,
.subdevice = 0x0334,
.card = CX88_BOARD_ADSTECH_DVB_T_PCI,
},{
.subvendor = 0x153b,
.subdevice = 0x1166,
.card = CX88_BOARD_TERRATEC_CINERGY_1400_DVB_T1,
},{
.subvendor = 0x18ac,
.subdevice = 0xd500,
.card = CX88_BOARD_DVICO_FUSIONHDTV_5_GOLD,
},{
.subvendor = 0x1461,
.subdevice = 0x8011,
.card = CX88_BOARD_AVERMEDIA_ULTRATV_MC_550,
},{
.subvendor = PCI_VENDOR_ID_ATI,
.subdevice = 0xa101,
.card = CX88_BOARD_ATI_HDTVWONDER,
},{
.subvendor = 0x107d,
.subdevice = 0x665f,
.card = CX88_BOARD_WINFAST_DTV1000,
},{
.subvendor = 0x1461,
.subdevice = 0x000a,
.card = CX88_BOARD_AVERTV_303,
},{
.subvendor = 0x0070,
.subdevice = 0x9200,
.card = CX88_BOARD_HAUPPAUGE_NOVASE2_S1,
},{
.subvendor = 0x0070,
.subdevice = 0x9201,
.card = CX88_BOARD_HAUPPAUGE_NOVASPLUS_S1,
},{
.subvendor = 0x0070,
.subdevice = 0x9202,
.card = CX88_BOARD_HAUPPAUGE_NOVASPLUS_S1,
},{
.subvendor = 0x17de,
.subdevice = 0x08b2,
.card = CX88_BOARD_KWORLD_DVBS_100,
},{
.subvendor = 0x0070,
.subdevice = 0x9400,
.card = CX88_BOARD_HAUPPAUGE_HVR1100,
},{
.subvendor = 0x0070,
.subdevice = 0x9402,
.card = CX88_BOARD_HAUPPAUGE_HVR1100,
},{
.subvendor = 0x0070,
.subdevice = 0x9800,
.card = CX88_BOARD_HAUPPAUGE_HVR1100LP,
},{
.subvendor = 0x0070,
.subdevice = 0x9802,
.card = CX88_BOARD_HAUPPAUGE_HVR1100LP,
},{
.subvendor = 0x0070,
.subdevice = 0x9001,
.card = CX88_BOARD_HAUPPAUGE_DVB_T1,
},{
.subvendor = 0x1822,
.subdevice = 0x0025,
.card = CX88_BOARD_DNTV_LIVE_DVB_T_PRO,
},{
.subvendor = 0x17de,
.subdevice = 0x08a1,
.card = CX88_BOARD_KWORLD_DVB_T_CX22702,
},{
.subvendor = 0x18ac,
.subdevice = 0xdb50,
.card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_DUAL,
},{
.subvendor = 0x18ac,
.subdevice = 0xdb54,
.card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_DUAL,
/* Re-branded DViCO: DigitalNow DVB-T Dual */
},{
.subvendor = 0x18ac,
.subdevice = 0xdb11,
.card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_PLUS,
/* Re-branded DViCO: UltraView DVB-T Plus */
}, {
.subvendor = 0x18ac,
.subdevice = 0xdb30,
.card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_PRO,
}, {
.subvendor = 0x17de,
.subdevice = 0x0840,
.card = CX88_BOARD_KWORLD_HARDWARE_MPEG_TV_XPERT,
},{
.subvendor = 0x1421,
.subdevice = 0x0305,
.card = CX88_BOARD_KWORLD_HARDWARE_MPEG_TV_XPERT,
},{
.subvendor = 0x18ac,
.subdevice = 0xdb40,
.card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_HYBRID,
},{
.subvendor = 0x18ac,
.subdevice = 0xdb44,
.card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_HYBRID,
},{
.subvendor = 0x7063,
.subdevice = 0x5500,
.card = CX88_BOARD_PCHDTV_HD5500,
},{
.subvendor = 0x17de,
.subdevice = 0x0841,
.card = CX88_BOARD_KWORLD_MCE200_DELUXE,
},{
.subvendor = 0x1822,
.subdevice = 0x0019,
.card = CX88_BOARD_DNTV_LIVE_DVB_T_PRO,
},{
.subvendor = 0x1554,
.subdevice = 0x4813,
.card = CX88_BOARD_PIXELVIEW_PLAYTV_P7000,
},{
.subvendor = 0x14f1,
.subdevice = 0x0842,
.card = CX88_BOARD_NPGTECH_REALTV_TOP10FM,
},{
.subvendor = 0x107d,
.subdevice = 0x665e,
.card = CX88_BOARD_WINFAST_DTV2000H,
},{
.subvendor = 0x107d,
.subdevice = 0x6f2b,
.card = CX88_BOARD_WINFAST_DTV2000H_J,
},{
.subvendor = 0x18ac,
.subdevice = 0xd800, /* FusionHDTV 3 Gold (original revision) */
.card = CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_Q,
},{
.subvendor = 0x14f1,
.subdevice = 0x0084,
.card = CX88_BOARD_GENIATECH_DVBS,
},{
.subvendor = 0x0070,
.subdevice = 0x1404,
.card = CX88_BOARD_HAUPPAUGE_HVR3000,
}, {
.subvendor = 0x18ac,
.subdevice = 0xdc00,
.card = CX88_BOARD_SAMSUNG_SMT_7020,
}, {
.subvendor = 0x18ac,
.subdevice = 0xdccd,
.card = CX88_BOARD_SAMSUNG_SMT_7020,
},{
.subvendor = 0x1461,
.subdevice = 0xc111, /* AverMedia M150-D */
/* This board is known to work with the ASUS PVR416 config */
.card = CX88_BOARD_ASUS_PVR_416,
},{
.subvendor = 0xc180,
.subdevice = 0xc980,
.card = CX88_BOARD_TE_DTV_250_OEM_SWANN,
},{
.subvendor = 0x0070,
.subdevice = 0x9600,
.card = CX88_BOARD_HAUPPAUGE_HVR1300,
},{
.subvendor = 0x0070,
.subdevice = 0x9601,
.card = CX88_BOARD_HAUPPAUGE_HVR1300,
},{
.subvendor = 0x0070,
.subdevice = 0x9602,
.card = CX88_BOARD_HAUPPAUGE_HVR1300,
},{
.subvendor = 0x107d,
.subdevice = 0x6632,
.card = CX88_BOARD_LEADTEK_PVR2000,
},{
.subvendor = 0x12ab,
.subdevice = 0x2300, /* Club3D Zap TV2100 */
.card = CX88_BOARD_KWORLD_DVB_T_CX22702,
},{
.subvendor = 0x0070,
.subdevice = 0x9000,
.card = CX88_BOARD_HAUPPAUGE_DVB_T1,
},{
.subvendor = 0x0070,
.subdevice = 0x1400,
.card = CX88_BOARD_HAUPPAUGE_HVR3000,
},{
.subvendor = 0x0070,
.subdevice = 0x1401,
.card = CX88_BOARD_HAUPPAUGE_HVR3000,
},{
.subvendor = 0x0070,
.subdevice = 0x1402,
.card = CX88_BOARD_HAUPPAUGE_HVR3000,
},{
.subvendor = 0x1421,
.subdevice = 0x0341, /* ADS Tech InstantTV DVB-S */
.card = CX88_BOARD_KWORLD_DVBS_100,
},{
.subvendor = 0x1421,
.subdevice = 0x0390,
.card = CX88_BOARD_ADSTECH_PTV_390,
},{
.subvendor = 0x11bd,
.subdevice = 0x0051,
.card = CX88_BOARD_PINNACLE_PCTV_HD_800i,
}, {
.subvendor = 0x18ac,
.subdevice = 0xd530,
.card = CX88_BOARD_DVICO_FUSIONHDTV_5_PCI_NANO,
}, {
.subvendor = 0x12ab,
.subdevice = 0x1788,
.card = CX88_BOARD_PINNACLE_HYBRID_PCTV,
}, {
.subvendor = 0x14f1,
.subdevice = 0xea3d,
.card = CX88_BOARD_POWERCOLOR_REAL_ANGEL,
}, {
.subvendor = 0x107d,
.subdevice = 0x6f18,
.card = CX88_BOARD_WINFAST_TV2000_XP_GLOBAL,
}, {
.subvendor = 0x14f1,
.subdevice = 0x8852,
.card = CX88_BOARD_GENIATECH_X8000_MT,
}, {
.subvendor = 0x18ac,
.subdevice = 0xd610,
.card = CX88_BOARD_DVICO_FUSIONHDTV_7_GOLD,
}, {
.subvendor = 0x1554,
.subdevice = 0x4935,
.card = CX88_BOARD_PROLINK_PV_8000GT,
}, {
.subvendor = 0x1554,
.subdevice = 0x4976,
.card = CX88_BOARD_PROLINK_PV_GLOBAL_XTREME,
}, {
.subvendor = 0x17de,
.subdevice = 0x08c1,
.card = CX88_BOARD_KWORLD_ATSC_120,
}, {
.subvendor = 0x0070,
.subdevice = 0x6900,
.card = CX88_BOARD_HAUPPAUGE_HVR4000,
}, {
.subvendor = 0x0070,
.subdevice = 0x6904,
.card = CX88_BOARD_HAUPPAUGE_HVR4000,
}, {
.subvendor = 0x0070,
.subdevice = 0x6902,
.card = CX88_BOARD_HAUPPAUGE_HVR4000,
}, {
.subvendor = 0x0070,
.subdevice = 0x6905,
.card = CX88_BOARD_HAUPPAUGE_HVR4000LITE,
}, {
.subvendor = 0x0070,
.subdevice = 0x6906,
.card = CX88_BOARD_HAUPPAUGE_HVR4000LITE,
}, {
.subvendor = 0xd420,
.subdevice = 0x9022,
.card = CX88_BOARD_TEVII_S420,
}, {
.subvendor = 0xd460,
.subdevice = 0x9022,
.card = CX88_BOARD_TEVII_S460,
}, {
.subvendor = 0xA044,
.subdevice = 0x2011,
.card = CX88_BOARD_OMICOM_SS4_PCI,
}, {
.subvendor = 0x8910,
.subdevice = 0x8888,
.card = CX88_BOARD_TBS_8910,
}, {
.subvendor = 0x8920,
.subdevice = 0x8888,
.card = CX88_BOARD_TBS_8920,
}, {
.subvendor = 0xb022,
.subdevice = 0x3022,
.card = CX88_BOARD_PROF_6200,
}, {
.subvendor = 0xB033,
.subdevice = 0x3033,
.card = CX88_BOARD_PROF_7300,
}, {
.subvendor = 0xb200,
.subdevice = 0x4200,
.card = CX88_BOARD_SATTRADE_ST4200,
}, {
.subvendor = 0x153b,
.subdevice = 0x1177,
.card = CX88_BOARD_TERRATEC_CINERGY_HT_PCI_MKII,
}, {
.subvendor = 0x0070,
.subdevice = 0x9290,
.card = CX88_BOARD_HAUPPAUGE_IRONLY,
}, {
.subvendor = 0x107d,
.subdevice = 0x6654,
.card = CX88_BOARD_WINFAST_DTV1800H,
}, {
/* PVR2000 PAL Model [107d:6630] */
.subvendor = 0x107d,
.subdevice = 0x6630,
.card = CX88_BOARD_LEADTEK_PVR2000,
}, {
/* PVR2000 PAL Model [107d:6638] */
.subvendor = 0x107d,
.subdevice = 0x6638,
.card = CX88_BOARD_LEADTEK_PVR2000,
}, {
/* PVR2000 NTSC Model [107d:6631] */
.subvendor = 0x107d,
.subdevice = 0x6631,
.card = CX88_BOARD_LEADTEK_PVR2000,
}, {
/* PVR2000 NTSC Model [107d:6637] */
.subvendor = 0x107d,
.subdevice = 0x6637,
.card = CX88_BOARD_LEADTEK_PVR2000,
}, {
/* PVR2000 NTSC Model [107d:663d] */
.subvendor = 0x107d,
.subdevice = 0x663d,
.card = CX88_BOARD_LEADTEK_PVR2000,
}, {
/* DV2000 NTSC Model [107d:6621] */
.subvendor = 0x107d,
.subdevice = 0x6621,
.card = CX88_BOARD_WINFAST_DV2000,
}, {
/* TV2000 XP Global [107d:6618] */
.subvendor = 0x107d,
.subdevice = 0x6618,
.card = CX88_BOARD_WINFAST_TV2000_XP_GLOBAL,
}, {
.subvendor = 0xb034,
.subdevice = 0x3034,
.card = CX88_BOARD_PROF_7301,
}, {
.subvendor = 0x1822,
.subdevice = 0x0023,
.card = CX88_BOARD_TWINHAN_VP1027_DVBS,
},
};
/* ----------------------------------------------------------------------- */
/* some leadtek specific stuff */
static void leadtek_eeprom(struct cx88_core *core, u8 *eeprom_data)
{
if (eeprom_data[4] != 0x7d ||
eeprom_data[5] != 0x10 ||
eeprom_data[7] != 0x66) {
warn_printk(core, "Leadtek eeprom invalid.\n");
return;
}
/* Terry Wu <terrywu2009@gmail.com> */
switch (eeprom_data[6]) {
case 0x13: /* SSID 6613 for TV2000 XP Expert NTSC Model */
case 0x21: /* SSID 6621 for DV2000 NTSC Model */
case 0x31: /* SSID 6631 for PVR2000 NTSC Model */
case 0x37: /* SSID 6637 for PVR2000 NTSC Model */
case 0x3d: /* SSID 6637 for PVR2000 NTSC Model */
core->board.tuner_type = TUNER_PHILIPS_FM1236_MK3;
break;
default:
core->board.tuner_type = TUNER_PHILIPS_FM1216ME_MK3;
break;
}
info_printk(core, "Leadtek Winfast 2000XP Expert config: "
"tuner=%d, eeprom[0]=0x%02x\n",
core->board.tuner_type, eeprom_data[0]);
}
static void hauppauge_eeprom(struct cx88_core *core, u8 *eeprom_data)
{
struct tveeprom tv;
tveeprom_hauppauge_analog(&core->i2c_client, &tv, eeprom_data);
core->board.tuner_type = tv.tuner_type;
core->tuner_formats = tv.tuner_formats;
core->board.radio.type = tv.has_radio ? CX88_RADIO : 0;
/* Make sure we support the board model */
switch (tv.model)
{
case 14009: /* WinTV-HVR3000 (Retail, IR, b/panel video, 3.5mm audio in) */
case 14019: /* WinTV-HVR3000 (Retail, IR Blaster, b/panel video, 3.5mm audio in) */
case 14029: /* WinTV-HVR3000 (Retail, IR, b/panel video, 3.5mm audio in - 880 bridge) */
case 14109: /* WinTV-HVR3000 (Retail, IR, b/panel video, 3.5mm audio in - low profile) */
case 14129: /* WinTV-HVR3000 (Retail, IR, b/panel video, 3.5mm audio in - 880 bridge - LP) */
case 14559: /* WinTV-HVR3000 (OEM, no IR, b/panel video, 3.5mm audio in) */
case 14569: /* WinTV-HVR3000 (OEM, no IR, no back panel video) */
case 14659: /* WinTV-HVR3000 (OEM, no IR, b/panel video, RCA audio in - Low profile) */
case 14669: /* WinTV-HVR3000 (OEM, no IR, no b/panel video - Low profile) */
case 28552: /* WinTV-PVR 'Roslyn' (No IR) */
case 34519: /* WinTV-PCI-FM */
case 69009:
/* WinTV-HVR4000 (DVBS/S2/T, Video and IR, back panel inputs) */
case 69100: /* WinTV-HVR4000LITE (DVBS/S2, IR) */
case 69500: /* WinTV-HVR4000LITE (DVBS/S2, No IR) */
case 69559:
/* WinTV-HVR4000 (DVBS/S2/T, Video no IR, back panel inputs) */
case 69569: /* WinTV-HVR4000 (DVBS/S2/T, Video no IR) */
case 90002: /* Nova-T-PCI (9002) */
case 92001: /* Nova-S-Plus (Video and IR) */
case 92002: /* Nova-S-Plus (Video and IR) */
case 90003: /* Nova-T-PCI (9002 No RF out) */
case 90500: /* Nova-T-PCI (oem) */
case 90501: /* Nova-T-PCI (oem/IR) */
case 92000: /* Nova-SE2 (OEM, No Video or IR) */
case 92900: /* WinTV-IROnly (No analog or digital Video inputs) */
case 94009: /* WinTV-HVR1100 (Video and IR Retail) */
case 94501: /* WinTV-HVR1100 (Video and IR OEM) */
case 96009: /* WinTV-HVR1300 (PAL Video, MPEG Video and IR RX) */
case 96019: /* WinTV-HVR1300 (PAL Video, MPEG Video and IR RX/TX) */
case 96559: /* WinTV-HVR1300 (PAL Video, MPEG Video no IR) */
case 96569: /* WinTV-HVR1300 () */
case 96659: /* WinTV-HVR1300 () */
case 98559: /* WinTV-HVR1100LP (Video no IR, Retail - Low Profile) */
/* known */
break;
case CX88_BOARD_SAMSUNG_SMT_7020:
cx_set(MO_GP0_IO, 0x008989FF);
break;
default:
warn_printk(core, "warning: unknown hauppauge model #%d\n",
tv.model);
break;
}
info_printk(core, "hauppauge eeprom: model=%d\n", tv.model);
}
/* ----------------------------------------------------------------------- */
/* some GDI (was: Modular Technology) specific stuff */
static const struct {
int id;
int fm;
const char *name;
} gdi_tuner[] = {
[ 0x01 ] = { .id = TUNER_ABSENT,
.name = "NTSC_M" },
[ 0x02 ] = { .id = TUNER_ABSENT,
.name = "PAL_B" },
[ 0x03 ] = { .id = TUNER_ABSENT,
.name = "PAL_I" },
[ 0x04 ] = { .id = TUNER_ABSENT,
.name = "PAL_D" },
[ 0x05 ] = { .id = TUNER_ABSENT,
.name = "SECAM" },
[ 0x10 ] = { .id = TUNER_ABSENT,
.fm = 1,
.name = "TEMIC_4049" },
[ 0x11 ] = { .id = TUNER_TEMIC_4136FY5,
.name = "TEMIC_4136" },
[ 0x12 ] = { .id = TUNER_ABSENT,
.name = "TEMIC_4146" },
[ 0x20 ] = { .id = TUNER_PHILIPS_FQ1216ME,
.fm = 1,
.name = "PHILIPS_FQ1216_MK3" },
[ 0x21 ] = { .id = TUNER_ABSENT, .fm = 1,
.name = "PHILIPS_FQ1236_MK3" },
[ 0x22 ] = { .id = TUNER_ABSENT,
.name = "PHILIPS_FI1236_MK3" },
[ 0x23 ] = { .id = TUNER_ABSENT,
.name = "PHILIPS_FI1216_MK3" },
};
static void gdi_eeprom(struct cx88_core *core, u8 *eeprom_data)
{
const char *name = (eeprom_data[0x0d] < ARRAY_SIZE(gdi_tuner))
? gdi_tuner[eeprom_data[0x0d]].name : NULL;
info_printk(core, "GDI: tuner=%s\n", name ? name : "unknown");
if (NULL == name)
return;
core->board.tuner_type = gdi_tuner[eeprom_data[0x0d]].id;
core->board.radio.type = gdi_tuner[eeprom_data[0x0d]].fm ?
CX88_RADIO : 0;
}
/* ------------------------------------------------------------------- */
/* some Divco specific stuff */
static int cx88_dvico_xc2028_callback(struct cx88_core *core,
int command, int arg)
{
switch (command) {
case XC2028_TUNER_RESET:
switch (core->boardnr) {
case CX88_BOARD_DVICO_FUSIONHDTV_5_PCI_NANO:
/* GPIO-4 xc3028 tuner */
cx_set(MO_GP0_IO, 0x00001000);
cx_clear(MO_GP0_IO, 0x00000010);
msleep(100);
cx_set(MO_GP0_IO, 0x00000010);
msleep(100);
break;
default:
cx_write(MO_GP0_IO, 0x101000);
mdelay(5);
cx_set(MO_GP0_IO, 0x101010);
}
break;
default:
return -EINVAL;
}
return 0;
}
/* ----------------------------------------------------------------------- */
/* some Geniatech specific stuff */
static int cx88_xc3028_geniatech_tuner_callback(struct cx88_core *core,
int command, int mode)
{
switch (command) {
case XC2028_TUNER_RESET:
switch (INPUT(core->input).type) {
case CX88_RADIO:
break;
case CX88_VMUX_DVB:
cx_write(MO_GP1_IO, 0x030302);
mdelay(50);
break;
default:
cx_write(MO_GP1_IO, 0x030301);
mdelay(50);
}
cx_write(MO_GP1_IO, 0x101010);
mdelay(50);
cx_write(MO_GP1_IO, 0x101000);
mdelay(50);
cx_write(MO_GP1_IO, 0x101010);
mdelay(50);
return 0;
}
return -EINVAL;
}
static int cx88_xc3028_winfast1800h_callback(struct cx88_core *core,
int command, int arg)
{
switch (command) {
case XC2028_TUNER_RESET:
/* GPIO 12 (xc3028 tuner reset) */
cx_set(MO_GP1_IO, 0x1010);
mdelay(50);
cx_clear(MO_GP1_IO, 0x10);
mdelay(50);
cx_set(MO_GP1_IO, 0x10);
mdelay(50);
return 0;
}
return -EINVAL;
}
/* ------------------------------------------------------------------- */
/* some Divco specific stuff */
static int cx88_pv_8000gt_callback(struct cx88_core *core,
int command, int arg)
{
switch (command) {
case XC2028_TUNER_RESET:
cx_write(MO_GP2_IO, 0xcf7);
mdelay(50);
cx_write(MO_GP2_IO, 0xef5);
mdelay(50);
cx_write(MO_GP2_IO, 0xcf7);
break;
default:
return -EINVAL;
}
return 0;
}
/* ----------------------------------------------------------------------- */
/* some DViCO specific stuff */
static void dvico_fusionhdtv_hybrid_init(struct cx88_core *core)
{
struct i2c_msg msg = { .addr = 0x45, .flags = 0 };
int i, err;
static u8 init_bufs[13][5] = {
{ 0x10, 0x00, 0x20, 0x01, 0x03 },
{ 0x10, 0x10, 0x01, 0x00, 0x21 },
{ 0x10, 0x10, 0x10, 0x00, 0xCA },
{ 0x10, 0x10, 0x12, 0x00, 0x08 },
{ 0x10, 0x10, 0x13, 0x00, 0x0A },
{ 0x10, 0x10, 0x16, 0x01, 0xC0 },
{ 0x10, 0x10, 0x22, 0x01, 0x3D },
{ 0x10, 0x10, 0x73, 0x01, 0x2E },
{ 0x10, 0x10, 0x72, 0x00, 0xC5 },
{ 0x10, 0x10, 0x71, 0x01, 0x97 },
{ 0x10, 0x10, 0x70, 0x00, 0x0F },
{ 0x10, 0x10, 0xB0, 0x00, 0x01 },
{ 0x03, 0x0C },
};
for (i = 0; i < ARRAY_SIZE(init_bufs); i++) {
msg.buf = init_bufs[i];
msg.len = (i != 12 ? 5 : 2);
err = i2c_transfer(&core->i2c_adap, &msg, 1);
if (err != 1) {
warn_printk(core, "dvico_fusionhdtv_hybrid_init buf %d "
"failed (err = %d)!\n", i, err);
return;
}
}
}
static int cx88_xc2028_tuner_callback(struct cx88_core *core,
int command, int arg)
{
/* Board-specific callbacks */
switch (core->boardnr) {
case CX88_BOARD_POWERCOLOR_REAL_ANGEL:
case CX88_BOARD_GENIATECH_X8000_MT:
case CX88_BOARD_KWORLD_ATSC_120:
return cx88_xc3028_geniatech_tuner_callback(core,
command, arg);
case CX88_BOARD_PROLINK_PV_8000GT:
case CX88_BOARD_PROLINK_PV_GLOBAL_XTREME:
return cx88_pv_8000gt_callback(core, command, arg);
case CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_PRO:
case CX88_BOARD_DVICO_FUSIONHDTV_5_PCI_NANO:
return cx88_dvico_xc2028_callback(core, command, arg);
case CX88_BOARD_WINFAST_TV2000_XP_GLOBAL:
case CX88_BOARD_WINFAST_DTV1800H:
return cx88_xc3028_winfast1800h_callback(core, command, arg);
}
switch (command) {
case XC2028_TUNER_RESET:
switch (INPUT(core->input).type) {
case CX88_RADIO:
info_printk(core, "setting GPIO to radio!\n");
cx_write(MO_GP0_IO, 0x4ff);
mdelay(250);
cx_write(MO_GP2_IO, 0xff);
mdelay(250);
break;
case CX88_VMUX_DVB: /* Digital TV*/
default: /* Analog TV */
info_printk(core, "setting GPIO to TV!\n");
break;
}
cx_write(MO_GP1_IO, 0x101010);
mdelay(250);
cx_write(MO_GP1_IO, 0x101000);
mdelay(250);
cx_write(MO_GP1_IO, 0x101010);
mdelay(250);
return 0;
}
return -EINVAL;
}
/* ----------------------------------------------------------------------- */
/* Tuner callback function. Currently only needed for the Pinnacle *
* PCTV HD 800i with an xc5000 sillicon tuner. This is used for both *
* analog tuner attach (tuner-core.c) and dvb tuner attach (cx88-dvb.c) */
static int cx88_xc5000_tuner_callback(struct cx88_core *core,
int command, int arg)
{
switch (core->boardnr) {
case CX88_BOARD_PINNACLE_PCTV_HD_800i:
if (command == 0) { /* This is the reset command from xc5000 */
/* djh - According to the engineer at PCTV Systems,
the xc5000 reset pin is supposed to be on GPIO12.
However, despite three nights of effort, pulling
that GPIO low didn't reset the xc5000. While
pulling MO_SRST_IO low does reset the xc5000, this
also resets in the s5h1409 being reset as well.
This causes tuning to always fail since the internal
state of the s5h1409 does not match the driver's
state. Given that the only two conditions in which
the driver performs a reset is during firmware load
and powering down the chip, I am taking out the
reset. We know that the chip is being reset
when the cx88 comes online, and not being able to
do power management for this board is worse than
not having any tuning at all. */
return 0;
} else {
err_printk(core, "xc5000: unknown tuner "
"callback command.\n");
return -EINVAL;
}
break;
case CX88_BOARD_DVICO_FUSIONHDTV_7_GOLD:
if (command == 0) { /* This is the reset command from xc5000 */
cx_clear(MO_GP0_IO, 0x00000010);
msleep(10);
cx_set(MO_GP0_IO, 0x00000010);
return 0;
} else {
printk(KERN_ERR
"xc5000: unknown tuner callback command.\n");
return -EINVAL;
}
break;
}
return 0; /* Should never be here */
}
int cx88_tuner_callback(void *priv, int component, int command, int arg)
{
struct i2c_algo_bit_data *i2c_algo = priv;
struct cx88_core *core;
if (!i2c_algo) {
printk(KERN_ERR "cx88: Error - i2c private data undefined.\n");
return -EINVAL;
}
core = i2c_algo->data;
if (!core) {
printk(KERN_ERR "cx88: Error - device struct undefined.\n");
return -EINVAL;
}
if (component != DVB_FRONTEND_COMPONENT_TUNER)
return -EINVAL;
switch (core->board.tuner_type) {
case TUNER_XC2028:
info_printk(core, "Calling XC2028/3028 callback\n");
return cx88_xc2028_tuner_callback(core, command, arg);
case TUNER_XC5000:
info_printk(core, "Calling XC5000 callback\n");
return cx88_xc5000_tuner_callback(core, command, arg);
}
err_printk(core, "Error: Calling callback for tuner %d\n",
core->board.tuner_type);
return -EINVAL;
}
EXPORT_SYMBOL(cx88_tuner_callback);
/* ----------------------------------------------------------------------- */
static void cx88_card_list(struct cx88_core *core, struct pci_dev *pci)
{
int i;
if (0 == pci->subsystem_vendor &&
0 == pci->subsystem_device) {
printk(KERN_ERR
"%s: Your board has no valid PCI Subsystem ID and thus can't\n"
"%s: be autodetected. Please pass card=<n> insmod option to\n"
"%s: workaround that. Redirect complaints to the vendor of\n"
"%s: the TV card. Best regards,\n"
"%s: -- tux\n",
core->name,core->name,core->name,core->name,core->name);
} else {
printk(KERN_ERR
"%s: Your board isn't known (yet) to the driver. You can\n"
"%s: try to pick one of the existing card configs via\n"
"%s: card=<n> insmod option. Updating to the latest\n"
"%s: version might help as well.\n",
core->name,core->name,core->name,core->name);
}
err_printk(core, "Here is a list of valid choices for the card=<n> "
"insmod option:\n");
for (i = 0; i < ARRAY_SIZE(cx88_boards); i++)
printk(KERN_ERR "%s: card=%d -> %s\n",
core->name, i, cx88_boards[i].name);
}
static void cx88_card_setup_pre_i2c(struct cx88_core *core)
{
switch (core->boardnr) {
case CX88_BOARD_HAUPPAUGE_HVR1300:
/*
* Bring the 702 demod up before i2c scanning/attach or devices are hidden
* We leave here with the 702 on the bus
*
* "reset the IR receiver on GPIO[3]"
* Reported by Mike Crash <mike AT mikecrash.com>
*/
cx_write(MO_GP0_IO, 0x0000ef88);
udelay(1000);
cx_clear(MO_GP0_IO, 0x00000088);
udelay(50);
cx_set(MO_GP0_IO, 0x00000088); /* 702 out of reset */
udelay(1000);
break;
case CX88_BOARD_PROLINK_PV_GLOBAL_XTREME:
case CX88_BOARD_PROLINK_PV_8000GT:
cx_write(MO_GP2_IO, 0xcf7);
mdelay(50);
cx_write(MO_GP2_IO, 0xef5);
mdelay(50);
cx_write(MO_GP2_IO, 0xcf7);
msleep(10);
break;
case CX88_BOARD_DVICO_FUSIONHDTV_7_GOLD:
/* Enable the xc5000 tuner */
cx_set(MO_GP0_IO, 0x00001010);
break;
case CX88_BOARD_HAUPPAUGE_HVR3000:
case CX88_BOARD_HAUPPAUGE_HVR4000:
/* Init GPIO */
cx_write(MO_GP0_IO, core->board.input[0].gpio0);
udelay(1000);
cx_clear(MO_GP0_IO, 0x00000080);
udelay(50);
cx_set(MO_GP0_IO, 0x00000080); /* 702 out of reset */
udelay(1000);
break;
case CX88_BOARD_WINFAST_TV2000_XP_GLOBAL:
case CX88_BOARD_WINFAST_DTV1800H:
/* GPIO 12 (xc3028 tuner reset) */
cx_set(MO_GP1_IO, 0x1010);
mdelay(50);
cx_clear(MO_GP1_IO, 0x10);
mdelay(50);
cx_set(MO_GP1_IO, 0x10);
mdelay(50);
break;
case CX88_BOARD_TWINHAN_VP1027_DVBS:
cx_write(MO_GP0_IO, 0x00003230);
cx_write(MO_GP0_IO, 0x00003210);
msleep(1);
cx_write(MO_GP0_IO, 0x00001230);
break;
}
}
/*
* Sets board-dependent xc3028 configuration
*/
void cx88_setup_xc3028(struct cx88_core *core, struct xc2028_ctrl *ctl)
{
memset(ctl, 0, sizeof(*ctl));
ctl->fname = XC2028_DEFAULT_FIRMWARE;
ctl->max_len = 64;
switch (core->boardnr) {
case CX88_BOARD_POWERCOLOR_REAL_ANGEL:
/* Now works with firmware version 2.7 */
if (core->i2c_algo.udelay < 16)
core->i2c_algo.udelay = 16;
break;
case CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_PRO:
case CX88_BOARD_WINFAST_DTV1800H:
ctl->demod = XC3028_FE_ZARLINK456;
break;
case CX88_BOARD_KWORLD_ATSC_120:
case CX88_BOARD_DVICO_FUSIONHDTV_5_PCI_NANO:
ctl->demod = XC3028_FE_OREN538;
break;
case CX88_BOARD_GENIATECH_X8000_MT:
/* FIXME: For this board, the xc3028 never recovers after being
powered down (the reset GPIO probably is not set properly).
We don't have access to the hardware so we cannot determine
which GPIO is used for xc3028, so just disable power xc3028
power management for now */
ctl->disable_power_mgmt = 1;
break;
case CX88_BOARD_WINFAST_TV2000_XP_GLOBAL:
case CX88_BOARD_PROLINK_PV_GLOBAL_XTREME:
case CX88_BOARD_PROLINK_PV_8000GT:
/*
* Those boards uses non-MTS firmware
*/
break;
case CX88_BOARD_PINNACLE_HYBRID_PCTV:
case CX88_BOARD_TERRATEC_CINERGY_HT_PCI_MKII:
ctl->demod = XC3028_FE_ZARLINK456;
ctl->mts = 1;
break;
default:
ctl->demod = XC3028_FE_OREN538;
ctl->mts = 1;
}
}
EXPORT_SYMBOL_GPL(cx88_setup_xc3028);
static void cx88_card_setup(struct cx88_core *core)
{
static u8 eeprom[256];
struct tuner_setup tun_setup;
unsigned int mode_mask = T_RADIO |
T_ANALOG_TV |
T_DIGITAL_TV;
memset(&tun_setup, 0, sizeof(tun_setup));
if (0 == core->i2c_rc) {
core->i2c_client.addr = 0xa0 >> 1;
tveeprom_read(&core->i2c_client, eeprom, sizeof(eeprom));
}
switch (core->boardnr) {
case CX88_BOARD_HAUPPAUGE:
case CX88_BOARD_HAUPPAUGE_ROSLYN:
if (0 == core->i2c_rc)
hauppauge_eeprom(core, eeprom+8);
break;
case CX88_BOARD_GDI:
if (0 == core->i2c_rc)
gdi_eeprom(core, eeprom);
break;
case CX88_BOARD_LEADTEK_PVR2000:
case CX88_BOARD_WINFAST_DV2000:
case CX88_BOARD_WINFAST2000XP_EXPERT:
if (0 == core->i2c_rc)
leadtek_eeprom(core, eeprom);
break;
case CX88_BOARD_HAUPPAUGE_NOVASPLUS_S1:
case CX88_BOARD_HAUPPAUGE_NOVASE2_S1:
case CX88_BOARD_HAUPPAUGE_DVB_T1:
case CX88_BOARD_HAUPPAUGE_HVR1100:
case CX88_BOARD_HAUPPAUGE_HVR1100LP:
case CX88_BOARD_HAUPPAUGE_HVR3000:
case CX88_BOARD_HAUPPAUGE_HVR1300:
case CX88_BOARD_HAUPPAUGE_HVR4000:
case CX88_BOARD_HAUPPAUGE_HVR4000LITE:
case CX88_BOARD_HAUPPAUGE_IRONLY:
if (0 == core->i2c_rc)
hauppauge_eeprom(core, eeprom);
break;
case CX88_BOARD_KWORLD_DVBS_100:
cx_write(MO_GP0_IO, 0x000007f8);
cx_write(MO_GP1_IO, 0x00000001);
break;
case CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_PRO:
/* GPIO0:0 is hooked to demod reset */
/* GPIO0:4 is hooked to xc3028 reset */
cx_write(MO_GP0_IO, 0x00111100);
msleep(1);
cx_write(MO_GP0_IO, 0x00111111);
break;
case CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_DUAL:
/* GPIO0:6 is hooked to FX2 reset pin */
cx_set(MO_GP0_IO, 0x00004040);
cx_clear(MO_GP0_IO, 0x00000040);
msleep(1000);
cx_set(MO_GP0_IO, 0x00004040);
/* FALLTHROUGH */
case CX88_BOARD_DVICO_FUSIONHDTV_DVB_T1:
case CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_PLUS:
case CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_HYBRID:
/* GPIO0:0 is hooked to mt352 reset pin */
cx_set(MO_GP0_IO, 0x00000101);
cx_clear(MO_GP0_IO, 0x00000001);
msleep(1);
cx_set(MO_GP0_IO, 0x00000101);
if (0 == core->i2c_rc &&
core->boardnr == CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_HYBRID)
dvico_fusionhdtv_hybrid_init(core);
break;
case CX88_BOARD_KWORLD_DVB_T:
case CX88_BOARD_DNTV_LIVE_DVB_T:
cx_set(MO_GP0_IO, 0x00000707);
cx_set(MO_GP2_IO, 0x00000101);
cx_clear(MO_GP2_IO, 0x00000001);
msleep(1);
cx_clear(MO_GP0_IO, 0x00000007);
cx_set(MO_GP2_IO, 0x00000101);
break;
case CX88_BOARD_DNTV_LIVE_DVB_T_PRO:
cx_write(MO_GP0_IO, 0x00080808);
break;
case CX88_BOARD_ATI_HDTVWONDER:
if (0 == core->i2c_rc) {
/* enable tuner */
int i;
static const u8 buffer [][2] = {
{0x10,0x12},
{0x13,0x04},
{0x16,0x00},
{0x14,0x04},
{0x17,0x00}
};
core->i2c_client.addr = 0x0a;
for (i = 0; i < ARRAY_SIZE(buffer); i++)
if (2 != i2c_master_send(&core->i2c_client,
buffer[i],2))
warn_printk(core, "Unable to enable "
"tuner(%i).\n", i);
}
break;
case CX88_BOARD_MSI_TVANYWHERE_MASTER:
{
struct v4l2_priv_tun_config tea5767_cfg;
struct tea5767_ctrl ctl;
memset(&ctl, 0, sizeof(ctl));
ctl.high_cut = 1;
ctl.st_noise = 1;
ctl.deemph_75 = 1;
ctl.xtal_freq = TEA5767_HIGH_LO_13MHz;
tea5767_cfg.tuner = TUNER_TEA5767;
tea5767_cfg.priv = &ctl;
call_all(core, tuner, s_config, &tea5767_cfg);
break;
}
case CX88_BOARD_TEVII_S420:
case CX88_BOARD_TEVII_S460:
case CX88_BOARD_OMICOM_SS4_PCI:
case CX88_BOARD_TBS_8910:
case CX88_BOARD_TBS_8920:
case CX88_BOARD_PROF_6200:
case CX88_BOARD_PROF_7300:
case CX88_BOARD_PROF_7301:
case CX88_BOARD_SATTRADE_ST4200:
cx_write(MO_GP0_IO, 0x8000);
msleep(100);
cx_write(MO_SRST_IO, 0);
msleep(10);
cx_write(MO_GP0_IO, 0x8080);
msleep(100);
cx_write(MO_SRST_IO, 1);
msleep(100);
break;
} /*end switch() */
/* Setup tuners */
if ((core->board.radio_type != UNSET)) {
tun_setup.mode_mask = T_RADIO;
tun_setup.type = core->board.radio_type;
tun_setup.addr = core->board.radio_addr;
tun_setup.tuner_callback = cx88_tuner_callback;
call_all(core, tuner, s_type_addr, &tun_setup);
mode_mask &= ~T_RADIO;
}
if (core->board.tuner_type != TUNER_ABSENT) {
tun_setup.mode_mask = mode_mask;
tun_setup.type = core->board.tuner_type;
tun_setup.addr = core->board.tuner_addr;
tun_setup.tuner_callback = cx88_tuner_callback;
call_all(core, tuner, s_type_addr, &tun_setup);
}
if (core->board.tda9887_conf) {
struct v4l2_priv_tun_config tda9887_cfg;
tda9887_cfg.tuner = TUNER_TDA9887;
tda9887_cfg.priv = &core->board.tda9887_conf;
call_all(core, tuner, s_config, &tda9887_cfg);
}
if (core->board.tuner_type == TUNER_XC2028) {
struct v4l2_priv_tun_config xc2028_cfg;
struct xc2028_ctrl ctl;
/* Fills device-dependent initialization parameters */
cx88_setup_xc3028(core, &ctl);
/* Sends parameters to xc2028/3028 tuner */
memset(&xc2028_cfg, 0, sizeof(xc2028_cfg));
xc2028_cfg.tuner = TUNER_XC2028;
xc2028_cfg.priv = &ctl;
info_printk(core, "Asking xc2028/3028 to load firmware %s\n",
ctl.fname);
call_all(core, tuner, s_config, &xc2028_cfg);
}
call_all(core, core, s_power, 0);
}
/* ------------------------------------------------------------------ */
static int cx88_pci_quirks(const char *name, struct pci_dev *pci)
{
unsigned int lat = UNSET;
u8 ctrl = 0;
u8 value;
/* check pci quirks */
if (pci_pci_problems & PCIPCI_TRITON) {
printk(KERN_INFO "%s: quirk: PCIPCI_TRITON -- set TBFX\n",
name);
ctrl |= CX88X_EN_TBFX;
}
if (pci_pci_problems & PCIPCI_NATOMA) {
printk(KERN_INFO "%s: quirk: PCIPCI_NATOMA -- set TBFX\n",
name);
ctrl |= CX88X_EN_TBFX;
}
if (pci_pci_problems & PCIPCI_VIAETBF) {
printk(KERN_INFO "%s: quirk: PCIPCI_VIAETBF -- set TBFX\n",
name);
ctrl |= CX88X_EN_TBFX;
}
if (pci_pci_problems & PCIPCI_VSFX) {
printk(KERN_INFO "%s: quirk: PCIPCI_VSFX -- set VSFX\n",
name);
ctrl |= CX88X_EN_VSFX;
}
#ifdef PCIPCI_ALIMAGIK
if (pci_pci_problems & PCIPCI_ALIMAGIK) {
printk(KERN_INFO "%s: quirk: PCIPCI_ALIMAGIK -- latency fixup\n",
name);
lat = 0x0A;
}
#endif
/* check insmod options */
if (UNSET != latency)
lat = latency;
/* apply stuff */
if (ctrl) {
pci_read_config_byte(pci, CX88X_DEVCTRL, &value);
value |= ctrl;
pci_write_config_byte(pci, CX88X_DEVCTRL, value);
}
if (UNSET != lat) {
printk(KERN_INFO "%s: setting pci latency timer to %d\n",
name, latency);
pci_write_config_byte(pci, PCI_LATENCY_TIMER, latency);
}
return 0;
}
int cx88_get_resources(const struct cx88_core *core, struct pci_dev *pci)
{
if (request_mem_region(pci_resource_start(pci,0),
pci_resource_len(pci,0),
core->name))
return 0;
printk(KERN_ERR
"%s/%d: Can't get MMIO memory @ 0x%llx, subsystem: %04x:%04x\n",
core->name, PCI_FUNC(pci->devfn),
(unsigned long long)pci_resource_start(pci, 0),
pci->subsystem_vendor, pci->subsystem_device);
return -EBUSY;
}
/* Allocate and initialize the cx88 core struct. One should hold the
* devlist mutex before calling this. */
struct cx88_core *cx88_core_create(struct pci_dev *pci, int nr)
{
struct cx88_core *core;
int i;
core = kzalloc(sizeof(*core), GFP_KERNEL);
if (core == NULL)
return NULL;
atomic_inc(&core->refcount);
core->pci_bus = pci->bus->number;
core->pci_slot = PCI_SLOT(pci->devfn);
core->pci_irqmask = PCI_INT_RISC_RD_BERRINT | PCI_INT_RISC_WR_BERRINT |
PCI_INT_BRDG_BERRINT | PCI_INT_SRC_DMA_BERRINT |
PCI_INT_DST_DMA_BERRINT | PCI_INT_IPB_DMA_BERRINT;
mutex_init(&core->lock);
core->nr = nr;
sprintf(core->name, "cx88[%d]", core->nr);
strcpy(core->v4l2_dev.name, core->name);
if (v4l2_device_register(NULL, &core->v4l2_dev)) {
kfree(core);
return NULL;
}
if (0 != cx88_get_resources(core, pci)) {
v4l2_device_unregister(&core->v4l2_dev);
kfree(core);
return NULL;
}
/* PCI stuff */
cx88_pci_quirks(core->name, pci);
core->lmmio = ioremap(pci_resource_start(pci, 0),
pci_resource_len(pci, 0));
core->bmmio = (u8 __iomem *)core->lmmio;
if (core->lmmio == NULL) {
kfree(core);
return NULL;
}
/* board config */
core->boardnr = UNSET;
if (card[core->nr] < ARRAY_SIZE(cx88_boards))
core->boardnr = card[core->nr];
for (i = 0; UNSET == core->boardnr && i < ARRAY_SIZE(cx88_subids); i++)
if (pci->subsystem_vendor == cx88_subids[i].subvendor &&
pci->subsystem_device == cx88_subids[i].subdevice)
core->boardnr = cx88_subids[i].card;
if (UNSET == core->boardnr) {
core->boardnr = CX88_BOARD_UNKNOWN;
cx88_card_list(core, pci);
}
memcpy(&core->board, &cx88_boards[core->boardnr], sizeof(core->board));
if (!core->board.num_frontends && (core->board.mpeg & CX88_MPEG_DVB))
core->board.num_frontends = 1;
info_printk(core, "subsystem: %04x:%04x, board: %s [card=%d,%s], frontend(s): %d\n",
pci->subsystem_vendor, pci->subsystem_device, core->board.name,
core->boardnr, card[core->nr] == core->boardnr ?
"insmod option" : "autodetected",
core->board.num_frontends);
if (tuner[core->nr] != UNSET)
core->board.tuner_type = tuner[core->nr];
if (radio[core->nr] != UNSET)
core->board.radio_type = radio[core->nr];
info_printk(core, "TV tuner type %d, Radio tuner type %d\n",
core->board.tuner_type, core->board.radio_type);
/* init hardware */
cx88_reset(core);
cx88_card_setup_pre_i2c(core);
cx88_i2c_init(core, pci);
/* load tuner module, if needed */
if (TUNER_ABSENT != core->board.tuner_type) {
/* Ignore 0x6b and 0x6f on cx88 boards.
* FusionHDTV5 RT Gold has an ir receiver at 0x6b
* and an RTC at 0x6f which can get corrupted if probed. */
static const unsigned short tv_addrs[] = {
0x42, 0x43, 0x4a, 0x4b, /* tda8290 */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6a, 0x6c, 0x6d, 0x6e,
I2C_CLIENT_END
};
int has_demod = (core->board.tda9887_conf & TDA9887_PRESENT);
/* I don't trust the radio_type as is stored in the card
definitions, so we just probe for it.
The radio_type is sometimes missing, or set to UNSET but
later code configures a tea5767.
*/
v4l2_i2c_new_subdev(&core->v4l2_dev, &core->i2c_adap,
"tuner", 0, v4l2_i2c_tuner_addrs(ADDRS_RADIO));
if (has_demod)
v4l2_i2c_new_subdev(&core->v4l2_dev,
&core->i2c_adap, "tuner",
0, v4l2_i2c_tuner_addrs(ADDRS_DEMOD));
if (core->board.tuner_addr == ADDR_UNSET) {
v4l2_i2c_new_subdev(&core->v4l2_dev,
&core->i2c_adap, "tuner",
0, has_demod ? tv_addrs + 4 : tv_addrs);
} else {
v4l2_i2c_new_subdev(&core->v4l2_dev, &core->i2c_adap,
"tuner", core->board.tuner_addr, NULL);
}
}
cx88_card_setup(core);
if (!disable_ir) {
cx88_i2c_init_ir(core);
cx88_ir_init(core, pci);
}
return core;
}
| gpl-2.0 |
CumulusNetworks/linux-apd | drivers/tty/n_gsm.c | 364 | 80778 | /*
* n_gsm.c GSM 0710 tty multiplexor
* Copyright (c) 2009/10 Intel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* * THIS IS A DEVELOPMENT SNAPSHOT IT IS NOT A FINAL RELEASE *
*
* TO DO:
* Mostly done: ioctls for setting modes/timing
* Partly done: hooks so you can pull off frames to non tty devs
* Restart DLCI 0 when it closes ?
* Improve the tx engine
* Resolve tx side locking by adding a queue_head and routing
* all control traffic via it
* General tidy/document
* Review the locking/move to refcounts more (mux now moved to an
* alloc/free model ready)
* Use newest tty open/close port helpers and install hooks
* What to do about power functions ?
* Termios setting and negotiation
* Do we need a 'which mux are you' ioctl to correlate mux and tty sets
*
*/
#include <linux/types.h>
#include <linux/major.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/fcntl.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/tty.h>
#include <linux/ctype.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/bitops.h>
#include <linux/file.h>
#include <linux/uaccess.h>
#include <linux/module.h>
#include <linux/timer.h>
#include <linux/tty_flip.h>
#include <linux/tty_driver.h>
#include <linux/serial.h>
#include <linux/kfifo.h>
#include <linux/skbuff.h>
#include <net/arp.h>
#include <linux/ip.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/gsmmux.h>
static int debug;
module_param(debug, int, 0600);
/* Defaults: these are from the specification */
#define T1 10 /* 100mS */
#define T2 34 /* 333mS */
#define N2 3 /* Retry 3 times */
/* Use long timers for testing at low speed with debug on */
#ifdef DEBUG_TIMING
#define T1 100
#define T2 200
#endif
/*
* Semi-arbitrary buffer size limits. 0710 is normally run with 32-64 byte
* limits so this is plenty
*/
#define MAX_MRU 1500
#define MAX_MTU 1500
#define GSM_NET_TX_TIMEOUT (HZ*10)
/**
* struct gsm_mux_net - network interface
* @struct gsm_dlci* dlci
* @struct net_device_stats stats;
*
* Created when net interface is initialized.
**/
struct gsm_mux_net {
struct kref ref;
struct gsm_dlci *dlci;
struct net_device_stats stats;
};
#define STATS(net) (((struct gsm_mux_net *)netdev_priv(net))->stats)
/*
* Each block of data we have queued to go out is in the form of
* a gsm_msg which holds everything we need in a link layer independent
* format
*/
struct gsm_msg {
struct list_head list;
u8 addr; /* DLCI address + flags */
u8 ctrl; /* Control byte + flags */
unsigned int len; /* Length of data block (can be zero) */
unsigned char *data; /* Points into buffer but not at the start */
unsigned char buffer[0];
};
/*
* Each active data link has a gsm_dlci structure associated which ties
* the link layer to an optional tty (if the tty side is open). To avoid
* complexity right now these are only ever freed up when the mux is
* shut down.
*
* At the moment we don't free DLCI objects until the mux is torn down
* this avoid object life time issues but might be worth review later.
*/
struct gsm_dlci {
struct gsm_mux *gsm;
int addr;
int state;
#define DLCI_CLOSED 0
#define DLCI_OPENING 1 /* Sending SABM not seen UA */
#define DLCI_OPEN 2 /* SABM/UA complete */
#define DLCI_CLOSING 3 /* Sending DISC not seen UA/DM */
struct mutex mutex;
/* Link layer */
spinlock_t lock; /* Protects the internal state */
struct timer_list t1; /* Retransmit timer for SABM and UA */
int retries;
/* Uplink tty if active */
struct tty_port port; /* The tty bound to this DLCI if there is one */
struct kfifo *fifo; /* Queue fifo for the DLCI */
struct kfifo _fifo; /* For new fifo API porting only */
int adaption; /* Adaption layer in use */
int prev_adaption;
u32 modem_rx; /* Our incoming virtual modem lines */
u32 modem_tx; /* Our outgoing modem lines */
int dead; /* Refuse re-open */
/* Flow control */
int throttled; /* Private copy of throttle state */
int constipated; /* Throttle status for outgoing */
/* Packetised I/O */
struct sk_buff *skb; /* Frame being sent */
struct sk_buff_head skb_list; /* Queued frames */
/* Data handling callback */
void (*data)(struct gsm_dlci *dlci, u8 *data, int len);
void (*prev_data)(struct gsm_dlci *dlci, u8 *data, int len);
struct net_device *net; /* network interface, if created */
};
/* DLCI 0, 62/63 are special or reserved see gsmtty_open */
#define NUM_DLCI 64
/*
* DLCI 0 is used to pass control blocks out of band of the data
* flow (and with a higher link priority). One command can be outstanding
* at a time and we use this structure to manage them. They are created
* and destroyed by the user context, and updated by the receive paths
* and timers
*/
struct gsm_control {
u8 cmd; /* Command we are issuing */
u8 *data; /* Data for the command in case we retransmit */
int len; /* Length of block for retransmission */
int done; /* Done flag */
int error; /* Error if any */
};
/*
* Each GSM mux we have is represented by this structure. If we are
* operating as an ldisc then we use this structure as our ldisc
* state. We need to sort out lifetimes and locking with respect
* to the gsm mux array. For now we don't free DLCI objects that
* have been instantiated until the mux itself is terminated.
*
* To consider further: tty open versus mux shutdown.
*/
struct gsm_mux {
struct tty_struct *tty; /* The tty our ldisc is bound to */
spinlock_t lock;
struct mutex mutex;
unsigned int num;
struct kref ref;
/* Events on the GSM channel */
wait_queue_head_t event;
/* Bits for GSM mode decoding */
/* Framing Layer */
unsigned char *buf;
int state;
#define GSM_SEARCH 0
#define GSM_START 1
#define GSM_ADDRESS 2
#define GSM_CONTROL 3
#define GSM_LEN 4
#define GSM_DATA 5
#define GSM_FCS 6
#define GSM_OVERRUN 7
#define GSM_LEN0 8
#define GSM_LEN1 9
#define GSM_SSOF 10
unsigned int len;
unsigned int address;
unsigned int count;
int escape;
int encoding;
u8 control;
u8 fcs;
u8 received_fcs;
u8 *txframe; /* TX framing buffer */
/* Methods for the receiver side */
void (*receive)(struct gsm_mux *gsm, u8 ch);
void (*error)(struct gsm_mux *gsm, u8 ch, u8 flag);
/* And transmit side */
int (*output)(struct gsm_mux *mux, u8 *data, int len);
/* Link Layer */
unsigned int mru;
unsigned int mtu;
int initiator; /* Did we initiate connection */
int dead; /* Has the mux been shut down */
struct gsm_dlci *dlci[NUM_DLCI];
int constipated; /* Asked by remote to shut up */
spinlock_t tx_lock;
unsigned int tx_bytes; /* TX data outstanding */
#define TX_THRESH_HI 8192
#define TX_THRESH_LO 2048
struct list_head tx_list; /* Pending data packets */
/* Control messages */
struct timer_list t2_timer; /* Retransmit timer for commands */
int cretries; /* Command retry counter */
struct gsm_control *pending_cmd;/* Our current pending command */
spinlock_t control_lock; /* Protects the pending command */
/* Configuration */
int adaption; /* 1 or 2 supported */
u8 ftype; /* UI or UIH */
int t1, t2; /* Timers in 1/100th of a sec */
int n2; /* Retry count */
/* Statistics (not currently exposed) */
unsigned long bad_fcs;
unsigned long malformed;
unsigned long io_error;
unsigned long bad_size;
unsigned long unsupported;
};
/*
* Mux objects - needed so that we can translate a tty index into the
* relevant mux and DLCI.
*/
#define MAX_MUX 4 /* 256 minors */
static struct gsm_mux *gsm_mux[MAX_MUX]; /* GSM muxes */
static spinlock_t gsm_mux_lock;
static struct tty_driver *gsm_tty_driver;
/*
* This section of the driver logic implements the GSM encodings
* both the basic and the 'advanced'. Reliable transport is not
* supported.
*/
#define CR 0x02
#define EA 0x01
#define PF 0x10
/* I is special: the rest are ..*/
#define RR 0x01
#define UI 0x03
#define RNR 0x05
#define REJ 0x09
#define DM 0x0F
#define SABM 0x2F
#define DISC 0x43
#define UA 0x63
#define UIH 0xEF
/* Channel commands */
#define CMD_NSC 0x09
#define CMD_TEST 0x11
#define CMD_PSC 0x21
#define CMD_RLS 0x29
#define CMD_FCOFF 0x31
#define CMD_PN 0x41
#define CMD_RPN 0x49
#define CMD_FCON 0x51
#define CMD_CLD 0x61
#define CMD_SNC 0x69
#define CMD_MSC 0x71
/* Virtual modem bits */
#define MDM_FC 0x01
#define MDM_RTC 0x02
#define MDM_RTR 0x04
#define MDM_IC 0x20
#define MDM_DV 0x40
#define GSM0_SOF 0xF9
#define GSM1_SOF 0x7E
#define GSM1_ESCAPE 0x7D
#define GSM1_ESCAPE_BITS 0x20
#define XON 0x11
#define XOFF 0x13
static const struct tty_port_operations gsm_port_ops;
/*
* CRC table for GSM 0710
*/
static const u8 gsm_fcs8[256] = {
0x00, 0x91, 0xE3, 0x72, 0x07, 0x96, 0xE4, 0x75,
0x0E, 0x9F, 0xED, 0x7C, 0x09, 0x98, 0xEA, 0x7B,
0x1C, 0x8D, 0xFF, 0x6E, 0x1B, 0x8A, 0xF8, 0x69,
0x12, 0x83, 0xF1, 0x60, 0x15, 0x84, 0xF6, 0x67,
0x38, 0xA9, 0xDB, 0x4A, 0x3F, 0xAE, 0xDC, 0x4D,
0x36, 0xA7, 0xD5, 0x44, 0x31, 0xA0, 0xD2, 0x43,
0x24, 0xB5, 0xC7, 0x56, 0x23, 0xB2, 0xC0, 0x51,
0x2A, 0xBB, 0xC9, 0x58, 0x2D, 0xBC, 0xCE, 0x5F,
0x70, 0xE1, 0x93, 0x02, 0x77, 0xE6, 0x94, 0x05,
0x7E, 0xEF, 0x9D, 0x0C, 0x79, 0xE8, 0x9A, 0x0B,
0x6C, 0xFD, 0x8F, 0x1E, 0x6B, 0xFA, 0x88, 0x19,
0x62, 0xF3, 0x81, 0x10, 0x65, 0xF4, 0x86, 0x17,
0x48, 0xD9, 0xAB, 0x3A, 0x4F, 0xDE, 0xAC, 0x3D,
0x46, 0xD7, 0xA5, 0x34, 0x41, 0xD0, 0xA2, 0x33,
0x54, 0xC5, 0xB7, 0x26, 0x53, 0xC2, 0xB0, 0x21,
0x5A, 0xCB, 0xB9, 0x28, 0x5D, 0xCC, 0xBE, 0x2F,
0xE0, 0x71, 0x03, 0x92, 0xE7, 0x76, 0x04, 0x95,
0xEE, 0x7F, 0x0D, 0x9C, 0xE9, 0x78, 0x0A, 0x9B,
0xFC, 0x6D, 0x1F, 0x8E, 0xFB, 0x6A, 0x18, 0x89,
0xF2, 0x63, 0x11, 0x80, 0xF5, 0x64, 0x16, 0x87,
0xD8, 0x49, 0x3B, 0xAA, 0xDF, 0x4E, 0x3C, 0xAD,
0xD6, 0x47, 0x35, 0xA4, 0xD1, 0x40, 0x32, 0xA3,
0xC4, 0x55, 0x27, 0xB6, 0xC3, 0x52, 0x20, 0xB1,
0xCA, 0x5B, 0x29, 0xB8, 0xCD, 0x5C, 0x2E, 0xBF,
0x90, 0x01, 0x73, 0xE2, 0x97, 0x06, 0x74, 0xE5,
0x9E, 0x0F, 0x7D, 0xEC, 0x99, 0x08, 0x7A, 0xEB,
0x8C, 0x1D, 0x6F, 0xFE, 0x8B, 0x1A, 0x68, 0xF9,
0x82, 0x13, 0x61, 0xF0, 0x85, 0x14, 0x66, 0xF7,
0xA8, 0x39, 0x4B, 0xDA, 0xAF, 0x3E, 0x4C, 0xDD,
0xA6, 0x37, 0x45, 0xD4, 0xA1, 0x30, 0x42, 0xD3,
0xB4, 0x25, 0x57, 0xC6, 0xB3, 0x22, 0x50, 0xC1,
0xBA, 0x2B, 0x59, 0xC8, 0xBD, 0x2C, 0x5E, 0xCF
};
#define INIT_FCS 0xFF
#define GOOD_FCS 0xCF
/**
* gsm_fcs_add - update FCS
* @fcs: Current FCS
* @c: Next data
*
* Update the FCS to include c. Uses the algorithm in the specification
* notes.
*/
static inline u8 gsm_fcs_add(u8 fcs, u8 c)
{
return gsm_fcs8[fcs ^ c];
}
/**
* gsm_fcs_add_block - update FCS for a block
* @fcs: Current FCS
* @c: buffer of data
* @len: length of buffer
*
* Update the FCS to include c. Uses the algorithm in the specification
* notes.
*/
static inline u8 gsm_fcs_add_block(u8 fcs, u8 *c, int len)
{
while (len--)
fcs = gsm_fcs8[fcs ^ *c++];
return fcs;
}
/**
* gsm_read_ea - read a byte into an EA
* @val: variable holding value
* c: byte going into the EA
*
* Processes one byte of an EA. Updates the passed variable
* and returns 1 if the EA is now completely read
*/
static int gsm_read_ea(unsigned int *val, u8 c)
{
/* Add the next 7 bits into the value */
*val <<= 7;
*val |= c >> 1;
/* Was this the last byte of the EA 1 = yes*/
return c & EA;
}
/**
* gsm_encode_modem - encode modem data bits
* @dlci: DLCI to encode from
*
* Returns the correct GSM encoded modem status bits (6 bit field) for
* the current status of the DLCI and attached tty object
*/
static u8 gsm_encode_modem(const struct gsm_dlci *dlci)
{
u8 modembits = 0;
/* FC is true flow control not modem bits */
if (dlci->throttled)
modembits |= MDM_FC;
if (dlci->modem_tx & TIOCM_DTR)
modembits |= MDM_RTC;
if (dlci->modem_tx & TIOCM_RTS)
modembits |= MDM_RTR;
if (dlci->modem_tx & TIOCM_RI)
modembits |= MDM_IC;
if (dlci->modem_tx & TIOCM_CD)
modembits |= MDM_DV;
return modembits;
}
/**
* gsm_print_packet - display a frame for debug
* @hdr: header to print before decode
* @addr: address EA from the frame
* @cr: C/R bit from the frame
* @control: control including PF bit
* @data: following data bytes
* @dlen: length of data
*
* Displays a packet in human readable format for debugging purposes. The
* style is based on amateur radio LAP-B dump display.
*/
static void gsm_print_packet(const char *hdr, int addr, int cr,
u8 control, const u8 *data, int dlen)
{
if (!(debug & 1))
return;
pr_info("%s %d) %c: ", hdr, addr, "RC"[cr]);
switch (control & ~PF) {
case SABM:
pr_cont("SABM");
break;
case UA:
pr_cont("UA");
break;
case DISC:
pr_cont("DISC");
break;
case DM:
pr_cont("DM");
break;
case UI:
pr_cont("UI");
break;
case UIH:
pr_cont("UIH");
break;
default:
if (!(control & 0x01)) {
pr_cont("I N(S)%d N(R)%d",
(control & 0x0E) >> 1, (control & 0xE0) >> 5);
} else switch (control & 0x0F) {
case RR:
pr_cont("RR(%d)", (control & 0xE0) >> 5);
break;
case RNR:
pr_cont("RNR(%d)", (control & 0xE0) >> 5);
break;
case REJ:
pr_cont("REJ(%d)", (control & 0xE0) >> 5);
break;
default:
pr_cont("[%02X]", control);
}
}
if (control & PF)
pr_cont("(P)");
else
pr_cont("(F)");
if (dlen) {
int ct = 0;
while (dlen--) {
if (ct % 8 == 0) {
pr_cont("\n");
pr_debug(" ");
}
pr_cont("%02X ", *data++);
ct++;
}
}
pr_cont("\n");
}
/*
* Link level transmission side
*/
/**
* gsm_stuff_packet - bytestuff a packet
* @ibuf: input
* @obuf: output
* @len: length of input
*
* Expand a buffer by bytestuffing it. The worst case size change
* is doubling and the caller is responsible for handing out
* suitable sized buffers.
*/
static int gsm_stuff_frame(const u8 *input, u8 *output, int len)
{
int olen = 0;
while (len--) {
if (*input == GSM1_SOF || *input == GSM1_ESCAPE
|| *input == XON || *input == XOFF) {
*output++ = GSM1_ESCAPE;
*output++ = *input++ ^ GSM1_ESCAPE_BITS;
olen++;
} else
*output++ = *input++;
olen++;
}
return olen;
}
/**
* gsm_send - send a control frame
* @gsm: our GSM mux
* @addr: address for control frame
* @cr: command/response bit
* @control: control byte including PF bit
*
* Format up and transmit a control frame. These do not go via the
* queueing logic as they should be transmitted ahead of data when
* they are needed.
*
* FIXME: Lock versus data TX path
*/
static void gsm_send(struct gsm_mux *gsm, int addr, int cr, int control)
{
int len;
u8 cbuf[10];
u8 ibuf[3];
switch (gsm->encoding) {
case 0:
cbuf[0] = GSM0_SOF;
cbuf[1] = (addr << 2) | (cr << 1) | EA;
cbuf[2] = control;
cbuf[3] = EA; /* Length of data = 0 */
cbuf[4] = 0xFF - gsm_fcs_add_block(INIT_FCS, cbuf + 1, 3);
cbuf[5] = GSM0_SOF;
len = 6;
break;
case 1:
case 2:
/* Control frame + packing (but not frame stuffing) in mode 1 */
ibuf[0] = (addr << 2) | (cr << 1) | EA;
ibuf[1] = control;
ibuf[2] = 0xFF - gsm_fcs_add_block(INIT_FCS, ibuf, 2);
/* Stuffing may double the size worst case */
len = gsm_stuff_frame(ibuf, cbuf + 1, 3);
/* Now add the SOF markers */
cbuf[0] = GSM1_SOF;
cbuf[len + 1] = GSM1_SOF;
/* FIXME: we can omit the lead one in many cases */
len += 2;
break;
default:
WARN_ON(1);
return;
}
gsm->output(gsm, cbuf, len);
gsm_print_packet("-->", addr, cr, control, NULL, 0);
}
/**
* gsm_response - send a control response
* @gsm: our GSM mux
* @addr: address for control frame
* @control: control byte including PF bit
*
* Format up and transmit a link level response frame.
*/
static inline void gsm_response(struct gsm_mux *gsm, int addr, int control)
{
gsm_send(gsm, addr, 0, control);
}
/**
* gsm_command - send a control command
* @gsm: our GSM mux
* @addr: address for control frame
* @control: control byte including PF bit
*
* Format up and transmit a link level command frame.
*/
static inline void gsm_command(struct gsm_mux *gsm, int addr, int control)
{
gsm_send(gsm, addr, 1, control);
}
/* Data transmission */
#define HDR_LEN 6 /* ADDR CTRL [LEN.2] DATA FCS */
/**
* gsm_data_alloc - allocate data frame
* @gsm: GSM mux
* @addr: DLCI address
* @len: length excluding header and FCS
* @ctrl: control byte
*
* Allocate a new data buffer for sending frames with data. Space is left
* at the front for header bytes but that is treated as an implementation
* detail and not for the high level code to use
*/
static struct gsm_msg *gsm_data_alloc(struct gsm_mux *gsm, u8 addr, int len,
u8 ctrl)
{
struct gsm_msg *m = kmalloc(sizeof(struct gsm_msg) + len + HDR_LEN,
GFP_ATOMIC);
if (m == NULL)
return NULL;
m->data = m->buffer + HDR_LEN - 1; /* Allow for FCS */
m->len = len;
m->addr = addr;
m->ctrl = ctrl;
INIT_LIST_HEAD(&m->list);
return m;
}
/**
* gsm_data_kick - poke the queue
* @gsm: GSM Mux
*
* The tty device has called us to indicate that room has appeared in
* the transmit queue. Ram more data into the pipe if we have any
* If we have been flow-stopped by a CMD_FCOFF, then we can only
* send messages on DLCI0 until CMD_FCON
*
* FIXME: lock against link layer control transmissions
*/
static void gsm_data_kick(struct gsm_mux *gsm)
{
struct gsm_msg *msg, *nmsg;
int len;
int skip_sof = 0;
list_for_each_entry_safe(msg, nmsg, &gsm->tx_list, list) {
if (gsm->constipated && msg->addr)
continue;
if (gsm->encoding != 0) {
gsm->txframe[0] = GSM1_SOF;
len = gsm_stuff_frame(msg->data,
gsm->txframe + 1, msg->len);
gsm->txframe[len + 1] = GSM1_SOF;
len += 2;
} else {
gsm->txframe[0] = GSM0_SOF;
memcpy(gsm->txframe + 1 , msg->data, msg->len);
gsm->txframe[msg->len + 1] = GSM0_SOF;
len = msg->len + 2;
}
if (debug & 4)
print_hex_dump_bytes("gsm_data_kick: ",
DUMP_PREFIX_OFFSET,
gsm->txframe, len);
if (gsm->output(gsm, gsm->txframe + skip_sof,
len - skip_sof) < 0)
break;
/* FIXME: Can eliminate one SOF in many more cases */
gsm->tx_bytes -= msg->len;
/* For a burst of frames skip the extra SOF within the
burst */
skip_sof = 1;
list_del(&msg->list);
kfree(msg);
}
}
/**
* __gsm_data_queue - queue a UI or UIH frame
* @dlci: DLCI sending the data
* @msg: message queued
*
* Add data to the transmit queue and try and get stuff moving
* out of the mux tty if not already doing so. The Caller must hold
* the gsm tx lock.
*/
static void __gsm_data_queue(struct gsm_dlci *dlci, struct gsm_msg *msg)
{
struct gsm_mux *gsm = dlci->gsm;
u8 *dp = msg->data;
u8 *fcs = dp + msg->len;
/* Fill in the header */
if (gsm->encoding == 0) {
if (msg->len < 128)
*--dp = (msg->len << 1) | EA;
else {
*--dp = (msg->len >> 7); /* bits 7 - 15 */
*--dp = (msg->len & 127) << 1; /* bits 0 - 6 */
}
}
*--dp = msg->ctrl;
if (gsm->initiator)
*--dp = (msg->addr << 2) | 2 | EA;
else
*--dp = (msg->addr << 2) | EA;
*fcs = gsm_fcs_add_block(INIT_FCS, dp , msg->data - dp);
/* Ugly protocol layering violation */
if (msg->ctrl == UI || msg->ctrl == (UI|PF))
*fcs = gsm_fcs_add_block(*fcs, msg->data, msg->len);
*fcs = 0xFF - *fcs;
gsm_print_packet("Q> ", msg->addr, gsm->initiator, msg->ctrl,
msg->data, msg->len);
/* Move the header back and adjust the length, also allow for the FCS
now tacked on the end */
msg->len += (msg->data - dp) + 1;
msg->data = dp;
/* Add to the actual output queue */
list_add_tail(&msg->list, &gsm->tx_list);
gsm->tx_bytes += msg->len;
gsm_data_kick(gsm);
}
/**
* gsm_data_queue - queue a UI or UIH frame
* @dlci: DLCI sending the data
* @msg: message queued
*
* Add data to the transmit queue and try and get stuff moving
* out of the mux tty if not already doing so. Take the
* the gsm tx lock and dlci lock.
*/
static void gsm_data_queue(struct gsm_dlci *dlci, struct gsm_msg *msg)
{
unsigned long flags;
spin_lock_irqsave(&dlci->gsm->tx_lock, flags);
__gsm_data_queue(dlci, msg);
spin_unlock_irqrestore(&dlci->gsm->tx_lock, flags);
}
/**
* gsm_dlci_data_output - try and push data out of a DLCI
* @gsm: mux
* @dlci: the DLCI to pull data from
*
* Pull data from a DLCI and send it into the transmit queue if there
* is data. Keep to the MRU of the mux. This path handles the usual tty
* interface which is a byte stream with optional modem data.
*
* Caller must hold the tx_lock of the mux.
*/
static int gsm_dlci_data_output(struct gsm_mux *gsm, struct gsm_dlci *dlci)
{
struct gsm_msg *msg;
u8 *dp;
int len, total_size, size;
int h = dlci->adaption - 1;
total_size = 0;
while (1) {
len = kfifo_len(dlci->fifo);
if (len == 0)
return total_size;
/* MTU/MRU count only the data bits */
if (len > gsm->mtu)
len = gsm->mtu;
size = len + h;
msg = gsm_data_alloc(gsm, dlci->addr, size, gsm->ftype);
/* FIXME: need a timer or something to kick this so it can't
get stuck with no work outstanding and no buffer free */
if (msg == NULL)
return -ENOMEM;
dp = msg->data;
switch (dlci->adaption) {
case 1: /* Unstructured */
break;
case 2: /* Unstructed with modem bits.
Always one byte as we never send inline break data */
*dp++ = gsm_encode_modem(dlci);
break;
}
WARN_ON(kfifo_out_locked(dlci->fifo, dp , len, &dlci->lock) != len);
__gsm_data_queue(dlci, msg);
total_size += size;
}
/* Bytes of data we used up */
return total_size;
}
/**
* gsm_dlci_data_output_framed - try and push data out of a DLCI
* @gsm: mux
* @dlci: the DLCI to pull data from
*
* Pull data from a DLCI and send it into the transmit queue if there
* is data. Keep to the MRU of the mux. This path handles framed data
* queued as skbuffs to the DLCI.
*
* Caller must hold the tx_lock of the mux.
*/
static int gsm_dlci_data_output_framed(struct gsm_mux *gsm,
struct gsm_dlci *dlci)
{
struct gsm_msg *msg;
u8 *dp;
int len, size;
int last = 0, first = 0;
int overhead = 0;
/* One byte per frame is used for B/F flags */
if (dlci->adaption == 4)
overhead = 1;
/* dlci->skb is locked by tx_lock */
if (dlci->skb == NULL) {
dlci->skb = skb_dequeue_tail(&dlci->skb_list);
if (dlci->skb == NULL)
return 0;
first = 1;
}
len = dlci->skb->len + overhead;
/* MTU/MRU count only the data bits */
if (len > gsm->mtu) {
if (dlci->adaption == 3) {
/* Over long frame, bin it */
dev_kfree_skb_any(dlci->skb);
dlci->skb = NULL;
return 0;
}
len = gsm->mtu;
} else
last = 1;
size = len + overhead;
msg = gsm_data_alloc(gsm, dlci->addr, size, gsm->ftype);
/* FIXME: need a timer or something to kick this so it can't
get stuck with no work outstanding and no buffer free */
if (msg == NULL) {
skb_queue_tail(&dlci->skb_list, dlci->skb);
dlci->skb = NULL;
return -ENOMEM;
}
dp = msg->data;
if (dlci->adaption == 4) { /* Interruptible framed (Packetised Data) */
/* Flag byte to carry the start/end info */
*dp++ = last << 7 | first << 6 | 1; /* EA */
len--;
}
memcpy(dp, dlci->skb->data, len);
skb_pull(dlci->skb, len);
__gsm_data_queue(dlci, msg);
if (last) {
dev_kfree_skb_any(dlci->skb);
dlci->skb = NULL;
}
return size;
}
/**
* gsm_dlci_data_sweep - look for data to send
* @gsm: the GSM mux
*
* Sweep the GSM mux channels in priority order looking for ones with
* data to send. We could do with optimising this scan a bit. We aim
* to fill the queue totally or up to TX_THRESH_HI bytes. Once we hit
* TX_THRESH_LO we get called again
*
* FIXME: We should round robin between groups and in theory you can
* renegotiate DLCI priorities with optional stuff. Needs optimising.
*/
static void gsm_dlci_data_sweep(struct gsm_mux *gsm)
{
int len;
/* Priority ordering: We should do priority with RR of the groups */
int i = 1;
while (i < NUM_DLCI) {
struct gsm_dlci *dlci;
if (gsm->tx_bytes > TX_THRESH_HI)
break;
dlci = gsm->dlci[i];
if (dlci == NULL || dlci->constipated) {
i++;
continue;
}
if (dlci->adaption < 3 && !dlci->net)
len = gsm_dlci_data_output(gsm, dlci);
else
len = gsm_dlci_data_output_framed(gsm, dlci);
if (len < 0)
break;
/* DLCI empty - try the next */
if (len == 0)
i++;
}
}
/**
* gsm_dlci_data_kick - transmit if possible
* @dlci: DLCI to kick
*
* Transmit data from this DLCI if the queue is empty. We can't rely on
* a tty wakeup except when we filled the pipe so we need to fire off
* new data ourselves in other cases.
*/
static void gsm_dlci_data_kick(struct gsm_dlci *dlci)
{
unsigned long flags;
int sweep;
if (dlci->constipated)
return;
spin_lock_irqsave(&dlci->gsm->tx_lock, flags);
/* If we have nothing running then we need to fire up */
sweep = (dlci->gsm->tx_bytes < TX_THRESH_LO);
if (dlci->gsm->tx_bytes == 0) {
if (dlci->net)
gsm_dlci_data_output_framed(dlci->gsm, dlci);
else
gsm_dlci_data_output(dlci->gsm, dlci);
}
if (sweep)
gsm_dlci_data_sweep(dlci->gsm);
spin_unlock_irqrestore(&dlci->gsm->tx_lock, flags);
}
/*
* Control message processing
*/
/**
* gsm_control_reply - send a response frame to a control
* @gsm: gsm channel
* @cmd: the command to use
* @data: data to follow encoded info
* @dlen: length of data
*
* Encode up and queue a UI/UIH frame containing our response.
*/
static void gsm_control_reply(struct gsm_mux *gsm, int cmd, u8 *data,
int dlen)
{
struct gsm_msg *msg;
msg = gsm_data_alloc(gsm, 0, dlen + 2, gsm->ftype);
if (msg == NULL)
return;
msg->data[0] = (cmd & 0xFE) << 1 | EA; /* Clear C/R */
msg->data[1] = (dlen << 1) | EA;
memcpy(msg->data + 2, data, dlen);
gsm_data_queue(gsm->dlci[0], msg);
}
/**
* gsm_process_modem - process received modem status
* @tty: virtual tty bound to the DLCI
* @dlci: DLCI to affect
* @modem: modem bits (full EA)
*
* Used when a modem control message or line state inline in adaption
* layer 2 is processed. Sort out the local modem state and throttles
*/
static void gsm_process_modem(struct tty_struct *tty, struct gsm_dlci *dlci,
u32 modem, int clen)
{
int mlines = 0;
u8 brk = 0;
int fc;
/* The modem status command can either contain one octet (v.24 signals)
or two octets (v.24 signals + break signals). The length field will
either be 2 or 3 respectively. This is specified in section
5.4.6.3.7 of the 27.010 mux spec. */
if (clen == 2)
modem = modem & 0x7f;
else {
brk = modem & 0x7f;
modem = (modem >> 7) & 0x7f;
}
/* Flow control/ready to communicate */
fc = (modem & MDM_FC) || !(modem & MDM_RTR);
if (fc && !dlci->constipated) {
/* Need to throttle our output on this device */
dlci->constipated = 1;
} else if (!fc && dlci->constipated) {
dlci->constipated = 0;
gsm_dlci_data_kick(dlci);
}
/* Map modem bits */
if (modem & MDM_RTC)
mlines |= TIOCM_DSR | TIOCM_DTR;
if (modem & MDM_RTR)
mlines |= TIOCM_RTS | TIOCM_CTS;
if (modem & MDM_IC)
mlines |= TIOCM_RI;
if (modem & MDM_DV)
mlines |= TIOCM_CD;
/* Carrier drop -> hangup */
if (tty) {
if ((mlines & TIOCM_CD) == 0 && (dlci->modem_rx & TIOCM_CD))
if (!(tty->termios.c_cflag & CLOCAL))
tty_hangup(tty);
}
if (brk & 0x01)
tty_insert_flip_char(&dlci->port, 0, TTY_BREAK);
dlci->modem_rx = mlines;
}
/**
* gsm_control_modem - modem status received
* @gsm: GSM channel
* @data: data following command
* @clen: command length
*
* We have received a modem status control message. This is used by
* the GSM mux protocol to pass virtual modem line status and optionally
* to indicate break signals. Unpack it, convert to Linux representation
* and if need be stuff a break message down the tty.
*/
static void gsm_control_modem(struct gsm_mux *gsm, u8 *data, int clen)
{
unsigned int addr = 0;
unsigned int modem = 0;
unsigned int brk = 0;
struct gsm_dlci *dlci;
int len = clen;
u8 *dp = data;
struct tty_struct *tty;
while (gsm_read_ea(&addr, *dp++) == 0) {
len--;
if (len == 0)
return;
}
/* Must be at least one byte following the EA */
len--;
if (len <= 0)
return;
addr >>= 1;
/* Closed port, or invalid ? */
if (addr == 0 || addr >= NUM_DLCI || gsm->dlci[addr] == NULL)
return;
dlci = gsm->dlci[addr];
while (gsm_read_ea(&modem, *dp++) == 0) {
len--;
if (len == 0)
return;
}
len--;
if (len > 0) {
while (gsm_read_ea(&brk, *dp++) == 0) {
len--;
if (len == 0)
return;
}
modem <<= 7;
modem |= (brk & 0x7f);
}
tty = tty_port_tty_get(&dlci->port);
gsm_process_modem(tty, dlci, modem, clen);
if (tty) {
tty_wakeup(tty);
tty_kref_put(tty);
}
gsm_control_reply(gsm, CMD_MSC, data, clen);
}
/**
* gsm_control_rls - remote line status
* @gsm: GSM channel
* @data: data bytes
* @clen: data length
*
* The modem sends us a two byte message on the control channel whenever
* it wishes to send us an error state from the virtual link. Stuff
* this into the uplink tty if present
*/
static void gsm_control_rls(struct gsm_mux *gsm, u8 *data, int clen)
{
struct tty_port *port;
unsigned int addr = 0;
u8 bits;
int len = clen;
u8 *dp = data;
while (gsm_read_ea(&addr, *dp++) == 0) {
len--;
if (len == 0)
return;
}
/* Must be at least one byte following ea */
len--;
if (len <= 0)
return;
addr >>= 1;
/* Closed port, or invalid ? */
if (addr == 0 || addr >= NUM_DLCI || gsm->dlci[addr] == NULL)
return;
/* No error ? */
bits = *dp;
if ((bits & 1) == 0)
return;
port = &gsm->dlci[addr]->port;
if (bits & 2)
tty_insert_flip_char(port, 0, TTY_OVERRUN);
if (bits & 4)
tty_insert_flip_char(port, 0, TTY_PARITY);
if (bits & 8)
tty_insert_flip_char(port, 0, TTY_FRAME);
tty_flip_buffer_push(port);
gsm_control_reply(gsm, CMD_RLS, data, clen);
}
static void gsm_dlci_begin_close(struct gsm_dlci *dlci);
/**
* gsm_control_message - DLCI 0 control processing
* @gsm: our GSM mux
* @command: the command EA
* @data: data beyond the command/length EAs
* @clen: length
*
* Input processor for control messages from the other end of the link.
* Processes the incoming request and queues a response frame or an
* NSC response if not supported
*/
static void gsm_control_message(struct gsm_mux *gsm, unsigned int command,
u8 *data, int clen)
{
u8 buf[1];
unsigned long flags;
switch (command) {
case CMD_CLD: {
struct gsm_dlci *dlci = gsm->dlci[0];
/* Modem wishes to close down */
if (dlci) {
dlci->dead = 1;
gsm->dead = 1;
gsm_dlci_begin_close(dlci);
}
}
break;
case CMD_TEST:
/* Modem wishes to test, reply with the data */
gsm_control_reply(gsm, CMD_TEST, data, clen);
break;
case CMD_FCON:
/* Modem can accept data again */
gsm->constipated = 0;
gsm_control_reply(gsm, CMD_FCON, NULL, 0);
/* Kick the link in case it is idling */
spin_lock_irqsave(&gsm->tx_lock, flags);
gsm_data_kick(gsm);
spin_unlock_irqrestore(&gsm->tx_lock, flags);
break;
case CMD_FCOFF:
/* Modem wants us to STFU */
gsm->constipated = 1;
gsm_control_reply(gsm, CMD_FCOFF, NULL, 0);
break;
case CMD_MSC:
/* Out of band modem line change indicator for a DLCI */
gsm_control_modem(gsm, data, clen);
break;
case CMD_RLS:
/* Out of band error reception for a DLCI */
gsm_control_rls(gsm, data, clen);
break;
case CMD_PSC:
/* Modem wishes to enter power saving state */
gsm_control_reply(gsm, CMD_PSC, NULL, 0);
break;
/* Optional unsupported commands */
case CMD_PN: /* Parameter negotiation */
case CMD_RPN: /* Remote port negotiation */
case CMD_SNC: /* Service negotiation command */
default:
/* Reply to bad commands with an NSC */
buf[0] = command;
gsm_control_reply(gsm, CMD_NSC, buf, 1);
break;
}
}
/**
* gsm_control_response - process a response to our control
* @gsm: our GSM mux
* @command: the command (response) EA
* @data: data beyond the command/length EA
* @clen: length
*
* Process a response to an outstanding command. We only allow a single
* control message in flight so this is fairly easy. All the clean up
* is done by the caller, we just update the fields, flag it as done
* and return
*/
static void gsm_control_response(struct gsm_mux *gsm, unsigned int command,
u8 *data, int clen)
{
struct gsm_control *ctrl;
unsigned long flags;
spin_lock_irqsave(&gsm->control_lock, flags);
ctrl = gsm->pending_cmd;
/* Does the reply match our command */
command |= 1;
if (ctrl != NULL && (command == ctrl->cmd || command == CMD_NSC)) {
/* Our command was replied to, kill the retry timer */
del_timer(&gsm->t2_timer);
gsm->pending_cmd = NULL;
/* Rejected by the other end */
if (command == CMD_NSC)
ctrl->error = -EOPNOTSUPP;
ctrl->done = 1;
wake_up(&gsm->event);
}
spin_unlock_irqrestore(&gsm->control_lock, flags);
}
/**
* gsm_control_transmit - send control packet
* @gsm: gsm mux
* @ctrl: frame to send
*
* Send out a pending control command (called under control lock)
*/
static void gsm_control_transmit(struct gsm_mux *gsm, struct gsm_control *ctrl)
{
struct gsm_msg *msg = gsm_data_alloc(gsm, 0, ctrl->len + 1, gsm->ftype);
if (msg == NULL)
return;
msg->data[0] = (ctrl->cmd << 1) | 2 | EA; /* command */
memcpy(msg->data + 1, ctrl->data, ctrl->len);
gsm_data_queue(gsm->dlci[0], msg);
}
/**
* gsm_control_retransmit - retransmit a control frame
* @data: pointer to our gsm object
*
* Called off the T2 timer expiry in order to retransmit control frames
* that have been lost in the system somewhere. The control_lock protects
* us from colliding with another sender or a receive completion event.
* In that situation the timer may still occur in a small window but
* gsm->pending_cmd will be NULL and we just let the timer expire.
*/
static void gsm_control_retransmit(unsigned long data)
{
struct gsm_mux *gsm = (struct gsm_mux *)data;
struct gsm_control *ctrl;
unsigned long flags;
spin_lock_irqsave(&gsm->control_lock, flags);
ctrl = gsm->pending_cmd;
if (ctrl) {
gsm->cretries--;
if (gsm->cretries == 0) {
gsm->pending_cmd = NULL;
ctrl->error = -ETIMEDOUT;
ctrl->done = 1;
spin_unlock_irqrestore(&gsm->control_lock, flags);
wake_up(&gsm->event);
return;
}
gsm_control_transmit(gsm, ctrl);
mod_timer(&gsm->t2_timer, jiffies + gsm->t2 * HZ / 100);
}
spin_unlock_irqrestore(&gsm->control_lock, flags);
}
/**
* gsm_control_send - send a control frame on DLCI 0
* @gsm: the GSM channel
* @command: command to send including CR bit
* @data: bytes of data (must be kmalloced)
* @len: length of the block to send
*
* Queue and dispatch a control command. Only one command can be
* active at a time. In theory more can be outstanding but the matching
* gets really complicated so for now stick to one outstanding.
*/
static struct gsm_control *gsm_control_send(struct gsm_mux *gsm,
unsigned int command, u8 *data, int clen)
{
struct gsm_control *ctrl = kzalloc(sizeof(struct gsm_control),
GFP_KERNEL);
unsigned long flags;
if (ctrl == NULL)
return NULL;
retry:
wait_event(gsm->event, gsm->pending_cmd == NULL);
spin_lock_irqsave(&gsm->control_lock, flags);
if (gsm->pending_cmd != NULL) {
spin_unlock_irqrestore(&gsm->control_lock, flags);
goto retry;
}
ctrl->cmd = command;
ctrl->data = data;
ctrl->len = clen;
gsm->pending_cmd = ctrl;
gsm->cretries = gsm->n2;
mod_timer(&gsm->t2_timer, jiffies + gsm->t2 * HZ / 100);
gsm_control_transmit(gsm, ctrl);
spin_unlock_irqrestore(&gsm->control_lock, flags);
return ctrl;
}
/**
* gsm_control_wait - wait for a control to finish
* @gsm: GSM mux
* @control: control we are waiting on
*
* Waits for the control to complete or time out. Frees any used
* resources and returns 0 for success, or an error if the remote
* rejected or ignored the request.
*/
static int gsm_control_wait(struct gsm_mux *gsm, struct gsm_control *control)
{
int err;
wait_event(gsm->event, control->done == 1);
err = control->error;
kfree(control);
return err;
}
/*
* DLCI level handling: Needs krefs
*/
/*
* State transitions and timers
*/
/**
* gsm_dlci_close - a DLCI has closed
* @dlci: DLCI that closed
*
* Perform processing when moving a DLCI into closed state. If there
* is an attached tty this is hung up
*/
static void gsm_dlci_close(struct gsm_dlci *dlci)
{
del_timer(&dlci->t1);
if (debug & 8)
pr_debug("DLCI %d goes closed.\n", dlci->addr);
dlci->state = DLCI_CLOSED;
if (dlci->addr != 0) {
tty_port_tty_hangup(&dlci->port, false);
kfifo_reset(dlci->fifo);
} else
dlci->gsm->dead = 1;
wake_up(&dlci->gsm->event);
/* A DLCI 0 close is a MUX termination so we need to kick that
back to userspace somehow */
}
/**
* gsm_dlci_open - a DLCI has opened
* @dlci: DLCI that opened
*
* Perform processing when moving a DLCI into open state.
*/
static void gsm_dlci_open(struct gsm_dlci *dlci)
{
/* Note that SABM UA .. SABM UA first UA lost can mean that we go
open -> open */
del_timer(&dlci->t1);
/* This will let a tty open continue */
dlci->state = DLCI_OPEN;
if (debug & 8)
pr_debug("DLCI %d goes open.\n", dlci->addr);
wake_up(&dlci->gsm->event);
}
/**
* gsm_dlci_t1 - T1 timer expiry
* @dlci: DLCI that opened
*
* The T1 timer handles retransmits of control frames (essentially of
* SABM and DISC). We resend the command until the retry count runs out
* in which case an opening port goes back to closed and a closing port
* is simply put into closed state (any further frames from the other
* end will get a DM response)
*/
static void gsm_dlci_t1(unsigned long data)
{
struct gsm_dlci *dlci = (struct gsm_dlci *)data;
struct gsm_mux *gsm = dlci->gsm;
switch (dlci->state) {
case DLCI_OPENING:
dlci->retries--;
if (dlci->retries) {
gsm_command(dlci->gsm, dlci->addr, SABM|PF);
mod_timer(&dlci->t1, jiffies + gsm->t1 * HZ / 100);
} else
gsm_dlci_close(dlci);
break;
case DLCI_CLOSING:
dlci->retries--;
if (dlci->retries) {
gsm_command(dlci->gsm, dlci->addr, DISC|PF);
mod_timer(&dlci->t1, jiffies + gsm->t1 * HZ / 100);
} else
gsm_dlci_close(dlci);
break;
}
}
/**
* gsm_dlci_begin_open - start channel open procedure
* @dlci: DLCI to open
*
* Commence opening a DLCI from the Linux side. We issue SABM messages
* to the modem which should then reply with a UA, at which point we
* will move into open state. Opening is done asynchronously with retry
* running off timers and the responses.
*/
static void gsm_dlci_begin_open(struct gsm_dlci *dlci)
{
struct gsm_mux *gsm = dlci->gsm;
if (dlci->state == DLCI_OPEN || dlci->state == DLCI_OPENING)
return;
dlci->retries = gsm->n2;
dlci->state = DLCI_OPENING;
gsm_command(dlci->gsm, dlci->addr, SABM|PF);
mod_timer(&dlci->t1, jiffies + gsm->t1 * HZ / 100);
}
/**
* gsm_dlci_begin_close - start channel open procedure
* @dlci: DLCI to open
*
* Commence closing a DLCI from the Linux side. We issue DISC messages
* to the modem which should then reply with a UA, at which point we
* will move into closed state. Closing is done asynchronously with retry
* off timers. We may also receive a DM reply from the other end which
* indicates the channel was already closed.
*/
static void gsm_dlci_begin_close(struct gsm_dlci *dlci)
{
struct gsm_mux *gsm = dlci->gsm;
if (dlci->state == DLCI_CLOSED || dlci->state == DLCI_CLOSING)
return;
dlci->retries = gsm->n2;
dlci->state = DLCI_CLOSING;
gsm_command(dlci->gsm, dlci->addr, DISC|PF);
mod_timer(&dlci->t1, jiffies + gsm->t1 * HZ / 100);
}
/**
* gsm_dlci_data - data arrived
* @dlci: channel
* @data: block of bytes received
* @len: length of received block
*
* A UI or UIH frame has arrived which contains data for a channel
* other than the control channel. If the relevant virtual tty is
* open we shovel the bits down it, if not we drop them.
*/
static void gsm_dlci_data(struct gsm_dlci *dlci, u8 *data, int clen)
{
/* krefs .. */
struct tty_port *port = &dlci->port;
struct tty_struct *tty;
unsigned int modem = 0;
int len = clen;
if (debug & 16)
pr_debug("%d bytes for tty\n", len);
switch (dlci->adaption) {
/* Unsupported types */
/* Packetised interruptible data */
case 4:
break;
/* Packetised uininterruptible voice/data */
case 3:
break;
/* Asynchronous serial with line state in each frame */
case 2:
while (gsm_read_ea(&modem, *data++) == 0) {
len--;
if (len == 0)
return;
}
tty = tty_port_tty_get(port);
if (tty) {
gsm_process_modem(tty, dlci, modem, clen);
tty_kref_put(tty);
}
/* Line state will go via DLCI 0 controls only */
case 1:
default:
tty_insert_flip_string(port, data, len);
tty_flip_buffer_push(port);
}
}
/**
* gsm_dlci_control - data arrived on control channel
* @dlci: channel
* @data: block of bytes received
* @len: length of received block
*
* A UI or UIH frame has arrived which contains data for DLCI 0 the
* control channel. This should contain a command EA followed by
* control data bytes. The command EA contains a command/response bit
* and we divide up the work accordingly.
*/
static void gsm_dlci_command(struct gsm_dlci *dlci, u8 *data, int len)
{
/* See what command is involved */
unsigned int command = 0;
while (len-- > 0) {
if (gsm_read_ea(&command, *data++) == 1) {
int clen = *data++;
len--;
/* FIXME: this is properly an EA */
clen >>= 1;
/* Malformed command ? */
if (clen > len)
return;
if (command & 1)
gsm_control_message(dlci->gsm, command,
data, clen);
else
gsm_control_response(dlci->gsm, command,
data, clen);
return;
}
}
}
/*
* Allocate/Free DLCI channels
*/
/**
* gsm_dlci_alloc - allocate a DLCI
* @gsm: GSM mux
* @addr: address of the DLCI
*
* Allocate and install a new DLCI object into the GSM mux.
*
* FIXME: review locking races
*/
static struct gsm_dlci *gsm_dlci_alloc(struct gsm_mux *gsm, int addr)
{
struct gsm_dlci *dlci = kzalloc(sizeof(struct gsm_dlci), GFP_ATOMIC);
if (dlci == NULL)
return NULL;
spin_lock_init(&dlci->lock);
mutex_init(&dlci->mutex);
dlci->fifo = &dlci->_fifo;
if (kfifo_alloc(&dlci->_fifo, 4096, GFP_KERNEL) < 0) {
kfree(dlci);
return NULL;
}
skb_queue_head_init(&dlci->skb_list);
init_timer(&dlci->t1);
dlci->t1.function = gsm_dlci_t1;
dlci->t1.data = (unsigned long)dlci;
tty_port_init(&dlci->port);
dlci->port.ops = &gsm_port_ops;
dlci->gsm = gsm;
dlci->addr = addr;
dlci->adaption = gsm->adaption;
dlci->state = DLCI_CLOSED;
if (addr)
dlci->data = gsm_dlci_data;
else
dlci->data = gsm_dlci_command;
gsm->dlci[addr] = dlci;
return dlci;
}
/**
* gsm_dlci_free - free DLCI
* @dlci: DLCI to free
*
* Free up a DLCI.
*
* Can sleep.
*/
static void gsm_dlci_free(struct tty_port *port)
{
struct gsm_dlci *dlci = container_of(port, struct gsm_dlci, port);
del_timer_sync(&dlci->t1);
dlci->gsm->dlci[dlci->addr] = NULL;
kfifo_free(dlci->fifo);
while ((dlci->skb = skb_dequeue(&dlci->skb_list)))
dev_kfree_skb(dlci->skb);
kfree(dlci);
}
static inline void dlci_get(struct gsm_dlci *dlci)
{
tty_port_get(&dlci->port);
}
static inline void dlci_put(struct gsm_dlci *dlci)
{
tty_port_put(&dlci->port);
}
static void gsm_destroy_network(struct gsm_dlci *dlci);
/**
* gsm_dlci_release - release DLCI
* @dlci: DLCI to destroy
*
* Release a DLCI. Actual free is deferred until either
* mux is closed or tty is closed - whichever is last.
*
* Can sleep.
*/
static void gsm_dlci_release(struct gsm_dlci *dlci)
{
struct tty_struct *tty = tty_port_tty_get(&dlci->port);
if (tty) {
mutex_lock(&dlci->mutex);
gsm_destroy_network(dlci);
mutex_unlock(&dlci->mutex);
tty_vhangup(tty);
tty_port_tty_set(&dlci->port, NULL);
tty_kref_put(tty);
}
dlci->state = DLCI_CLOSED;
dlci_put(dlci);
}
/*
* LAPBish link layer logic
*/
/**
* gsm_queue - a GSM frame is ready to process
* @gsm: pointer to our gsm mux
*
* At this point in time a frame has arrived and been demangled from
* the line encoding. All the differences between the encodings have
* been handled below us and the frame is unpacked into the structures.
* The fcs holds the header FCS but any data FCS must be added here.
*/
static void gsm_queue(struct gsm_mux *gsm)
{
struct gsm_dlci *dlci;
u8 cr;
int address;
/* We have to sneak a look at the packet body to do the FCS.
A somewhat layering violation in the spec */
if ((gsm->control & ~PF) == UI)
gsm->fcs = gsm_fcs_add_block(gsm->fcs, gsm->buf, gsm->len);
if (gsm->encoding == 0) {
/* WARNING: gsm->received_fcs is used for
gsm->encoding = 0 only.
In this case it contain the last piece of data
required to generate final CRC */
gsm->fcs = gsm_fcs_add(gsm->fcs, gsm->received_fcs);
}
if (gsm->fcs != GOOD_FCS) {
gsm->bad_fcs++;
if (debug & 4)
pr_debug("BAD FCS %02x\n", gsm->fcs);
return;
}
address = gsm->address >> 1;
if (address >= NUM_DLCI)
goto invalid;
cr = gsm->address & 1; /* C/R bit */
gsm_print_packet("<--", address, cr, gsm->control, gsm->buf, gsm->len);
cr ^= 1 - gsm->initiator; /* Flip so 1 always means command */
dlci = gsm->dlci[address];
switch (gsm->control) {
case SABM|PF:
if (cr == 0)
goto invalid;
if (dlci == NULL)
dlci = gsm_dlci_alloc(gsm, address);
if (dlci == NULL)
return;
if (dlci->dead)
gsm_response(gsm, address, DM);
else {
gsm_response(gsm, address, UA);
gsm_dlci_open(dlci);
}
break;
case DISC|PF:
if (cr == 0)
goto invalid;
if (dlci == NULL || dlci->state == DLCI_CLOSED) {
gsm_response(gsm, address, DM);
return;
}
/* Real close complete */
gsm_response(gsm, address, UA);
gsm_dlci_close(dlci);
break;
case UA:
case UA|PF:
if (cr == 0 || dlci == NULL)
break;
switch (dlci->state) {
case DLCI_CLOSING:
gsm_dlci_close(dlci);
break;
case DLCI_OPENING:
gsm_dlci_open(dlci);
break;
}
break;
case DM: /* DM can be valid unsolicited */
case DM|PF:
if (cr)
goto invalid;
if (dlci == NULL)
return;
gsm_dlci_close(dlci);
break;
case UI:
case UI|PF:
case UIH:
case UIH|PF:
#if 0
if (cr)
goto invalid;
#endif
if (dlci == NULL || dlci->state != DLCI_OPEN) {
gsm_command(gsm, address, DM|PF);
return;
}
dlci->data(dlci, gsm->buf, gsm->len);
break;
default:
goto invalid;
}
return;
invalid:
gsm->malformed++;
return;
}
/**
* gsm0_receive - perform processing for non-transparency
* @gsm: gsm data for this ldisc instance
* @c: character
*
* Receive bytes in gsm mode 0
*/
static void gsm0_receive(struct gsm_mux *gsm, unsigned char c)
{
unsigned int len;
switch (gsm->state) {
case GSM_SEARCH: /* SOF marker */
if (c == GSM0_SOF) {
gsm->state = GSM_ADDRESS;
gsm->address = 0;
gsm->len = 0;
gsm->fcs = INIT_FCS;
}
break;
case GSM_ADDRESS: /* Address EA */
gsm->fcs = gsm_fcs_add(gsm->fcs, c);
if (gsm_read_ea(&gsm->address, c))
gsm->state = GSM_CONTROL;
break;
case GSM_CONTROL: /* Control Byte */
gsm->fcs = gsm_fcs_add(gsm->fcs, c);
gsm->control = c;
gsm->state = GSM_LEN0;
break;
case GSM_LEN0: /* Length EA */
gsm->fcs = gsm_fcs_add(gsm->fcs, c);
if (gsm_read_ea(&gsm->len, c)) {
if (gsm->len > gsm->mru) {
gsm->bad_size++;
gsm->state = GSM_SEARCH;
break;
}
gsm->count = 0;
if (!gsm->len)
gsm->state = GSM_FCS;
else
gsm->state = GSM_DATA;
break;
}
gsm->state = GSM_LEN1;
break;
case GSM_LEN1:
gsm->fcs = gsm_fcs_add(gsm->fcs, c);
len = c;
gsm->len |= len << 7;
if (gsm->len > gsm->mru) {
gsm->bad_size++;
gsm->state = GSM_SEARCH;
break;
}
gsm->count = 0;
if (!gsm->len)
gsm->state = GSM_FCS;
else
gsm->state = GSM_DATA;
break;
case GSM_DATA: /* Data */
gsm->buf[gsm->count++] = c;
if (gsm->count == gsm->len)
gsm->state = GSM_FCS;
break;
case GSM_FCS: /* FCS follows the packet */
gsm->received_fcs = c;
gsm_queue(gsm);
gsm->state = GSM_SSOF;
break;
case GSM_SSOF:
if (c == GSM0_SOF) {
gsm->state = GSM_SEARCH;
break;
}
break;
}
}
/**
* gsm1_receive - perform processing for non-transparency
* @gsm: gsm data for this ldisc instance
* @c: character
*
* Receive bytes in mode 1 (Advanced option)
*/
static void gsm1_receive(struct gsm_mux *gsm, unsigned char c)
{
if (c == GSM1_SOF) {
/* EOF is only valid in frame if we have got to the data state
and received at least one byte (the FCS) */
if (gsm->state == GSM_DATA && gsm->count) {
/* Extract the FCS */
gsm->count--;
gsm->fcs = gsm_fcs_add(gsm->fcs, gsm->buf[gsm->count]);
gsm->len = gsm->count;
gsm_queue(gsm);
gsm->state = GSM_START;
return;
}
/* Any partial frame was a runt so go back to start */
if (gsm->state != GSM_START) {
gsm->malformed++;
gsm->state = GSM_START;
}
/* A SOF in GSM_START means we are still reading idling or
framing bytes */
return;
}
if (c == GSM1_ESCAPE) {
gsm->escape = 1;
return;
}
/* Only an unescaped SOF gets us out of GSM search */
if (gsm->state == GSM_SEARCH)
return;
if (gsm->escape) {
c ^= GSM1_ESCAPE_BITS;
gsm->escape = 0;
}
switch (gsm->state) {
case GSM_START: /* First byte after SOF */
gsm->address = 0;
gsm->state = GSM_ADDRESS;
gsm->fcs = INIT_FCS;
/* Drop through */
case GSM_ADDRESS: /* Address continuation */
gsm->fcs = gsm_fcs_add(gsm->fcs, c);
if (gsm_read_ea(&gsm->address, c))
gsm->state = GSM_CONTROL;
break;
case GSM_CONTROL: /* Control Byte */
gsm->fcs = gsm_fcs_add(gsm->fcs, c);
gsm->control = c;
gsm->count = 0;
gsm->state = GSM_DATA;
break;
case GSM_DATA: /* Data */
if (gsm->count > gsm->mru) { /* Allow one for the FCS */
gsm->state = GSM_OVERRUN;
gsm->bad_size++;
} else
gsm->buf[gsm->count++] = c;
break;
case GSM_OVERRUN: /* Over-long - eg a dropped SOF */
break;
}
}
/**
* gsm_error - handle tty error
* @gsm: ldisc data
* @data: byte received (may be invalid)
* @flag: error received
*
* Handle an error in the receipt of data for a frame. Currently we just
* go back to hunting for a SOF.
*
* FIXME: better diagnostics ?
*/
static void gsm_error(struct gsm_mux *gsm,
unsigned char data, unsigned char flag)
{
gsm->state = GSM_SEARCH;
gsm->io_error++;
}
/**
* gsm_cleanup_mux - generic GSM protocol cleanup
* @gsm: our mux
*
* Clean up the bits of the mux which are the same for all framing
* protocols. Remove the mux from the mux table, stop all the timers
* and then shut down each device hanging up the channels as we go.
*/
static void gsm_cleanup_mux(struct gsm_mux *gsm)
{
int i;
struct gsm_dlci *dlci = gsm->dlci[0];
struct gsm_msg *txq, *ntxq;
struct gsm_control *gc;
gsm->dead = 1;
spin_lock(&gsm_mux_lock);
for (i = 0; i < MAX_MUX; i++) {
if (gsm_mux[i] == gsm) {
gsm_mux[i] = NULL;
break;
}
}
spin_unlock(&gsm_mux_lock);
WARN_ON(i == MAX_MUX);
/* In theory disconnecting DLCI 0 is sufficient but for some
modems this is apparently not the case. */
if (dlci) {
gc = gsm_control_send(gsm, CMD_CLD, NULL, 0);
if (gc)
gsm_control_wait(gsm, gc);
}
del_timer_sync(&gsm->t2_timer);
/* Now we are sure T2 has stopped */
if (dlci) {
dlci->dead = 1;
gsm_dlci_begin_close(dlci);
wait_event_interruptible(gsm->event,
dlci->state == DLCI_CLOSED);
}
/* Free up any link layer users */
mutex_lock(&gsm->mutex);
for (i = 0; i < NUM_DLCI; i++)
if (gsm->dlci[i])
gsm_dlci_release(gsm->dlci[i]);
mutex_unlock(&gsm->mutex);
/* Now wipe the queues */
list_for_each_entry_safe(txq, ntxq, &gsm->tx_list, list)
kfree(txq);
INIT_LIST_HEAD(&gsm->tx_list);
}
/**
* gsm_activate_mux - generic GSM setup
* @gsm: our mux
*
* Set up the bits of the mux which are the same for all framing
* protocols. Add the mux to the mux table so it can be opened and
* finally kick off connecting to DLCI 0 on the modem.
*/
static int gsm_activate_mux(struct gsm_mux *gsm)
{
struct gsm_dlci *dlci;
int i = 0;
setup_timer(&gsm->t2_timer, gsm_control_retransmit, (unsigned long)gsm);
init_waitqueue_head(&gsm->event);
spin_lock_init(&gsm->control_lock);
spin_lock_init(&gsm->tx_lock);
if (gsm->encoding == 0)
gsm->receive = gsm0_receive;
else
gsm->receive = gsm1_receive;
gsm->error = gsm_error;
spin_lock(&gsm_mux_lock);
for (i = 0; i < MAX_MUX; i++) {
if (gsm_mux[i] == NULL) {
gsm->num = i;
gsm_mux[i] = gsm;
break;
}
}
spin_unlock(&gsm_mux_lock);
if (i == MAX_MUX)
return -EBUSY;
dlci = gsm_dlci_alloc(gsm, 0);
if (dlci == NULL)
return -ENOMEM;
gsm->dead = 0; /* Tty opens are now permissible */
return 0;
}
/**
* gsm_free_mux - free up a mux
* @mux: mux to free
*
* Dispose of allocated resources for a dead mux
*/
static void gsm_free_mux(struct gsm_mux *gsm)
{
kfree(gsm->txframe);
kfree(gsm->buf);
kfree(gsm);
}
/**
* gsm_free_muxr - free up a mux
* @mux: mux to free
*
* Dispose of allocated resources for a dead mux
*/
static void gsm_free_muxr(struct kref *ref)
{
struct gsm_mux *gsm = container_of(ref, struct gsm_mux, ref);
gsm_free_mux(gsm);
}
static inline void mux_get(struct gsm_mux *gsm)
{
kref_get(&gsm->ref);
}
static inline void mux_put(struct gsm_mux *gsm)
{
kref_put(&gsm->ref, gsm_free_muxr);
}
/**
* gsm_alloc_mux - allocate a mux
*
* Creates a new mux ready for activation.
*/
static struct gsm_mux *gsm_alloc_mux(void)
{
struct gsm_mux *gsm = kzalloc(sizeof(struct gsm_mux), GFP_KERNEL);
if (gsm == NULL)
return NULL;
gsm->buf = kmalloc(MAX_MRU + 1, GFP_KERNEL);
if (gsm->buf == NULL) {
kfree(gsm);
return NULL;
}
gsm->txframe = kmalloc(2 * MAX_MRU + 2, GFP_KERNEL);
if (gsm->txframe == NULL) {
kfree(gsm->buf);
kfree(gsm);
return NULL;
}
spin_lock_init(&gsm->lock);
mutex_init(&gsm->mutex);
kref_init(&gsm->ref);
INIT_LIST_HEAD(&gsm->tx_list);
gsm->t1 = T1;
gsm->t2 = T2;
gsm->n2 = N2;
gsm->ftype = UIH;
gsm->adaption = 1;
gsm->encoding = 1;
gsm->mru = 64; /* Default to encoding 1 so these should be 64 */
gsm->mtu = 64;
gsm->dead = 1; /* Avoid early tty opens */
return gsm;
}
/**
* gsmld_output - write to link
* @gsm: our mux
* @data: bytes to output
* @len: size
*
* Write a block of data from the GSM mux to the data channel. This
* will eventually be serialized from above but at the moment isn't.
*/
static int gsmld_output(struct gsm_mux *gsm, u8 *data, int len)
{
if (tty_write_room(gsm->tty) < len) {
set_bit(TTY_DO_WRITE_WAKEUP, &gsm->tty->flags);
return -ENOSPC;
}
if (debug & 4)
print_hex_dump_bytes("gsmld_output: ", DUMP_PREFIX_OFFSET,
data, len);
gsm->tty->ops->write(gsm->tty, data, len);
return len;
}
/**
* gsmld_attach_gsm - mode set up
* @tty: our tty structure
* @gsm: our mux
*
* Set up the MUX for basic mode and commence connecting to the
* modem. Currently called from the line discipline set up but
* will need moving to an ioctl path.
*/
static int gsmld_attach_gsm(struct tty_struct *tty, struct gsm_mux *gsm)
{
int ret, i, base;
gsm->tty = tty_kref_get(tty);
gsm->output = gsmld_output;
ret = gsm_activate_mux(gsm);
if (ret != 0)
tty_kref_put(gsm->tty);
else {
/* Don't register device 0 - this is the control channel and not
a usable tty interface */
base = gsm->num << 6; /* Base for this MUX */
for (i = 1; i < NUM_DLCI; i++)
tty_register_device(gsm_tty_driver, base + i, NULL);
}
return ret;
}
/**
* gsmld_detach_gsm - stop doing 0710 mux
* @tty: tty attached to the mux
* @gsm: mux
*
* Shutdown and then clean up the resources used by the line discipline
*/
static void gsmld_detach_gsm(struct tty_struct *tty, struct gsm_mux *gsm)
{
int i;
int base = gsm->num << 6; /* Base for this MUX */
WARN_ON(tty != gsm->tty);
for (i = 1; i < NUM_DLCI; i++)
tty_unregister_device(gsm_tty_driver, base + i);
gsm_cleanup_mux(gsm);
tty_kref_put(gsm->tty);
gsm->tty = NULL;
}
static void gsmld_receive_buf(struct tty_struct *tty, const unsigned char *cp,
char *fp, int count)
{
struct gsm_mux *gsm = tty->disc_data;
const unsigned char *dp;
char *f;
int i;
char flags = TTY_NORMAL;
if (debug & 4)
print_hex_dump_bytes("gsmld_receive: ", DUMP_PREFIX_OFFSET,
cp, count);
for (i = count, dp = cp, f = fp; i; i--, dp++) {
if (f)
flags = *f++;
switch (flags) {
case TTY_NORMAL:
gsm->receive(gsm, *dp);
break;
case TTY_OVERRUN:
case TTY_BREAK:
case TTY_PARITY:
case TTY_FRAME:
gsm->error(gsm, *dp, flags);
break;
default:
WARN_ONCE(1, "%s: unknown flag %d\n",
tty_name(tty), flags);
break;
}
}
/* FASYNC if needed ? */
/* If clogged call tty_throttle(tty); */
}
/**
* gsmld_chars_in_buffer - report available bytes
* @tty: tty device
*
* Report the number of characters buffered to be delivered to user
* at this instant in time.
*
* Locking: gsm lock
*/
static ssize_t gsmld_chars_in_buffer(struct tty_struct *tty)
{
return 0;
}
/**
* gsmld_flush_buffer - clean input queue
* @tty: terminal device
*
* Flush the input buffer. Called when the line discipline is
* being closed, when the tty layer wants the buffer flushed (eg
* at hangup).
*/
static void gsmld_flush_buffer(struct tty_struct *tty)
{
}
/**
* gsmld_close - close the ldisc for this tty
* @tty: device
*
* Called from the terminal layer when this line discipline is
* being shut down, either because of a close or becsuse of a
* discipline change. The function will not be called while other
* ldisc methods are in progress.
*/
static void gsmld_close(struct tty_struct *tty)
{
struct gsm_mux *gsm = tty->disc_data;
gsmld_detach_gsm(tty, gsm);
gsmld_flush_buffer(tty);
/* Do other clean up here */
mux_put(gsm);
}
/**
* gsmld_open - open an ldisc
* @tty: terminal to open
*
* Called when this line discipline is being attached to the
* terminal device. Can sleep. Called serialized so that no
* other events will occur in parallel. No further open will occur
* until a close.
*/
static int gsmld_open(struct tty_struct *tty)
{
struct gsm_mux *gsm;
int ret;
if (tty->ops->write == NULL)
return -EINVAL;
/* Attach our ldisc data */
gsm = gsm_alloc_mux();
if (gsm == NULL)
return -ENOMEM;
tty->disc_data = gsm;
tty->receive_room = 65536;
/* Attach the initial passive connection */
gsm->encoding = 1;
ret = gsmld_attach_gsm(tty, gsm);
if (ret != 0) {
gsm_cleanup_mux(gsm);
mux_put(gsm);
}
return ret;
}
/**
* gsmld_write_wakeup - asynchronous I/O notifier
* @tty: tty device
*
* Required for the ptys, serial driver etc. since processes
* that attach themselves to the master and rely on ASYNC
* IO must be woken up
*/
static void gsmld_write_wakeup(struct tty_struct *tty)
{
struct gsm_mux *gsm = tty->disc_data;
unsigned long flags;
/* Queue poll */
clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
spin_lock_irqsave(&gsm->tx_lock, flags);
gsm_data_kick(gsm);
if (gsm->tx_bytes < TX_THRESH_LO) {
gsm_dlci_data_sweep(gsm);
}
spin_unlock_irqrestore(&gsm->tx_lock, flags);
}
/**
* gsmld_read - read function for tty
* @tty: tty device
* @file: file object
* @buf: userspace buffer pointer
* @nr: size of I/O
*
* Perform reads for the line discipline. We are guaranteed that the
* line discipline will not be closed under us but we may get multiple
* parallel readers and must handle this ourselves. We may also get
* a hangup. Always called in user context, may sleep.
*
* This code must be sure never to sleep through a hangup.
*/
static ssize_t gsmld_read(struct tty_struct *tty, struct file *file,
unsigned char __user *buf, size_t nr)
{
return -EOPNOTSUPP;
}
/**
* gsmld_write - write function for tty
* @tty: tty device
* @file: file object
* @buf: userspace buffer pointer
* @nr: size of I/O
*
* Called when the owner of the device wants to send a frame
* itself (or some other control data). The data is transferred
* as-is and must be properly framed and checksummed as appropriate
* by userspace. Frames are either sent whole or not at all as this
* avoids pain user side.
*/
static ssize_t gsmld_write(struct tty_struct *tty, struct file *file,
const unsigned char *buf, size_t nr)
{
int space = tty_write_room(tty);
if (space >= nr)
return tty->ops->write(tty, buf, nr);
set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
return -ENOBUFS;
}
/**
* gsmld_poll - poll method for N_GSM0710
* @tty: terminal device
* @file: file accessing it
* @wait: poll table
*
* Called when the line discipline is asked to poll() for data or
* for special events. This code is not serialized with respect to
* other events save open/close.
*
* This code must be sure never to sleep through a hangup.
* Called without the kernel lock held - fine
*/
static unsigned int gsmld_poll(struct tty_struct *tty, struct file *file,
poll_table *wait)
{
unsigned int mask = 0;
struct gsm_mux *gsm = tty->disc_data;
poll_wait(file, &tty->read_wait, wait);
poll_wait(file, &tty->write_wait, wait);
if (tty_hung_up_p(file))
mask |= POLLHUP;
if (!tty_is_writelocked(tty) && tty_write_room(tty) > 0)
mask |= POLLOUT | POLLWRNORM;
if (gsm->dead)
mask |= POLLHUP;
return mask;
}
static int gsmld_config(struct tty_struct *tty, struct gsm_mux *gsm,
struct gsm_config *c)
{
int need_close = 0;
int need_restart = 0;
/* Stuff we don't support yet - UI or I frame transport, windowing */
if ((c->adaption != 1 && c->adaption != 2) || c->k)
return -EOPNOTSUPP;
/* Check the MRU/MTU range looks sane */
if (c->mru > MAX_MRU || c->mtu > MAX_MTU || c->mru < 8 || c->mtu < 8)
return -EINVAL;
if (c->n2 < 3)
return -EINVAL;
if (c->encapsulation > 1) /* Basic, advanced, no I */
return -EINVAL;
if (c->initiator > 1)
return -EINVAL;
if (c->i == 0 || c->i > 2) /* UIH and UI only */
return -EINVAL;
/*
* See what is needed for reconfiguration
*/
/* Timing fields */
if (c->t1 != 0 && c->t1 != gsm->t1)
need_restart = 1;
if (c->t2 != 0 && c->t2 != gsm->t2)
need_restart = 1;
if (c->encapsulation != gsm->encoding)
need_restart = 1;
if (c->adaption != gsm->adaption)
need_restart = 1;
/* Requires care */
if (c->initiator != gsm->initiator)
need_close = 1;
if (c->mru != gsm->mru)
need_restart = 1;
if (c->mtu != gsm->mtu)
need_restart = 1;
/*
* Close down what is needed, restart and initiate the new
* configuration
*/
if (need_close || need_restart) {
gsm_dlci_begin_close(gsm->dlci[0]);
/* This will timeout if the link is down due to N2 expiring */
wait_event_interruptible(gsm->event,
gsm->dlci[0]->state == DLCI_CLOSED);
if (signal_pending(current))
return -EINTR;
}
if (need_restart)
gsm_cleanup_mux(gsm);
gsm->initiator = c->initiator;
gsm->mru = c->mru;
gsm->mtu = c->mtu;
gsm->encoding = c->encapsulation;
gsm->adaption = c->adaption;
gsm->n2 = c->n2;
if (c->i == 1)
gsm->ftype = UIH;
else if (c->i == 2)
gsm->ftype = UI;
if (c->t1)
gsm->t1 = c->t1;
if (c->t2)
gsm->t2 = c->t2;
/* FIXME: We need to separate activation/deactivation from adding
and removing from the mux array */
if (need_restart)
gsm_activate_mux(gsm);
if (gsm->initiator && need_close)
gsm_dlci_begin_open(gsm->dlci[0]);
return 0;
}
static int gsmld_ioctl(struct tty_struct *tty, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct gsm_config c;
struct gsm_mux *gsm = tty->disc_data;
switch (cmd) {
case GSMIOC_GETCONF:
memset(&c, 0, sizeof(c));
c.adaption = gsm->adaption;
c.encapsulation = gsm->encoding;
c.initiator = gsm->initiator;
c.t1 = gsm->t1;
c.t2 = gsm->t2;
c.t3 = 0; /* Not supported */
c.n2 = gsm->n2;
if (gsm->ftype == UIH)
c.i = 1;
else
c.i = 2;
pr_debug("Ftype %d i %d\n", gsm->ftype, c.i);
c.mru = gsm->mru;
c.mtu = gsm->mtu;
c.k = 0;
if (copy_to_user((void *)arg, &c, sizeof(c)))
return -EFAULT;
return 0;
case GSMIOC_SETCONF:
if (copy_from_user(&c, (void *)arg, sizeof(c)))
return -EFAULT;
return gsmld_config(tty, gsm, &c);
default:
return n_tty_ioctl_helper(tty, file, cmd, arg);
}
}
/*
* Network interface
*
*/
static int gsm_mux_net_open(struct net_device *net)
{
pr_debug("%s called\n", __func__);
netif_start_queue(net);
return 0;
}
static int gsm_mux_net_close(struct net_device *net)
{
netif_stop_queue(net);
return 0;
}
static struct net_device_stats *gsm_mux_net_get_stats(struct net_device *net)
{
return &((struct gsm_mux_net *)netdev_priv(net))->stats;
}
static void dlci_net_free(struct gsm_dlci *dlci)
{
if (!dlci->net) {
WARN_ON(1);
return;
}
dlci->adaption = dlci->prev_adaption;
dlci->data = dlci->prev_data;
free_netdev(dlci->net);
dlci->net = NULL;
}
static void net_free(struct kref *ref)
{
struct gsm_mux_net *mux_net;
struct gsm_dlci *dlci;
mux_net = container_of(ref, struct gsm_mux_net, ref);
dlci = mux_net->dlci;
if (dlci->net) {
unregister_netdev(dlci->net);
dlci_net_free(dlci);
}
}
static inline void muxnet_get(struct gsm_mux_net *mux_net)
{
kref_get(&mux_net->ref);
}
static inline void muxnet_put(struct gsm_mux_net *mux_net)
{
kref_put(&mux_net->ref, net_free);
}
static int gsm_mux_net_start_xmit(struct sk_buff *skb,
struct net_device *net)
{
struct gsm_mux_net *mux_net = netdev_priv(net);
struct gsm_dlci *dlci = mux_net->dlci;
muxnet_get(mux_net);
skb_queue_head(&dlci->skb_list, skb);
STATS(net).tx_packets++;
STATS(net).tx_bytes += skb->len;
gsm_dlci_data_kick(dlci);
/* And tell the kernel when the last transmit started. */
net->trans_start = jiffies;
muxnet_put(mux_net);
return NETDEV_TX_OK;
}
/* called when a packet did not ack after watchdogtimeout */
static void gsm_mux_net_tx_timeout(struct net_device *net)
{
/* Tell syslog we are hosed. */
dev_dbg(&net->dev, "Tx timed out.\n");
/* Update statistics */
STATS(net).tx_errors++;
}
static void gsm_mux_rx_netchar(struct gsm_dlci *dlci,
unsigned char *in_buf, int size)
{
struct net_device *net = dlci->net;
struct sk_buff *skb;
struct gsm_mux_net *mux_net = netdev_priv(net);
muxnet_get(mux_net);
/* Allocate an sk_buff */
skb = dev_alloc_skb(size + NET_IP_ALIGN);
if (!skb) {
/* We got no receive buffer. */
STATS(net).rx_dropped++;
muxnet_put(mux_net);
return;
}
skb_reserve(skb, NET_IP_ALIGN);
memcpy(skb_put(skb, size), in_buf, size);
skb->dev = net;
skb->protocol = htons(ETH_P_IP);
/* Ship it off to the kernel */
netif_rx(skb);
/* update out statistics */
STATS(net).rx_packets++;
STATS(net).rx_bytes += size;
muxnet_put(mux_net);
return;
}
static int gsm_change_mtu(struct net_device *net, int new_mtu)
{
struct gsm_mux_net *mux_net = netdev_priv(net);
if ((new_mtu < 8) || (new_mtu > mux_net->dlci->gsm->mtu))
return -EINVAL;
net->mtu = new_mtu;
return 0;
}
static void gsm_mux_net_init(struct net_device *net)
{
static const struct net_device_ops gsm_netdev_ops = {
.ndo_open = gsm_mux_net_open,
.ndo_stop = gsm_mux_net_close,
.ndo_start_xmit = gsm_mux_net_start_xmit,
.ndo_tx_timeout = gsm_mux_net_tx_timeout,
.ndo_get_stats = gsm_mux_net_get_stats,
.ndo_change_mtu = gsm_change_mtu,
};
net->netdev_ops = &gsm_netdev_ops;
/* fill in the other fields */
net->watchdog_timeo = GSM_NET_TX_TIMEOUT;
net->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
net->type = ARPHRD_NONE;
net->tx_queue_len = 10;
}
/* caller holds the dlci mutex */
static void gsm_destroy_network(struct gsm_dlci *dlci)
{
struct gsm_mux_net *mux_net;
pr_debug("destroy network interface");
if (!dlci->net)
return;
mux_net = netdev_priv(dlci->net);
muxnet_put(mux_net);
}
/* caller holds the dlci mutex */
static int gsm_create_network(struct gsm_dlci *dlci, struct gsm_netconfig *nc)
{
char *netname;
int retval = 0;
struct net_device *net;
struct gsm_mux_net *mux_net;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
/* Already in a non tty mode */
if (dlci->adaption > 2)
return -EBUSY;
if (nc->protocol != htons(ETH_P_IP))
return -EPROTONOSUPPORT;
if (nc->adaption != 3 && nc->adaption != 4)
return -EPROTONOSUPPORT;
pr_debug("create network interface");
netname = "gsm%d";
if (nc->if_name[0] != '\0')
netname = nc->if_name;
net = alloc_netdev(sizeof(struct gsm_mux_net), netname,
NET_NAME_UNKNOWN, gsm_mux_net_init);
if (!net) {
pr_err("alloc_netdev failed");
return -ENOMEM;
}
net->mtu = dlci->gsm->mtu;
mux_net = netdev_priv(net);
mux_net->dlci = dlci;
kref_init(&mux_net->ref);
strncpy(nc->if_name, net->name, IFNAMSIZ); /* return net name */
/* reconfigure dlci for network */
dlci->prev_adaption = dlci->adaption;
dlci->prev_data = dlci->data;
dlci->adaption = nc->adaption;
dlci->data = gsm_mux_rx_netchar;
dlci->net = net;
pr_debug("register netdev");
retval = register_netdev(net);
if (retval) {
pr_err("network register fail %d\n", retval);
dlci_net_free(dlci);
return retval;
}
return net->ifindex; /* return network index */
}
/* Line discipline for real tty */
static struct tty_ldisc_ops tty_ldisc_packet = {
.owner = THIS_MODULE,
.magic = TTY_LDISC_MAGIC,
.name = "n_gsm",
.open = gsmld_open,
.close = gsmld_close,
.flush_buffer = gsmld_flush_buffer,
.chars_in_buffer = gsmld_chars_in_buffer,
.read = gsmld_read,
.write = gsmld_write,
.ioctl = gsmld_ioctl,
.poll = gsmld_poll,
.receive_buf = gsmld_receive_buf,
.write_wakeup = gsmld_write_wakeup
};
/*
* Virtual tty side
*/
#define TX_SIZE 512
static int gsmtty_modem_update(struct gsm_dlci *dlci, u8 brk)
{
u8 modembits[5];
struct gsm_control *ctrl;
int len = 2;
if (brk)
len++;
modembits[0] = len << 1 | EA; /* Data bytes */
modembits[1] = dlci->addr << 2 | 3; /* DLCI, EA, 1 */
modembits[2] = gsm_encode_modem(dlci) << 1 | EA;
if (brk)
modembits[3] = brk << 4 | 2 | EA; /* Valid, EA */
ctrl = gsm_control_send(dlci->gsm, CMD_MSC, modembits, len + 1);
if (ctrl == NULL)
return -ENOMEM;
return gsm_control_wait(dlci->gsm, ctrl);
}
static int gsm_carrier_raised(struct tty_port *port)
{
struct gsm_dlci *dlci = container_of(port, struct gsm_dlci, port);
/* Not yet open so no carrier info */
if (dlci->state != DLCI_OPEN)
return 0;
if (debug & 2)
return 1;
return dlci->modem_rx & TIOCM_CD;
}
static void gsm_dtr_rts(struct tty_port *port, int onoff)
{
struct gsm_dlci *dlci = container_of(port, struct gsm_dlci, port);
unsigned int modem_tx = dlci->modem_tx;
if (onoff)
modem_tx |= TIOCM_DTR | TIOCM_RTS;
else
modem_tx &= ~(TIOCM_DTR | TIOCM_RTS);
if (modem_tx != dlci->modem_tx) {
dlci->modem_tx = modem_tx;
gsmtty_modem_update(dlci, 0);
}
}
static const struct tty_port_operations gsm_port_ops = {
.carrier_raised = gsm_carrier_raised,
.dtr_rts = gsm_dtr_rts,
.destruct = gsm_dlci_free,
};
static int gsmtty_install(struct tty_driver *driver, struct tty_struct *tty)
{
struct gsm_mux *gsm;
struct gsm_dlci *dlci;
unsigned int line = tty->index;
unsigned int mux = line >> 6;
bool alloc = false;
int ret;
line = line & 0x3F;
if (mux >= MAX_MUX)
return -ENXIO;
/* FIXME: we need to lock gsm_mux for lifetimes of ttys eventually */
if (gsm_mux[mux] == NULL)
return -EUNATCH;
if (line == 0 || line > 61) /* 62/63 reserved */
return -ECHRNG;
gsm = gsm_mux[mux];
if (gsm->dead)
return -EL2HLT;
/* If DLCI 0 is not yet fully open return an error.
This is ok from a locking
perspective as we don't have to worry about this
if DLCI0 is lost */
mutex_lock(&gsm->mutex);
if (gsm->dlci[0] && gsm->dlci[0]->state != DLCI_OPEN) {
mutex_unlock(&gsm->mutex);
return -EL2NSYNC;
}
dlci = gsm->dlci[line];
if (dlci == NULL) {
alloc = true;
dlci = gsm_dlci_alloc(gsm, line);
}
if (dlci == NULL) {
mutex_unlock(&gsm->mutex);
return -ENOMEM;
}
ret = tty_port_install(&dlci->port, driver, tty);
if (ret) {
if (alloc)
dlci_put(dlci);
mutex_unlock(&gsm->mutex);
return ret;
}
dlci_get(dlci);
dlci_get(gsm->dlci[0]);
mux_get(gsm);
tty->driver_data = dlci;
mutex_unlock(&gsm->mutex);
return 0;
}
static int gsmtty_open(struct tty_struct *tty, struct file *filp)
{
struct gsm_dlci *dlci = tty->driver_data;
struct tty_port *port = &dlci->port;
port->count++;
tty_port_tty_set(port, tty);
dlci->modem_rx = 0;
/* We could in theory open and close before we wait - eg if we get
a DM straight back. This is ok as that will have caused a hangup */
set_bit(ASYNCB_INITIALIZED, &port->flags);
/* Start sending off SABM messages */
gsm_dlci_begin_open(dlci);
/* And wait for virtual carrier */
return tty_port_block_til_ready(port, tty, filp);
}
static void gsmtty_close(struct tty_struct *tty, struct file *filp)
{
struct gsm_dlci *dlci = tty->driver_data;
struct gsm_mux *gsm;
if (dlci == NULL)
return;
if (dlci->state == DLCI_CLOSED)
return;
mutex_lock(&dlci->mutex);
gsm_destroy_network(dlci);
mutex_unlock(&dlci->mutex);
gsm = dlci->gsm;
if (tty_port_close_start(&dlci->port, tty, filp) == 0)
return;
gsm_dlci_begin_close(dlci);
if (test_bit(ASYNCB_INITIALIZED, &dlci->port.flags)) {
if (C_HUPCL(tty))
tty_port_lower_dtr_rts(&dlci->port);
}
tty_port_close_end(&dlci->port, tty);
tty_port_tty_set(&dlci->port, NULL);
return;
}
static void gsmtty_hangup(struct tty_struct *tty)
{
struct gsm_dlci *dlci = tty->driver_data;
if (dlci->state == DLCI_CLOSED)
return;
tty_port_hangup(&dlci->port);
gsm_dlci_begin_close(dlci);
}
static int gsmtty_write(struct tty_struct *tty, const unsigned char *buf,
int len)
{
int sent;
struct gsm_dlci *dlci = tty->driver_data;
if (dlci->state == DLCI_CLOSED)
return -EINVAL;
/* Stuff the bytes into the fifo queue */
sent = kfifo_in_locked(dlci->fifo, buf, len, &dlci->lock);
/* Need to kick the channel */
gsm_dlci_data_kick(dlci);
return sent;
}
static int gsmtty_write_room(struct tty_struct *tty)
{
struct gsm_dlci *dlci = tty->driver_data;
if (dlci->state == DLCI_CLOSED)
return -EINVAL;
return TX_SIZE - kfifo_len(dlci->fifo);
}
static int gsmtty_chars_in_buffer(struct tty_struct *tty)
{
struct gsm_dlci *dlci = tty->driver_data;
if (dlci->state == DLCI_CLOSED)
return -EINVAL;
return kfifo_len(dlci->fifo);
}
static void gsmtty_flush_buffer(struct tty_struct *tty)
{
struct gsm_dlci *dlci = tty->driver_data;
if (dlci->state == DLCI_CLOSED)
return;
/* Caution needed: If we implement reliable transport classes
then the data being transmitted can't simply be junked once
it has first hit the stack. Until then we can just blow it
away */
kfifo_reset(dlci->fifo);
/* Need to unhook this DLCI from the transmit queue logic */
}
static void gsmtty_wait_until_sent(struct tty_struct *tty, int timeout)
{
/* The FIFO handles the queue so the kernel will do the right
thing waiting on chars_in_buffer before calling us. No work
to do here */
}
static int gsmtty_tiocmget(struct tty_struct *tty)
{
struct gsm_dlci *dlci = tty->driver_data;
if (dlci->state == DLCI_CLOSED)
return -EINVAL;
return dlci->modem_rx;
}
static int gsmtty_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct gsm_dlci *dlci = tty->driver_data;
unsigned int modem_tx = dlci->modem_tx;
if (dlci->state == DLCI_CLOSED)
return -EINVAL;
modem_tx &= ~clear;
modem_tx |= set;
if (modem_tx != dlci->modem_tx) {
dlci->modem_tx = modem_tx;
return gsmtty_modem_update(dlci, 0);
}
return 0;
}
static int gsmtty_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct gsm_dlci *dlci = tty->driver_data;
struct gsm_netconfig nc;
int index;
if (dlci->state == DLCI_CLOSED)
return -EINVAL;
switch (cmd) {
case GSMIOC_ENABLE_NET:
if (copy_from_user(&nc, (void __user *)arg, sizeof(nc)))
return -EFAULT;
nc.if_name[IFNAMSIZ-1] = '\0';
/* return net interface index or error code */
mutex_lock(&dlci->mutex);
index = gsm_create_network(dlci, &nc);
mutex_unlock(&dlci->mutex);
if (copy_to_user((void __user *)arg, &nc, sizeof(nc)))
return -EFAULT;
return index;
case GSMIOC_DISABLE_NET:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
mutex_lock(&dlci->mutex);
gsm_destroy_network(dlci);
mutex_unlock(&dlci->mutex);
return 0;
default:
return -ENOIOCTLCMD;
}
}
static void gsmtty_set_termios(struct tty_struct *tty, struct ktermios *old)
{
struct gsm_dlci *dlci = tty->driver_data;
if (dlci->state == DLCI_CLOSED)
return;
/* For the moment its fixed. In actual fact the speed information
for the virtual channel can be propogated in both directions by
the RPN control message. This however rapidly gets nasty as we
then have to remap modem signals each way according to whether
our virtual cable is null modem etc .. */
tty_termios_copy_hw(&tty->termios, old);
}
static void gsmtty_throttle(struct tty_struct *tty)
{
struct gsm_dlci *dlci = tty->driver_data;
if (dlci->state == DLCI_CLOSED)
return;
if (tty->termios.c_cflag & CRTSCTS)
dlci->modem_tx &= ~TIOCM_DTR;
dlci->throttled = 1;
/* Send an MSC with DTR cleared */
gsmtty_modem_update(dlci, 0);
}
static void gsmtty_unthrottle(struct tty_struct *tty)
{
struct gsm_dlci *dlci = tty->driver_data;
if (dlci->state == DLCI_CLOSED)
return;
if (tty->termios.c_cflag & CRTSCTS)
dlci->modem_tx |= TIOCM_DTR;
dlci->throttled = 0;
/* Send an MSC with DTR set */
gsmtty_modem_update(dlci, 0);
}
static int gsmtty_break_ctl(struct tty_struct *tty, int state)
{
struct gsm_dlci *dlci = tty->driver_data;
int encode = 0; /* Off */
if (dlci->state == DLCI_CLOSED)
return -EINVAL;
if (state == -1) /* "On indefinitely" - we can't encode this
properly */
encode = 0x0F;
else if (state > 0) {
encode = state / 200; /* mS to encoding */
if (encode > 0x0F)
encode = 0x0F; /* Best effort */
}
return gsmtty_modem_update(dlci, encode);
}
static void gsmtty_cleanup(struct tty_struct *tty)
{
struct gsm_dlci *dlci = tty->driver_data;
struct gsm_mux *gsm = dlci->gsm;
dlci_put(dlci);
dlci_put(gsm->dlci[0]);
mux_put(gsm);
}
/* Virtual ttys for the demux */
static const struct tty_operations gsmtty_ops = {
.install = gsmtty_install,
.open = gsmtty_open,
.close = gsmtty_close,
.write = gsmtty_write,
.write_room = gsmtty_write_room,
.chars_in_buffer = gsmtty_chars_in_buffer,
.flush_buffer = gsmtty_flush_buffer,
.ioctl = gsmtty_ioctl,
.throttle = gsmtty_throttle,
.unthrottle = gsmtty_unthrottle,
.set_termios = gsmtty_set_termios,
.hangup = gsmtty_hangup,
.wait_until_sent = gsmtty_wait_until_sent,
.tiocmget = gsmtty_tiocmget,
.tiocmset = gsmtty_tiocmset,
.break_ctl = gsmtty_break_ctl,
.cleanup = gsmtty_cleanup,
};
static int __init gsm_init(void)
{
/* Fill in our line protocol discipline, and register it */
int status = tty_register_ldisc(N_GSM0710, &tty_ldisc_packet);
if (status != 0) {
pr_err("n_gsm: can't register line discipline (err = %d)\n",
status);
return status;
}
gsm_tty_driver = alloc_tty_driver(256);
if (!gsm_tty_driver) {
tty_unregister_ldisc(N_GSM0710);
pr_err("gsm_init: tty allocation failed.\n");
return -EINVAL;
}
gsm_tty_driver->driver_name = "gsmtty";
gsm_tty_driver->name = "gsmtty";
gsm_tty_driver->major = 0; /* Dynamic */
gsm_tty_driver->minor_start = 0;
gsm_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
gsm_tty_driver->subtype = SERIAL_TYPE_NORMAL;
gsm_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV
| TTY_DRIVER_HARDWARE_BREAK;
gsm_tty_driver->init_termios = tty_std_termios;
/* Fixme */
gsm_tty_driver->init_termios.c_lflag &= ~ECHO;
tty_set_operations(gsm_tty_driver, &gsmtty_ops);
spin_lock_init(&gsm_mux_lock);
if (tty_register_driver(gsm_tty_driver)) {
put_tty_driver(gsm_tty_driver);
tty_unregister_ldisc(N_GSM0710);
pr_err("gsm_init: tty registration failed.\n");
return -EBUSY;
}
pr_debug("gsm_init: loaded as %d,%d.\n",
gsm_tty_driver->major, gsm_tty_driver->minor_start);
return 0;
}
static void __exit gsm_exit(void)
{
int status = tty_unregister_ldisc(N_GSM0710);
if (status != 0)
pr_err("n_gsm: can't unregister line discipline (err = %d)\n",
status);
tty_unregister_driver(gsm_tty_driver);
put_tty_driver(gsm_tty_driver);
}
module_init(gsm_init);
module_exit(gsm_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_LDISC(N_GSM0710);
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.