aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorzhihui wu <wu.zhihui1@zte.com.cn>2017-04-18 01:55:59 +0000
committerGerrit Code Review <gerrit@opnfv.org>2017-04-18 01:55:59 +0000
commitb40f4ca8366037551d17ce93f892caba464f9bc0 (patch)
treefd67da80c8136c85938a0c15f45c708d3b9231fa
parente734d1720f447e41e8b7923618fbfaf4b2ec8138 (diff)
parent3ac6741125382fa2c836a099915acc4ad862dcc1 (diff)
Merge "apex integration"
-rw-r--r--qtip/ansible_library/modules/apex.py133
-rwxr-xr-xtests/data/external/apex/baremetal_info.json57
-rwxr-xr-xtests/data/external/apex/server_info.json37
-rw-r--r--tests/unit/ansible_library/modules/apex_test.py30
4 files changed, 257 insertions, 0 deletions
diff --git a/qtip/ansible_library/modules/apex.py b/qtip/ansible_library/modules/apex.py
new file mode 100644
index 00000000..218440b2
--- /dev/null
+++ b/qtip/ansible_library/modules/apex.py
@@ -0,0 +1,133 @@
+#!/usr/bin/python
+
+###############################################################
+# Copyright (c) 2017 ZTE Corporation
+#
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Apache License, Version 2.0
+# which accompanies this distribution, and is available at
+# http://www.apache.org/licenses/LICENSE-2.0
+##############################################################################
+
+from collections import defaultdict
+import json
+import re
+
+from ansible.module_utils.basic import AnsibleModule
+
+
+ANSIBLE_METADATA = {'metadata_version': '1.0',
+ 'status': ['preview'],
+ 'supported_by': 'community'}
+
+DOCUMENTATION = '''
+---
+module: apex
+short_description: collecting facts from apex environments
+description:
+ - Use this module to create a dynamic inventory from apex undercloud.
+version_added: "2.2"
+author: "Zhihui Wu"
+options:
+notes:
+requirements:
+ - Host 'apex-undercloud' is in ~/.ssh/config
+'''
+
+RETURN = '''
+ansible_facts:
+ description: facts collected for ansible
+ returned: success
+ type: dictionary
+ contains:
+ hosts:
+ description: host grouped by hostname, cluster, role and manufacture
+ type: dict
+ hosts_meta:
+ description: hosts meta data indexed by hostname
+ type: dict
+'''
+
+EXAMPLES = '''
+---
+- hosts: apex-undercloud
+ tasks:
+ - name: collect facts of apex hosts
+ apex:
+ - debug: var=hostvarsi
+ - name: add compute node to ansible inventory
+ add_host:
+ name: "{{ hosts_meta[item]['ip'] }}"
+ groups: compute
+ ansible_user: root
+ ansible_ssh_common_args: '-o StrictHostKeyChecking=No -o ProxyJump=apex-master'
+ with_items: "{{ hosts.compute }}"
+- hosts: compute
+ tasks:
+ - name: check ssh connection
+ ping:
+'''
+
+
+def generate_inventory(baremetal_info, server_info):
+ """Generate ansible inventory from node list in json format
+
+ Modified from https://github.com/martineg/ansible-apex-inventory/blob/master/apex.py
+ """
+
+ hosts = defaultdict(list)
+ hosts_meta = {}
+
+ for node in baremetal_info:
+ if node['Provisioning State'].lower() == 'active':
+ role = re.findall('.+profile:(\w+)$', node['Properties']['capabilities'])[0]
+ for server in server_info:
+ if server['ID'] == node['Instance UUID']:
+ node_ip = re.findall('.+=(\d+.\d+.\d+.\d+)$', server['Networks'])[0]
+ hosts[role].append(node_ip)
+ # To match ssh.cfg.j2 template
+ hosts_meta[node_ip] = {'ansible_ssh_host': node_ip}
+
+ for host in hosts:
+ hosts[host].sort()
+
+ return {'hosts': hosts, 'hosts_meta': hosts_meta}
+
+
+def main():
+ module = AnsibleModule(argument_spec=dict())
+
+ (rc, out, err) = module.run_command(['source ~/stackrc'])
+
+ if rc is not None and rc != 0:
+ return module.fail_json(msg=err)
+
+ cmd = [module.get_bin_path('openstack', True),
+ 'baremetal',
+ 'list',
+ '--fields instance_uuid properties provision_state',
+ '--format json']
+ (rc, out, err) = module.run_command(cmd)
+
+ if rc is not None and rc != 0:
+ return module.fail_json(msg=err)
+
+ baremetal_info = json.loads(out)
+
+ cmd = [module.get_bin_path('openstack', True),
+ 'server',
+ 'list',
+ '--format json']
+ (rc, out, err) = module.run_command(cmd)
+
+ if rc is not None and rc != 0:
+ return module.fail_json(msg=err)
+
+ server_info = json.loads(out)
+
+ module.exit_json(changed=False,
+ ansible_facts=generate_inventory(baremetal_info, server_info))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tests/data/external/apex/baremetal_info.json b/tests/data/external/apex/baremetal_info.json
new file mode 100755
index 00000000..8efe4e71
--- /dev/null
+++ b/tests/data/external/apex/baremetal_info.json
@@ -0,0 +1,57 @@
+[
+ {
+ "Properties": {
+ "memory_mb": "8192",
+ "cpu_arch": "x86_64",
+ "local_gb": "41",
+ "cpus": "4",
+ "capabilities": "boot_option:local,profile:compute"
+ },
+ "Provisioning State": "active",
+ "Instance UUID": "367827af-966c-4c91-bad4-d8dc12750eac"
+ },
+ {
+ "Properties": {
+ "memory_mb": "8192",
+ "cpu_arch": "x86_64",
+ "local_gb": "41",
+ "cpus": "4",
+ "capabilities": "boot_option:local,profile:compute"
+ },
+ "Provisioning State": "active",
+ "Instance UUID": "f214f844-ec4d-4f33-9d16-9aa21ade3cb4"
+ },
+ {
+ "Properties": {
+ "memory_mb": "8192",
+ "cpu_arch": "x86_64",
+ "local_gb": "41",
+ "cpus": "4",
+ "capabilities": "boot_option:local,profile:control"
+ },
+ "Provisioning State": "active",
+ "Instance UUID": "06234a4d-45fb-4930-bf8a-9b1627b1621f"
+ },
+ {
+ "Properties": {
+ "memory_mb": "8192",
+ "cpu_arch": "x86_64",
+ "local_gb": "41",
+ "cpus": "4",
+ "capabilities": "boot_option:local,profile:control"
+ },
+ "Provisioning State": "active",
+ "Instance UUID": "6dfd4c85-8a05-49ea-bd73-15dbaf84fa9b"
+ },
+ {
+ "Properties": {
+ "memory_mb": "8192",
+ "cpu_arch": "x86_64",
+ "local_gb": "41",
+ "cpus": "4",
+ "capabilities": "boot_option:local,profile:control"
+ },
+ "Provisioning State": "active",
+ "Instance UUID": "25b73b47-7c22-4f58-8ff3-ba5d714baa7c"
+ }
+]
diff --git a/tests/data/external/apex/server_info.json b/tests/data/external/apex/server_info.json
new file mode 100755
index 00000000..71bc40c5
--- /dev/null
+++ b/tests/data/external/apex/server_info.json
@@ -0,0 +1,37 @@
+[
+ {
+ "Status": "ACTIVE",
+ "Networks": "ctlplane=192.0.2.9",
+ "ID": "06234a4d-45fb-4930-bf8a-9b1627b1621f",
+ "Image Name": "overcloud-full",
+ "Name": "overcloud-controller-2"
+ },
+ {
+ "Status": "ACTIVE",
+ "Networks": "ctlplane=192.0.2.7",
+ "ID": "6dfd4c85-8a05-49ea-bd73-15dbaf84fa9b",
+ "Image Name": "overcloud-full",
+ "Name": "overcloud-controller-0"
+ },
+ {
+ "Status": "ACTIVE",
+ "Networks": "ctlplane=192.0.2.8",
+ "ID": "25b73b47-7c22-4f58-8ff3-ba5d714baa7c",
+ "Image Name": "overcloud-full",
+ "Name": "overcloud-controller-1"
+ },
+ {
+ "Status": "ACTIVE",
+ "Networks": "ctlplane=192.0.2.6",
+ "ID": "f214f844-ec4d-4f33-9d16-9aa21ade3cb4",
+ "Image Name": "overcloud-full",
+ "Name": "overcloud-novacompute-0"
+ },
+ {
+ "Status": "ACTIVE",
+ "Networks": "ctlplane=192.0.2.5",
+ "ID": "367827af-966c-4c91-bad4-d8dc12750eac",
+ "Image Name": "overcloud-full",
+ "Name": "overcloud-novacompute-1"
+ }
+] \ No newline at end of file
diff --git a/tests/unit/ansible_library/modules/apex_test.py b/tests/unit/ansible_library/modules/apex_test.py
new file mode 100644
index 00000000..8a1d0673
--- /dev/null
+++ b/tests/unit/ansible_library/modules/apex_test.py
@@ -0,0 +1,30 @@
+###############################################################
+# Copyright (c) 2017 ZTE Corporation
+#
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Apache License, Version 2.0
+# which accompanies this distribution, and is available at
+# http://www.apache.org/licenses/LICENSE-2.0
+##############################################################################
+
+import json
+import os
+
+from qtip.ansible_library.modules import apex
+
+
+def test_generate_inventory(data_root):
+ baremetal_info = json.load(open(os.path.join(data_root, 'external',
+ 'apex', 'baremetal_info.json')))
+ server_info = json.load(open(os.path.join(data_root, 'external',
+ 'apex', 'server_info.json')))
+ inventory = apex.generate_inventory(baremetal_info, server_info)
+ assert dict(inventory['hosts']) == {
+ u'compute': [u'192.0.2.5', u'192.0.2.6'],
+ u'control': [u'192.0.2.7', u'192.0.2.8', u'192.0.2.9']}
+ assert dict(inventory['hosts_meta']) == {
+ u'192.0.2.5': {'ansible_ssh_host': u'192.0.2.5'},
+ u'192.0.2.6': {'ansible_ssh_host': u'192.0.2.6'},
+ u'192.0.2.7': {'ansible_ssh_host': u'192.0.2.7'},
+ u'192.0.2.8': {'ansible_ssh_host': u'192.0.2.8'},
+ u'192.0.2.9': {'ansible_ssh_host': u'192.0.2.9'}}
onstant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */ }
/*
 * Compaq iPAQ h3xxx Atmel microcontroller companion support
 *
 * This is an Atmel AT90LS8535 with a special flashed-in firmware that
 * implements the special protocol used by this driver.
 *
 * based on previous kernel 2.4 version by Andrew Christian
 * Author : Alessandro Gardich <gremlin@gremlin.it>
 * Author : Dmitry Artamonow <mad_soft@inbox.ru>
 * Author : Linus Walleij <linus.walleij@linaro.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */

#include <linux/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/pm.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/mfd/core.h>
#include <linux/mfd/ipaq-micro.h>
#include <linux/string.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <linux/list.h>

#include <mach/hardware.h>

static void ipaq_micro_trigger_tx(struct ipaq_micro *micro)
{
	struct ipaq_micro_txdev *tx = &micro->tx;
	struct ipaq_micro_msg *msg = micro->msg;
	int i, bp;
	u8 checksum;
	u32 val;

	bp = 0;
	tx->buf[bp++] = CHAR_SOF;

	checksum = ((msg->id & 0x0f) << 4) | (msg->tx_len & 0x0f);
	tx->buf[bp++] = checksum;

	for (i = 0; i < msg->tx_len; i++) {
		tx->buf[bp++] = msg->tx_data[i];
		checksum += msg->tx_data[i];
	}

	tx->buf[bp++] = checksum;
	tx->len = bp;
	tx->index = 0;
	print_hex_dump_debug("data: ", DUMP_PREFIX_OFFSET, 16, 1,
			     tx->buf, tx->len, true);

	/* Enable interrupt */
	val = readl(micro->base + UTCR3);
	val |= UTCR3_TIE;
	writel(val, micro->base + UTCR3);
}

int ipaq_micro_tx_msg(struct ipaq_micro *micro, struct ipaq_micro_msg *msg)
{
	unsigned long flags;

	dev_dbg(micro->dev, "TX msg: %02x, %d bytes\n", msg->id, msg->tx_len);

	spin_lock_irqsave(&micro->lock, flags);
	if (micro->msg) {
		list_add_tail(&msg->node, &micro->queue);
		spin_unlock_irqrestore(&micro->lock, flags);
		return 0;
	}
	micro->msg = msg;
	ipaq_micro_trigger_tx(micro);
	spin_unlock_irqrestore(&micro->lock, flags);
	return 0;
}
EXPORT_SYMBOL(ipaq_micro_tx_msg);

static void micro_rx_msg(struct ipaq_micro *micro, u8 id, int len, u8 *data)
{
	int i;

	dev_dbg(micro->dev, "RX msg: %02x, %d bytes\n", id, len);

	spin_lock(&micro->lock);
	switch (id) {
	case MSG_VERSION:
	case MSG_EEPROM_READ:
	case MSG_EEPROM_WRITE:
	case MSG_BACKLIGHT:
	case MSG_NOTIFY_LED:
	case MSG_THERMAL_SENSOR:
	case MSG_BATTERY:
		/* Handle synchronous messages */
		if (micro->msg && micro->msg->id == id) {
			struct ipaq_micro_msg *msg = micro->msg;

			memcpy(msg->rx_data, data, len);
			msg->rx_len = len;
			complete(&micro->msg->ack);
			if (!list_empty(&micro->queue)) {
				micro->msg = list_entry(micro->queue.next,
							struct ipaq_micro_msg,
							node);
				list_del_init(&micro->msg->node);
				ipaq_micro_trigger_tx(micro);
			} else
				micro->msg = NULL;
			dev_dbg(micro->dev, "OK RX message 0x%02x\n", id);
		} else {
			dev_err(micro->dev,
				"out of band RX message 0x%02x\n", id);
			if (!micro->msg)
				dev_info(micro->dev, "no message queued\n");
			else
				dev_info(micro->dev, "expected message %02x\n",
					 micro->msg->id);
		}
		break;
	case MSG_KEYBOARD:
		if (micro->key)
			micro->key(micro->key_data, len, data);
		else
			dev_dbg(micro->dev, "key message ignored, no handle\n");
		break;
	case MSG_TOUCHSCREEN:
		if (micro->ts)
			micro->ts(micro->ts_data, len, data);
		else
			dev_dbg(micro->dev, "touchscreen message ignored, no handle\n");
		break;
	default:
		dev_err(micro->dev,
			"unknown msg %d [%d] ", id, len);
		for (i = 0; i < len; ++i)
			pr_cont("0x%02x ", data[i]);
		pr_cont("\n");
	}
	spin_unlock(&micro->lock);
}

static void micro_process_char(struct ipaq_micro *micro, u8 ch)
{
	struct ipaq_micro_rxdev *rx = &micro->rx;

	switch (rx->state) {
	case STATE_SOF:	/* Looking for SOF */
		if (ch == CHAR_SOF)
			rx->state = STATE_ID; /* Next byte is the id and len */
		break;
	case STATE_ID: /* Looking for id and len byte */
		rx->id = (ch & 0xf0) >> 4;
		rx->len = (ch & 0x0f);
		rx->index = 0;
		rx->chksum = ch;
		rx->state = (rx->len > 0) ? STATE_DATA : STATE_CHKSUM;
		break;
	case STATE_DATA: /* Looking for 'len' data bytes */
		rx->chksum += ch;
		rx->buf[rx->index] = ch;
		if (++rx->index == rx->len)
			rx->state = STATE_CHKSUM;
		break;
	case STATE_CHKSUM: /* Looking for the checksum */
		if (ch == rx->chksum)
			micro_rx_msg(micro, rx->id, rx->len, rx->buf);
		rx->state = STATE_SOF;
		break;
	}
}

static void micro_rx_chars(struct ipaq_micro *micro)
{
	u32 status, ch;

	while ((status = readl(micro->base + UTSR1)) & UTSR1_RNE) {
		ch = readl(micro->base + UTDR);
		if (status & UTSR1_PRE)
			dev_err(micro->dev, "rx: parity error\n");
		else if (status & UTSR1_FRE)
			dev_err(micro->dev, "rx: framing error\n");
		else if (status & UTSR1_ROR)
			dev_err(micro->dev, "rx: overrun error\n");
		micro_process_char(micro, ch);
	}
}

static void ipaq_micro_get_version(struct ipaq_micro *micro)
{
	struct ipaq_micro_msg msg = {
		.id = MSG_VERSION,
	};

	ipaq_micro_tx_msg_sync(micro, &msg);
	if (msg.rx_len == 4) {
		memcpy(micro->version, msg.rx_data, 4);
		micro->version[4] = '\0';
	} else if (msg.rx_len == 9) {
		memcpy(micro->version, msg.rx_data, 4);
		micro->version[4] = '\0';
		/* Bytes 4-7 are "pack", byte 8 is "boot type" */
	} else {
		dev_err(micro->dev,
			"illegal version message %d bytes\n", msg.rx_len);
	}
}

static void ipaq_micro_eeprom_read(struct ipaq_micro *micro,
				   u8 address, u8 len, u8 *data)
{
	struct ipaq_micro_msg msg = {
		.id = MSG_EEPROM_READ,
	};
	u8 i;

	for (i = 0; i < len; i++) {
		msg.tx_data[0] = address + i;
		msg.tx_data[1] = 1;
		msg.tx_len = 2;
		ipaq_micro_tx_msg_sync(micro, &msg);
		memcpy(data + (i * 2), msg.rx_data, 2);
	}
}

static char *ipaq_micro_str(u8 *wchar, u8 len)
{
	char retstr[256];
	u8 i;

	for (i = 0; i < len / 2; i++)
		retstr[i] = wchar[i * 2];
	return kstrdup(retstr, GFP_KERNEL);
}

static u16 ipaq_micro_to_u16(u8 *data)
{
	return data[1] << 8 | data[0];
}

static void __init ipaq_micro_eeprom_dump(struct ipaq_micro *micro)
{
	u8 dump[256];
	char *str;

	ipaq_micro_eeprom_read(micro, 0, 128, dump);
	str = ipaq_micro_str(dump, 10);
	if (str) {
		dev_info(micro->dev, "HW version %s\n", str);
		kfree(str);
	}
	str = ipaq_micro_str(dump+10, 40);
	if (str) {
		dev_info(micro->dev, "serial number: %s\n", str);
		/* Feed the random pool with this */
		add_device_randomness(str, strlen(str));
		kfree(str);
	}
	str = ipaq_micro_str(dump+50, 20);
	if (str) {
		dev_info(micro->dev, "module ID: %s\n", str);
		kfree(str);
	}
	str = ipaq_micro_str(dump+70, 10);
	if (str) {
		dev_info(micro->dev, "product revision: %s\n", str);
		kfree(str);
	}
	dev_info(micro->dev, "product ID: %u\n", ipaq_micro_to_u16(dump+80));
	dev_info(micro->dev, "frame rate: %u fps\n",
		 ipaq_micro_to_u16(dump+82));
	dev_info(micro->dev, "page mode: %u\n", ipaq_micro_to_u16(dump+84));
	dev_info(micro->dev, "country ID: %u\n", ipaq_micro_to_u16(dump+86));
	dev_info(micro->dev, "color display: %s\n",
		 ipaq_micro_to_u16(dump+88) ? "yes" : "no");
	dev_info(micro->dev, "ROM size: %u MiB\n", ipaq_micro_to_u16(dump+90));
	dev_info(micro->dev, "RAM size: %u KiB\n", ipaq_micro_to_u16(dump+92));
	dev_info(micro->dev, "screen: %u x %u\n",
		 ipaq_micro_to_u16(dump+94), ipaq_micro_to_u16(dump+96));
	print_hex_dump_debug("eeprom: ", DUMP_PREFIX_OFFSET, 16, 1,
			     dump, 256, true);

}

static void micro_tx_chars(struct ipaq_micro *micro)
{
	struct ipaq_micro_txdev *tx = &micro->tx;
	u32 val;

	while ((tx->index < tx->len) &&
	       (readl(micro->base + UTSR1) & UTSR1_TNF)) {
		writel(tx->buf[tx->index], micro->base + UTDR);
		tx->index++;
	}

	/* Stop interrupts */
	val = readl(micro->base + UTCR3);
	val &= ~UTCR3_TIE;
	writel(val, micro->base + UTCR3);
}

static void micro_reset_comm(struct ipaq_micro *micro)
{
	struct ipaq_micro_rxdev *rx = &micro->rx;
	u32 val;

	if (micro->msg)
		complete(&micro->msg->ack);

	/* Initialize Serial channel protocol frame */
	rx->state = STATE_SOF;  /* Reset the state machine */

	/* Set up interrupts */
	writel(0x01, micro->sdlc + 0x0); /* Select UART mode */

	/* Clean up CR3 */
	writel(0x0, micro->base + UTCR3);

	/* Format: 8N1 */
	writel(UTCR0_8BitData | UTCR0_1StpBit, micro->base + UTCR0);

	/* Baud rate: 115200 */
	writel(0x0, micro->base + UTCR1);
	writel(0x1, micro->base + UTCR2);

	/* Clear SR0 */
	writel(0xff, micro->base + UTSR0);

	/* Enable RX int, disable TX int */
	writel(UTCR3_TXE | UTCR3_RXE | UTCR3_RIE, micro->base + UTCR3);
	val = readl(micro->base + UTCR3);
	val &= ~UTCR3_TIE;
	writel(val, micro->base + UTCR3);
}

static irqreturn_t micro_serial_isr(int irq, void *dev_id)
{
	struct ipaq_micro *micro = dev_id;
	struct ipaq_micro_txdev *tx = &micro->tx;
	u32 status;

	status = readl(micro->base + UTSR0);
	do {
		if (status & (UTSR0_RID | UTSR0_RFS)) {
			if (status & UTSR0_RID)
				/* Clear the Receiver IDLE bit */
				writel(UTSR0_RID, micro->base + UTSR0);
			micro_rx_chars(micro);
		}

		/* Clear break bits */
		if (status & (UTSR0_RBB | UTSR0_REB))
			writel(status & (UTSR0_RBB | UTSR0_REB),
			       micro->base + UTSR0);

		if (status & UTSR0_TFS)
			micro_tx_chars(micro);

		status = readl(micro->base + UTSR0);

	} while (((tx->index < tx->len) && (status & UTSR0_TFS)) ||
		 (status & (UTSR0_RFS | UTSR0_RID)));

	return IRQ_HANDLED;
}

static const struct mfd_cell micro_cells[] = {
	{ .name = "ipaq-micro-backlight", },
	{ .name = "ipaq-micro-battery", },
	{ .name = "ipaq-micro-keys", },
	{ .name = "ipaq-micro-ts", },
	{ .name = "ipaq-micro-leds", },
};

static int micro_resume(struct device *dev)
{
	struct ipaq_micro *micro = dev_get_drvdata(dev);

	micro_reset_comm(micro);
	mdelay(10);

	return 0;
}

static int __init micro_probe(struct platform_device *pdev)
{
	struct ipaq_micro *micro;
	struct resource *res;
	int ret;
	int irq;

	micro = devm_kzalloc(&pdev->dev, sizeof(*micro), GFP_KERNEL);
	if (!micro)
		return -ENOMEM;

	micro->dev = &pdev->dev;

	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	if (!res)
		return -EINVAL;

	micro->base = devm_ioremap_resource(&pdev->dev, res);
	if (IS_ERR(micro->base))
		return PTR_ERR(micro->base);

	res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
	if (!res)
		return -EINVAL;

	micro->sdlc = devm_ioremap_resource(&pdev->dev, res);
	if (IS_ERR(micro->sdlc))
		return PTR_ERR(micro->sdlc);

	micro_reset_comm(micro);

	irq = platform_get_irq(pdev, 0);
	if (!irq)
		return -EINVAL;
	ret = devm_request_irq(&pdev->dev, irq, micro_serial_isr,
			       IRQF_SHARED, "ipaq-micro",
			       micro);
	if (ret) {
		dev_err(&pdev->dev, "unable to grab serial port IRQ\n");
		return ret;
	} else
		dev_info(&pdev->dev, "grabbed serial port IRQ\n");

	spin_lock_init(&micro->lock);
	INIT_LIST_HEAD(&micro->queue);
	platform_set_drvdata(pdev, micro);

	ret = mfd_add_devices(&pdev->dev, pdev->id, micro_cells,
			      ARRAY_SIZE(micro_cells), NULL, 0, NULL);
	if (ret) {
		dev_err(&pdev->dev, "error adding MFD cells");
		return ret;
	}

	/* Check version */
	ipaq_micro_get_version(micro);
	dev_info(&pdev->dev, "Atmel micro ASIC version %s\n", micro->version);
	ipaq_micro_eeprom_dump(micro);

	return 0;
}

static const struct dev_pm_ops micro_dev_pm_ops = {
	SET_SYSTEM_SLEEP_PM_OPS(NULL, micro_resume)
};

static struct platform_driver micro_device_driver = {
	.driver   = {
		.name	= "ipaq-h3xxx-micro",
		.pm	= &micro_dev_pm_ops,
		.suppress_bind_attrs = true,
	},
};
builtin_platform_driver_probe(micro_device_driver, micro_probe);