text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```groovy
package easymvp.gradle.plugin
import org.gradle.api.Plugin
import org.gradle.api.Project
import static easymvp.gradle.plugin.Version.GROUP
import static easymvp.gradle.plugin.Version.VERSION
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
class EasyMVPRx2Plugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.dependencies {
compile "$GROUP:easymvp-rx2-api:$VERSION"
}
}
}
``` | /content/code_sandbox/easymvp-plugin/src/main/groovy/easymvp/gradle/plugin/EasyMVPRx2Plugin.groovy | groovy | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 110 |
```groovy
package easymvp.gradle.plugin
import org.gradle.api.Plugin
import org.gradle.api.Project
import static easymvp.gradle.plugin.Version.GROUP
import static easymvp.gradle.plugin.Version.VERSION
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
class EasyMVPRxPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.dependencies {
compile "$GROUP:easymvp-rx-api:$VERSION"
}
}
}
``` | /content/code_sandbox/easymvp-plugin/src/main/groovy/easymvp/gradle/plugin/EasyMVPRxPlugin.groovy | groovy | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 108 |
```java
package easymvp.gradle.plugin;
public class Version {
public static final String GROUP = "com.sixthsolution.easymvp";
public static final String VERSION = "@version@";
}
``` | /content/code_sandbox/easymvp-plugin/src/main/templates/Version.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 42 |
```groovy
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*
*/
package easymvp.gradle.plugin
import com.neenbedankt.gradle.androidapt.AndroidAptPlugin
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.ProjectConfigurationException
import weaver.plugin.WeaverPlugin
import static easymvp.gradle.plugin.Version.GROUP
import static easymvp.gradle.plugin.Version.VERSION
class EasyMVPPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
def hasPlugin = { String name -> project.plugins.hasPlugin(name) }
def hasConfiguration = { String name -> project.configurations.hasProperty(name) }
def isLibrary = false
if (hasPlugin("com.android.application") || hasPlugin("android") ||
hasPlugin("com.android.test")) {
isLibrary = false
} else if (hasPlugin("com.android.library") || hasPlugin("android-library")) {
isLibrary = true
} else {
throw new ProjectConfigurationException("The android/android-library plugin must be applied to this project", null)
}
boolean isKotlinProject = hasPlugin("kotlin-android")
if (!hasConfiguration("annotationProcessor") && !hasPlugin("com.neenbedankt.android-apt") && !isKotlinProject) {
project.plugins.apply(AndroidAptPlugin)
}
if (!hasPlugin('weaver')) {
project.plugins.apply(WeaverPlugin)
}
project.dependencies {
compile "$GROUP:easymvp-api:$VERSION"
weaver "$GROUP:easymvp-weaver:$VERSION"
}
if (isKotlinProject) {
project.dependencies.add("kapt", "$GROUP:easymvp-compiler:$VERSION")
} else if (hasConfiguration("annotationProcessor") && !hasPlugin("com.neenbedankt.android-apt")) {
project.dependencies.add("annotationProcessor", "$GROUP:easymvp-compiler:$VERSION")
} else {
project.dependencies.add("apt", "$GROUP:easymvp-compiler:$VERSION")
}
// project.configurations.all {
// resolutionStrategy {
// force 'com.google.code.findbugs:jsr305:1.3.9', 'com.google.code.findbugs:jsr305:2.0.1'
// }
// }
project.android {
packagingOptions {
exclude 'META-INF/LICENSE'
}
}
}
}
``` | /content/code_sandbox/easymvp-plugin/src/main/groovy/easymvp/gradle/plugin/EasyMVPPlugin.groovy | groovy | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 541 |
```gradle
ext.ver = [sourceCompatibilityVersion: JavaVersion.VERSION_1_7,
targetCompatibilityVersion: JavaVersion.VERSION_1_7]
ext.deps = [//plugins
androidPlugin : "com.android.tools.build:gradle:3.0.0-alpha7",
weaverPlugin : "io.saeid.weaver:weaver-plugin:1.0.0-beta6",
androidApt : "com.neenbedankt.gradle.plugins:android-apt:1.8",
versioning : "net.nemerosa:versioning:1.7.1",
buildInfoExtractorGradle: "org.jfrog.buildinfo:build-info-extractor-gradle:4.4.5",
gradleBintrayPlugin : "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7",
hugo : "com.jakewharton.hugo:hugo-plugin:1.2.1",
//project dependencies
android : 'com.google.android:android:4.1.1.4',
weaverProcessor : "io.saeid.weaver:weaver-processor:1.0.0-beta5",
javaPoet : "com.squareup:javapoet:1.7.0",
rxJava : "io.reactivex:rxjava:1.2.1",
rxJava2 : "io.reactivex.rxjava2:rxjava:2.0.7",
javax : "javax.inject:javax.inject:1",
jsr305 : "com.google.code.findbugs:jsr305:2.0.1",
//tests dependencies
junit : "junit:junit:4.12",
hamcrest : "org.hamcrest:hamcrest-library:1.3",
truth : "com.google.truth:truth:0.30",
compileTesting : "com.google.testing.compile:compile-testing:0.8",
autoService : "com.google.auto.service:auto-service:1.0-rc2"]
``` | /content/code_sandbox/buildsystem/dependencies.gradle | gradle | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 448 |
```gradle
import java.text.SimpleDateFormat
apply plugin: 'com.jfrog.bintray'
apply plugin: "com.jfrog.artifactory"
apply plugin: 'maven-publish'
apply plugin: 'net.nemerosa.versioning'
Date buildTimeAndDate = new Date()
def buildDate = new SimpleDateFormat('yyyy-MM-dd').format(buildTimeAndDate)
def buildTime = new SimpleDateFormat('HH:mm:ss.SSSZ').format(buildTimeAndDate)
def travisSlug = System.getenv("TRAVIS_REPO_SLUG")
def bintrayUser = ''
def bintrayKey = ''
if (travisSlug) {
bintrayUser = System.getenv('BINTRAY_USERNAME')
bintrayKey = System.getenv('BINTRAY_APIKEY')
} else if (project.rootProject.file('local.properties').exists()) {
Properties prop = new Properties()
prop.load(project.rootProject.file('local.properties').newDataInputStream())
bintrayUser = prop.getProperty("user")
bintrayKey = prop.getProperty("apiKey")
}
def pomConfig = {
name project.name
description DESC
url 'path_to_url
inceptionYear '2016'
licenses {
license([:]) {
url 'path_to_url
distribution 'repo'
}
}
scm {
url 'path_to_url
}
developers {
[
SaeedMasoumi: 'Saeed Masoumi'
].each { devId, devName ->
developer {
id devId
name devName
roles {
role 'Developer'
}
}
}
}
contributors {
[
].each { cName ->
contributor {
name cName
roles {
role 'contributor'
}
}
}
}
}
jar {
manifest {
attributes(
'Built-By': System.properties['user.name'],
'Created-By': "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']})".toString(),
'Build-Date': buildDate,
'Build-Time': buildTime,
'Build-Revision': versioning.info.commit,
'Specification-Title': project.name,
'Specification-Version': project.version,
'Specification-Vendor': 'EasyMVP',
'Implementation-Title': project.name,
'Implementation-Version': project.version,
'Implementation-Vendor': 'EasyMVP'
)
}
metaInf {
from rootProject.file('.')
include 'LICENSE'
}
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives sourcesJar
archives javadocJar
}
artifactoryPublish {
dependsOn sourcesJar, javadocJar
}
publishing {
publications {
mavenCustom(MavenPublication) {
from components.java
artifact sourcesJar
artifact javadocJar
pom.withXml {
// all dependencies should use the default scope (compile) but
// Gradle insists in using runtime as default
asNode().dependencies.dependency.each { dep ->
if (dep.scope.text() == 'runtime') {
dep.remove(dep.scope)
}
}
asNode().children().last() + pomConfig
}
}
}
}
////////release
bintray {
user = bintrayUser
key = bintrayKey
publications = ['mavenCustom']
publish = true
pkg {
repo = 'easymvp'
name = project.name
desc = DESC
userOrg = "6thsolution"
licenses = ['Apache-2.0']
websiteUrl = 'path_to_url
vcsUrl = 'path_to_url
licenses = ['Apache-2.0']
issueTrackerUrl = 'path_to_url
labels = ['android']
publicDownloadNumbers = true
githubRepo = '6thsolution/EasyMVP'
githubReleaseNotesFile = 'README.md'
version {
name = VERSION_NAME
desc = DESC
released = new Date()
}
}
}
////////snapshots
artifactory {
contextUrl = 'path_to_url
publish {
repository {
repoKey = 'oss-snapshot-local'
username = bintrayUser
password = bintrayKey
}
defaults {
publications('mavenCustom')
publishArtifacts = true
}
}
resolve {
repoKey = 'jcenter'
}
}
def publishTask
if (VERSION_NAME.endsWith("SNAPSHOT")) {
publishTask = tasks.artifactoryPublish
} else {
publishTask = tasks.bintrayUpload
}
task publishFromCI(dependsOn: publishTask) {
}
``` | /content/code_sandbox/buildsystem/jfrog-uploader.gradle | gradle | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 1,061 |
```java
package easymvp.compiler;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public enum ViewType {
ACTIVITY,
SUPPORT_ACTIVITY,
FRAGMENT,
SUPPORT_FRAGMENT,
CUSTOM_VIEW,
CONDUCTOR_CONTROLLER
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/ViewType.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 60 |
```java
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*
*/
package easymvp.compiler;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
final class Validator {
static boolean isClass(Element element) {
return element.getKind() == ElementKind.CLASS;
}
static boolean isAbstractClass(Element element) {
return isClass(element) && getModifiers(element).contains(Modifier.ABSTRACT);
}
static boolean isNotAbstractClass(Element element) {
return isClass(element) && !getModifiers(element).contains(Modifier.ABSTRACT);
}
static boolean isSubType(Element child, String parentCanonicalName,
ProcessingEnvironment procEnv) {
return procEnv.getTypeUtils()
.isSubtype(child.asType(), getTypeElement(procEnv, parentCanonicalName).asType());
}
static boolean isPrivate(Element element) {
return getModifiers(element).contains(Modifier.PRIVATE);
}
static boolean isMethod(Element element) {
return ElementKind.METHOD == element.getKind();
}
static TypeElement getTypeElement(ProcessingEnvironment procEnv, String canonicalName) {
return procEnv.getElementUtils().getTypeElement(canonicalName);
}
static Set<Modifier> getModifiers(Element element) {
return element.getModifiers();
}
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/Validator.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 350 |
```java
package easymvp.compiler.generator;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public abstract class ClassGenerator {
private String packageName;
private String name;
private ClassName className;
public ClassGenerator(String packageName, String className) {
this.packageName = packageName;
this.name = className;
this.className = ClassName.get(packageName, className);
}
public abstract JavaFile build();
public String getPackageName() {
return packageName;
}
public String getName() {
return name;
}
public ClassName getClassName() {
return className;
}
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/generator/ClassGenerator.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 151 |
```java
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*
*/
package easymvp.compiler;
import com.google.auto.common.SuperficialValidation;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.ClassName;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.inject.Inject;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.MirroredTypeException;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
import easymvp.annotation.ActivityView;
import easymvp.annotation.CustomView;
import easymvp.annotation.FragmentView;
import easymvp.annotation.Presenter;
import easymvp.annotation.PresenterId;
import easymvp.annotation.conductor.ConductorController;
import easymvp.compiler.generator.ClassGenerator;
import easymvp.compiler.generator.DelegateClassGenerator;
import easymvp.compiler.generator.PresenterLoaderGenerator;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
@AutoService(Processor.class)
public class EasyMVPProcessor extends AbstractProcessor {
private static final String ANDROID_ACTIVITY_CLASS_NAME = "android.app.Activity";
private static final String ANDROID_SUPPORT_ACTIVITY_CLASS_NAME =
"android.support.v7.app.AppCompatActivity";
private static final String ANDROID_FRAGMENT_CLASS_NAME = "android.app.Fragment";
private static final String ANDROID_SUPPORT_FRAGMENT_CLASS_NAME =
"android.support.v4.app.Fragment";
private static final String ANDROID_CUSTOM_VIEW_CLASS_NAME = "android.view.View";
private static final String CONDUCTOR_CONTROLLER_CLASS_NAME =
"com.bluelinelabs.conductor.Controller";
private static final String DELEGATE_CLASS_SUFFIX = "_ViewDelegate";
private Messager messager;
private Elements elementUtils;
private Types typeUtils;
private Filer filer;
/** A flag that allow processor to generate presenter loaders only once to avoid IO exception */
private boolean isLoadersCopied = false;
private boolean isSupportLoadersCopied = false;
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
elementUtils = processingEnv.getElementUtils();
filer = processingEnv.getFiler();
messager = processingEnv.getMessager();
typeUtils = processingEnv.getTypeUtils();
}
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> types = new LinkedHashSet<>();
types.add(ActivityView.class.getCanonicalName());
types.add(FragmentView.class.getCanonicalName());
types.add(CustomView.class.getCanonicalName());
types.add(Presenter.class.getCanonicalName());
types.add(ConductorController.class.getCanonicalName());
return types;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Map<TypeElement, DelegateClassGenerator> delegates = makeDelegates(roundEnv);
for (Map.Entry<TypeElement, DelegateClassGenerator> entry : delegates.entrySet()) {
write(entry.getValue());
}
generatePresenterLoaders();
return true;
}
private void generatePresenterLoaders() {
if (!isLoadersCopied) {
PresenterLoaderGenerator
androidPresenterLoader = new PresenterLoaderGenerator(false);
write(androidPresenterLoader);
isLoadersCopied = true;
}
if (!isSupportLoadersCopied) {
PresenterLoaderGenerator supportLibraryPresenterLoader =
new PresenterLoaderGenerator(true);
write(supportLibraryPresenterLoader);
isSupportLoadersCopied = true;
}
}
private void write(ClassGenerator classGenerator) {
try {
classGenerator.build().writeTo(filer);
} catch (Exception e) {
error("Unable to write ( " + e.getMessage() + " )");
//TODO for presenter loader classes it throws "attempt to recreate" exception.
}
}
private Map<TypeElement, DelegateClassGenerator> makeDelegates(
RoundEnvironment roundEnv) {
//Key is view class as TypeElement
Map<TypeElement, DelegateClassGenerator> delegateClassMap =
new LinkedHashMap<>();
for (Element element : roundEnv.getElementsAnnotatedWith(ActivityView.class)) {
parseActivityView(element, delegateClassMap);
}
for (Element element : roundEnv.getElementsAnnotatedWith(FragmentView.class)) {
parseFragmentView(element, delegateClassMap);
}
for (Element element : roundEnv.getElementsAnnotatedWith(CustomView.class)) {
parseCustomView(element, delegateClassMap);
}
for (Element element : roundEnv.getElementsAnnotatedWith(ConductorController.class)) {
parseConductorController(element, delegateClassMap);
}
for (Element element : roundEnv.getElementsAnnotatedWith(Presenter.class)) {
parsePresenterInjection(element, delegateClassMap);
}
for (Element element : roundEnv.getElementsAnnotatedWith(PresenterId.class)) {
parsePresenterId(element, delegateClassMap);
}
return delegateClassMap;
}
private void parseActivityView(Element element,
Map<TypeElement, DelegateClassGenerator> delegateClassMap) {
//TODO print errors
if (!SuperficialValidation.validateElement(element)) {
error("Superficial validation error for %s", element.getSimpleName());
return;
}
if (!Validator.isNotAbstractClass(element)) {
error("%s is abstract", element.getSimpleName());
return;
}
boolean isActivity =
Validator.isSubType(element, ANDROID_ACTIVITY_CLASS_NAME, processingEnv);
boolean isSupportActivity =
Validator.isSubType(element, ANDROID_SUPPORT_ACTIVITY_CLASS_NAME, processingEnv);
if (!isActivity && !isSupportActivity) {
error("%s must extend Activity or AppCompatActivity", element.getSimpleName());
return;
}
//getEnclosing for class type will returns its package/
TypeElement enclosingElement = (TypeElement) element;
DelegateClassGenerator delegateClassGenerator =
getDelegate(enclosingElement, delegateClassMap);
ActivityView annotation = element.getAnnotation(ActivityView.class);
delegateClassGenerator.setResourceID(annotation.layout());
if (isSupportActivity) {
delegateClassGenerator.setViewType(ViewType.SUPPORT_ACTIVITY);
} else {
delegateClassGenerator.setViewType(ViewType.ACTIVITY);
}
try {
annotation.presenter();
} catch (MirroredTypeException mte) {
parsePresenter(delegateClassGenerator, mte);
}
}
private void parseFragmentView(Element element,
Map<TypeElement, DelegateClassGenerator> delegateClassMap) {
//TODO print errors
if (!SuperficialValidation.validateElement(element)) {
error("Superficial validation error for %s", element.getSimpleName());
return;
}
if (!Validator.isNotAbstractClass(element)) {
error("%s is abstract", element.getSimpleName());
return;
}
boolean isFragment =
Validator.isSubType(element, ANDROID_FRAGMENT_CLASS_NAME, processingEnv);
boolean isSupportFragment =
Validator.isSubType(element, ANDROID_SUPPORT_FRAGMENT_CLASS_NAME, processingEnv);
if (!isFragment && !isSupportFragment) {
error("%s must extend Fragment or support Fragment", element.getSimpleName());
return;
}
//getEnclosing for class type will returns its package/
TypeElement enclosingElement = (TypeElement) element;
DelegateClassGenerator delegateClassGenerator =
getDelegate(enclosingElement, delegateClassMap);
if (isFragment) {
delegateClassGenerator.setViewType(ViewType.FRAGMENT);
} else {
delegateClassGenerator.setViewType(ViewType.SUPPORT_FRAGMENT);
}
FragmentView annotation = element.getAnnotation(FragmentView.class);
try {
annotation.presenter();
} catch (MirroredTypeException mte) {
parsePresenter(delegateClassGenerator, mte);
}
}
private void parseCustomView(Element element,
Map<TypeElement, DelegateClassGenerator> delegateClassMap) {
//TODO print errors
if (!SuperficialValidation.validateElement(element)) {
error("Superficial validation error for %s", element.getSimpleName());
return;
}
if (!Validator.isNotAbstractClass(element)) {
error("%s is abstract", element.getSimpleName());
return;
}
if (!Validator.isSubType(element, ANDROID_CUSTOM_VIEW_CLASS_NAME, processingEnv)) {
error("%s must extend View", element.getSimpleName());
return;
}
//getEnclosing for class type will returns its package/
TypeElement enclosingElement = (TypeElement) element;
DelegateClassGenerator delegateClassGenerator =
getDelegate(enclosingElement, delegateClassMap);
delegateClassGenerator.setViewType(ViewType.CUSTOM_VIEW);
CustomView annotation = element.getAnnotation(CustomView.class);
try {
annotation.presenter();
} catch (MirroredTypeException mte) {
parsePresenter(delegateClassGenerator, mte);
}
}
private void parseConductorController(Element element,
Map<TypeElement, DelegateClassGenerator> delegateClassMap) {
if (!SuperficialValidation.validateElement(element)) {
error("Superficial validation error for %s", element.getSimpleName());
return;
}
if (!Validator.isNotAbstractClass(element)) {
error("%s is abstract", element.getSimpleName());
return;
}
if (!Validator.isSubType(element, CONDUCTOR_CONTROLLER_CLASS_NAME, processingEnv)) {
error("%s must extend View", element.getSimpleName());
return;
}
//getEnclosing for class type will returns its package/
TypeElement enclosingElement = (TypeElement) element;
DelegateClassGenerator delegateClassGenerator =
getDelegate(enclosingElement, delegateClassMap);
delegateClassGenerator.setViewType(ViewType.CONDUCTOR_CONTROLLER);
ConductorController annotation = element.getAnnotation(ConductorController.class);
try {
annotation.presenter();
} catch (MirroredTypeException mte) {
parsePresenter(delegateClassGenerator, mte);
}
}
private void parsePresenterInjection(Element element,
Map<TypeElement, DelegateClassGenerator> delegateClassMap) {
//TODO print errors
if (!SuperficialValidation.validateElement(element)) {
error("Superficial validation error for %s", element.getSimpleName());
return;
}
if (Validator.isPrivate(element)) {
error("%s can't be private", element.getSimpleName());
return;
}
VariableElement variableElement = (VariableElement) element;
DelegateClassGenerator delegateClassGenerator =
getDelegate((TypeElement) element.getEnclosingElement(),
delegateClassMap);
delegateClassGenerator.setViewPresenterField(variableElement.getSimpleName().toString());
if (variableElement.getAnnotation(Inject.class) != null) {
delegateClassGenerator.injectablePresenterInView(true);
}
delegateClassGenerator.setPresenterTypeInView(variableElement.asType().toString());
}
private void parsePresenterId(Element element,
Map<TypeElement, DelegateClassGenerator> delegateClassMap) {
if (!SuperficialValidation.validateElement(element)) {
error("Superficial validation error for %s", element.getSimpleName());
return;
}
if (Validator.isPrivate(element)) {
error("%s can't be private", element.getSimpleName());
return;
}
if (Validator.isMethod(element)) {
ExecutableType emeth = (ExecutableType) element.asType();
if (!emeth.getReturnType().getKind().equals(TypeKind.LONG) &&
!emeth.getReturnType().getKind().equals(TypeKind.INT)) {
error("%s must have return type int or long", element);
}
} else {
TypeKind kind = element.asType().getKind();
if (kind != TypeKind.INT && kind != TypeKind.LONG) {
error("%s must be int or long", element.getSimpleName());
return;
}
}
String presenterId = element.toString();
DelegateClassGenerator delegateClassGenerator =
getDelegate((TypeElement) element.getEnclosingElement(),
delegateClassMap);
delegateClassGenerator.setPresenterId(presenterId);
}
private void parsePresenter(DelegateClassGenerator delegateClassGenerator,
MirroredTypeException mte) {
TypeElement presenterElement = getTypeElement(mte);
delegateClassGenerator.setPresenter(getClassName(presenterElement));
String presenterView = findViewTypeOfPresenter(presenterElement);
delegateClassGenerator.setPresenterViewQualifiedName(presenterView);
}
private String findViewTypeOfPresenter(TypeElement presenterElement) {
TypeElement currentClass = presenterElement;
while (currentClass != null) {
if (currentClass.getSuperclass() instanceof DeclaredType) {
List<? extends TypeMirror> superClassParameters =
((DeclaredType) currentClass.getSuperclass()).getTypeArguments();
if (superClassParameters.size() == 1) {
String type = superClassParameters.get(0).toString();
if (!"V".equals(type)) return type;
}
}
currentClass = getSuperClass(currentClass);
}
return "";
}
private TypeElement getSuperClass(TypeElement typeElement) {
if (!(typeElement.getSuperclass() instanceof DeclaredType)) return null;
DeclaredType declaredAncestor = (DeclaredType) typeElement.getSuperclass();
return (TypeElement) declaredAncestor.asElement();
}
private DelegateClassGenerator getDelegate(TypeElement enclosingElement,
Map<TypeElement, DelegateClassGenerator> delegateClassMap) {
DelegateClassGenerator
delegateClassGenerator = delegateClassMap.get(enclosingElement);
if (delegateClassGenerator == null) {
ClassName viewClass = getClassName(enclosingElement);
String packageName = getPackageName(enclosingElement);
String delegateClassName = getSimpleClassName(enclosingElement) + DELEGATE_CLASS_SUFFIX;
delegateClassGenerator =
new DelegateClassGenerator(packageName, delegateClassName, viewClass);
delegateClassMap.put(enclosingElement, delegateClassGenerator);
}
return delegateClassGenerator;
}
private String getSimpleClassName(TypeElement type) {
return type.getSimpleName().toString();
}
private ClassName getClassName(TypeElement typeElement) {
return ClassName.bestGuess(typeElement.getQualifiedName().toString());
}
private String getPackageName(TypeElement type) {
return elementUtils.getPackageOf(type).getQualifiedName().toString();
}
private TypeElement getTypeElement(String canonicalName) {
return elementUtils.getTypeElement(canonicalName);
}
private TypeElement getTypeElement(MirroredTypeException mte) {
DeclaredType declaredType = (DeclaredType) mte.getTypeMirror();
return (TypeElement) declaredType.asElement();
}
/**
* {@link com.squareup.javapoet.ClassName#canonicalName} is not public.
*/
private String classNameToCanonicalName(ClassName className) {
List<String> names = new ArrayList<>();
names.add(className.packageName());
names.addAll(className.simpleNames());
return names.get(0).isEmpty()
? join(".", names.subList(1, names.size()))
: join(".", names);
}
private String join(String separator, List<String> parts) {
if (parts.isEmpty()) return "";
StringBuilder result = new StringBuilder();
result.append(parts.get(0));
for (int i = 1; i < parts.size(); i++) {
result.append(separator).append(parts.get(i));
}
return result.toString();
}
private void error(String message, Object... args) {
messager.printMessage(Diagnostic.Kind.ERROR, String.format(message, args));
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/EasyMVPProcessor.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 3,425 |
```java
package easymvp.compiler.generator;
import com.squareup.javapoet.ClassName;
import easymvp.compiler.ViewType;
import static easymvp.compiler.util.ClassNames.*;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public class AndroidLoaderUtils {
static ClassName getLoader(boolean supportLibrary) {
return get(supportLibrary, SUPPORT_LOADER, LOADER);
}
static ClassName getLoader(ViewType viewType) {
return get(viewType, SUPPORT_LOADER, LOADER);
}
public static ClassName getLoader() {
return LOADER;
}
public static ClassName getSupportLoader() {
return SUPPORT_LOADER;
}
public static ClassName getLoaderManager() {
return LOADER_MANAGER;
}
public static ClassName getSupportLoaderManager() {
return SUPPORT_LOADER_MANAGER;
}
public static ClassName getLoaderCallbacks() {
return LOADER_CALLBACKS;
}
public static ClassName getSupportLoaderCallbacks() {
return SUPPORT_LOADER_CALLBACKS;
}
public static ClassName getPresenterLoader() {
return PRESENTER_LOADER;
}
public static ClassName getSupportPresenterLoader() {
return SUPPORT_PRESENTER_LOADER;
}
static ClassName getLoaderCallbacks(ViewType viewType) {
return get(viewType, SUPPORT_LOADER_CALLBACKS, LOADER_CALLBACKS);
}
static ClassName getPresenterLoader(ViewType viewType) {
return get(viewType, SUPPORT_PRESENTER_LOADER, PRESENTER_LOADER);
}
static ClassName getPresenterLoader(boolean supportLibrary) {
return get(supportLibrary, SUPPORT_PRESENTER_LOADER, PRESENTER_LOADER);
}
private static ClassName get(ViewType viewType, ClassName supportVersion,
ClassName defaultVersion) {
switch (viewType) {
case SUPPORT_ACTIVITY:
case SUPPORT_FRAGMENT:
return supportVersion;
case FRAGMENT:
return defaultVersion;
default:
return defaultVersion;
}
}
private static ClassName get(boolean isSupportLibrary, ClassName supportVersion,
ClassName defaultVersion) {
if (isSupportLibrary) {
return supportVersion;
} else {
return defaultVersion;
}
}
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/generator/AndroidLoaderUtils.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 464 |
```java
package easymvp.compiler.generator;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import javax.lang.model.element.Modifier;
import easymvp.Presenter;
import static easymvp.compiler.util.ClassNames.CONTEXT;
import static easymvp.compiler.util.ClassNames.PROVIDER;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public final class PresenterLoaderGenerator extends ClassGenerator {
private static final String METHOD_GET_PRESENTER = "get";
private static final TypeName PRESENTER_FACTORY_FIELD =
ParameterizedTypeName.get(PROVIDER, TypeVariableName.get("P"));
//All generated fields for our custom loader
private static final String FIELD_PRESENTER = "presenter";
private static final String FIELD_PRESENTER_FACTORY = "presenterFactory";
//All methods that MUST be implemented
private static final String METHOD_ON_START_LOADING = "onStartLoading";
private static final String METHOD_ON_FORCE_LOAD = "onForceLoad";
private static final String METHOD_ON_RESET = "onReset";
private boolean supportLibrary;
public PresenterLoaderGenerator(boolean supportLibrary) {
super(AndroidLoaderUtils.getPresenterLoader(supportLibrary).packageName(),
AndroidLoaderUtils.getPresenterLoader(supportLibrary).simpleName());
this.supportLibrary = supportLibrary;
}
@Override
public JavaFile build() {
TypeSpec.Builder result =
TypeSpec.classBuilder(getClassName()).addModifiers(Modifier.PUBLIC)
.addTypeVariable(TypeVariableName.get("P", Presenter.class))
.superclass(ParameterizedTypeName.get(AndroidLoaderUtils.getLoader(supportLibrary),
TypeVariableName.get("P")));
addConstructor(result);
addFields(result);
addMethods(result);
return JavaFile.builder(getPackageName(), result.build())
.addFileComment("Generated class from EasyMVP. Do not modify!").build();
}
private void addConstructor(TypeSpec.Builder result) {
result.addMethod(MethodSpec.constructorBuilder()
.addParameter(CONTEXT, "context")
.addParameter(
ParameterSpec.builder(PRESENTER_FACTORY_FIELD, "presenterFactory")
.build())
.addModifiers(Modifier.PUBLIC)
.addStatement("super(context)")
.addStatement("this.$L = $L", FIELD_PRESENTER_FACTORY, "presenterFactory")
.build());
}
private void addFields(TypeSpec.Builder result) {
result.addField(FieldSpec.builder(TypeVariableName.get("P"), FIELD_PRESENTER)
.addModifiers(Modifier.PRIVATE)
.build());
result.addField(
FieldSpec.builder(PRESENTER_FACTORY_FIELD, FIELD_PRESENTER_FACTORY)
.addModifiers(Modifier.PRIVATE)
.build());
}
private void addMethods(TypeSpec.Builder result) {
result.addMethod(getOnStartLoadingMethod())
.addMethod(getOnForceLoadMethod())
.addMethod(getOnResetMethod());
}
private MethodSpec getOnStartLoadingMethod() {
MethodSpec.Builder method = getDefaultMethod(METHOD_ON_START_LOADING);
method.beginControlFlow("if ($L != null)", FIELD_PRESENTER)
.addStatement("deliverResult($L)", FIELD_PRESENTER)
.endControlFlow()
.beginControlFlow("else")
.addStatement("forceLoad()")
.endControlFlow();
return method.build();
}
private MethodSpec getOnForceLoadMethod() {
MethodSpec.Builder method = getDefaultMethod(METHOD_ON_FORCE_LOAD);
method.addStatement("$L = $L.$L()", FIELD_PRESENTER, FIELD_PRESENTER_FACTORY,
METHOD_GET_PRESENTER);
method.addStatement("deliverResult($L)", FIELD_PRESENTER);
return method.build();
}
private MethodSpec getOnResetMethod() {
MethodSpec.Builder method = getDefaultMethod(METHOD_ON_RESET);
method.beginControlFlow("if ($L != null)", FIELD_PRESENTER);
method.addStatement(callPresenterPreDestroy(FIELD_PRESENTER));
method.addStatement("$L = null", FIELD_PRESENTER);
method.endControlFlow();
return method.build();
}
private MethodSpec.Builder getDefaultMethod(String methodName) {
return MethodSpec.methodBuilder(methodName)
.addModifiers(Modifier.PROTECTED)
.returns(void.class)
.addAnnotation(Override.class);
}
private String callPresenterPreDestroy(String presenterVar) {
return presenterVar + ".onDestroyed()";
}
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/generator/PresenterLoaderGenerator.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 1,001 |
```java
package easymvp.compiler.generator.decorator;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import easymvp.compiler.generator.DelegateClassGenerator;
import static easymvp.compiler.generator.AndroidLoaderUtils.getSupportLoader;
import static easymvp.compiler.generator.AndroidLoaderUtils.getSupportLoaderCallbacks;
import static easymvp.compiler.generator.AndroidLoaderUtils.getSupportLoaderManager;
import static easymvp.compiler.generator.AndroidLoaderUtils.getSupportPresenterLoader;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public class SupportActivityDecorator extends ActivityDecorator {
public SupportActivityDecorator(DelegateClassGenerator delegateClassGenerator) {
super(delegateClassGenerator);
}
@Override
public MethodSpec getLoaderManagerMethod(MethodSpec.Builder methodSignature) {
return methodSignature.addStatement("return view.getSupportLoaderManager()")
.returns(getSupportLoaderManager())
.build();
}
@Override
protected ClassName getPresenterLoaderClass() {
return getSupportPresenterLoader();
}
@Override
protected ClassName getLoaderCallbacksClass() {
return getSupportLoaderCallbacks();
}
@Override
protected ClassName getLoaderClass() {
return getSupportLoader();
}
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/generator/decorator/SupportActivityDecorator.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 262 |
```java
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*
*/
package easymvp.compiler.generator;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import javax.lang.model.element.Modifier;
import easymvp.compiler.ViewType;
import easymvp.compiler.generator.decorator.ActivityDecorator;
import easymvp.compiler.generator.decorator.BaseDecorator;
import easymvp.compiler.generator.decorator.ConductorControllerDecorator;
import easymvp.compiler.generator.decorator.CustomViewDecorator;
import easymvp.compiler.generator.decorator.FragmentDecorator;
import easymvp.compiler.generator.decorator.SupportActivityDecorator;
import easymvp.compiler.generator.decorator.SupportFragmentDecorator;
import static easymvp.compiler.util.ClassNames.PROVIDER;
import static easymvp.compiler.util.ClassNames.VIEW_DELEGATE;
/**
* This class is responsible for generating .java files, which implement {@link
* easymvp.internal.ViewDelegate}.
*
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public class DelegateClassGenerator extends ClassGenerator {
private final ClassName viewClass;
private ClassName presenterClass;
private ViewType viewType;
private int resourceID = -1;
private String presenterFieldNameInView = "";
private String presenterViewQualifiedName;
private boolean injectablePresenterInView = false;
private ClassName presenterTypeInView;
private BaseDecorator decorator;
private String presenterId = "";
public String getPresenterId() {
return presenterId;
}
public DelegateClassGenerator(String packageName, String className, ClassName viewClass) {
super(packageName, className);
this.viewClass = viewClass;
}
public ClassName getViewClass() {
return viewClass;
}
public String getPresenterViewQualifiedName() {
return presenterViewQualifiedName;
}
public void setPresenterViewQualifiedName(String presenterViewQualifiedName) {
this.presenterViewQualifiedName = presenterViewQualifiedName;
}
public void setViewType(ViewType viewType) {
this.viewType = viewType;
switch (viewType) {
case ACTIVITY:
decorator = new ActivityDecorator(this);
break;
case SUPPORT_ACTIVITY:
decorator = new SupportActivityDecorator(this);
break;
case FRAGMENT:
decorator = new FragmentDecorator(this);
break;
case SUPPORT_FRAGMENT:
decorator = new SupportFragmentDecorator(this);
break;
case CUSTOM_VIEW:
decorator = new CustomViewDecorator(this);
break;
case CONDUCTOR_CONTROLLER:
decorator = new ConductorControllerDecorator(this);
break;
}
}
public void setResourceID(int resourceID) {
this.resourceID = resourceID;
}
public void setPresenter(ClassName presenter) {
this.presenterClass = presenter;
}
public void setViewPresenterField(String fieldName) {
presenterFieldNameInView = fieldName;
}
@Override
public JavaFile build() {
TypeSpec.Builder result =
TypeSpec.classBuilder(getClassName()).addModifiers(Modifier.PUBLIC)
.addSuperinterface(
ParameterizedTypeName.get(VIEW_DELEGATE, viewClass,
getPresenterFactoryTypeName()));
decorator.build(result);
return JavaFile.builder(getPackageName(), result.build())
.addFileComment("Generated class from EasyMVP. Do not modify!").build();
}
public void injectablePresenterInView(boolean injectable) {
this.injectablePresenterInView = injectable;
}
private TypeName getPresenterFactoryTypeName() {
return ParameterizedTypeName.get(PROVIDER, presenterClass);
}
public ClassName getPresenterClass() {
return presenterClass;
}
public boolean isInjectablePresenterInView() {
return injectablePresenterInView;
}
public ClassName getPresenterTypeInView() {
return presenterTypeInView;
}
public void setPresenterTypeInView(String presenterTypeInView) {
this.presenterTypeInView = ClassName.bestGuess(presenterTypeInView);
}
public String getPresenterFieldNameInView() {
return presenterFieldNameInView;
}
public int getResourceID() {
return resourceID;
}
public void setPresenterId(String presenterId) {
this.presenterId = presenterId;
}
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/generator/DelegateClassGenerator.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 921 |
```java
package easymvp.compiler.generator.decorator;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import easymvp.compiler.generator.DelegateClassGenerator;
import static easymvp.compiler.generator.AndroidLoaderUtils.getLoader;
import static easymvp.compiler.generator.AndroidLoaderUtils.getLoaderCallbacks;
import static easymvp.compiler.generator.AndroidLoaderUtils.getLoaderManager;
import static easymvp.compiler.generator.AndroidLoaderUtils.getPresenterLoader;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public class ActivityDecorator extends BaseDecorator {
public ActivityDecorator(DelegateClassGenerator delegateClassGenerator) {
super(delegateClassGenerator);
}
@Override
public MethodSpec getLoaderManagerMethod(MethodSpec.Builder methodSignature) {
return methodSignature.addStatement("return view.getLoaderManager()")
.returns(getLoaderManager())
.build();
}
@Override
public String createContextField(String viewField) {
return "final $T context = " + viewField + ".getApplicationContext()";
}
@Override
protected void implementInitializer(MethodSpec.Builder method) {
int resId = delegateClassGenerator.getResourceID();
if (resId != -1) {
//Avoid lint error
method.addAnnotation(
AnnotationSpec.builder(SuppressWarnings.class)
.addMember("value", "\"ResourceType\"")
.build());
method.addStatement("view.setContentView(" + resId + ")");
}
}
@Override
protected ClassName getPresenterLoaderClass() {
return getPresenterLoader();
}
@Override
protected ClassName getLoaderCallbacksClass() {
return getLoaderCallbacks();
}
@Override
protected ClassName getLoaderClass() {
return getLoader();
}
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/generator/decorator/ActivityDecorator.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 385 |
```java
package easymvp.compiler.generator.decorator;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import easymvp.compiler.generator.DelegateClassGenerator;
import static easymvp.compiler.generator.AndroidLoaderUtils.getLoader;
import static easymvp.compiler.generator.AndroidLoaderUtils.getLoaderCallbacks;
import static easymvp.compiler.generator.AndroidLoaderUtils.getLoaderManager;
import static easymvp.compiler.generator.AndroidLoaderUtils.getPresenterLoader;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public class FragmentDecorator extends BaseDecorator {
public FragmentDecorator(DelegateClassGenerator delegateClassGenerator) {
super(delegateClassGenerator);
}
@Override
public MethodSpec getLoaderManagerMethod(MethodSpec.Builder methodSignature) {
return methodSignature.addStatement("return view.getLoaderManager()")
.returns(getLoaderManager())
.build();
}
@Override
public String createContextField(String viewField) {
return "final $T context = " + viewField + ".getActivity().getApplicationContext()";
}
@Override
protected void implementInitializer(MethodSpec.Builder method) {
}
@Override
protected ClassName getPresenterLoaderClass() {
return getPresenterLoader();
}
@Override
protected ClassName getLoaderCallbacksClass() {
return getLoaderCallbacks();
}
@Override
protected ClassName getLoaderClass() {
return getLoader();
}
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/generator/decorator/FragmentDecorator.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 305 |
```java
package easymvp.compiler.generator.decorator;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import easymvp.compiler.generator.DelegateClassGenerator;
import static easymvp.compiler.generator.AndroidLoaderUtils.getSupportLoader;
import static easymvp.compiler.generator.AndroidLoaderUtils.getSupportLoaderCallbacks;
import static easymvp.compiler.generator.AndroidLoaderUtils.getSupportLoaderManager;
import static easymvp.compiler.generator.AndroidLoaderUtils.getSupportPresenterLoader;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public class SupportFragmentDecorator extends BaseDecorator {
public SupportFragmentDecorator(DelegateClassGenerator delegateClassGenerator) {
super(delegateClassGenerator);
}
@Override
public MethodSpec getLoaderManagerMethod(MethodSpec.Builder methodSignature) {
return methodSignature.addStatement("return view.getLoaderManager()")
.returns(getSupportLoaderManager())
.build();
}
@Override
public String createContextField(String viewField) {
return "final $T context = " + viewField + ".getActivity().getApplicationContext()";
}
@Override
protected void implementInitializer(MethodSpec.Builder method) {
}
@Override
protected ClassName getPresenterLoaderClass() {
return getSupportPresenterLoader();
}
@Override
protected ClassName getLoaderCallbacksClass() {
return getSupportLoaderCallbacks();
}
@Override
protected ClassName getLoaderClass() {
return getSupportLoader();
}
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/generator/decorator/SupportFragmentDecorator.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 315 |
```java
package easymvp.compiler.generator.decorator;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import javax.lang.model.element.Modifier;
import easymvp.compiler.generator.DelegateClassGenerator;
import static easymvp.compiler.generator.AndroidLoaderUtils.getSupportLoader;
import static easymvp.compiler.generator.AndroidLoaderUtils.getSupportLoaderCallbacks;
import static easymvp.compiler.generator.AndroidLoaderUtils.getSupportLoaderManager;
import static easymvp.compiler.generator.AndroidLoaderUtils.getSupportPresenterLoader;
import static easymvp.compiler.util.ClassNames.APPCOMPAT_ACTIVITY_CLASS;
import static easymvp.compiler.util.ClassNames.CONTEXT;
import static easymvp.compiler.util.ClassNames.CONTEXT_WRAPPER;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public class CustomViewDecorator extends BaseDecorator {
public CustomViewDecorator(DelegateClassGenerator delegateClassGenerator) {
super(delegateClassGenerator);
}
@Override
protected void addMethods(TypeSpec.Builder result) {
super.addMethods(result);
result.addMethod(MethodSpec.methodBuilder("scanActivity")
.addModifiers(Modifier.PRIVATE)
.returns(APPCOMPAT_ACTIVITY_CLASS)
.addParameter(CONTEXT, "context")
.beginControlFlow("if(context instanceof $T)", APPCOMPAT_ACTIVITY_CLASS)
.addStatement("return ($T)context", APPCOMPAT_ACTIVITY_CLASS)
.endControlFlow()
.beginControlFlow("else if(context instanceof $T)", CONTEXT_WRAPPER)
.addStatement("return scanActivity((($T)context).getBaseContext())",
CONTEXT_WRAPPER)
.endControlFlow()
.addStatement("return null")
.build());
}
@Override
public MethodSpec getLoaderManagerMethod(MethodSpec.Builder methodSignature) {
return methodSignature.addStatement("return scanActivity(view.getContext()).getSupportLoaderManager()",
APPCOMPAT_ACTIVITY_CLASS)
.returns(getSupportLoaderManager())
.build();
}
@Override
public String createContextField(String viewField) {
return "final $T context = " + viewField + ".getContext()";
}
@Override
protected void implementInitializer(MethodSpec.Builder method) {
}
@Override
protected ClassName getPresenterLoaderClass() {
return getSupportPresenterLoader();
}
@Override
protected ClassName getLoaderCallbacksClass() {
return getSupportLoaderCallbacks();
}
@Override
protected ClassName getLoaderClass() {
return getSupportLoader();
}
@Override
protected MethodSpec.Builder getOnLoaderResetMethod(ParameterizedTypeName loader) {
return getCallbacksMethod(METHOD_ON_LOADER_RESET)
.returns(TypeName.VOID)
.addParameter(loader, "loader")
.addStatement("delegate.get().detachView()")
.addStatement("delegate.get().$L = null", FIELD_PRESENTER);
}
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/generator/decorator/CustomViewDecorator.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 641 |
```java
package easymvp.compiler.generator.decorator;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import easymvp.compiler.generator.DelegateClassGenerator;
import static easymvp.compiler.generator.AndroidLoaderUtils.getLoader;
import static easymvp.compiler.generator.AndroidLoaderUtils.getLoaderCallbacks;
import static easymvp.compiler.generator.AndroidLoaderUtils.getLoaderManager;
import static easymvp.compiler.generator.AndroidLoaderUtils.getPresenterLoader;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
public class ConductorControllerDecorator extends BaseDecorator {
public ConductorControllerDecorator(DelegateClassGenerator delegateClassGenerator) {
super(delegateClassGenerator);
}
@Override
public MethodSpec getLoaderManagerMethod(MethodSpec.Builder methodSignature) {
return methodSignature.addStatement("return view.getActivity().getLoaderManager()")
.returns(getLoaderManager())
.build();
}
@Override
public String createContextField(String viewField) {
return "final $T context = " + viewField + ".getActivity().getApplicationContext()";
}
@Override
protected void implementInitializer(MethodSpec.Builder method) {
}
@Override
protected String addStatementInOnDestroyMethod() {
return "if (view.getActivity() == null) return;\n"
+ "getLoaderManager(view).destroyLoader(loaderId)";
}
@Override
protected ClassName getPresenterLoaderClass() {
return getPresenterLoader();
}
@Override
protected ClassName getLoaderCallbacksClass() {
return getLoaderCallbacks();
}
@Override
protected ClassName getLoaderClass() {
return getLoader();
}
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/generator/decorator/ConductorControllerDecorator.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 356 |
```java
package easymvp.compiler.util;
import com.squareup.javapoet.ClassName;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public final class ClassNames {
public static final ClassName CONTEXT = ClassName.get("android.content", "Context");
public static final ClassName BUNDLE = ClassName.get("android.os", "Bundle");
public static final ClassName WEAK_REFERENCE = ClassName.get("java.lang.ref", "WeakReference");
public static final ClassName PROVIDER = ClassName.get("javax.inject", "Provider");
public static final ClassName APPCOMPAT_ACTIVITY_CLASS =
ClassName.get("android.support.v7.app", "AppCompatActivity");
public static final ClassName CONTEXT_WRAPPER =
ClassName.get("android.content", "ContextWrapper");
public static final ClassName VIEW_DELEGATE =
ClassName.get("easymvp.internal", "ViewDelegate");
//loaders related class names
public static final ClassName LOADER = ClassName.get("android.content", "Loader");
public static final ClassName SUPPORT_LOADER =
ClassName.get("android.support.v4.content", "Loader");
public static final ClassName LOADER_MANAGER = ClassName.get("android.app", "LoaderManager");
public static final ClassName SUPPORT_LOADER_MANAGER =
ClassName.get("android.support.v4.app", "LoaderManager");
public static final ClassName LOADER_CALLBACKS =
ClassName.get("android.app.LoaderManager", "LoaderCallbacks");
public static final ClassName SUPPORT_LOADER_CALLBACKS =
ClassName.get("android.support.v4.app.LoaderManager", "LoaderCallbacks");
public static final ClassName PRESENTER_LOADER =
ClassName.get("easymvp.loader", "PresenterLoader");
public static final ClassName SUPPORT_PRESENTER_LOADER =
ClassName.get("easymvp.loader", "SupportPresenterLoader");
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/util/ClassNames.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 375 |
```java
package easymvp;
import java.lang.ref.WeakReference;
import javax.annotation.Nullable;
/**
* The base class for implementing a {@link Presenter}.
*
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public abstract class AbstractPresenter<V> implements Presenter<V> {
private WeakReference<V> view;
@Override
public void onViewAttached(V view) {
this.view = new WeakReference<>(view);
}
@Override
public void onViewDetached() {
if (view != null) view.clear();
}
@Override
public void onDestroyed() {
view = null;
}
@Nullable
@Override
public V getView() {
return view == null ? null : view.get();
}
@Override
public boolean isViewAttached() {
return view != null && view.get() != null;
}
}
``` | /content/code_sandbox/easymvp-api/src/main/java/easymvp/AbstractPresenter.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 193 |
```java
package easymvp;
import javax.annotation.Nullable;
/**
* Base interface for all presenters in Model-View-Presenter pattern.
* <p>
* The {@code Presenter} is responsible for orchestrating all the application's use cases,
* So it acts as a middle man that retrieves model from data-layer and shows it in the view.
* <p>
* In MVP pattern, view is made completely passive and is no longer responsible for updating itself from the model.
* So it routes all user actions to the presenter and the presenter decides the action to take.
*
* @param <V> Generic type of view that the presenter interacts with. To make presenter
* testable, the view should be implemented with an interface and presenter refers to it instead of the view implementation.
* This will allow to write unit tests without any android SDK dependency.
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public interface Presenter<V> {
/**
* Called when the view attached to the screen.
* <p>
* This method will be invoked during {@link android.app.Activity#onStart()}, {@link android.app.Fragment#onResume()}
* and {@link android.view.View#onAttachedToWindow()}.
* @param view the view that the presenter interacts with
*/
void onViewAttached(V view);
/**
* Called when the view detached from the screen.
* <p>
* This method will be invoked during {@link android.app.Activity#onStop()}, {@link android.app.Fragment#onPause()}
* and {@link android.view.View#onDetachedFromWindow()}.
*/
void onViewDetached();
/**
* Called when a user leaves the view completely. After the invocation of this method, presenter instance will be destroyed.
* <p>
* Note that on configuration changes like rotation, presenter instance will be alive.
*/
void onDestroyed();
/**
* @return Returns true if the view is currently attached to the presenter, otherwise returns false.
**/
boolean isViewAttached();
/**
* @return Returns the attached view. If view is already detached, null will be returned.
*/
@Nullable
V getView();
}
``` | /content/code_sandbox/easymvp-api/src/main/java/easymvp/Presenter.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 467 |
```java
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*
*/
package easymvp.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* {@code FragmentView} should be used on {@code android.app.Fragment} or
* {@code android.support.v4.app.Fragment} classes to enable usage of EasyMVP.
* <p>
* Here is an example:
* <pre class="prettyprint">
* {@literal @}FragmentView(presenter = MyPresenter.class)
* public class MyFragment extends Fragment implement MyView {
* //...
* }
* </pre>
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
@Retention(value = RUNTIME)
@Target(value = TYPE)
public @interface FragmentView {
/**
* @return the presenter class.
*/
Class<? extends easymvp.Presenter> presenter();
}
``` | /content/code_sandbox/easymvp-api/src/main/java/easymvp/annotation/FragmentView.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 239 |
```java
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*
*/
package easymvp.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* {@code ActivityView} should be used on {@code android.support.v7.app.AppCompatActivity} classes
* to enable usage of EasyMVP.
* <p>
* Here is an example:
* <pre class="prettyprint">
* {@literal @}ActivityView(presenter = MyPresenter.class, layout = R.layout.my_activity)
* public class MyActivity extends AppCompatActivity implement MyView {
* //...
* }
* </pre>
* @author Saeed Masoumi (saeed@6thsolution.com)
* @see easymvp.Presenter
*/
@Retention(value = RUNTIME)
@Target(value = TYPE)
public @interface ActivityView {
/**
* @return the presenter class.
*/
Class<? extends easymvp.Presenter> presenter();
/**
* The R.layout.* field which refer to the layout, so there is no need to call {@code
* setContentView(R.layout.youLayout}.
* <p>
* By default content view will not be set.
*
* @return the id of the layout.
*/
int layout() default -1;
}
``` | /content/code_sandbox/easymvp-api/src/main/java/easymvp/annotation/ActivityView.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 320 |
```java
package easymvp.compiler.generator.decorator;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import easymvp.compiler.generator.DelegateClassGenerator;
import java.util.concurrent.atomic.AtomicInteger;
import javax.lang.model.element.Modifier;
import static easymvp.compiler.util.ClassNames.BUNDLE;
import static easymvp.compiler.util.ClassNames.CONTEXT;
import static easymvp.compiler.util.ClassNames.PROVIDER;
import static easymvp.compiler.util.ClassNames.WEAK_REFERENCE;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public abstract class BaseDecorator {
protected static final String FIELD_PRESENTER = "presenter";
protected static final String METHOD_ON_LOADER_RESET = "onLoaderReset";
private static final String METHOD_INITIALIZE = "initialize";
private static final String METHOD_ATTACH_VIEW = "attachView";
private static final String METHOD_DETACH_VIEW = "detachView";
private static final String METHOD_DESTROY = "destroy";
private static final String METHOD_GET_LOADER_MANAGER = "getLoaderManager";
private static final String CLASS_PRESENTER_FACTORY = "PresenterFactory";
private static final String CLASS_PRESENTER_LOADER_CALLBACKS = "PresenterLoaderCallbacks";
private static final String METHOD_ON_CREATE_LOADER = "onCreateLoader";
private static final String METHOD_ON_LOAD_FINISHED = "onLoadFinished";
private static final String FIELD_PRESENTER_DELIVERED = "presenterDelivered";
private static final AtomicInteger LOADER_ID = new AtomicInteger(500);
protected DelegateClassGenerator delegateClassGenerator;
public BaseDecorator(DelegateClassGenerator delegateClassGenerator) {
this.delegateClassGenerator = delegateClassGenerator;
}
/**
* {@code getLoaderManager(T view);}
*/
public abstract MethodSpec getLoaderManagerMethod(MethodSpec.Builder methodSignature);
public abstract String createContextField(String viewField);
public void build(TypeSpec.Builder result) {
addFields(result);
addMethods(result);
addInnerClasses(result);
}
protected void addFields(TypeSpec.Builder result) {
ParameterizedTypeName loader = ParameterizedTypeName.get(getLoaderClass(),
delegateClassGenerator.getPresenterClass());
result.addField(
FieldSpec.builder(delegateClassGenerator.getPresenterClass(), FIELD_PRESENTER,
Modifier.PRIVATE).build())
.addField(FieldSpec.builder(loader, "loader", Modifier.PRIVATE).build())
.addField(FieldSpec.builder(TypeName.INT, "loaderId", Modifier.PRIVATE).build());
}
protected void addMethods(TypeSpec.Builder result) {
result.addMethod(getInitializeMethod())
.addMethod(getInitializeMethodWithFactory())
.addMethod(getAttachViewMethod())
.addMethod(getDetachViewMethod())
.addMethod(getDestroyMethod())
.addMethod(getLoaderManagerMethod(getLoaderMethodSignature()));
}
protected void addInnerClasses(TypeSpec.Builder result) {
if (!delegateClassGenerator.isInjectablePresenterInView()) {
result.addType(getPresenterFactoryClass(result));
}
result.addType(getPresenterLoaderCallbacks());
}
private MethodSpec getInitializeMethod() {
MethodSpec.Builder method = MethodSpec.methodBuilder(METHOD_INITIALIZE)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addParameter(delegateClassGenerator.getViewClass(), "view")
.returns(TypeName.VOID);
if (delegateClassGenerator.isInjectablePresenterInView()) {
method.addStatement("// Intentionally left blank!");
} else {
initLoader(method, "new " + CLASS_PRESENTER_FACTORY + "()");
implementInitializer(method);
}
return method.build();
}
private MethodSpec getInitializeMethodWithFactory() {
MethodSpec.Builder method = MethodSpec.methodBuilder(METHOD_INITIALIZE)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addParameter(delegateClassGenerator.getViewClass(), "view")
.returns(TypeName.VOID);
method.addParameter(ParameterSpec.builder(presenterFactoryTypeName(), "presenterFactory",
Modifier.FINAL).build());
if (!delegateClassGenerator.isInjectablePresenterInView()) {
method.addStatement("// Intentionally left blank!");
} else {
initLoader(method, "presenterFactory");
implementInitializer(method);
}
return method.build();
}
private void initLoader(MethodSpec.Builder method, String presenterProvider) {
method.addStatement(createContextField("view"), CONTEXT);
String predefinedPresenterId = delegateClassGenerator.getPresenterId();
String presenterId;
if (predefinedPresenterId != null && !predefinedPresenterId.isEmpty()) {
presenterId = "view." + predefinedPresenterId;
} else {
presenterId = LOADER_ID.incrementAndGet() + "";
}
method.addStatement("loaderId = $L", presenterId);
method.addStatement("loader = $L(view).initLoader($L,null,$L)", METHOD_GET_LOADER_MANAGER,
presenterId,
"new PresenterLoaderCallbacks(context, view, this, " + presenterProvider + ")");
}
protected abstract void implementInitializer(MethodSpec.Builder method);
private MethodSpec getAttachViewMethod() {
MethodSpec.Builder method = MethodSpec.methodBuilder(METHOD_ATTACH_VIEW)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addParameter(delegateClassGenerator.getViewClass(), "view")
.returns(TypeName.VOID);
method.addStatement(callPresenterAttachView(FIELD_PRESENTER, "view", "$T"),
ClassName.bestGuess(delegateClassGenerator.getPresenterViewQualifiedName()));
return method.build();
}
private MethodSpec getDetachViewMethod() {
MethodSpec.Builder method = MethodSpec.methodBuilder(METHOD_DETACH_VIEW)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class);
method.addStatement(callPresenterDetachView(FIELD_PRESENTER));
return method.build();
}
private MethodSpec getDestroyMethod() {
MethodSpec.Builder method = MethodSpec.methodBuilder(METHOD_DESTROY)
.addModifiers(Modifier.PUBLIC)
.addParameter(delegateClassGenerator.getViewClass(), "view")
.addAnnotation(Override.class);
method.addStatement(addStatementInOnDestroyMethod());
return method.build();
}
protected String addStatementInOnDestroyMethod() {
return "// Intentionally left blank!";
}
private String callPresenterAttachView(String presenterVar, String viewVar,
String presenterViewType) {
return String.format("if ( %s != null) %s.onViewAttached((%s)%s)", presenterVar,
presenterVar, presenterViewType, viewVar);
}
private String callPresenterDetachView(String presenterVar) {
return String.format("if ( %s != null) %s.onViewDetached()", presenterVar, presenterVar);
}
private MethodSpec.Builder getLoaderMethodSignature() {
return MethodSpec.methodBuilder(METHOD_GET_LOADER_MANAGER)
.addModifiers(Modifier.PRIVATE)
.addParameter(delegateClassGenerator.getViewClass(), "view");
}
private TypeSpec getPresenterFactoryClass(TypeSpec.Builder result) {
// result.addType(
return TypeSpec.classBuilder(CLASS_PRESENTER_FACTORY)
.addSuperinterface(presenterFactoryTypeName())
.addModifiers(Modifier.PRIVATE, Modifier.STATIC)
.addMethod(MethodSpec.methodBuilder("get")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addStatement("return new $T()", delegateClassGenerator.getPresenterClass())
.returns(delegateClassGenerator.getPresenterClass())
.build())
.build();
}
private TypeName presenterFactoryTypeName() {
return ParameterizedTypeName.get(PROVIDER, delegateClassGenerator.getPresenterClass());
}
private TypeSpec getPresenterLoaderCallbacks() {
ParameterizedTypeName loader = ParameterizedTypeName.get(getLoaderClass(),
delegateClassGenerator.getPresenterClass());
TypeName contextWeakReference = ParameterizedTypeName.get(WEAK_REFERENCE, CONTEXT);
TypeName viewWeakReference =
ParameterizedTypeName.get(WEAK_REFERENCE, delegateClassGenerator.getViewClass());
TypeName delegateWeakReference =
ParameterizedTypeName.get(WEAK_REFERENCE, delegateClassGenerator.getClassName());
TypeSpec.Builder result = TypeSpec.classBuilder(CLASS_PRESENTER_LOADER_CALLBACKS)
.addSuperinterface(ParameterizedTypeName.get(getLoaderCallbacksClass(),
delegateClassGenerator.getPresenterClass()))
.addModifiers(Modifier.PRIVATE, Modifier.STATIC)
.addField(FieldSpec.builder(boolean.class, FIELD_PRESENTER_DELIVERED,
Modifier.PRIVATE).initializer("false").build())
.addField(FieldSpec.builder(contextWeakReference, "context", Modifier.PRIVATE)
.initializer("null")
.build())
.addField(FieldSpec.builder(viewWeakReference, "view", Modifier.PRIVATE)
.initializer("null")
.build())
.addField(FieldSpec.builder(delegateWeakReference, "delegate", Modifier.PRIVATE)
.initializer("null")
.build())
.addField(
FieldSpec.builder(presenterFactoryTypeName(), "provider", Modifier.PRIVATE)
.initializer("null")
.build())
//adding constructor
.addMethod(MethodSpec.constructorBuilder()
.addParameter(CONTEXT, "context")
.addParameter(delegateClassGenerator.getViewClass(), "view")
.addParameter(delegateClassGenerator.getClassName(), "delegate")
.addParameter(presenterFactoryTypeName(), "provider")
.addStatement("this.context = new $T(context)", contextWeakReference)
.addStatement("this.view = new $T(view)", viewWeakReference)
.addStatement("this.delegate = new $T(delegate)", delegateWeakReference)
.addStatement("this.provider = provider")
.build())
//create presenter loader
.addMethod(getCallbacksMethod(METHOD_ON_CREATE_LOADER).returns(loader)
.addParameter(int.class, "id")
.addParameter(BUNDLE, "bundle")
.addStatement("return new $T($L,$L)", getPresenterLoaderClass(),
"context.get()", "provider")
.build());
//implement onLoadFinished
MethodSpec.Builder onLoadFinished =
getCallbacksMethod(METHOD_ON_LOAD_FINISHED).returns(TypeName.VOID)
.addParameter(loader, "loader")
.addParameter(delegateClassGenerator.getPresenterClass(), "presenter")
.beginControlFlow("if (!$L)", FIELD_PRESENTER_DELIVERED)
.addStatement("delegate.get().$L = presenter", FIELD_PRESENTER);
String presenterFieldInView = delegateClassGenerator.getPresenterFieldNameInView();
if (presenterFieldInView != null && !presenterFieldInView.isEmpty()) {
onLoadFinished.addStatement("view.get().$L = ($T) $L", presenterFieldInView,
delegateClassGenerator.getPresenterTypeInView(), FIELD_PRESENTER);
}
onLoadFinished.addStatement("$L = true", FIELD_PRESENTER_DELIVERED).endControlFlow();
//implement onLoaderReset
MethodSpec.Builder onLoaderReset = getOnLoaderResetMethod(loader);
if (presenterFieldInView != null && !presenterFieldInView.isEmpty()) {
onLoaderReset.beginControlFlow("if (view.get() != null)").
addStatement("view.get().$L = null", presenterFieldInView).endControlFlow();
}
result.addMethod(onLoadFinished.build());
result.addMethod(onLoaderReset.build());
return result.build();
}
protected abstract ClassName getPresenterLoaderClass();
protected MethodSpec.Builder getCallbacksMethod(String methodName) {
return MethodSpec.methodBuilder(methodName)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class);
}
protected abstract ClassName getLoaderCallbacksClass();
protected abstract ClassName getLoaderClass();
protected MethodSpec.Builder getOnLoaderResetMethod(ParameterizedTypeName loader) {
return getCallbacksMethod(METHOD_ON_LOADER_RESET).returns(TypeName.VOID)
.addParameter(loader, "loader")
.beginControlFlow("if (delegate.get() != null)")
.addStatement("delegate.get().$L = null", FIELD_PRESENTER)
.endControlFlow();
}
}
``` | /content/code_sandbox/easymvp-compiler/src/main/java/easymvp/compiler/generator/decorator/BaseDecorator.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 2,596 |
```java
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*
*/
package easymvp.annotation;
import android.os.Bundle;
import android.view.View;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Annotation to inject the presenter that already defined in a {@link ActivityView#presenter()},
* a {@link FragmentView#presenter()} or a {@link CustomView#presenter()}.
* <p>
* It must be applied into the view implementation classes (<code>Activity</code>, <code>Fragment</code> or <code>Custom View</code>),
* otherwise it won't work.
* <p>
* You have access to the presenter instance after super call in {@link android.app.Activity#onCreate(Bundle)},
* {@link android.app.Fragment#onActivityCreated(Bundle)} and {@link View#onAttachedToWindow} methods.
* Also during configuration changes, same instance of presenter will be injected.
* <p>
* Here is an example:
* <pre class="prettyprint">
* {@literal @}FragmentView(presenter = MyPresenter.class)
* public class MyFragment extends Fragment{
* {@literal @}Presenter
* MyPresenter presenter;
*
* }
*
* public class MyPresenter extends AbstractPresenter<MyView>{
*
* public MyPresenter(){
*
* }
* }
*
* interface MyView{
*
* }
* </pre>
* <p>
* By default you can't pass any objects to the constructor of presenters,
* but you can use <a href="path_to_url">Dagger</a> to inject presenters.
* <p>
* Here is an example of using dagger:
* <pre class="prettyprint">
* {@literal @}FragmentView(presenter = MyPresenter.class)
* public class MyFragment extends Fragment{
*
* {@literal @}Inject
* {@literal @}Presenter
* MyPresenter presenter;
*
* {@literal @}Override
* void onCreate(Bundle b){
* SomeComponent.injectTo(this);
* }
* }
*
* public class MyPresenter extends AbstractPresenter<MyView>{
*
* public MyPresenter(){
*
* }
* }
* interface MyView{
*
* }
* </pre>
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
@Retention(value = RUNTIME)
@Target(value = FIELD)
public @interface Presenter {
}
``` | /content/code_sandbox/easymvp-api/src/main/java/easymvp/annotation/Presenter.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 563 |
```java
package easymvp.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* If you want to use multiple instances of a {@code Fragment}, {@code View} or a conductor {@code
* Controller} class in a single {@code Activity}, {@code Fragment} or whatever, You will encounter
* in an easyMVP limitation which will inject same instance of Presenter. To solve this you can use
* {@code @PresenterId} annotation in your {@code Fragment} ,{@code View} or your conductor {@code
* Controller} and pass a unique Id for each instantiated view.
*
* @author Saeed Masoumi (s-masoumi@live.com)
*/
@Retention(value = RUNTIME)
@Target(value = {METHOD, FIELD})
public @interface PresenterId {
}
``` | /content/code_sandbox/easymvp-api/src/main/java/easymvp/annotation/PresenterId.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 200 |
```java
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*
*/
package easymvp.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* {@code CustomView} should be used on {@code android.view.View} classes to enable usage of EasyMVP.
* <p>
* Here is an example:
* <pre class="prettyprint">
* {@literal @}CustomView(presenter = MyPresenter.class)
* public class MyCustomView extends View implement MyView {
* //...
* }
* </pre>
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
@Retention(value = RUNTIME)
@Target(value = TYPE)
public @interface CustomView {
/**
* @return the presenter class.
*/
Class<? extends easymvp.Presenter> presenter();
}
``` | /content/code_sandbox/easymvp-api/src/main/java/easymvp/annotation/CustomView.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 228 |
```java
package easymvp.annotation.conductor;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Annotates a {@code com.bluelinelabs.conductor.ConductorController} class to binds {@link
* easymvp.Presenter} lifecycle.
*
* @author Saeed Masoumi (s-masoumi@live.com)
*/
@Retention(value = RUNTIME)
@Target(value = TYPE)
public @interface ConductorController {
/**
* @return the presenter class.
*/
Class<? extends easymvp.Presenter> presenter();
}
``` | /content/code_sandbox/easymvp-api/src/main/java/easymvp/annotation/conductor/ConductorController.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 141 |
```java
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*
*/
package easymvp.internal;
/**
* Internal usage!
* <p>
* It's a delegate between the Presenter and the View.
* The annotation processor will use this interface to generate delegate classes.
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public interface ViewDelegate<V, P> {
void initialize(V view, P presenterFactory);
void initialize(V view);
void attachView(V view);
void detachView();
void destroy(V view);
}
``` | /content/code_sandbox/easymvp-api/src/main/java/easymvp/internal/ViewDelegate.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 145 |
```java
package easymvp;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
/**
* Created by megrez on 2017/3/12.
*/
public class RxPresenter<V> extends AbstractPresenter<V> {
private CompositeDisposable subscriptions = new CompositeDisposable();
@Override
public void onDestroyed() {
super.onDestroyed();
subscriptions.dispose();
}
public void addSubscription(Disposable subscription) {
subscriptions.add(subscription);
}
public void removeSubscription(Disposable subscription) {
subscriptions.remove(subscription);
}
}
``` | /content/code_sandbox/easymvp-rx2-api/src/main/java/easymvp/RxPresenter.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 121 |
```java
package easymvp.usecase;
import easymvp.executer.PostExecutionThread;
import easymvp.executer.UseCaseExecutor;
import io.reactivex.Single;
import io.reactivex.SingleTransformer;
import io.reactivex.annotations.Nullable;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
public abstract class SingleUseCase<R, Q> extends UseCase<Single, Q> {
private final SingleTransformer<? super R, ? extends R> schedulersTransformer;
public SingleUseCase(final UseCaseExecutor useCaseExecutor,
final PostExecutionThread postExecutionThread) {
super(useCaseExecutor, postExecutionThread);
schedulersTransformer = new SingleTransformer<R, R>() {
@Override
public Single<R> apply(Single<R> single) {
return single.subscribeOn(useCaseExecutor.getScheduler())
.observeOn(postExecutionThread.getScheduler());
}
};
}
@Override
public Single<R> execute(@Nullable Q param) {
return interact(param).compose(getSchedulersTransformer());
}
@Override
protected abstract Single<R> interact(@Nullable Q param);
private SingleTransformer<? super R, ? extends R> getSchedulersTransformer() {
return schedulersTransformer;
}
}
``` | /content/code_sandbox/easymvp-rx2-api/src/main/java/easymvp/usecase/SingleUseCase.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 261 |
```java
package easymvp.usecase;
import easymvp.executer.PostExecutionThread;
import easymvp.executer.UseCaseExecutor;
import io.reactivex.Completable;
import io.reactivex.CompletableTransformer;
import javax.annotation.Nullable;
/**
* Created by megrez on 2017/3/12.
*/
public abstract class CompletableUseCase<Q> extends UseCase<Completable, Q> {
private final CompletableTransformer schedulersTransformer;
public CompletableUseCase(final UseCaseExecutor useCaseExecutor,
final PostExecutionThread postExecutionThread) {
super(useCaseExecutor, postExecutionThread);
schedulersTransformer = new CompletableTransformer() {
@Override
public Completable apply(Completable completable) {
return completable.subscribeOn(useCaseExecutor.getScheduler())
.observeOn(postExecutionThread.getScheduler());
}
};
}
@Override
public Completable execute(@Nullable Q param) {
return interact(param).compose(getSchedulersTransformer());
}
private CompletableTransformer getSchedulersTransformer() {
return schedulersTransformer;
}
}
``` | /content/code_sandbox/easymvp-rx2-api/src/main/java/easymvp/usecase/CompletableUseCase.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 228 |
```java
package easymvp.usecase;
import javax.annotation.Nullable;
import easymvp.executer.PostExecutionThread;
import easymvp.executer.UseCaseExecutor;
import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
public abstract class FlowableUseCase<R, Q> extends UseCase<Flowable, Q> {
private final FlowableTransformer<? super R, ? extends R> schedulersTransformer;
public FlowableUseCase(final UseCaseExecutor useCaseExecutor,
final PostExecutionThread postExecutionThread) {
super(useCaseExecutor, postExecutionThread);
schedulersTransformer = new FlowableTransformer<R, R>() {
@Override
public Flowable<R> apply(Flowable<R> rObservable) {
return rObservable.subscribeOn(useCaseExecutor.getScheduler())
.observeOn(postExecutionThread.getScheduler());
}
};
}
@Override
public Flowable<R> execute(@Nullable Q param) {
return interact(param).compose(getSchedulersTransformer());
}
@Override
protected abstract Flowable<R> interact(@Nullable Q param);
private FlowableTransformer<? super R, ? extends R> getSchedulersTransformer() {
return schedulersTransformer;
}
}
``` | /content/code_sandbox/easymvp-rx2-api/src/main/java/easymvp/usecase/FlowableUseCase.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 274 |
```java
package easymvp.usecase;
import javax.annotation.Nullable;
import easymvp.executer.PostExecutionThread;
import easymvp.executer.UseCaseExecutor;
import io.reactivex.Maybe;
import io.reactivex.MaybeTransformer;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
public abstract class MaybeUseCase<R, Q> extends UseCase<Maybe, Q> {
private final MaybeTransformer<? super R, ? extends R> schedulersTransformer;
public MaybeUseCase(final UseCaseExecutor useCaseExecutor,
final PostExecutionThread postExecutionThread) {
super(useCaseExecutor, postExecutionThread);
schedulersTransformer = new MaybeTransformer<R, R>() {
@Override
public Maybe<R> apply(Maybe<R> single) {
return single.subscribeOn(useCaseExecutor.getScheduler())
.observeOn(postExecutionThread.getScheduler());
}
};
}
@Override
public Maybe<R> execute(@Nullable Q param) {
return interact(param).compose(getSchedulersTransformer());
}
@Override
protected abstract Maybe<R> interact(@Nullable Q param);
private MaybeTransformer<? super R, ? extends R> getSchedulersTransformer() {
return schedulersTransformer;
}
}
``` | /content/code_sandbox/easymvp-rx2-api/src/main/java/easymvp/usecase/MaybeUseCase.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 260 |
```java
package easymvp.usecase;
import easymvp.executer.PostExecutionThread;
import easymvp.executer.UseCaseExecutor;
import io.reactivex.Observable;
import io.reactivex.ObservableTransformer;
import javax.annotation.Nullable;
/**
* Created by megrez on 2017/3/12.
*/
public abstract class ObservableUseCase<R, Q> extends UseCase<Observable, Q> {
private final ObservableTransformer<? super R, ? extends R> schedulersTransformer;
public ObservableUseCase(final UseCaseExecutor useCaseExecutor,
final PostExecutionThread postExecutionThread) {
super(useCaseExecutor, postExecutionThread);
schedulersTransformer = new ObservableTransformer<R, R>() {
@Override
public Observable<R> apply(Observable<R> rObservable) {
return rObservable.subscribeOn(useCaseExecutor.getScheduler())
.observeOn(postExecutionThread.getScheduler());
}
};
}
@Override
public Observable<R> execute(@Nullable Q param) {
return interact(param).compose(getSchedulersTransformer());
}
@Override
protected abstract Observable<R> interact(@Nullable Q param);
private ObservableTransformer<? super R, ? extends R> getSchedulersTransformer() {
return schedulersTransformer;
}
}
``` | /content/code_sandbox/easymvp-rx2-api/src/main/java/easymvp/usecase/ObservableUseCase.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 258 |
```java
package easymvp.usecase;
import easymvp.executer.PostExecutionThread;
import easymvp.executer.UseCaseExecutor;
import io.reactivex.Scheduler;
import javax.annotation.Nullable;
/**
* Each {@code UseCase} of the system orchestrate the flow of data to and from the entities.
* <p>
* Outer layers of system can execute use cases by calling {@link #execute(Object)}} method. Also
* you can use {@link #useCaseExecutor} to execute the job in a background thread and {@link
* #postExecutionThread} to post the result to another thread(usually UI thread).
*
* @param <P> The response type of a use case.
* @param <Q> The request type of a use case.
* Created by megrez on 2017/3/12.
*/
public abstract class UseCase<P,Q> {
private final UseCaseExecutor useCaseExecutor;
private final PostExecutionThread postExecutionThread;
public UseCase(UseCaseExecutor useCaseExecutor,
PostExecutionThread postExecutionThread) {
this.useCaseExecutor = useCaseExecutor;
this.postExecutionThread = postExecutionThread;
}
/**
* Executes use case. It should call {@link #interact(Object)} to get response value.
*/
public abstract P execute(@Nullable Q param);
/**
* A hook for interacting with the given parameter(request value) and returning a response value for
* each concrete implementation.
* <p>
* It should be called inside {@link #execute(Object)}.
*
* @param param The request value.
* @return Returns the response value.
*/
protected abstract P interact(@Nullable Q param);
public Scheduler getUseCaseExecutor() {
return useCaseExecutor.getScheduler();
}
public Scheduler getPostExecutionThread() {
return postExecutionThread.getScheduler();
}
}
``` | /content/code_sandbox/easymvp-rx2-api/src/main/java/easymvp/usecase/UseCase.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 398 |
```java
package easymvp.executer;
import io.reactivex.Scheduler;
/**
* Created by megrez on 2017/3/12.
*/
public interface PostExecutionThread {
Scheduler getScheduler();
}
``` | /content/code_sandbox/easymvp-rx2-api/src/main/java/easymvp/executer/PostExecutionThread.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 43 |
```java
package easymvp.executer;
import io.reactivex.Scheduler;
/**
* Created by megrez on 2017/3/12.
*/
public interface UseCaseExecutor {
Scheduler getScheduler();
}
``` | /content/code_sandbox/easymvp-rx2-api/src/main/java/easymvp/executer/UseCaseExecutor.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 43 |
```java
package easymvp.boundary;
import io.reactivex.functions.Function;
/**
* {@code DataMapper} transforms entities from the format most convenient for the use cases, to the
* format most convenient for the presentation layer.
*
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public abstract class DataMapper<T, R> implements Function<T, R> {
}
``` | /content/code_sandbox/easymvp-rx2-api/src/main/java/easymvp/boundary/DataMapper.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 83 |
```cmake
#
# 86Box A hypervisor and IBM PC system emulator that specializes in
# running old operating systems and software designed for IBM
# PC systems and compatibles from 1981 through fairly recent
# system designs based on the PCI bus.
#
# This file is part of the 86Box distribution.
#
# CMake toolchain file for Clang on Windows builds (ARM64 target).
#
# Authors: David Hrdlika, <hrdlickadavid@outlook.com>
#
#
include(${CMAKE_CURRENT_LIST_DIR}/flags-gcc-armv7.cmake)
# Use the GCC-compatible Clang executables in order to use our flags
set(CMAKE_C_COMPILER clang)
set(CMAKE_CXX_COMPILER clang++)
# `llvm-rc` is barely usable as of LLVM 13, using MS' rc.exe for now
set(CMAKE_RC_COMPILER rc)
set(CMAKE_C_COMPILER_TARGET arm-pc-windows-msvc)
set(CMAKE_CXX_COMPILER_TARGET arm-pc-windows-msvc)
set(CMAKE_SYSTEM_PROCESSOR ARM)
# TODO: set the vcpkg target triplet perhaps?
``` | /content/code_sandbox/cmake/llvm-win32-arm.cmake | cmake | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 243 |
```cmake
#
# 86Box A hypervisor and IBM PC system emulator that specializes in
# running old operating systems and software designed for IBM
# PC systems and compatibles from 1981 through fairly recent
# system designs based on the PCI bus.
#
# This file is part of the 86Box distribution.
#
# CMake toolchain file defining GCC compiler flags.
#
# Authors: David Hrdlika, <hrdlickadavid@outlook.com>
#
#
# Define our flags
string(APPEND CMAKE_C_FLAGS_INIT " -fomit-frame-pointer -Wall -fno-strict-aliasing -Werror=implicit-int -Werror=implicit-function-declaration -Werror=int-conversion -Werror=strict-prototypes -Werror=old-style-definition")
string(APPEND CMAKE_CXX_FLAGS_INIT " -fomit-frame-pointer -Wall -fno-strict-aliasing")
string(APPEND CMAKE_C_FLAGS_RELEASE_INIT " -g0 -O3")
string(APPEND CMAKE_CXX_FLAGS_RELEASE_INIT " -g0 -O3")
string(APPEND CMAKE_C_FLAGS_DEBUG_INIT " -ggdb -Og")
string(APPEND CMAKE_CXX_FLAGS_DEBUG_INIT " -ggdb -Og")
string(APPEND CMAKE_C_FLAGS_OPTIMIZED_INIT " -march=native -mtune=native -O3 -ffp-contract=fast -flto")
string(APPEND CMAKE_CXX_FLAGS_OPTIMIZED_INIT " -march=native -mtune=native -O3 -ffp-contract=fast -flto")
# Set up the variables
foreach(LANG C;CXX)
set(CMAKE_${LANG}_FLAGS "$ENV{${LANG}FLAGS} ${CMAKE_${LANG}_FLAGS_INIT}" CACHE STRING "Flags used by the ${LANG} compiler during all build types.")
mark_as_advanced(CMAKE_${LANG}_FLAGS)
foreach(CONFIG RELEASE;DEBUG;OPTIMIZED)
set(CMAKE_${LANG}_FLAGS_${CONFIG} "${CMAKE_${LANG}_FLAGS_${CONFIG}_INIT}" CACHE STRING "Flags used by the ${LANG} compiler during ${CONFIG} builds.")
mark_as_advanced(CMAKE_${LANG}_FLAGS_${CONFIG})
endforeach()
endforeach()
``` | /content/code_sandbox/cmake/flags-gcc.cmake | cmake | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 483 |
```cmake
#
# 86Box A hypervisor and IBM PC system emulator that specializes in
# running old operating systems and software designed for IBM
# PC systems and compatibles from 1981 through fairly recent
# system designs based on the PCI bus.
#
# This file is part of the 86Box distribution.
#
# CMake toolchain file defining GCC compiler flags
# for AArch64 (ARM64) targets.
#
# Authors: David Hrdlika, <hrdlickadavid@outlook.com>
#
#
string(APPEND CMAKE_C_FLAGS_INIT " -march=armv8-a")
string(APPEND CMAKE_CXX_FLAGS_INIT " -march=armv8-a")
include(${CMAKE_CURRENT_LIST_DIR}/flags-gcc.cmake)
``` | /content/code_sandbox/cmake/flags-gcc-aarch64.cmake | cmake | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 171 |
```cmake
#
# 86Box A hypervisor and IBM PC system emulator that specializes in
# running old operating systems and software designed for IBM
# PC systems and compatibles from 1981 through fairly recent
# system designs based on the PCI bus.
#
# This file is part of the 86Box distribution.
#
# CMake toolchain file for Clang on Windows builds (x86 target).
#
# Authors: David Hrdlika, <hrdlickadavid@outlook.com>
#
#
include(${CMAKE_CURRENT_LIST_DIR}/flags-gcc-i686.cmake)
# Use the GCC-compatible Clang executables in order to use our flags
set(CMAKE_C_COMPILER clang)
set(CMAKE_CXX_COMPILER clang++)
# `llvm-rc` is barely usable as of LLVM 13, using MS' rc.exe for now
set(CMAKE_RC_COMPILER rc)
set(CMAKE_C_COMPILER_TARGET i686-pc-windows-msvc)
set(CMAKE_CXX_COMPILER_TARGET i686-pc-windows-msvc)
set(CMAKE_SYSTEM_PROCESSOR X86)
# TODO: set the vcpkg target triplet perhaps?
``` | /content/code_sandbox/cmake/llvm-win32-i686.cmake | cmake | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 245 |
```cmake
#
# 86Box A hypervisor and IBM PC system emulator that specializes in
# running old operating systems and software designed for IBM
# PC systems and compatibles from 1981 through fairly recent
# system designs based on the PCI bus.
#
# This file is part of the 86Box distribution.
#
# CMake toolchain file defining GCC compiler flags
# for 32-bit x86 targets.
#
# Authors: David Hrdlika, <hrdlickadavid@outlook.com>
#
#
string(APPEND CMAKE_C_FLAGS_INIT " -m32 -march=i686 -msse2 -mfpmath=sse -mstackrealign")
string(APPEND CMAKE_CXX_FLAGS_INIT " -m32 -march=i686 -msse2 -mfpmath=sse -mstackrealign")
include(${CMAKE_CURRENT_LIST_DIR}/flags-gcc.cmake)
``` | /content/code_sandbox/cmake/flags-gcc-i686.cmake | cmake | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 199 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Configure-time architecture detection for the CMake build.
*
*
*
* Authors: David Hrdlika, <hrdlickadavid@outlook.com>
*
*/
#if defined(__arm__) || defined(__TARGET_ARCH_ARM)
# error ARCH arm
#elif defined(__aarch64__) || defined(_M_ARM64)
# error ARCH arm64
#elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
# error ARCH i386
#elif defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(_M_X64)
# error ARCH x86_64
#endif
#error ARCH unknown
``` | /content/code_sandbox/src/arch_detect.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 218 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Distributed DMA emulation.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include "cpu.h"
#include <86box/device.h>
#include <86box/mem.h>
#include <86box/io.h>
#include <86box/pci.h>
#include <86box/pic.h>
#include <86box/timer.h>
#include <86box/keyboard.h>
#include <86box/nvr.h>
#include <86box/pit.h>
#include <86box/dma.h>
#include <86box/ddma.h>
#include <86box/plat_unused.h>
#ifdef ENABLE_DDMA_LOG
int ddma_do_log = ENABLE_DDMA_LOG;
static void
ddma_log(const char *fmt, ...)
{
va_list ap;
if (ddma_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define ddma_log(fmt, ...)
#endif
static uint8_t
ddma_reg_read(uint16_t addr, void *priv)
{
const ddma_channel_t *dev = (ddma_channel_t *) priv;
uint8_t ret = 0xff;
int ch = dev->channel;
uint8_t dmab = (ch >= 4) ? 0xc0 : 0x00;
switch (addr & 0x0f) {
case 0x00:
ret = dma[ch].ac & 0xff;
break;
case 0x01:
ret = (dma[ch].ac >> 8) & 0xff;
break;
case 0x02:
ret = dma[ch].page;
break;
case 0x04:
ret = dma[ch].cc & 0xff;
break;
case 0x05:
ret = (dma[ch].cc >> 8) & 0xff;
break;
case 0x09:
ret = inb(dmab + 0x08);
break;
default:
break;
}
return ret;
}
static void
ddma_reg_write(uint16_t addr, uint8_t val, void *priv)
{
const ddma_channel_t *dev = (ddma_channel_t *) priv;
int ch = dev->channel;
uint8_t page_regs[4] = { 7, 3, 1, 2 };
uint8_t dmab = (ch >= 4) ? 0xc0 : 0x00;
switch (addr & 0x0f) {
case 0x00:
dma[ch].ab = (dma[ch].ab & 0xffff00) | val;
dma[ch].ac = dma[ch].ab;
break;
case 0x01:
dma[ch].ab = (dma[ch].ab & 0xff00ff) | (val << 8);
dma[ch].ac = dma[ch].ab;
break;
case 0x02:
if (ch >= 4)
outb(0x88 + page_regs[ch & 3], val);
else
outb(0x80 + page_regs[ch & 3], val);
break;
case 0x04:
dma[ch].cb = (dma[ch].cb & 0xffff00) | val;
dma[ch].cc = dma[ch].cb;
break;
case 0x05:
dma[ch].cb = (dma[ch].cb & 0xff00ff) | (val << 8);
dma[ch].cc = dma[ch].cb;
break;
case 0x08:
outb(dmab + 0x08, val);
break;
case 0x09:
outb(dmab + 0x09, val);
break;
case 0x0a:
outb(dmab + 0x0a, val);
break;
case 0x0b:
outb(dmab + 0x0b, val);
break;
case 0x0d:
outb(dmab + 0x0d, val);
break;
case 0x0e:
for (uint8_t i = 0; i < 4; i++)
outb(dmab + 0x0a, i);
break;
case 0x0f:
outb(dmab + 0x0a, (val << 2) | (ch & 3));
break;
default:
break;
}
}
void
ddma_update_io_mapping(ddma_t *dev, int ch, uint8_t base_l, uint8_t base_h, int enable)
{
if (dev->channels[ch].enable && (dev->channels[ch].io_base != 0x0000))
io_removehandler(dev->channels[ch].io_base, 0x10, ddma_reg_read, NULL, NULL, ddma_reg_write, NULL, NULL, &dev->channels[ch]);
dev->channels[ch].io_base = base_l | (base_h << 8);
dev->channels[ch].enable = enable;
if (dev->channels[ch].enable && (dev->channels[ch].io_base != 0x0000))
io_sethandler(dev->channels[ch].io_base, 0x10, ddma_reg_read, NULL, NULL, ddma_reg_write, NULL, NULL, &dev->channels[ch]);
}
static void
ddma_close(void *priv)
{
ddma_t *dev = (ddma_t *) priv;
free(dev);
}
static void *
ddma_init(UNUSED(const device_t *info))
{
ddma_t *dev;
dev = (ddma_t *) malloc(sizeof(ddma_t));
if (dev == NULL)
return (NULL);
memset(dev, 0x00, sizeof(ddma_t));
for (uint8_t i = 0; i < 8; i++)
dev->channels[i].channel = i;
return dev;
}
const device_t ddma_device = {
.name = "Distributed DMA",
.internal_name = "ddma",
.flags = DEVICE_PCI,
.local = 0,
.init = ddma_init,
.close = ddma_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/ddma.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,539 |
```cmake
#
# 86Box A hypervisor and IBM PC system emulator that specializes in
# running old operating systems and software designed for IBM
# PC systems and compatibles from 1981 through fairly recent
# system designs based on the PCI bus.
#
# This file is part of the 86Box distribution.
#
# CMake toolchain file defining GCC compiler flags
# for 64-bit x86 targets.
#
# Authors: David Hrdlika, <hrdlickadavid@outlook.com>
#
#
string(APPEND CMAKE_C_FLAGS_INIT " -m64 -march=x86-64 -msse2 -mfpmath=sse -mstackrealign")
string(APPEND CMAKE_CXX_FLAGS_INIT " -m64 -march=x86-64 -msse2 -mfpmath=sse -mstackrealign")
include(${CMAKE_CURRENT_LIST_DIR}/flags-gcc.cmake)
``` | /content/code_sandbox/cmake/flags-gcc-x86_64.cmake | cmake | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 203 |
```cmake
#
# 86Box A hypervisor and IBM PC system emulator that specializes in
# running old operating systems and software designed for IBM
# PC systems and compatibles from 1981 through fairly recent
# system designs based on the PCI bus.
#
# This file is part of the 86Box distribution.
#
# CMake toolchain file for Clang on Windows builds (x64/AMD64 target).
#
# Authors: David Hrdlika, <hrdlickadavid@outlook.com>
#
#
include(${CMAKE_CURRENT_LIST_DIR}/flags-gcc-x86_64.cmake)
# Use the GCC-compatible Clang executables in order to use our flags
set(CMAKE_C_COMPILER clang)
set(CMAKE_CXX_COMPILER clang++)
# `llvm-rc` is barely usable as of LLVM 13, using MS' rc.exe for now
set(CMAKE_RC_COMPILER rc)
set(CMAKE_C_COMPILER_TARGET x86_64-pc-windows-msvc)
set(CMAKE_CXX_COMPILER_TARGET x86_64-pc-windows-msvc)
set(CMAKE_SYSTEM_PROCESSOR AMD64)
# TODO: set the vcpkg target triplet perhaps?
``` | /content/code_sandbox/cmake/llvm-win32-x86_64.cmake | cmake | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 254 |
```shell
#!/bin/sh
#
# 86Box A hypervisor and IBM PC system emulator that specializes in
# running old operating systems and software designed for IBM
# PC systems and compatibles from 1981 through fairly recent
# system designs based on the PCI bus.
#
# This file is part of the 86Box distribution.
#
# Convenience script for changing the emulator's version.
#
#
# Authors: RichardG, <richardg867@gmail.com>
#
#
# Parse arguments.
newversion="$1"
romversion="$2"
if [ -z "$(echo "$newversion" | grep '\.')" ]
then
echo '[!] Usage: bumpversion.sh x.y[.z] [romversion]'
exit 1
fi
shift
if [ -z "${romversion}" ]; then
# Get the latest ROM release from the GitHub API.
romversion=$(curl --silent "path_to_url" |
grep '"tag_name":' |
sed -E 's/.*"v([^"]+)".*/\1/')
fi
# Switch to the repository root directory.
cd "$(dirname "$0")" || exit
pretty_date() {
# Ensure we get the date in English.
LANG=en_US.UTF-8 date '+%a %b %d %Y'
}
# Patch files.
patch_file() {
# Stop if the file doesn't exist.
[ ! -e "$1" ] && return
# Patch file.
if sed -i -r -e "$3" "$1"
then
echo "[-] Patched $2 on $1"
else
echo "[!] Patching $2 on $1 failed"
fi
}
patch_file CMakeLists.txt VERSION 's/^(\s*VERSION ).+/\1'"$newversion"'/'
patch_file vcpkg.json version-string 's/(^\s*"version-string"\s*:\s*")[^"]+/\1'"$newversion"'/'
patch_file src/unix/assets/*.spec Version 's/(Version:\s+)[0-9].+/\1'"$newversion"'/'
patch_file src/unix/assets/*.spec '%global romver' 's/(^%global\ romver\s+)[0-9]{8}/\1'"$romversion"'/'
patch_file src/unix/assets/*.spec 'changelog version' 's/(^[*]\s.*>\s+)[0-9].+/\1'"$newversion"-1'/'
patch_file src/unix/assets/*.spec 'changelog date' 's/(^[*]\s)[a-zA-Z]{3}\s[a-zA-Z]{3}\s[0-9]{2}\s[0-9]{4}/\1'"$(pretty_date)"'/'
patch_file src/unix/assets/*.metainfo.xml release 's/(<release version=")[^"]+(" date=")[^"]+/\1'"$newversion"'\2'"$(date +%Y-%m-%d)"'/'
patch_file debian/changelog 'changelog date' 's/> .+/> '"$(date -R)"'/'
patch_file debian/changelog 'changelog version' 's/86box \(.+\)/86box \('"$newversion"'\)/'
``` | /content/code_sandbox/bumpversion.sh | shell | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 698 |
```cmake
#
# 86Box A hypervisor and IBM PC system emulator that specializes in
# running old operating systems and software designed for IBM
# PC systems and compatibles from 1981 through fairly recent
# system designs based on the PCI bus.
#
# This file is part of the 86Box distribution.
#
# CMake toolchain file defining Clang compiler flags
# for AArch64 (ARM64)-based Apple Silicon targets.
#
# Authors: David Hrdlika, <hrdlickadavid@outlook.com>
# dob205
#
#
string(APPEND CMAKE_C_FLAGS_INIT " -march=armv8.5-a+simd")
string(APPEND CMAKE_CXX_FLAGS_INIT " -march=armv8.5-a+simd")
include(${CMAKE_CURRENT_LIST_DIR}/flags-gcc.cmake)
``` | /content/code_sandbox/cmake/llvm-macos-aarch64.cmake | cmake | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 188 |
```cmake
#
# 86Box A hypervisor and IBM PC system emulator that specializes in
# running old operating systems and software designed for IBM
# PC systems and compatibles from 1981 through fairly recent
# system designs based on the PCI bus.
#
# This file is part of the 86Box distribution.
#
# CMake toolchain file for Clang on Windows builds (ARM64 target).
#
# Authors: David Hrdlika, <hrdlickadavid@outlook.com>
#
#
include(${CMAKE_CURRENT_LIST_DIR}/flags-gcc-aarch64.cmake)
# Use the GCC-compatible Clang executables in order to use our flags
set(CMAKE_C_COMPILER clang)
set(CMAKE_CXX_COMPILER clang++)
# `llvm-rc` is barely usable as of LLVM 13, using MS' rc.exe for now
set(CMAKE_RC_COMPILER rc)
set(CMAKE_C_COMPILER_TARGET aarch64-pc-windows-msvc)
set(CMAKE_CXX_COMPILER_TARGET aarch64-pc-windows-msvc)
set(CMAKE_SYSTEM_PROCESSOR ARM64)
# TODO: set the vcpkg target triplet perhaps?
``` | /content/code_sandbox/cmake/llvm-win32-aarch64.cmake | cmake | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 248 |
```cmake
#
# 86Box A hypervisor and IBM PC system emulator that specializes in
# running old operating systems and software designed for IBM
# PC systems and compatibles from 1981 through fairly recent
# system designs based on the PCI bus.
#
# This file is part of the 86Box distribution.
#
# CMake toolchain file defining GCC compiler flags
# for ARMv7 targets.
#
# Authors: David Hrdlika, <hrdlickadavid@outlook.com>
#
#
string(APPEND CMAKE_C_FLAGS_INIT " -march=armv7-a+fp -mfloat-abi=hard")
string(APPEND CMAKE_CXX_FLAGS_INIT " -march=armv7-a+fp -mfloat-abi=hard")
include(${CMAKE_CURRENT_LIST_DIR}/flags-gcc.cmake)
``` | /content/code_sandbox/cmake/flags-gcc-armv7.cmake | cmake | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 185 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the Intel PIC chip emulation, partially
* ported from reenigne's XTCE.
*
*
*
* Authors: Andrew Jenner, <path_to_url
* Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include "cpu.h"
#include <86box/machine.h>
#include <86box/io.h>
#include <86box/pci.h>
#include <86box/pic.h>
#include <86box/timer.h>
#include <86box/pit.h>
#include <86box/device.h>
#include <86box/apm.h>
#include <86box/nvr.h>
#include <86box/acpi.h>
#include <86box/plat_unused.h>
enum {
STATE_NONE = 0,
STATE_ICW2,
STATE_ICW3,
STATE_ICW4
};
pic_t pic;
pic_t pic2;
static pc_timer_t pic_timer;
static int shadow = 0;
static int elcr_enabled = 0;
static int tmr_inited = 0;
static int pic_pci = 0;
static int kbd_latch = 0;
static int mouse_latch = 0;
static uint16_t smi_irq_mask = 0x0000;
static uint16_t smi_irq_status = 0x0000;
static uint16_t latched_irqs = 0x0000;
static void (*update_pending)(void);
#ifdef ENABLE_PIC_LOG
int pic_do_log = ENABLE_PIC_LOG;
static void
pic_log(const char *fmt, ...)
{
va_list ap;
if (pic_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define pic_log(fmt, ...)
#endif
void
pic_reset_smi_irq_mask(void)
{
smi_irq_mask = 0x0000;
}
void
pic_set_smi_irq_mask(int irq, int set)
{
if ((irq >= 0) && (irq <= 15)) {
if (set)
smi_irq_mask |= (1 << irq);
else
smi_irq_mask &= ~(1 << irq);
}
}
uint16_t
pic_get_smi_irq_status(void)
{
return smi_irq_status;
}
void
pic_clear_smi_irq_status(int irq)
{
if ((irq >= 0) && (irq <= 15))
smi_irq_status &= ~(1 << irq);
}
void
pic_elcr_write(uint16_t port, uint8_t val, void *priv)
{
pic_t *dev = (pic_t *) priv;
pic_log("ELCR%i: WRITE %02X\n", port & 1, val);
if (port & 1)
val &= 0xde;
else
val &= 0xf8;
dev->elcr = val;
pic_log("ELCR %i: %c %c %c %c %c %c %c %c\n",
port & 1,
(val & 1) ? 'L' : 'E',
(val & 2) ? 'L' : 'E',
(val & 4) ? 'L' : 'E',
(val & 8) ? 'L' : 'E',
(val & 0x10) ? 'L' : 'E',
(val & 0x20) ? 'L' : 'E',
(val & 0x40) ? 'L' : 'E',
(val & 0x80) ? 'L' : 'E');
}
uint8_t
pic_elcr_read(UNUSED(uint16_t port), void *priv)
{
const pic_t *dev = (pic_t *) priv;
pic_log("ELCR%i: READ %02X\n", port & 1, dev->elcr);
return dev->elcr;
}
int
pic_elcr_get_enabled(void)
{
return elcr_enabled;
}
void
pic_elcr_set_enabled(int enabled)
{
elcr_enabled = enabled;
}
void
pic_elcr_io_handler(int set)
{
io_handler(set, 0x04d0, 0x0001,
pic_elcr_read, NULL, NULL,
pic_elcr_write, NULL, NULL, &pic);
io_handler(set, 0x04d1, 0x0001,
pic_elcr_read, NULL, NULL,
pic_elcr_write, NULL, NULL, &pic2);
}
static uint8_t
pic_cascade_mode(pic_t *dev)
{
return !(dev->icw1 & 2);
}
static __inline uint8_t
pic_slave_on(pic_t *dev, int channel)
{
pic_log("pic_slave_on(%i): %i, %02X, %02X\n", channel, pic_cascade_mode(dev), dev->icw4 & 0x0c, dev->icw3 & (1 << channel));
return pic_cascade_mode(dev) && (dev->is_master || ((dev->icw4 & 0x0c) == 0x0c)) && (dev->icw3 & (1 << channel));
}
static __inline int
find_best_interrupt(pic_t *dev)
{
uint8_t b;
uint8_t intr;
uint8_t j;
int8_t ret = -1;
for (uint8_t i = 0; i < 8; i++) {
j = (i + dev->priority) & 7;
b = 1 << j;
if (dev->isr & b)
break;
else if ((dev->state == 0) && ((dev->irr & ~dev->imr) & b)) {
ret = j;
break;
}
}
intr = dev->interrupt = (ret == -1) ? 0x17 : ret;
if (dev->at && (ret != -1)) {
if (dev == &pic2)
intr += 8;
if (cpu_fast_off_flags & (1u << intr))
cpu_fast_off_advance();
}
return ret;
}
static __inline void
pic_update_pending_xt(void)
{
if (!(pic.interrupt & 0x20))
pic.int_pending = (find_best_interrupt(&pic) != -1);
}
/* Only check if PIC 1 frozen, because it should not happen
that one is frozen but the other is not. */
static __inline void
pic_update_pending_at(void)
{
if (!(pic.interrupt & 0x20)) {
pic2.int_pending = (find_best_interrupt(&pic2) != -1);
if (pic2.int_pending)
pic.irr |= (1 << pic2.icw3);
else
pic.irr &= ~(1 << pic2.icw3);
pic.int_pending = (find_best_interrupt(&pic) != -1);
}
}
static void
pic_callback(void *priv)
{
update_pending();
}
void
pic_reset(void)
{
int is_at = IS_AT(machine);
is_at = is_at || !strcmp(machine_get_internal_name(), "xi8088");
memset(&pic, 0, sizeof(pic_t));
memset(&pic2, 0, sizeof(pic_t));
pic.is_master = 1;
pic.interrupt = pic2.interrupt = 0x17;
if (is_at)
pic.slaves[2] = &pic2;
if (tmr_inited)
timer_on_auto(&pic_timer, 0.0);
memset(&pic_timer, 0x00, sizeof(pc_timer_t));
timer_add(&pic_timer, pic_callback, &pic, 0);
tmr_inited = 1;
update_pending = is_at ? pic_update_pending_at : pic_update_pending_xt;
pic.at = pic2.at = is_at;
smi_irq_mask = smi_irq_status = 0x0000;
shadow = 0;
pic_pci = 0;
}
void
pic_set_shadow(int sh)
{
shadow = sh;
}
int
pic_get_pci_flag(void)
{
return pic_pci;
}
void
pic_set_pci_flag(int pci)
{
pic_pci = pci;
}
static uint8_t
pic_level_triggered(pic_t *dev, int irq)
{
if (elcr_enabled)
return !!(dev->elcr & (1 << irq));
else
return !!(dev->icw1 & 8);
}
int
picint_is_level(int irq)
{
return pic_level_triggered(((irq > 7) ? &pic2 : &pic), irq & 7);
}
static void
pic_acknowledge(pic_t *dev)
{
int pic_int = dev->interrupt & 7;
int pic_int_num = 1 << pic_int;
dev->isr |= pic_int_num;
if (!pic_level_triggered(dev, pic_int) || (dev->lines[pic_int] == 0))
dev->irr &= ~pic_int_num;
}
/* Find IRQ for non-specific EOI (either by command or automatic) by finding the highest IRQ
priority with ISR bit set, that is also not masked if the PIC is in special mask mode. */
static uint8_t
pic_non_specific_find(pic_t *dev)
{
uint8_t j;
uint8_t b;
uint8_t irq = 0xff;
for (uint8_t i = 0; i < 8; i++) {
j = (i + dev->priority) & 7;
b = (1 << j);
if ((dev->isr & b) && (!dev->special_mask_mode || !(dev->imr & b))) {
irq = j;
break;
}
}
return irq;
}
/* Do the EOI and rotation, if either is requested, on the given IRQ. */
static void
pic_action(pic_t *dev, uint8_t irq, uint8_t eoi, uint8_t rotate)
{
uint8_t b = (1 << irq);
if (irq != 0xff) {
if (eoi)
dev->isr &= ~b;
if (rotate)
dev->priority = (irq + 1) & 7;
update_pending();
}
}
/* Automatic non-specific EOI. */
static __inline void
pic_auto_non_specific_eoi(pic_t *dev)
{
uint8_t irq;
if (dev->icw4 & 2) {
irq = pic_non_specific_find(dev);
pic_action(dev, irq, 1, dev->auto_eoi_rotate);
}
}
/* Do the PIC command specified by bits 7-5 of the value written to the OCW2 register. */
static void
pic_command(pic_t *dev)
{
uint8_t irq = 0xff;
if (dev->ocw2 & 0x60) { /* SL and/or EOI set */
if (dev->ocw2 & 0x40) /* SL set, specific priority level */
irq = (dev->ocw2 & 0x07);
else /* SL clear, non-specific priority level (find highest with ISR set) */
irq = pic_non_specific_find(dev);
pic_action(dev, irq, dev->ocw2 & 0x20, dev->ocw2 & 0x80);
} else /* SL and EOI clear */
dev->auto_eoi_rotate = !!(dev->ocw2 & 0x80);
}
uint8_t
pic_latch_read(UNUSED(uint16_t addr), UNUSED(void *priv))
{
uint8_t ret = 0xff;
pic_log("pic_latch_read(%i, %i)\n", kbd_latch, mouse_latch);
if (kbd_latch && (latched_irqs & 0x0002))
picintc(0x0002);
if (mouse_latch && (latched_irqs & 0x1000))
picintc(0x1000);
/* Return FF - we just lower IRQ 1 and IRQ 12. */
return ret;
}
uint8_t
pic_read_icw(uint8_t pic_id, uint8_t icw)
{
pic_t *dev = pic_id ? &pic2 : &pic;
uint8_t ret = 0xff;
switch (icw) {
case 0x00:
ret = dev->icw1;
break;
case 0x01:
ret = dev->icw2;
break;
case 0x02:
ret = dev->icw3;
break;
case 0x03:
ret = dev->icw4;
break;
}
return ret;
}
uint8_t
pic_read_ocw(uint8_t pic_id, uint8_t ocw)
{
pic_t *dev = pic_id ? &pic2 : &pic;
uint8_t ret = 0xff;
switch (ocw) {
case 0x00:
ret = dev->ocw2;
break;
case 0x01:
ret = dev->ocw3;
break;
}
return ret;
}
uint8_t
pic_read(uint16_t addr, void *priv)
{
pic_t *dev = (pic_t *) priv;
if (shadow) {
/* VIA PIC shadow read */
if (addr & 0x0001)
dev->data_bus = ((dev->icw2 & 0xf8) >> 3) << 0;
else {
dev->data_bus = ((dev->ocw3 & 0x20) >> 5) << 4;
dev->data_bus |= ((dev->ocw2 & 0x80) >> 7) << 3;
dev->data_bus |= ((dev->icw4 & 0x10) >> 4) << 2;
dev->data_bus |= ((dev->icw4 & 0x02) >> 1) << 1;
dev->data_bus |= ((dev->icw4 & 0x08) >> 3) << 0;
}
} else {
/* Standard 8259 PIC read */
#ifndef UNDEFINED_READ
/* Put the IRR on to the data bus by default until the real PIC is probed. */
dev->data_bus = dev->irr;
#endif
if (dev->ocw3 & 0x04) {
dev->interrupt &= ~0x20; /* Freeze the interrupt until the poll is over. */
if (dev->int_pending) {
dev->data_bus = 0x80 | (dev->interrupt & 7);
pic_acknowledge(dev);
dev->int_pending = 0;
update_pending();
} else
dev->data_bus = 0x00;
dev->ocw3 &= ~0x04;
} else if (addr & 0x0001)
dev->data_bus = dev->imr;
else if (dev->ocw3 & 0x02) {
if (dev->ocw3 & 0x01)
dev->data_bus = dev->isr;
#ifdef UNDEFINED_READ
else
dev->data_bus = 0x00;
#endif
}
/* If A0 = 0, VIA shadow is disabled, and poll mode is disabled,
simply read whatever is currently on the data bus. */
}
pic_log("pic_read(%04X, %08X) = %02X\n", addr, priv, dev->data_bus);
return dev->data_bus;
}
static void
pic_write(uint16_t addr, uint8_t val, void *priv)
{
pic_t *dev = (pic_t *) priv;
pic_log("pic_write(%04X, %02X, %08X)\n", addr, val, priv);
dev->data_bus = val;
if (addr & 0x0001) {
switch (dev->state) {
case STATE_ICW2:
dev->icw2 = val;
if (pic_cascade_mode(dev))
dev->state = STATE_ICW3;
else
dev->state = (dev->icw1 & 1) ? STATE_ICW4 : STATE_NONE;
break;
case STATE_ICW3:
dev->icw3 = val;
dev->state = (dev->icw1 & 1) ? STATE_ICW4 : STATE_NONE;
break;
case STATE_ICW4:
dev->icw4 = val;
dev->state = STATE_NONE;
break;
case STATE_NONE:
dev->imr = val;
if (is286)
update_pending();
else
timer_on_auto(&pic_timer, .0 * ((10000000.0 * (double) xt_cpu_multi) / (double) cpu_s->rspeed));
break;
default:
break;
}
} else {
if (val & 0x10) {
/* Treat any write with any of the bits 7 to 5 set as invalid if PCI. */
if (pic_pci && (val & 0xe0))
return;
dev->icw1 = val;
dev->icw2 = dev->icw3 = 0x00;
if (!(dev->icw1 & 1))
dev->icw4 = 0x00;
dev->ocw2 = dev->ocw3 = 0x00;
dev->irr = 0x00;
for (uint8_t i = 0; i <= 7; i++) {
if (dev->lines[i] > 0)
dev->irr |= (1 << i);
}
dev->imr = dev->isr = 0x00;
dev->ack_bytes = dev->priority = 0x00;
dev->auto_eoi_rotate = dev->special_mask_mode = 0x00;
dev->interrupt = 0x17;
dev->int_pending = 0x00;
dev->state = STATE_ICW2;
update_pending();
} else if (val & 0x08) {
dev->ocw3 = val;
if (dev->ocw3 & 0x04)
dev->interrupt |= 0x20; /* Freeze the interrupt until the poll is over. */
if (dev->ocw3 & 0x40)
dev->special_mask_mode = !!(dev->ocw3 & 0x20);
} else {
dev->ocw2 = val;
pic_command(dev);
}
}
}
void
pic_set_pci(void)
{
for (uint8_t i = 0x0024; i < 0x0040; i += 4) {
io_sethandler(i, 0x0002, pic_read, NULL, NULL, pic_write, NULL, NULL, &pic);
io_sethandler(i + 0x0080, 0x0002, pic_read, NULL, NULL, pic_write, NULL, NULL, &pic2);
}
for (uint16_t i = 0x1120; i < 0x1140; i += 4) {
io_sethandler(i, 0x0002, pic_read, NULL, NULL, pic_write, NULL, NULL, &pic);
io_sethandler(i + 0x0080, 0x0002, pic_read, NULL, NULL, pic_write, NULL, NULL, &pic2);
}
}
void
pic_kbd_latch(int enable)
{
pic_log("PIC keyboard latch now %sabled\n", enable ? "en" : "dis");
if (!!(enable | mouse_latch) != !!(kbd_latch | mouse_latch))
io_handler(!!(enable | mouse_latch), 0x0060, 0x0001, pic_latch_read, NULL, NULL, NULL, NULL, NULL, NULL);
kbd_latch = !!enable;
if (!enable)
picintc(0x0002);
}
void
pic_mouse_latch(int enable)
{
pic_log("PIC mouse latch now %sabled\n", enable ? "en" : "dis");
if (!!(kbd_latch | enable) != !!(kbd_latch | mouse_latch))
io_handler(!!(kbd_latch | enable), 0x0060, 0x0001, pic_latch_read, NULL, NULL, NULL, NULL, NULL, NULL);
mouse_latch = !!enable;
if (!enable)
picintc(0x1000);
}
static void
pic_reset_hard(void)
{
pic_reset();
/* Explicitly reset the latches. */
kbd_latch = mouse_latch = 0;
latched_irqs = 0x0000;
/* The situation is as follows: There is a giant mess when it comes to these latches on real hardware,
to the point that there's even boards with board-level latched that get used in place of the latches
on the chipset, therefore, I'm just doing this here for the sake of simplicity. */
if (machine_has_bus(machine, MACHINE_BUS_PS2_LATCH)) {
pic_kbd_latch(0x01);
pic_mouse_latch(0x01);
} else {
pic_kbd_latch(0x00);
pic_mouse_latch(0x00);
}
}
void
pic_init(void)
{
pic_reset_hard();
shadow = 0;
io_sethandler(0x0020, 0x0002, pic_read, NULL, NULL, pic_write, NULL, NULL, &pic);
}
void
pic_init_pcjr(void)
{
pic_reset_hard();
shadow = 0;
io_sethandler(0x0020, 0x0008, pic_read, NULL, NULL, pic_write, NULL, NULL, &pic);
}
void
pic2_init(void)
{
io_sethandler(0x00a0, 0x0002, pic_read, NULL, NULL, pic_write, NULL, NULL, &pic2);
pic.slaves[2] = &pic2;
}
void
picint_common(uint16_t num, int level, int set, uint8_t *irq_state)
{
int raise;
int max = 16;
uint8_t b;
uint8_t slaves = 0;
uint16_t w;
uint16_t lines = level ? 0x0000 : num;
pic_t *dev;
/* Make sure to ignore all slave IRQ's, and in case of AT+,
translate IRQ 2 to IRQ 9. */
for (uint8_t i = 0; i < 8; i++) {
b = (uint8_t) (1 << i);
raise = num & b;
if (pic.icw3 & b) {
slaves++;
if (raise) {
num &= ~b;
if (pic.at && (i == 2))
num |= (1 << 9);
}
}
}
if (!slaves)
max = 8;
if (!num) {
pic_log("Attempting to %s null IRQ\n", set ? "raise" : "lower");
return;
}
if (level) {
dev = &pic;
for (uint16_t i = 0; i < max; i++) {
if (i == 8)
dev = &pic2;
b = i & 7;
w = 1 << i;
if (num & w) {
if ((!!*irq_state) != !!set)
set ? dev->lines[b]++ : dev->lines[b]--;
if (!pic_level_triggered(dev, b) ||
(((!!*irq_state) != !!set) && (dev->lines[b] == (!!set))))
lines |= w;
}
}
if ((!!*irq_state) != !!set)
*irq_state = set;
num = lines;
}
if (!slaves)
num &= 0x00ff;
if (num & 0x0100)
acpi_rtc_status = !!set;
if (num) {
if (set) {
if (smi_irq_mask & num) {
smi_raise();
smi_irq_status |= num;
}
if (num & 0xff00) {
/* Latch IRQ 12 if the mouse latch is enabled. */
if ((num & 0x1000) && mouse_latch)
latched_irqs |= 0x1000;
pic2.irr |= (num >> 8);
}
if (num & 0x00ff) {
/* Latch IRQ 1 if the keyboard latch is enabled. */
if (kbd_latch && (num & 0x0002))
latched_irqs |= 0x0002;
pic.irr |= (num & 0x00ff);
}
} else {
smi_irq_status &= ~num;
if (num & 0xff00) {
/* Unlatch IRQ 12 if the mouse latch is enabled. */
if ((num & 0x1000) && mouse_latch)
latched_irqs &= 0xefff;
pic2.irr &= ~(num >> 8);
}
if (num & 0x00ff) {
/* Unlatch IRQ 1 if the keyboard latch is enabled. */
if (kbd_latch && (num & 0x0002))
latched_irqs &= 0xfffd;
pic.irr &= ~(num & 0x00ff);
}
}
update_pending();
}
}
static uint8_t
pic_i86_mode(pic_t *dev)
{
return !!(dev->icw4 & 1);
}
static uint8_t
pic_irq_ack_read(pic_t *dev, int phase)
{
uint8_t intr = dev->interrupt & 0x47;
uint8_t slave = intr & 0x40;
intr &= 0x07;
pic_log(" pic_irq_ack_read(%08X, %i)\n", dev, phase);
if (dev != NULL) {
if (phase == 0) {
dev->interrupt |= 0x20; /* Freeze it so it still takes interrupts but they do not
override the one currently being processed. */
pic_acknowledge(dev);
if (slave)
dev->data_bus = pic_irq_ack_read(dev->slaves[intr], phase);
else
dev->data_bus = pic_i86_mode(dev) ? 0xff : 0xcd;
} else if (pic_i86_mode(dev)) {
dev->int_pending = 0;
if (slave)
dev->data_bus = pic_irq_ack_read(dev->slaves[intr], phase);
else
dev->data_bus = intr + (dev->icw2 & 0xf8);
pic_auto_non_specific_eoi(dev);
} else if (phase == 1) {
if (slave)
dev->data_bus = pic_irq_ack_read(dev->slaves[intr], phase);
else if (dev->icw1 & 0x04)
dev->data_bus = (intr << 2) + (dev->icw1 & 0xe0);
else
dev->data_bus = (intr << 3) + (dev->icw1 & 0xc0);
} else if (phase == 2) {
dev->int_pending = 0;
if (slave)
dev->data_bus = pic_irq_ack_read(dev->slaves[intr], phase);
else
dev->data_bus = dev->icw2;
pic_auto_non_specific_eoi(dev);
}
}
return dev->data_bus;
}
uint8_t
pic_irq_ack(void)
{
uint8_t ret;
/* Needed for Xi8088. */
if ((pic.ack_bytes == 0) && pic.int_pending && pic_slave_on(&pic, pic.interrupt)) {
if (!pic.slaves[pic.interrupt]->int_pending) {
/* If we are on AT, IRQ 2 is pending, and we cannot find a pending IRQ on PIC 2, fatal out. */
fatal("IRQ %i pending on AT without a pending IRQ on PIC %i (normal)\n", pic.interrupt, pic.interrupt);
exit(-1);
}
pic.interrupt |= 0x40; /* Mark slave pending. */
}
ret = pic_irq_ack_read(&pic, pic.ack_bytes);
pic.ack_bytes = (pic.ack_bytes + 1) % (pic_i86_mode(&pic) ? 2 : 3);
if (pic.ack_bytes == 0) {
/* Needed for Xi8088. */
if (pic.interrupt & 0x40)
pic2.interrupt = 0x17;
pic.interrupt = 0x17;
update_pending();
}
return ret;
}
int
picinterrupt(void)
{
int ret = -1;
if (pic.int_pending) {
if (pic_slave_on(&pic, pic.interrupt)) {
if (!pic.slaves[pic.interrupt]->int_pending) {
/* If we are on AT, IRQ 2 is pending, and we cannot find a pending IRQ on PIC 2, fatal out. */
// fatal("IRQ %i pending on AT without a pending IRQ on PIC %i (normal)\n", pic.interrupt, pic.interrupt);
// exit(-1);
/* Error correction mechanism: Do a supurious IRQ 15 (spurious IRQ 7 on PIC 2). */
pic.slaves[pic.interrupt]->int_pending = 1;
pic.slaves[pic.interrupt]->interrupt = 0x07;
} else
pic.interrupt |= 0x40; /* Mark slave pending. */
}
} else {
/* pic.int_pending was somehow cleared despite the fact we made it here,
do a spurious IRQ 7. */
pic.int_pending = 1;
pic.interrupt = 0x07;
}
if ((pic.interrupt == 0) && (pit_devs[1].data != NULL))
pit_devs[1].set_gate(pit_devs[1].data, 0, 0);
/* Two ACK's - do them in a loop to avoid potential compiler misoptimizations. */
for (uint8_t i = 0; i < 2; i++) {
ret = pic_irq_ack_read(&pic, pic.ack_bytes);
pic.ack_bytes = (pic.ack_bytes + 1) % (pic_i86_mode(&pic) ? 2 : 3);
if (pic.ack_bytes == 0) {
if (pic.interrupt & 0x40)
pic2.interrupt = 0x17;
pic.interrupt = 0x17;
update_pending();
}
}
return ret;
}
``` | /content/code_sandbox/src/pic.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 6,943 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* The handler of the new logging system.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
* Fred N. van Kempen, <decwiz@yahoo.com>
*
*/
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/config.h>
#include <86box/mem.h>
#include "cpu.h"
#include <86box/plat.h>
#include <86box/version.h>
#include <86box/log.h>
#ifndef RELEASE_BUILD
typedef struct log_t {
char buff[1024];
char *dev_name;
int seen;
int suppr_seen;
} log_t;
extern FILE *stdlog; /* file to log output to */
void
log_set_suppr_seen(void *priv, int suppr_seen)
{
log_t *log = (log_t *) priv;
log->suppr_seen = suppr_seen;
}
void
log_set_dev_name(void *priv, char *dev_name)
{
log_t *log = (log_t *) priv;
log->dev_name = dev_name;
}
static void
log_copy(log_t *log, char *dest, const char *src, size_t dest_size)
{
memset(dest, 0x00, dest_size * sizeof(char));
if (log && log->dev_name && strcmp(log->dev_name, "")) {
strcat(dest, log->dev_name);
strcat(dest, ": ");
}
strcat(dest, src);
}
/*
* Log something to the logfile or stdout.
*
* To avoid excessively-large logfiles because some
* module repeatedly logs, we keep track of what is
* being logged, and catch repeating entries.
*/
void
log_out(void *priv, const char *fmt, va_list ap)
{
log_t *log = (log_t *) priv;
char temp[1024];
char fmt2[1024];
if (log == NULL)
return;
if (strcmp(fmt, "") == 0)
return;
if (stdlog == NULL) {
if (log_path[0] != '\0') {
stdlog = plat_fopen(log_path, "w");
if (stdlog == NULL)
stdlog = stdout;
} else
stdlog = stdout;
}
vsprintf(temp, fmt, ap);
if (log->suppr_seen && !strcmp(log->buff, temp))
log->seen++;
else {
if (log->suppr_seen && log->seen) {
log_copy(log, fmt2, "*** %d repeats ***\n", 1024);
fprintf(stdlog, fmt2, log->seen);
}
log->seen = 0;
strcpy(log->buff, temp);
log_copy(log, fmt2, temp, 1024);
fprintf(stdlog, fmt2, ap);
}
fflush(stdlog);
}
void
log_fatal(void *priv, const char *fmt, ...)
{
log_t *log = (log_t *) priv;
char temp[1024];
char fmt2[1024];
va_list ap;
if (log == NULL)
return;
va_start(ap, fmt);
log_copy(log, fmt2, fmt, 1024);
vsprintf(temp, fmt2, ap);
fatal_ex(fmt2, ap);
va_end(ap);
exit(-1);
}
void *
log_open(char *dev_name)
{
log_t *log = malloc(sizeof(log_t));
memset(log, 0, sizeof(log_t));
log->dev_name = dev_name;
log->suppr_seen = 1;
return (void *) log;
}
void
log_close(void *priv)
{
log_t *log = (log_t *) priv;
free(log);
}
#endif
``` | /content/code_sandbox/src/log.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 932 |
```c
see COPYING for more details
*/
/*IBM 5150 cassette nonsense
Calls F979 twice
Expects CX to be nonzero, BX >$410 and <$540
CX is loops between bit 4 of $62 changing
BX is timer difference between calls
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <wchar.h>
#include <86box/timer.h>
#include <86box/pit.h>
#include <86box/ppi.h>
PPI ppi;
int ppispeakon;
void
ppi_reset(void)
{
memset(&ppi, 0x00, sizeof(PPI));
}
``` | /content/code_sandbox/src/ppi.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 141 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Define the XKBD to ScanCode translation tables for VNC.
*
* VNC uses the XKBD key code definitions to transport keystroke
* information, so we just need some tables to translate those
* into PC-ready scan codes.
*
* We only support XKBD pages 0 (Latin-1) and 255 (special keys)
* in these tables, other pages (languages) not [yet] supported.
*
* The tables define up to two keystrokes.. the upper byte is
* the first keystroke, and the lower byte the second. If value
* is 0x00, the keystroke is not sent.
*
* NOTE: The values are as defined in the Microsoft document named
* "Keyboard Scan Code Specification", version 1.3a of 2000/03/16.
*
*
*
* Authors: Fred N. van Kempen, <decwiz@yahoo.com>
* Based on raw code by RichardG, <richardg867@gmail.com>
*
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/keyboard.h>
#include <86box/plat.h>
#include <86box/vnc.h>
static int keysyms_00[] = {
0x0000, /* 0x00 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x08 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x10 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x18 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0039, /* 0x20 (XK_space) */
0x2a02, /* 0x21 (XK_exclam) */
0x2a28, /* 0x22 (XK_quotedbl) */
0x2a04, /* 0x23 (XK_numbersign) */
0x2a05, /* 0x24 (XK_dollar) */
0x2a06, /* 0x25 (XK_percent) */
0x2a08, /* 0x26 (XK_ampersand) */
0x0028, /* 0x27 (XK_apostrophe) */
0x2a0a, /* 0x28 (XK_parenleft) */
0x2a0b, /* 0x29 (XK_parenright) */
0x2a09, /* 0x2a (XK_asterisk) */
0x2a0d, /* 0x2b (XK_plus) */
0x0033, /* 0x2c (XK_comma) */
0x000c, /* 0x2d (XK_minus) */
0x0034, /* 0x2e (XK_period) */
0x0035, /* 0x2f (XK_slash) */
0x000b, /* 0x30 (XK_0) */
0x0002, /* 0x31 (XK_1) */
0x0003, /* 0x32 (XK_2) */
0x0004, /* 0x33 (XK_3) */
0x0005, /* 0x34 (XK_4) */
0x0006, /* 0x35 (XK_5) */
0x0007, /* 0x36 (XK_6) */
0x0008, /* 0x37 (XK_7) */
0x0009, /* 0x38 (XK_8) */
0x000a, /* 0x39 (XK_9) */
0x2a27, /* 0x3a (XK_colon) */
0x0027, /* 0x3b (XK_semicolon) */
0x2a33, /* 0x3c (XK_less) */
0x000d, /* 0x3d (XK_equal) */
0x2a34, /* 0x3e (XK_greater) */
0x2a35, /* 0x3f (XK_question) */
0x2a03, /* 0x40 (XK_at) */
0x2a1e, /* 0x41 (XK_A) */
0x2a30, /* 0x42 (XK_B) */
0x2a2e, /* 0x43 (XK_C) */
0x2a20, /* 0x44 (XK_D) */
0x2a12, /* 0x45 (XK_E) */
0x2a21, /* 0x46 (XK_F) */
0x2a22, /* 0x47 (XK_G) */
0x2a23, /* 0x48 (XK_H) */
0x2a17, /* 0x49 (XK_I) */
0x2a24, /* 0x4a (XK_J) */
0x2a25, /* 0x4b (XK_K) */
0x2a26, /* 0x4c (XK_L) */
0x2a32, /* 0x4d (XK_M) */
0x2a31, /* 0x4e (XK_N) */
0x2a18, /* 0x4f (XK_O) */
0x2a19, /* 0x50 (XK_P) */
0x2a10, /* 0x51 (XK_Q) */
0x2a13, /* 0x52 (XK_R) */
0x2a1f, /* 0x53 (XK_S) */
0x2a14, /* 0x54 (XK_T) */
0x2a16, /* 0x55 (XK_U) */
0x2a2f, /* 0x56 (XK_V) */
0x2a11, /* 0x57 (XK_W) */
0x2a2d, /* 0x58 (XK_X) */
0x2a15, /* 0x59 (XK_Y) */
0x2a2c, /* 0x5a (XK_Z) */
0x001a, /* 0x5b (XK_bracketleft) */
0x002b, /* 0x5c (XK_backslash) */
0x001b, /* 0x5d (XK_bracketright) */
0x2a07, /* 0x5e (XK_asciicircum) */
0x2a0c, /* 0x5f (XK_underscore) */
0x0029, /* 0x60 (XK_grave) */
0x001e, /* 0x61 (XK_a) */
0x0030, /* 0x62 (XK_b) */
0x002e, /* 0x63 (XK_c) */
0x0020, /* 0x64 (XK_d) */
0x0012, /* 0x65 (XK_e) */
0x0021, /* 0x66 (XK_f) */
0x0022, /* 0x67 (XK_g) */
0x0023, /* 0x68 (XK_h) */
0x0017, /* 0x69 (XK_i) */
0x0024, /* 0x6a (XK_j) */
0x0025, /* 0x6b (XK_k) */
0x0026, /* 0x6c (XK_l) */
0x0032, /* 0x6d (XK_m) */
0x0031, /* 0x6e (XK_n) */
0x0018, /* 0x6f (XK_o) */
0x0019, /* 0x70 (XK_p) */
0x0010, /* 0x71 (XK_q) */
0x0013, /* 0x72 (XK_r) */
0x001f, /* 0x73 (XK_s) */
0x0014, /* 0x74 (XK_t) */
0x0016, /* 0x75 (XK_u) */
0x002f, /* 0x76 (XK_v) */
0x0011, /* 0x77 (XK_w) */
0x002d, /* 0x78 (XK_x) */
0x0015, /* 0x79 (XK_y) */
0x002c, /* 0x7a (XK_z) */
0x2a1a, /* 0x7b (XK_braceleft) */
0x2a2b, /* 0x7c (XK_bar) */
0x2a1b, /* 0x7d (XK_braceright) */
0x2a29, /* 0x7e (XK_asciitilde) */
0x0053, /* 0x7f (XK_delete) */
0x0000, /* 0x80 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x88 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x90 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x98 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0xa0 (XK_nobreakspace) */
0x0000, /* 0xa1 (XK_exclamdown) */
0x0000, /* 0xa2 (XK_cent) */
0x0000, /* 0xa3 (XK_sterling) */
0x0000, /* 0xa4 (XK_currency) */
0x0000, /* 0xa5 (XK_yen) */
0x0000, /* 0xa6 (XK_brokenbar) */
0x0000, /* 0xa7 (XK_section) */
0x0000, /* 0xa8 (XK_diaeresis) */
0x0000, /* 0xa9 (XK_copyright) */
0x0000, /* 0xaa (XK_ordfeminine) */
0x0000, /* 0xab (XK_guillemotleft) */
0x0000, /* 0xac (XK_notsign) */
0x0000, /* 0xad (XK_hyphen) */
0x0000, /* 0xae (XK_registered) */
0x0000, /* 0xaf (XK_macron) */
0x0000, /* 0xb0 (XK_degree) */
0x0000, /* 0xb1 (XK_plusminus) */
0x0000, /* 0xb2 (XK_twosuperior) */
0x0000, /* 0xb3 (XK_threesuperior) */
0x0000, /* 0xb4 (XK_acute) */
0x0000, /* 0xb5 (XK_mu) */
0x0000, /* 0xb6 (XK_paragraph) */
0x0000, /* 0xb7 (XK_periodcentered) */
0x0000, /* 0xb8 (XK_cedilla) */
0x0000, /* 0xb9 (XK_onesuperior) */
0x0000, /* 0xba (XK_masculine) */
0x0000, /* 0xbb (XK_guillemotright) */
0x0000, /* 0xbc (XK_onequarter) */
0x0000, /* 0xbd (XK_onehalf) */
0x0000, /* 0xbe (XK_threequarters) */
0x0000, /* 0xbf (XK_questiondown) */
0x0000, /* 0xc0 (XK_Agrave) */
0x0000, /* 0xc1 (XK_Aacute) */
0x0000, /* 0xc2 (XK_Acircumflex) */
0x0000, /* 0xc3 (XK_Atilde) */
0x0000, /* 0xc4 (XK_Adiaeresis) */
0x0000, /* 0xc5 (XK_Aring) */
0x0000, /* 0xc6 (XK_AE) */
0x0000, /* 0xc7 (XK_Ccedilla) */
0x0000, /* 0xc8 (XK_Egrave) */
0x0000, /* 0xc9 (XK_Eacute) */
0x0000, /* 0xca (XK_Ecircumflex) */
0x0000, /* 0xcb (XK_Ediaeresis) */
0x0000, /* 0xcc (XK_Igrave) */
0x0000, /* 0xcd (XK_Iacute) */
0x0000, /* 0xce (XK_Icircumflex) */
0x0000, /* 0xcf (XK_Idiaeresis) */
0x0000, /* 0xd0 (XK_ETH, also XK_Eth) */
0x0000, /* 0xd1 (XK_Ntilde) */
0x0000, /* 0xd2 (XK_Ograve) */
0x0000, /* 0xd3 (XK_Oacute) */
0x0000, /* 0xd4 (XK_Ocircumflex) */
0x0000, /* 0xd5 (XK_Otilde) */
0x0000, /* 0xd6 (XK_Odiaeresis) */
0x0000, /* 0xd7 (XK_multiply) */
0x0000, /* 0xd8 (XK_Ooblique) */
0x0000, /* 0xd9 (XK_Ugrave) */
0x0000, /* 0xda (XK_Uacute) */
0x0000, /* 0xdb (XK_Ucircumflex) */
0x0000, /* 0xdc (XK_Udiaeresis) */
0x0000, /* 0xdd (XK_Yacute) */
0x0000, /* 0xde (XK_THORN) */
0x0000, /* 0xdf (XK_ssharp) */
0x0000, /* 0xe0 (XK_agrave) */
0x0000, /* 0xe1 (XK_aacute) */
0x0000, /* 0xe2 (XK_acircumflex) */
0x0000, /* 0xe3 (XK_atilde) */
0x0000, /* 0xe4 (XK_adiaeresis) */
0x0000, /* 0xe5 (XK_aring) */
0x0000, /* 0xe6 (XK_ae) */
0x0000, /* 0xe7 (XK_ccedilla) */
0x0000, /* 0xe8 (XK_egrave) */
0x0000, /* 0xe9 (XK_eacute) */
0x0000, /* 0xea (XK_ecircumflex) */
0x0000, /* 0xeb (XK_ediaeresis) */
0x0000, /* 0xec (XK_igrave) */
0x0000, /* 0xed (XK_iacute) */
0x0000, /* 0xee (XK_icircumflex) */
0x0000, /* 0xef (XK_idiaeresis) */
0x0000, /* 0xf0 (XK_eth) */
0x0000, /* 0xf1 (XK_ntilde) */
0x0000, /* 0xf2 (XK_ograve) */
0x0000, /* 0xf3 (XK_oacute) */
0x0000, /* 0xf4 (XK_ocircumflex) */
0x0000, /* 0xf5 (XK_otilde) */
0x0000, /* 0xf6 (XK_odiaeresis) */
0x0000, /* 0xf7 (XK_division) */
0x0000, /* 0xf8 (XK_oslash) */
0x0000, /* 0xf9 (XK_ugrave) */
0x0000, /* 0xfa (XK_uacute) */
0x0000, /* 0xfb (XK_ucircumflex) */
0x0000, /* 0xfc (XK_udiaeresis) */
0x0000, /* 0xfd (XK_yacute) */
0x0000, /* 0xfe (XK_thorn) */
0x0000 /* 0xff (XK_ydiaeresis) */
};
static int keysyms_ff[] = {
0x0000, /* 0x00 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x000e, /* 0x08 (XK_BackSpace) */
0x000f, /* 0x09 (XK_Tab) */
0x0000, /* 0x0a (XK_Linefeed) */
0x004c, /* 0x0b (XK_Clear) */
0x0000,
0x001c, /* 0x0d (XK_Return) */
0x0000,
0x0000,
0x0000, /* 0x10 */
0x0000,
0x0000,
0xff45, /* 0x13 (XK_Pause) */
0x0000, /* 0x14 (XK_Scroll_Lock) */
0x0000, /* 0x15 (XK_Sys_Req) */
0x0000,
0x0000,
0x0000, /* 0x18 */
0x0000,
0x0000,
0x0001, /* 0x1b (XK_Escape) */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x20 (XK_Multi_key) */
0x0000, /* 0x21 (XK_Kanji; Kanji, Kanji convert) */
0x0000, /* 0x22 (XK_Muhenkan; Cancel Conversion) */
0x0000, /* 0x23 (XK_Henkan_Mode; Start/Stop Conversion) */
0x0000, /* 0x24 (XK_Romaji; to Romaji) */
0x0000, /* 0x25 (XK_Hiragana; to Hiragana) */
0x0000, /* 0x26 (XK_Katakana; to Katakana) */
0x0000, /* 0x27 (XK_Hiragana_Katakana; Hiragana/Katakana toggle) */
0x0000, /* 0x28 (XK_Zenkaku; to Zenkaku) */
0x0000, /* 0x29 (XK_Hankaku; to Hankaku */
0x0000, /* 0x2a (XK_Zenkaku_Hankaku; Zenkaku/Hankaku toggle) */
0x0000, /* 0x2b (XK_Touroku; Add to Dictionary) */
0x0000, /* 0x2c (XK_Massyo; Delete from Dictionary) */
0x0000, /* 0x2d (XK_Kana_Lock; Kana Lock) */
0x0000, /* 0x2e (XK_Kana_Shift; Kana Shift) */
0x0000, /* 0x2f (XK_Eisu_Shift; Alphanumeric Shift) */
0x0000, /* 0x30 (XK_Eisu_toggle; Alphanumeric toggle) */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x38 */
0x0000,
0x0000,
0x0000,
0x0000, /* 0x3c (XK_SingleCandidate) */
0x0000, /* 0x3d (XK_MultipleCandidate/XK_Zen_Koho) */
0x0000, /* 0x3e (XK_PreviousCandidate/XK_Mae_Koho) */
0x0000,
0x0000, /* 0x40 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x48 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0xe047, /* 0x50 (XK_Home) */
0xe04b, /* 0x51 (XK_Left) */
0xe048, /* 0x52 (XK_Up) */
0xe04d, /* 0x53 (XK_Right) */
0xe050, /* 0x54 (XK_Down) */
0xe049, /* 0x55 (XK_Prior, XK_Page_Up) */
0xe051, /* 0x56 (XK_Next, XK_Page_Down) */
0xe04f, /* 0x57 (XK_End) */
0x0000, /* 0x58 (XK_Begin) */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x60 (XK_Select) */
0x0000, /* 0x61 (XK_Print) */
0x0000, /* 0x62 (XK_Execute) */
0xe052, /* 0x63 (XK_Insert) */
0x0000,
0x0000, /* 0x65 (XK_Undo) */
0x0000, /* 0x66 (XK_Redo) */
0xe05d, /* 0x67 (XK_Menu) */
0x0000, /* 0x68 (XK_Find) */
0x0000, /* 0x69 (XK_Cancel) */
0x0000, /* 0x6a (XK_Help) */
0x0000, /* 0x6b (XK_Break) */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x70 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x78 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x7e (XK_Mode_switch,XK_script_switch) */
0x0045, /* 0x7f (XK_Num_Lock) */
0x0039, /* 0x80 (XK_KP_Space) */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0x88 */
0x000f, /* 0x89 (XK_KP_Tab) */
0x0000,
0x0000,
0x0000,
0xe01c, /* 0x8d (XK_KP_Enter) */
0x0000,
0x0000,
0x0000, /* 0x90 */
0x0000, /* 0x91 (XK_KP_F1) */
0x0000, /* 0x92 (XK_KP_F2) */
0x0000, /* 0x93 (XK_KP_F3) */
0x0000, /* 0x94 (XK_KP_F4) */
0x0047, /* 0x95 (XK_KP_Home) */
0x004b, /* 0x96 (XK_KP_Left) */
0x0048, /* 0x97 (XK_KP_Up) */
0x004d, /* 0x98 (XK_KP_Right) */
0x0050, /* 0x99 (XK_KP_Down) */
0x0049, /* 0x9a (XK_KP_Prior,XK_KP_Page_Up) */
0x0051, /* 0x9b (XK_KP_Next,XK_KP_Page_Down) */
0x004f, /* 0x9c (XK_KP_End) */
0x0000, /* 0x9d (XK_KP_Begin) */
0x0052, /* 0x9e (XK_KP_Insert) */
0x0053, /* 0x9f (XK_KP_Delete) */
0x0000, /* 0xa0 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0xa8 */
0x0000,
0x0037, /* 0xaa (XK_KP_Multiply) */
0x004e, /* 0xab (XK_KP_Add) */
0x0000, /* 0xac (XK_KP_Separator) */
0x004a, /* 0xad (XK_KP_Subtract) */
0x0000, /* 0xae (XK_KP_Decimal) */
0x0035, /* 0xaf (XK_KP_Divide) */
0x0052, /* 0xb0 (XK_KP_0) */
0x004f, /* 0xb1 (XK_KP_1) */
0x0050, /* 0xb2 (XK_KP_2) */
0x0051, /* 0xb3 (XK_KP_3) */
0x004b, /* 0xb4 (XK_KP_4) */
0x004c, /* 0xb5 (XK_KP_5) */
0x004d, /* 0xb6 (XK_KP_6) */
0x0047, /* 0xb7 (XK_KP_7) */
0x0048, /* 0xb8 (XK_KP_8) */
0x0049, /* 0xb9 (XK_KP_9) */
0x0000,
0x0000,
0x0000,
0x000d, /* 0xbd (XK_KP_Equal) */
0x003b, /* 0xbe (XK_F1) */
0x003c, /* 0xbf (XK_F2) */
0x003d, /* 0xc0 (XK_F3) */
0x003e, /* 0xc1 (XK_F4) */
0x003f, /* 0xc2 (XK_F5) */
0x0040, /* 0xc3 (XK_F6) */
0x0041, /* 0xc4 (XK_F7) */
0x0042, /* 0xc5 (XK_F8) */
0x0043, /* 0xc6 (XK_F9) */
0x0044, /* 0xc7 (XK_F10) */
0x0057, /* 0xc8 (XK_F11,XK_L1) */
0x0058, /* 0xc9 (XK_F12,XK_L2) */
0x0000, /* 0xca (XK_F13,XK_L3) */
0x0000, /* 0xcb (XK_F14,XK_L4) */
0x0000, /* 0xcc (XK_F15,XK_L5) */
0x0000, /* 0xcd (XK_F16,XK_L6) */
0x0000, /* 0xce (XK_F17,XK_L7) */
0x0000, /* 0xcf (XK_F18,XK_L8) */
0x0000, /* 0xd0 (XK_F19,XK_L9) */
0x0000, /* 0xd1 (XK_F20,XK_L10) */
0x0000, /* 0xd2 (XK_F21,XK_R1) */
0x0000, /* 0xd3 (XK_F22,XK_R2) */
0x0000, /* 0xd4 (XK_F23,XK_R3) */
0x0000, /* 0xd5 (XK_F24,XK_R4) */
0x0000, /* 0xd6 (XK_F25,XK_R5) */
0x0000, /* 0xd7 (XK_F26,XK_R6) */
0x0000, /* 0xd8 (XK_F27,XK_R7) */
0x0000, /* 0xd9 (XK_F28,XK_R8) */
0x0000, /* 0xda (XK_F29,XK_R9) */
0x0000, /* 0xdb (XK_F30,XK_R10) */
0x0000, /* 0xdc (XK_F31,XK_R11) */
0x0000, /* 0xdd (XK_F32,XK_R12) */
0x0000, /* 0xde (XK_F33,XK_R13) */
0x0000, /* 0xdf (XK_F34,XK_R14) */
0x0000, /* 0xe0 (XK_F35,XK_R15) */
0x002a, /* 0xe1 (XK_Shift_L) */
0x0036, /* 0xe2 (XK_Shift_R) */
0x001d, /* 0xe3 (XK_Control_L) */
0xe01d, /* 0xe4 (XK_Control_R) */
0x003a, /* 0xe5 (XK_Caps_Lock) */
0x003a, /* 0xe6 (XK_Shift_Lock) */
0xe05b, /* 0xe7 (XK_Meta_L) */
0xe05c, /* 0xe8 (XK_Meta_R) */
0x0038, /* 0xe9 (XK_Alt_L) */
0xe038, /* 0xea (XK_Alt_R) */
0x0000, /* 0xeb (XK_Super_L) */
0x0000, /* 0xec (XK_Super_R) */
0x0000, /* 0xed (XK_Hyper_L) */
0x0000, /* 0xee (XK_Hyper_R) */
0x0000,
0x0000, /* 0xf0 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000, /* 0xf8 */
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0xe053 /* 0xff (XK_Delete) */
};
#ifdef ENABLE_VNC_KEYMAP_LOG
int vnc_keymap_do_log = ENABLE_VNC_KEYMAP_LOG;
static void
vnc_keymap_log(const char *fmt, ...)
{
va_list ap;
if (vnc_keymap_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define vnc_keymap_log(fmt, ...)
#endif
void
vnc_kbinput(int down, int k)
{
uint16_t scan;
switch (k >> 8) {
case 0x00: /* page 00, Latin-1 */
scan = keysyms_00[k & 0xff];
break;
case 0xff: /* page FF, Special */
scan = keysyms_ff[k & 0xff];
break;
default:
vnc_keymap_log("VNC: unhandled Xkbd page: %02x\n", k >> 8);
return;
}
if (scan == 0x0000) {
vnc_keymap_log("VNC: unhandled Xkbd key: %d (%04x)\n", k, k);
return;
}
/* Send this scancode sequence to the PC keyboard. */
switch (scan >> 8) {
default:
case 0x00:
if (scan & 0xff)
keyboard_input(down, scan & 0xff);
break;
case 0x2a:
if (scan & 0xff) {
if (down) {
keyboard_input(down, 0x2a);
keyboard_input(down, scan & 0xff);
} else {
keyboard_input(down, scan & 0xff);
keyboard_input(down, 0x2a);
}
}
break;
case 0xe0:
if (scan & 0xff)
keyboard_input(down, (scan & 0xff) | 0x100);
break;
case 0xe1:
if (scan == 0x1d)
keyboard_input(down, 0x100);
break;
}
}
``` | /content/code_sandbox/src/vnc_keymap.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 8,844 |
```c
see COPYING for more details
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <wchar.h>
#include <86box/86box.h>
#include <86box/io.h>
#include <86box/lpt.h>
#include <86box/pic.h>
#include <86box/sound.h>
#include <86box/prt_devs.h>
#include <86box/thread.h>
#include <86box/timer.h>
#include <86box/device.h>
#include <86box/network.h>
lpt_port_t lpt_ports[PARALLEL_MAX];
const lpt_device_t lpt_none_device = {
.name = "None",
.internal_name = "none",
.init = NULL,
.close = NULL,
.write_data = NULL,
.write_ctrl = NULL,
.read_data = NULL,
.read_status = NULL,
.read_ctrl = NULL
};
static const struct {
const char *internal_name;
const lpt_device_t *device;
} lpt_devices[] = {
// clang-format off
{"none", &lpt_none_device },
{"dss", &dss_device },
{"lpt_dac", &lpt_dac_device },
{"lpt_dac_stereo", &lpt_dac_stereo_device },
{"text_prt", &lpt_prt_text_device },
{"dot_matrix", &lpt_prt_escp_device },
{"postscript", &lpt_prt_ps_device },
#ifdef USE_PCL
{"pcl", &lpt_prt_pcl_device },
#endif
{"plip", &lpt_plip_device },
{"dongle_savquest", &lpt_hasp_savquest_device },
{"", NULL }
// clang-format on
};
const char *
lpt_device_get_name(int id)
{
if (strlen(lpt_devices[id].internal_name) == 0)
return NULL;
if (!lpt_devices[id].device)
return "None";
return lpt_devices[id].device->name;
}
const char *
lpt_device_get_internal_name(int id)
{
if (strlen(lpt_devices[id].internal_name) == 0)
return NULL;
return lpt_devices[id].internal_name;
}
int
lpt_device_get_from_internal_name(char *s)
{
int c = 0;
while (strlen(lpt_devices[c].internal_name) != 0) {
if (strcmp(lpt_devices[c].internal_name, s) == 0)
return c;
c++;
}
return 0;
}
void
lpt_devices_init(void)
{
for (uint8_t i = 0; i < PARALLEL_MAX; i++) {
lpt_ports[i].dt = (lpt_device_t *) lpt_devices[lpt_ports[i].device].device;
if (lpt_ports[i].dt && lpt_ports[i].dt->init)
lpt_ports[i].priv = lpt_ports[i].dt->init(&lpt_ports[i]);
}
}
void
lpt_devices_close(void)
{
lpt_port_t *dev;
for (uint8_t i = 0; i < PARALLEL_MAX; i++) {
dev = &lpt_ports[i];
if (lpt_ports[i].dt && lpt_ports[i].dt->close)
dev->dt->close(dev->priv);
dev->dt = NULL;
}
}
void
lpt_write(uint16_t port, uint8_t val, void *priv)
{
lpt_port_t *dev = (lpt_port_t *) priv;
switch (port & 3) {
case 0:
if (dev->dt && dev->dt->write_data && dev->priv)
dev->dt->write_data(val, dev->priv);
dev->dat = val;
break;
case 1:
break;
case 2:
if (dev->dt && dev->dt->write_ctrl && dev->priv)
dev->dt->write_ctrl(val, dev->priv);
dev->ctrl = val;
dev->enable_irq = val & 0x10;
break;
default:
break;
}
}
uint8_t
lpt_read(uint16_t port, void *priv)
{
uint8_t ret = 0xff;
lpt_port_t *dev = (lpt_port_t *) priv;
switch (port & 3) {
case 0:
if (dev->dt && dev->dt->read_data && dev->priv)
ret = dev->dt->read_data(dev->priv);
else
ret = dev->dat;
break;
case 1:
if (dev->dt && dev->dt->read_status && dev->priv)
ret = dev->dt->read_status(dev->priv) | 0x07;
else
ret = 0xdf;
break;
case 2:
if (dev->dt && dev->dt->read_ctrl && dev->priv)
ret = (dev->dt->read_ctrl(dev->priv) & 0xef) | dev->enable_irq;
else
ret = 0xe0 | dev->ctrl | dev->enable_irq;
break;
default:
break;
}
return ret;
}
uint8_t
lpt_read_port(int port, uint16_t reg)
{
lpt_port_t *dev = &(lpt_ports[port]);
uint8_t ret = lpt_read(reg, dev);
return ret;
}
uint8_t
lpt_read_status(int port)
{
lpt_port_t *dev = &(lpt_ports[port]);
uint8_t ret = 0xff;
if (dev->dt && dev->dt->read_status && dev->priv)
ret = dev->dt->read_status(dev->priv) | 0x07;
else
ret = 0xdf;
return ret;
}
void
lpt_irq(void *priv, int raise)
{
const lpt_port_t *dev = (lpt_port_t *) priv;
if (dev->enable_irq && (dev->irq != 0xff)) {
if (raise)
picint(1 << dev->irq);
else
picintc(1 << dev->irq);
}
}
void
lpt_init(void)
{
uint16_t default_ports[PARALLEL_MAX] = { LPT1_ADDR, LPT2_ADDR, LPT_MDA_ADDR, LPT4_ADDR };
uint8_t default_irqs[PARALLEL_MAX] = { LPT1_IRQ, LPT2_IRQ, LPT_MDA_IRQ, LPT4_IRQ };
for (uint8_t i = 0; i < PARALLEL_MAX; i++) {
lpt_ports[i].addr = 0xffff;
lpt_ports[i].irq = 0xff;
lpt_ports[i].enable_irq = 0x10;
if (lpt_ports[i].enabled) {
lpt_port_init(i, default_ports[i]);
lpt_port_irq(i, default_irqs[i]);
}
}
}
void
lpt_port_init(int i, uint16_t port)
{
if (lpt_ports[i].enabled) {
if (lpt_ports[i].addr != 0xffff)
io_removehandler(lpt_ports[i].addr, 0x0003, lpt_read, NULL, NULL, lpt_write, NULL, NULL, &lpt_ports[i]);
if (port != 0xffff)
io_sethandler(port, 0x0003, lpt_read, NULL, NULL, lpt_write, NULL, NULL, &lpt_ports[i]);
lpt_ports[i].addr = port;
} else
lpt_ports[i].addr = 0xffff;
}
void
lpt_port_irq(int i, uint8_t irq)
{
if (lpt_ports[i].enabled)
lpt_ports[i].irq = irq;
else
lpt_ports[i].irq = 0xff;
}
void
lpt_port_remove(int i)
{
if (lpt_ports[i].enabled && (lpt_ports[i].addr != 0xffff)) {
io_removehandler(lpt_ports[i].addr, 0x0003, lpt_read, NULL, NULL, lpt_write, NULL, NULL, &lpt_ports[i]);
lpt_ports[i].addr = 0xffff;
}
}
void
lpt1_remove_ams(void)
{
if (lpt_ports[0].enabled)
io_removehandler(lpt_ports[0].addr + 1, 0x0002, lpt_read, NULL, NULL, lpt_write, NULL, NULL, &lpt_ports[0]);
}
``` | /content/code_sandbox/src/lpt.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,928 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Skeleton I/O APIC implementation, currently housing the MPS
* table patcher for machines that require it.
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/io.h>
#include <86box/device.h>
#include <86box/machine.h>
#include <86box/mem.h>
#include <86box/chipset.h>
#include <86box/plat_unused.h>
typedef struct ioapic_t {
uint8_t dummy;
} ioapic_t;
#ifdef ENABLE_IOAPIC_LOG
int ioapic_do_log = ENABLE_IOAPIC_LOG;
static void
ioapic_log(const char *fmt, ...)
{
va_list ap;
if (ioapic_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define ioapic_log(fmt, ...)
#endif
static void
ioapic_write(UNUSED(uint16_t port), uint8_t val, UNUSED(void *priv))
{
uint32_t pcmp;
/* target POST FF, issued by Award before jumping to the bootloader */
if (val != 0xff)
return;
ioapic_log("IOAPIC: Caught POST %02X\n", val);
/* The _MP_ table must be located in the BIOS area, the EBDA, or the last 1k of conventional
memory; at a 16-byte boundary in all cases. Award writes both tables to the BIOS area. */
for (uint32_t addr = 0xf0000; addr <= 0xfffff; addr += 16) {
/* check signature for the _MP_ table (Floating Point Structure) */
if (mem_readl_phys(addr) != 0x5f504d5f) /* ASCII "_MP_" */
continue;
/* read and check pointer to the PCMP table (Configuration Table) */
pcmp = mem_readl_phys(addr + 4);
if ((pcmp < 0xf0000) || (pcmp > 0xfffff) || (mem_readl_phys(pcmp) != 0x504d4350)) /* ASCII "PCMP" */
continue;
/* patch over the signature on both tables */
ioapic_log("IOAPIC: Patching _MP_ [%08x] and PCMP [%08x] tables\n", addr, pcmp);
ram[addr] = ram[addr + 1] = ram[addr + 2] = ram[addr + 3] = 0xff;
ram[pcmp] = ram[pcmp + 1] = ram[pcmp + 2] = ram[pcmp + 3] = 0xff;
break;
}
}
static void
ioapic_reset(UNUSED(ioapic_t *dev))
{
//
}
static void
ioapic_close(void *priv)
{
ioapic_t *dev = (ioapic_t *) priv;
io_removehandler(0x80, 1,
NULL, NULL, NULL, ioapic_write, NULL, NULL, NULL);
free(dev);
}
static void *
ioapic_init(UNUSED(const device_t *info))
{
ioapic_t *dev = (ioapic_t *) malloc(sizeof(ioapic_t));
memset(dev, 0, sizeof(ioapic_t));
ioapic_reset(dev);
io_sethandler(0x80, 1,
NULL, NULL, NULL, ioapic_write, NULL, NULL, NULL);
return dev;
}
const device_t ioapic_device = {
.name = "I/O Advanced Programmable Interrupt Controller",
.internal_name = "ioapic",
.flags = DEVICE_AT,
.local = 0,
.init = ioapic_init,
.close = ioapic_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/ioapic.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 993 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Discord integration module.
*
*
*
* Authors: David Hrdlika, <hrdlickadavid@outlook.com>
*
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define HAVE_STDARG_H
#include "cpu/cpu.h"
#include <86box/86box.h>
#include <86box/discord.h>
#include <86box/machine.h>
#include <86box/plat.h>
#include <86box/plat_dynld.h>
#include <discord_game_sdk.h>
#ifdef _WIN32
# define PATH_DISCORD_DLL "discord_game_sdk.dll"
#elif defined __APPLE__
# define PATH_DISCORD_DLL "discord_game_sdk.dylib"
#else
# define PATH_DISCORD_DLL "discord_game_sdk.so"
#endif
int discord_loaded = 0;
static void *discord_handle = NULL;
static struct IDiscordCore *discord_core = NULL;
static struct IDiscordActivityManager *discord_activities = NULL;
static enum EDiscordResult(DISCORD_API *discord_create)(DiscordVersion version, struct DiscordCreateParams *params, struct IDiscordCore **result);
static dllimp_t discord_imports[] = {
{"DiscordCreate", &discord_create},
{ NULL, NULL }
};
#ifdef ENABLE_DISCORD_LOG
int discord_do_log = 1;
static void
discord_log(const char *fmt, ...)
{
va_list ap;
if (discord_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define discord_log(fmt, ...)
#endif
void
discord_update_activity(int paused)
{
struct DiscordActivity activity;
char cpufamily[1024];
char *paren;
if (discord_activities == NULL)
return;
discord_log("discord: discord_update_activity(paused=%d)\n", paused);
memset(&activity, 0x00, sizeof(activity));
strncpy(cpufamily, cpu_f->name, sizeof(cpufamily) - 1);
paren = strchr(cpufamily, '(');
if (paren)
*(paren - 1) = '\0';
#pragma GCC diagnostic push
#if defined(__GNUC__) && !defined(__clang__)
# pragma GCC diagnostic ignored "-Wformat-truncation"
#endif
if (strlen(vm_name) < 100) {
snprintf(activity.details, sizeof(activity.details), "Running \"%s\"", vm_name);
snprintf(activity.state, sizeof(activity.state), "%s (%s/%s)", strchr(machine_getname(), ']') + 2, cpufamily, cpu_s->name);
} else {
strncpy(activity.details, strchr(machine_getname(), ']') + 2, sizeof(activity.details) - 1);
snprintf(activity.state, sizeof(activity.state), "%s/%s", cpufamily, cpu_s->name);
}
#pragma GCC diagnostic pop
activity.timestamps.start = time(NULL);
/* Icon choosing for Discord based on 86Box.rc */
#ifdef RELEASE_BUILD
/* Icon by OBattler and laciba96 (green for release builds)*/
strcpy(activity.assets.large_image, "86box-green");
#elif BETA_BUILD
/* Icon by OBattler and laciba96 (yellow for beta builds done by Jenkins)*/
strcpy(activity.assets.large_image, "86box-yellow");
#elif ALPHA_BUILD
/* Icon by OBattler and laciba96 (red for alpha builds done by Jenkins)*/
strcpy(activity.assets.large_image, "86box-red");
#else
/* Icon by OBattler and laciba96 (gray for builds of branches and from the git master)*/
strcpy(activity.assets.large_image, "86box");
#endif
/* End of icon choosing */
if (paused) {
strcpy(activity.assets.small_image, "status-paused");
strcpy(activity.assets.small_text, "Paused");
} else {
strcpy(activity.assets.small_image, "status-running");
strcpy(activity.assets.small_text, "Running");
}
discord_activities->update_activity(discord_activities, &activity, NULL, NULL);
}
int
discord_load(void)
{
if (discord_handle != NULL)
return 1;
// Try to load the DLL
discord_handle = dynld_module(PATH_DISCORD_DLL, discord_imports);
if (discord_handle == NULL) {
discord_log("discord: couldn't load " PATH_DISCORD_DLL "\n");
discord_close();
return 0;
}
discord_loaded = 1;
return 1;
}
void
discord_init(void)
{
enum EDiscordResult result;
struct DiscordCreateParams params;
if (discord_handle == NULL)
return;
DiscordCreateParamsSetDefault(¶ms);
params.client_id = 906956844956782613;
params.flags = DiscordCreateFlags_NoRequireDiscord;
result = discord_create(DISCORD_VERSION, ¶ms, &discord_core);
if (result != DiscordResult_Ok) {
discord_log("discord: DiscordCreate returned %d\n", result);
discord_close();
return;
}
discord_activities = discord_core->get_activity_manager(discord_core);
return;
}
void
discord_close(void)
{
if (discord_core != NULL)
discord_core->destroy(discord_core);
discord_core = NULL;
discord_activities = NULL;
}
void
discord_run_callbacks(void)
{
if (discord_core == NULL)
return;
discord_core->run_callbacks(discord_core);
}
``` | /content/code_sandbox/src/discord.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,250 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the generic device interface to handle
* all devices attached to the emulator.
*
*
*
* Authors: Fred N. van Kempen, <decwiz@yahoo.com>
* Miran Grca, <mgrca8@gmail.com>
* Sarah Walker, <path_to_url
*
*
* This program is free software; you can redistribute it and/or modify
* (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
*
* along with this program; if not, write to the:
*
* Free Software Foundation, Inc.
* 59 Temple Place - Suite 330
* Boston, MA 02111-1307
* USA.
*/
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/ini.h>
#include <86box/config.h>
#include <86box/device.h>
#include <86box/machine.h>
#include <86box/mem.h>
#include <86box/rom.h>
#include <86box/sound.h>
#define DEVICE_MAX 256 /* max # of devices */
static device_t *devices[DEVICE_MAX];
static void *device_priv[DEVICE_MAX];
static device_context_t device_current;
static device_context_t device_prev;
static void *device_common_priv;
#ifdef ENABLE_DEVICE_LOG
int device_do_log = ENABLE_DEVICE_LOG;
static void
device_log(const char *fmt, ...)
{
va_list ap;
if (device_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define device_log(fmt, ...)
#endif
/* Initialize the module for use. */
void
device_init(void)
{
memset(devices, 0x00, sizeof(devices));
}
void
device_set_context(device_context_t *c, const device_t *dev, int inst)
{
memset(c, 0, sizeof(device_context_t));
c->dev = dev;
c->instance = inst;
if (inst) {
sprintf(c->name, "%s #%i", dev->name, inst);
/* If a numbered section is not present, but a non-numbered of the same name
is, rename the non-numbered section to numbered. */
const void *sec = config_find_section(c->name);
void * single_sec = config_find_section((char *) dev->name);
if ((sec == NULL) && (single_sec != NULL))
config_rename_section(single_sec, c->name);
} else
sprintf(c->name, "%s", dev->name);
}
static void
device_context_common(const device_t *dev, int inst)
{
memcpy(&device_prev, &device_current, sizeof(device_context_t));
device_set_context(&device_current, dev, inst);
}
void
device_context(const device_t *dev)
{
device_context_common(dev, 0);
}
void
device_context_inst(const device_t *dev, int inst)
{
device_context_common(dev, inst);
}
void
device_context_restore(void)
{
memcpy(&device_current, &device_prev, sizeof(device_context_t));
}
static void *
device_add_common(const device_t *dev, void *p, void *params, int inst)
{
device_t *init_dev = NULL;
void *priv = NULL;
int c;
if (params != NULL) {
init_dev = calloc(1, sizeof(device_t));
memcpy(init_dev, dev, sizeof(device_t));
init_dev->local |= (uintptr_t) params;
} else
init_dev = (device_t *) dev;
for (c = 0; c < 256; c++) {
if (!inst && (devices[c] == dev)) {
device_log("DEVICE: device already exists!\n");
return (NULL);
}
if (devices[c] == NULL)
break;
}
if (c >= DEVICE_MAX) {
fatal("DEVICE: too many devices\n");
return NULL;
}
/* Do this so that a chained device_add will not identify the same ID
its master device is already trying to assign. */
devices[c] = (device_t *) dev;
if (!strcmp(dev->name, "None") || !strcmp(dev->name, "Internal"))
fatal("Attempting to add dummy device of type: %s\n", dev->name);
if (p == NULL) {
memcpy(&device_prev, &device_current, sizeof(device_context_t));
device_set_context(&device_current, dev, inst);
if (dev->init != NULL) {
/* Give it our temporary device in case we have dynamically changed info->local. */
priv = dev->init(init_dev);
if (priv == NULL) {
#ifdef ENABLE_DEVICE_LOG
if (dev->name)
device_log("DEVICE: device '%s' init failed\n", dev->name);
else
device_log("DEVICE: device init failed\n");
#endif
devices[c] = NULL;
device_priv[c] = NULL;
if ((init_dev != NULL) && (init_dev != (device_t *) dev))
free(init_dev);
return (NULL);
}
}
#ifdef ENABLE_DEVICE_LOG
if (dev->name)
device_log("DEVICE: device '%s' init successful\n", dev->name);
else
device_log("DEVICE: device init successful\n");
#endif
memcpy(&device_current, &device_prev, sizeof(device_context_t));
device_priv[c] = priv;
} else
device_priv[c] = p;
if (init_dev != dev)
free(init_dev);
return priv;
}
const char *
device_get_internal_name(const device_t *dev)
{
if (dev == NULL)
return "";
return dev->internal_name;
}
void *
device_add(const device_t *dev)
{
return device_add_common(dev, NULL, NULL, 0);
}
void *
device_add_linked(const device_t *dev, void *priv)
{
void *ret;
device_common_priv = priv;
ret = device_add_common(dev, NULL, NULL, 0);
device_common_priv = NULL;
return ret;
}
void *
device_add_params(const device_t *dev, void *params)
{
return device_add_common(dev, NULL, params, 0);
}
/* For devices that do not have an init function (internal video etc.) */
void
device_add_ex(const device_t *dev, void *priv)
{
device_add_common(dev, priv, NULL, 0);
}
void
device_add_ex_params(const device_t *dev, void *priv, void *params)
{
device_add_common(dev, priv, params, 0);
}
void *
device_add_inst(const device_t *dev, int inst)
{
return device_add_common(dev, NULL, NULL, inst);
}
void *
device_add_inst_params(const device_t *dev, int inst, void *params)
{
return device_add_common(dev, NULL, params, inst);
}
/* For devices that do not have an init function (internal video etc.) */
void
device_add_inst_ex(const device_t *dev, void *priv, int inst)
{
device_add_common(dev, priv, NULL, inst);
}
void
device_add_inst_ex_params(const device_t *dev, void *priv, int inst, void *params)
{
device_add_common(dev, priv, params, inst);
}
void *
device_get_common_priv(void)
{
return device_common_priv;
}
void
device_close_all(void)
{
for (int16_t c = (DEVICE_MAX - 1); c >= 0; c--) {
if (devices[c] != NULL) {
#ifdef ENABLE_DEVICE_LOG
if (devices[c]->name)
device_log("Closing device: \"%s\"...\n", devices[c]->name);
#endif
if (devices[c]->close != NULL)
devices[c]->close(device_priv[c]);
devices[c] = device_priv[c] = NULL;
}
}
}
void
device_reset_all(uint32_t match_flags)
{
for (uint16_t c = 0; c < DEVICE_MAX; c++) {
if (devices[c] != NULL) {
if ((devices[c]->reset != NULL) && (devices[c]->flags & match_flags))
devices[c]->reset(device_priv[c]);
}
}
#ifdef UNCOMMENT_LATER
/* TODO: Actually convert the LPT devices to device_t's. */
if ((match_flags == DEVICE_ALL) || (match_flags == DEVICE_PCI))
lpt_reset();
#endif
}
void *
device_find_first_priv(uint32_t match_flags)
{
void *ret = NULL;
for (uint16_t c = 0; c < DEVICE_MAX; c++) {
if (devices[c] != NULL) {
if ((device_priv[c] != NULL) && (devices[c]->flags & match_flags)) {
ret = device_priv[c];
break;
}
}
}
return ret;
}
void *
device_get_priv(const device_t *dev)
{
for (uint16_t c = 0; c < DEVICE_MAX; c++) {
if (devices[c] != NULL) {
if (devices[c] == dev)
return (device_priv[c]);
}
}
return (NULL);
}
int
device_available(const device_t *dev)
{
const device_config_t *config = NULL;
const device_config_bios_t *bios = NULL;
if (dev != NULL) {
config = dev->config;
if (config != NULL) {
while (config->type != -1) {
if (config->type == CONFIG_BIOS) {
int roms_present = 0;
bios = (const device_config_bios_t *) config->bios;
/* Go through the ROM's in the device configuration. */
while (bios->files_no != 0) {
int i = 0;
for (int bf = 0; bf < bios->files_no; bf++)
i += !!rom_present(bios->files[bf]);
if (i == bios->files_no)
roms_present++;
bios++;
}
return (roms_present ? -1 : 0);
}
config++;
}
}
/* No CONFIG_BIOS field present, use the classic available(). */
if (dev->available != NULL)
return (dev->available());
else
return 1;
}
/* A NULL device is never available. */
return 0;
}
const char *
device_get_bios_file(const device_t *dev, const char *internal_name, int file_no)
{
const device_config_t *config = NULL;
const device_config_bios_t *bios = NULL;
if (dev != NULL) {
config = dev->config;
if (config != NULL) {
while (config->type != -1) {
if (config->type == CONFIG_BIOS) {
bios = config->bios;
/* Go through the ROM's in the device configuration. */
while (bios->files_no != 0) {
if (!strcmp(internal_name, bios->internal_name)) {
if (file_no < bios->files_no)
return bios->files[file_no];
else
return NULL;
}
bios++;
}
}
config++;
}
}
}
/* A NULL device is never available. */
return (NULL);
}
int
device_has_config(const device_t *dev)
{
int c = 0;
const device_config_t *config;
if (dev == NULL)
return 0;
if (dev->config == NULL)
return 0;
config = dev->config;
while (config->type != -1) {
c++;
config++;
}
return (c > 0) ? 1 : 0;
}
int
device_poll(const device_t *dev)
{
for (uint16_t c = 0; c < DEVICE_MAX; c++) {
if (devices[c] != NULL) {
if (devices[c] == dev) {
if (devices[c]->poll)
return (devices[c]->poll(device_priv[c]));
}
}
}
return 0;
}
void
device_get_name(const device_t *dev, int bus, char *name)
{
const char *sbus = NULL;
const char *fbus;
char *tname;
char pbus[8] = { 0 };
if (dev == NULL)
return;
name[0] = 0x00;
if (bus) {
if (dev->flags & DEVICE_ISA)
sbus = (dev->flags & DEVICE_AT) ? "ISA16" : "ISA";
else if (dev->flags & DEVICE_CBUS)
sbus = "C-BUS";
else if (dev->flags & DEVICE_MCA)
sbus = "MCA";
else if (dev->flags & DEVICE_EISA)
sbus = "EISA";
else if (dev->flags & DEVICE_VLB)
sbus = "VLB";
else if (dev->flags & DEVICE_PCI)
sbus = "PCI";
else if (dev->flags & DEVICE_AGP)
sbus = "AGP";
else if (dev->flags & DEVICE_AC97)
sbus = "AMR";
else if (dev->flags & DEVICE_COM)
sbus = "COM";
else if (dev->flags & DEVICE_LPT)
sbus = "LPT";
if (sbus != NULL) {
/* First concatenate [<Bus>] before the device's name. */
strcat(name, "[");
strcat(name, sbus);
strcat(name, "] ");
/* Then change string from ISA16 to ISA if applicable. */
if (!strcmp(sbus, "ISA16"))
sbus = "ISA";
else if (!strcmp(sbus, "COM") || !strcmp(sbus, "LPT")) {
sbus = NULL;
strcat(name, dev->name);
return;
}
/* Generate the bus string with parentheses. */
strcat(pbus, "(");
strcat(pbus, sbus);
strcat(pbus, ")");
/* Allocate the temporary device name string and set it to all zeroes. */
tname = (char *) malloc(strlen(dev->name) + 1);
memset(tname, 0x00, strlen(dev->name) + 1);
/* First strip the bus string with parentheses. */
fbus = strstr(dev->name, pbus);
if (fbus == dev->name)
strcat(tname, dev->name + strlen(pbus) + 1);
else if (fbus == NULL)
strcat(tname, dev->name);
else {
strncat(tname, dev->name, fbus - dev->name - 1);
strcat(tname, fbus + strlen(pbus));
}
/* Then also strip the bus string with parentheses. */
fbus = strstr(tname, sbus);
if (fbus == tname)
strcat(name, tname + strlen(sbus) + 1);
/* Special case to not strip the "oPCI" from "Ensoniq AudioPCI" or
the "-ISA" from "AMD PCnet-ISA". */
else if ((fbus == NULL) || (*(fbus - 1) == 'o') || (*(fbus - 1) == '-') || (*(fbus - 2) == 'r'))
strcat(name, tname);
else {
strncat(name, tname, fbus - tname - 1);
strcat(name, fbus + strlen(sbus));
}
/* Free the temporary device name string. */
free(tname);
tname = NULL;
} else
strcat(name, dev->name);
} else
strcat(name, dev->name);
}
void
device_speed_changed(void)
{
for (uint16_t c = 0; c < DEVICE_MAX; c++) {
if (devices[c] != NULL) {
device_log("DEVICE: device '%s' speed changed\n", devices[c]->name);
if (devices[c]->speed_changed != NULL)
devices[c]->speed_changed(device_priv[c]);
}
}
sound_speed_changed();
}
void
device_force_redraw(void)
{
for (uint16_t c = 0; c < DEVICE_MAX; c++) {
if (devices[c] != NULL) {
if (devices[c]->force_redraw != NULL)
devices[c]->force_redraw(device_priv[c]);
}
}
}
int
device_get_instance(void)
{
return device_current.instance;
}
const char *
device_get_config_string(const char *s)
{
const device_config_t *c = device_current.dev->config;
while (c && c->type != -1) {
if (!strcmp(s, c->name))
return (config_get_string((char *) device_current.name, (char *) s, (char *) c->default_string));
c++;
}
return (NULL);
}
int
device_get_config_int(const char *s)
{
const device_config_t *c = device_current.dev->config;
while (c && c->type != -1) {
if (!strcmp(s, c->name))
return (config_get_int((char *) device_current.name, (char *) s, c->default_int));
c++;
}
return 0;
}
int
device_get_config_int_ex(const char *s, int def)
{
const device_config_t *c = device_current.dev->config;
while (c && c->type != -1) {
if (!strcmp(s, c->name))
return (config_get_int((char *) device_current.name, (char *) s, def));
c++;
}
return def;
}
int
device_get_config_hex16(const char *s)
{
const device_config_t *c = device_current.dev->config;
while (c && c->type != -1) {
if (!strcmp(s, c->name))
return (config_get_hex16((char *) device_current.name, (char *) s, c->default_int));
c++;
}
return 0;
}
int
device_get_config_hex20(const char *s)
{
const device_config_t *c = device_current.dev->config;
while (c && c->type != -1) {
if (!strcmp(s, c->name))
return (config_get_hex20((char *) device_current.name, (char *) s, c->default_int));
c++;
}
return 0;
}
int
device_get_config_mac(const char *s, int def)
{
const device_config_t *c = device_current.dev->config;
while (c && c->type != -1) {
if (!strcmp(s, c->name))
return (config_get_mac((char *) device_current.name, (char *) s, def));
c++;
}
return def;
}
void
device_set_config_int(const char *s, int val)
{
const device_config_t *c = device_current.dev->config;
while (c && c->type != -1) {
if (!strcmp(s, c->name)) {
config_set_int((char *) device_current.name, (char *) s, val);
break;
}
c++;
}
}
void
device_set_config_hex16(const char *s, int val)
{
const device_config_t *c = device_current.dev->config;
while (c && c->type != -1) {
if (!strcmp(s, c->name)) {
config_set_hex16((char *) device_current.name, (char *) s, val);
break;
}
c++;
}
}
void
device_set_config_hex20(const char *s, int val)
{
const device_config_t *c = device_current.dev->config;
while (c && c->type != -1) {
if (!strcmp(s, c->name)) {
config_set_hex20((char *) device_current.name, (char *) s, val);
break;
}
c++;
}
}
void
device_set_config_mac(const char *s, int val)
{
const device_config_t *c = device_current.dev->config;
while (c && c->type != -1) {
if (!strcmp(s, c->name)) {
config_set_mac((char *) device_current.name, (char *) s, val);
break;
}
c++;
}
}
int
device_is_valid(const device_t *device, int m)
{
if (device == NULL)
return 1;
if ((device->flags & DEVICE_PCJR) && !machine_has_bus(m, MACHINE_BUS_PCJR))
return 0;
if ((device->flags & DEVICE_XTKBC) && machine_has_bus(m, MACHINE_BUS_ISA16) && !machine_has_bus(m, MACHINE_BUS_DM_KBC))
return 0;
if ((device->flags & DEVICE_AT) && !machine_has_bus(m, MACHINE_BUS_ISA16))
return 0;
if ((device->flags & DEVICE_ATKBC) && !machine_has_bus(m, MACHINE_BUS_ISA16) && !machine_has_bus(m, MACHINE_BUS_DM_KBC))
return 0;
if ((device->flags & DEVICE_ISA) && !machine_has_bus(m, MACHINE_BUS_ISA))
return 0;
if ((device->flags & DEVICE_CBUS) && !machine_has_bus(m, MACHINE_BUS_CBUS))
return 0;
if ((device->flags & DEVICE_PCMCIA) && !machine_has_bus(m, MACHINE_BUS_PCMCIA))
return 0;
if ((device->flags & DEVICE_MCA) && !machine_has_bus(m, MACHINE_BUS_MCA))
return 0;
if ((device->flags & DEVICE_HIL) && !machine_has_bus(m, MACHINE_BUS_HIL))
return 0;
if ((device->flags & DEVICE_EISA) && !machine_has_bus(m, MACHINE_BUS_EISA))
return 0;
if ((device->flags & DEVICE_OLB) && !machine_has_bus(m, MACHINE_BUS_OLB))
return 0;
if ((device->flags & DEVICE_VLB) && !machine_has_bus(m, MACHINE_BUS_VLB))
return 0;
if ((device->flags & DEVICE_PCI) && !machine_has_bus(m, MACHINE_BUS_PCI))
return 0;
if ((device->flags & DEVICE_CARDBUS) && !machine_has_bus(m, MACHINE_BUS_CARDBUS))
return 0;
if ((device->flags & DEVICE_USB) && !machine_has_bus(m, MACHINE_BUS_USB))
return 0;
if ((device->flags & DEVICE_AGP) && !machine_has_bus(m, MACHINE_BUS_AGP))
return 0;
if ((device->flags & DEVICE_PS2) && !machine_has_bus(m, MACHINE_BUS_PS2_PORTS))
return 0;
if ((device->flags & DEVICE_AC97) && !machine_has_bus(m, MACHINE_BUS_AC97))
return 0;
return 1;
}
int
machine_get_config_int(char *s)
{
const device_t *d = machine_get_device(machine);
const device_config_t *c;
if (d == NULL)
return 0;
c = d->config;
while (c && c->type != -1) {
if (!strcmp(s, c->name))
return (config_get_int((char *) d->name, s, c->default_int));
c++;
}
return 0;
}
char *
machine_get_config_string(char *s)
{
const device_t *d = machine_get_device(machine);
const device_config_t *c;
if (d == NULL)
return 0;
c = d->config;
while (c && c->type != -1) {
if (!strcmp(s, c->name))
return (config_get_string((char *) d->name, s, (char *) c->default_string));
c++;
}
return NULL;
}
const device_t*
device_context_get_device(void)
{
return device_current.dev;
}
const device_t device_none = {
.name = "None",
.internal_name = "none",
.flags = 0,
.local = 0,
.init = NULL,
.close = NULL,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t device_internal = {
.name = "Internal",
.internal_name = "internal",
.flags = 0,
.local = 0,
.init = NULL,
.close = NULL,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/device.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 5,580 |
```c
/*
* VARCem Virtual ARchaeological Computer EMulator.
* An emulator of (mostly) x86-based PC systems and devices,
* using the ISA,EISA,VLB,MCA and PCI system buses, roughly
* spanning the era between 1981 and 1995.
*
* Implement a generic NVRAM/CMOS/RTC device.
*
*
*
* Authors: Fred N. van Kempen, <decwiz@yahoo.com>,
* David Hrdlika, <hrdlickadavid@outlook.com>
*
*
* 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 entire
* above 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 copyright holder 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
* HOLDER 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 <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/machine.h>
#include <86box/mem.h>
#include <86box/timer.h>
#include <86box/path.h>
#include <86box/plat.h>
#include <86box/nvr.h>
int nvr_dosave; /* NVR is dirty, needs saved */
static int8_t days_in_month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static struct tm intclk;
static nvr_t *saved_nvr = NULL;
#ifdef ENABLE_NVR_LOG
int nvr_do_log = ENABLE_NVR_LOG;
static void
nvr_log(const char *fmt, ...)
{
va_list ap;
if (nvr_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define nvr_log(fmt, ...)
#endif
/* Determine whether or not the year is leap. */
int
nvr_is_leap(int year)
{
if (year % 400 == 0)
return 1;
if (year % 100 == 0)
return 0;
if (year % 4 == 0)
return 1;
return 0;
}
/* Determine the days in the current month. */
int
nvr_get_days(int month, int year)
{
if (month != 2)
return (days_in_month[month - 1]);
return (nvr_is_leap(year) ? 29 : 28);
}
/* One more second has passed, update the internal clock. */
void
rtc_tick(void)
{
/* Ping the internal clock. */
if (++intclk.tm_sec == 60) {
intclk.tm_sec = 0;
if (++intclk.tm_min == 60) {
intclk.tm_min = 0;
if (++intclk.tm_hour == 24) {
intclk.tm_hour = 0;
if (++intclk.tm_mday == (nvr_get_days(intclk.tm_mon, intclk.tm_year) + 1)) {
intclk.tm_mday = 1;
if (++intclk.tm_mon == 13) {
intclk.tm_mon = 1;
intclk.tm_year++;
}
}
}
}
}
}
/* This is the RTC one-second timer. */
static void
onesec_timer(void *priv)
{
nvr_t *nvr = (nvr_t *) priv;
int is_at;
if (++nvr->onesec_cnt >= 100) {
/* Update the internal clock. */
is_at = IS_AT(machine);
if (!is_at)
rtc_tick();
/* Update the RTC device if needed. */
if (nvr->tick != NULL)
(*nvr->tick)(nvr);
nvr->onesec_cnt = 0;
}
timer_advance_u64(&nvr->onesec_time, (uint64_t) (10000ULL * TIMER_USEC));
}
/* Initialize the generic NVRAM/RTC device. */
void
nvr_init(nvr_t *nvr)
{
int c;
/* Set up the NVR file's name. */
c = strlen(machine_get_internal_name()) + 5;
nvr->fn = (char *) malloc(c + 1);
sprintf(nvr->fn, "%s.nvr", machine_get_internal_name());
/* Initialize the internal clock as needed. */
memset(&intclk, 0x00, sizeof(intclk));
if (time_sync & TIME_SYNC_ENABLED) {
nvr_time_sync();
} else {
/* Reset the internal clock to 1980/01/01 00:00. */
intclk.tm_mon = 1;
intclk.tm_year = 1980;
}
/* Set up our timer. */
timer_add(&nvr->onesec_time, onesec_timer, nvr, 1);
/* It does not need saving yet. */
nvr_dosave = 0;
/* Save the NVR data pointer. */
saved_nvr = nvr;
/* Try to load the saved data. */
(void) nvr_load();
}
/* Get path to the NVR folder. */
char *
nvr_path(char *str)
{
static char temp[1024];
/* Get the full prefix in place. */
memset(temp, 0x00, sizeof(temp));
strcpy(temp, usr_path);
strcat(temp, NVR_PATH);
/* Create the directory if needed. */
if (!plat_dir_check(temp))
plat_dir_create(temp);
/* Now append the actual filename. */
path_slash(temp);
strcat(temp, str);
return temp;
}
/*
* Load an NVR from file.
*
* This function does two things, really. It clears and initializes
* the RTC and NVRAM areas, sets up defaults for the RTC part, and
* then attempts to load data from a saved file.
*
* Either way, after that, it will continue to configure the local
* RTC to operate, so it can update either the local RTC, and/or
* the one supplied by a client.
*/
int
nvr_load(void)
{
const char *path;
FILE *fp;
uint8_t regs[NVR_MAXSIZE] = { 0 };
/* Make sure we have been initialized. */
if (saved_nvr == NULL)
return 0;
/* Clear out any old data. */
memset(saved_nvr->regs, 0x00, sizeof(saved_nvr->regs));
/* Set the defaults. */
if (saved_nvr->reset != NULL)
saved_nvr->reset(saved_nvr);
/* Load the (relevant) part of the NVR contents. */
if (saved_nvr->size != 0) {
path = nvr_path(saved_nvr->fn);
nvr_log("NVR: loading from '%s'\n", path);
fp = plat_fopen(path, "rb");
saved_nvr->is_new = (fp == NULL);
if (fp != NULL) {
memcpy(regs, saved_nvr->regs, sizeof(regs));
/* Read NVR contents from file. */
if (fread(saved_nvr->regs, 1, saved_nvr->size, fp) != saved_nvr->size) {
memcpy(saved_nvr->regs, regs, sizeof(regs));
saved_nvr->is_new = 1;
}
(void) fclose(fp);
}
} else
saved_nvr->is_new = 1;
/* Get the local RTC running! */
if (saved_nvr->start != NULL)
saved_nvr->start(saved_nvr);
return 1;
}
void
nvr_set_ven_save(void (*ven_save)(void))
{
saved_nvr->ven_save = ven_save;
}
/* Save the current NVR to a file. */
int
nvr_save(void)
{
const char *path;
FILE *fp;
/* Make sure we have been initialized. */
if (saved_nvr == NULL)
return 0;
if (saved_nvr->size != 0) {
path = nvr_path(saved_nvr->fn);
nvr_log("NVR: saving to '%s'\n", path);
fp = plat_fopen(path, "wb");
if (fp != NULL) {
/* Save NVR contents to file. */
(void) fwrite(saved_nvr->regs, saved_nvr->size, 1, fp);
fclose(fp);
}
}
if (saved_nvr->ven_save)
saved_nvr->ven_save();
/* Device is clean again. */
nvr_dosave = 0;
return 1;
}
void
nvr_close(void)
{
saved_nvr = NULL;
}
void
nvr_time_sync(void)
{
struct tm *tm;
time_t now;
/* Get the current time of day, and convert to local time. */
(void) time(&now);
if (time_sync & TIME_SYNC_UTC)
tm = gmtime(&now);
else
tm = localtime(&now);
/* Set the internal clock. */
nvr_time_set(tm);
}
/* Get current time from internal clock. */
void
nvr_time_get(struct tm *tm)
{
uint8_t dom;
uint8_t mon;
uint8_t sum;
uint8_t wd;
uint16_t cent;
uint16_t yr;
tm->tm_sec = intclk.tm_sec;
tm->tm_min = intclk.tm_min;
tm->tm_hour = intclk.tm_hour;
dom = intclk.tm_mday;
mon = intclk.tm_mon;
yr = (intclk.tm_year % 100);
cent = ((intclk.tm_year - yr) / 100) % 4;
sum = dom + mon + yr + cent;
wd = ((sum + 6) % 7);
tm->tm_wday = wd;
tm->tm_mday = intclk.tm_mday;
tm->tm_mon = (intclk.tm_mon - 1);
tm->tm_year = (intclk.tm_year - 1900);
}
/* Set internal clock time. */
void
nvr_time_set(struct tm *tm)
{
intclk.tm_sec = tm->tm_sec;
intclk.tm_min = tm->tm_min;
intclk.tm_hour = tm->tm_hour;
intclk.tm_wday = tm->tm_wday;
intclk.tm_mday = tm->tm_mday;
intclk.tm_mon = (tm->tm_mon + 1);
intclk.tm_year = (tm->tm_year + 1900);
}
/* Open or create a file in the NVR area. */
FILE *
nvr_fopen(char *str, char *mode)
{
return (plat_fopen(nvr_path(str), mode));
}
``` | /content/code_sandbox/src/nvr.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,749 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implement a more-or-less defacto-standard RTC/NVRAM.
*
* When IBM released the PC/AT machine, it came standard with a
* battery-backed RTC chip to keep the time of day, something
* that was optional on standard PC's with a myriad variants
* being put on the market, often on cheap multi-I/O cards.
*
* The PC/AT had an on-board DS12885-series chip ("the black
* block") which was an RTC/clock chip with onboard oscillator
* and a backup battery (hence the big size.) The chip also had
* a small amount of RAM bytes available to the user, which was
* used by IBM's ROM BIOS to store machine configuration data.
* Later versions and clones used the 12886 and/or 1288(C)7
* series, or the MC146818 series, all with an external battery.
* Many of those batteries would create corrosion issues later
* on in mainboard life...
*
* Since then, pretty much any PC has an implementation of that
* device, which became known as the "nvr" or "cmos".
*
* NOTES Info extracted from the data sheets:
*
* * The century register at location 32h is a BCD register
* designed to automatically load the BCD value 20 as the
* year register changes from 99 to 00. The MSB of this
* register is not affected when the load of 20 occurs,
* and remains at the value written by the user.
*
* * Rate Selector (RS3:RS0)
* These four rate-selection bits select one of the 13
* taps on the 15-stage divider or disable the divider
* output. The tap selected can be used to generate an
* output square wave (SQW pin) and/or a periodic interrupt.
*
* The user can do one of the following:
* - enable the interrupt with the PIE bit;
* - enable the SQW output pin with the SQWE bit;
* - enable both at the same time and the same rate; or
* - enable neither.
*
* Table 3 lists the periodic interrupt rates and the square
* wave frequencies that can be chosen with the RS bits.
* These four read/write bits are not affected by !RESET.
*
* * Oscillator (DV2:DV0)
* These three bits are used to turn the oscillator on or
* off and to reset the countdown chain. A pattern of 010
* is the only combination of bits that turn the oscillator
* on and allow the RTC to keep time. A pattern of 11x
* enables the oscillator but holds the countdown chain in
* reset. The next update occurs at 500ms after a pattern
* of 010 is written to DV0, DV1, and DV2.
*
* * Update-In-Progress (UIP)
* This bit is a status flag that can be monitored. When the
* UIP bit is a 1, the update transfer occurs soon. When
* UIP is a 0, the update transfer does not occur for at
* least 244us. The time, calendar, and alarm information
* in RAM is fully available for access when the UIP bit
* is 0. The UIP bit is read-only and is not affected by
* !RESET. Writing the SET bit in Register B to a 1
* inhibits any update transfer and clears the UIP status bit.
*
* * Daylight Saving Enable (DSE)
* This bit is a read/write bit that enables two daylight
* saving adjustments when DSE is set to 1. On the first
* Sunday in April (or the last Sunday in April in the
* MC146818A), the time increments from 1:59:59 AM to
* 3:00:00 AM. On the last Sunday in October when the time
* first reaches 1:59:59 AM, it changes to 1:00:00 AM.
*
* When DSE is enabled, the internal logic test for the
* first/last Sunday condition at midnight. If the DSE bit
* is not set when the test occurs, the daylight saving
* function does not operate correctly. These adjustments
* do not occur when the DSE bit is 0. This bit is not
* affected by internal functions or !RESET.
*
* * 24/12
* The 24/12 control bit establishes the format of the hours
* byte. A 1 indicates the 24-hour mode and a 0 indicates
* the 12-hour mode. This bit is read/write and is not
* affected by internal functions or !RESET.
*
* * Data Mode (DM)
* This bit indicates whether time and calendar information
* is in binary or BCD format. The DM bit is set by the
* program to the appropriate format and can be read as
* required. This bit is not modified by internal functions
* or !RESET. A 1 in DM signifies binary data, while a 0 in
* DM specifies BCD data.
*
* * Square-Wave Enable (SQWE)
* When this bit is set to 1, a square-wave signal at the
* frequency set by the rate-selection bits RS3-RS0 is driven
* out on the SQW pin. When the SQWE bit is set to 0, the
* SQW pin is held low. SQWE is a read/write bit and is
* cleared by !RESET. SQWE is low if disabled, and is high
* impedance when VCC is below VPF. SQWE is cleared to 0 on
* !RESET.
*
* * Update-Ended Interrupt Enable (UIE)
* This bit is a read/write bit that enables the update-end
* flag (UF) bit in Register C to assert !IRQ. The !RESET
* pin going low or the SET bit going high clears the UIE bit.
* The internal functions of the device do not affect the UIE
* bit, but is cleared to 0 on !RESET.
*
* * Alarm Interrupt Enable (AIE)
* This bit is a read/write bit that, when set to 1, permits
* the alarm flag (AF) bit in Register C to assert !IRQ. An
* alarm interrupt occurs for each second that the three time
* bytes equal the three alarm bytes, including a don't-care
* alarm code of binary 11XXXXXX. The AF bit does not
* initiate the !IRQ signal when the AIE bit is set to 0.
* The internal functions of the device do not affect the AIE
* bit, but is cleared to 0 on !RESET.
*
* * Periodic Interrupt Enable (PIE)
* The PIE bit is a read/write bit that allows the periodic
* interrupt flag (PF) bit in Register C to drive the !IRQ pin
* low. When the PIE bit is set to 1, periodic interrupts are
* generated by driving the !IRQ pin low at a rate specified
* by the RS3-RS0 bits of Register A. A 0 in the PIE bit
* blocks the !IRQ output from being driven by a periodic
* interrupt, but the PF bit is still set at the periodic
* rate. PIE is not modified b any internal device functions,
* but is cleared to 0 on !RESET.
*
* * SET
* When the SET bit is 0, the update transfer functions
* normally by advancing the counts once per second. When
* the SET bit is written to 1, any update transfer is
* inhibited, and the program can initialize the time and
* calendar bytes without an update occurring in the midst of
* initializing. Read cycles can be executed in a similar
* manner. SET is a read/write bit and is not affected by
* !RESET or internal functions of the device.
*
* * Update-Ended Interrupt Flag (UF)
* This bit is set after each update cycle. When the UIE
* bit is set to 1, the 1 in UF causes the IRQF bit to be
* a 1, which asserts the !IRQ pin. This bit can be
* cleared by reading Register C or with a !RESET.
*
* * Alarm Interrupt Flag (AF)
* A 1 in the AF bit indicates that the current time has
* matched the alarm time. If the AIE bit is also 1, the
* !IRQ pin goes low and a 1 appears in the IRQF bit. This
* bit can be cleared by reading Register C or with a
* !RESET.
*
* * Periodic Interrupt Flag (PF)
* This bit is read-only and is set to 1 when an edge is
* detected on the selected tap of the divider chain. The
* RS3 through RS0 bits establish the periodic rate. PF is
* set to 1 independent of the state of the PIE bit. When
* both PF and PIE are 1s, the !IRQ signal is active and
* sets the IRQF bit. This bit can be cleared by reading
* Register C or with a !RESET.
*
* * Interrupt Request Flag (IRQF)
* The interrupt request flag (IRQF) is set to a 1 when one
* or more of the following are true:
* - PF == PIE == 1
* - AF == AIE == 1
* - UF == UIE == 1
* Any time the IRQF bit is a 1, the !IRQ pin is driven low.
* All flag bits are cleared after Register C is read by the
* program or when the !RESET pin is low.
*
* * Valid RAM and Time (VRT)
* This bit indicates the condition of the battery connected
* to the VBAT pin. This bit is not writeable and should
* always be 1 when read. If a 0 is ever present, an
* exhausted internal lithium energy source is indicated and
* both the contents of the RTC data and RAM data are
* questionable. This bit is unaffected by !RESET.
*
* This file implements a generic version of the RTC/NVRAM chip,
* including the later update (DS12887A) which implemented a
* "century" register to be compatible with Y2K.
*
*
*
* Authors: Fred N. van Kempen, <decwiz@yahoo.com>
* Miran Grca, <mgrca8@gmail.com>
* Mahod,
*
*
* This program is free software; you can redistribute it and/or modify
* (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
*
* along with this program; if not, write to the:
*
* Free Software Foundation, Inc.
* 59 Temple Place - Suite 330
* Boston, MA 02111-1307
* USA.
*/
#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <time.h>
#include <86box/86box.h>
#include "cpu.h"
#include <86box/machine.h>
#include <86box/io.h>
#include <86box/mem.h>
#include <86box/nmi.h>
#include <86box/pic.h>
#include <86box/timer.h>
#include <86box/pit.h>
#include <86box/rom.h>
#include <86box/device.h>
#include <86box/nvr.h>
/* RTC registers and bit definitions. */
#define RTC_SECONDS 0
#define RTC_ALSECONDS 1
#define AL_DONTCARE 0xc0 /* Alarm time is not set */
#define RTC_MINUTES 2
#define RTC_ALMINUTES 3
#define RTC_HOURS 4
#define RTC_AMPM 0x80 /* PM flag if 12h format in use */
#define RTC_ALHOURS 5
#define RTC_DOW 6
#define RTC_DOM 7
#define RTC_MONTH 8
#define RTC_YEAR 9
#define RTC_REGA 10
#define REGA_UIP 0x80
#define REGA_DV2 0x40
#define REGA_DV1 0x20
#define REGA_DV0 0x10
#define REGA_DV 0x70
#define REGA_RS3 0x08
#define REGA_RS2 0x04
#define REGA_RS1 0x02
#define REGA_RS0 0x01
#define REGA_RS 0x0f
#define RTC_REGB 11
#define REGB_SET 0x80
#define REGB_PIE 0x40
#define REGB_AIE 0x20
#define REGB_UIE 0x10
#define REGB_SQWE 0x08
#define REGB_DM 0x04
#define REGB_2412 0x02
#define REGB_DSE 0x01
#define RTC_REGC 12
#define REGC_IRQF 0x80
#define REGC_PF 0x40
#define REGC_AF 0x20
#define REGC_UF 0x10
#define RTC_REGD 13
#define REGD_VRT 0x80
#define RTC_CENTURY_AT 0x32 /* century register for AT etc */
#define RTC_CENTURY_PS 0x37 /* century register for PS/1 PS/2 */
#define RTC_CENTURY_ELT 0x1A /* century register for Epson Equity LT */
#define RTC_ALDAY 0x7D /* VIA VT82C586B - alarm day */
#define RTC_ALMONTH 0x7E /* VIA VT82C586B - alarm month */
#define RTC_CENTURY_VIA 0x7F /* century register for VIA VT82C586B */
#define RTC_ALDAY_SIS 0x7E /* Day of Month Alarm for SiS */
#define RTC_ALMONT_SIS 0x7F /* Month Alarm for SiS */
#define RTC_REGS 14 /* number of registers */
#define FLAG_NO_NMI 0x01
#define FLAG_AMI_1992_HACK 0x02
#define FLAG_AMI_1994_HACK 0x04
#define FLAG_AMI_1995_HACK 0x08
#define FLAG_P6RP4_HACK 0x10
#define FLAG_PIIX4 0x20
#define FLAG_MULTI_BANK 0x40
typedef struct local_t {
int8_t stat;
uint8_t cent;
uint8_t def;
uint8_t flags;
uint8_t read_addr;
uint8_t wp_0d;
uint8_t wp_32;
uint8_t irq_state;
uint8_t smi_status;
uint8_t wp[2];
uint8_t bank[8];
uint8_t *lock;
int16_t count;
int16_t state;
uint16_t addr[8];
int32_t smi_enable;
uint64_t ecount;
uint64_t rtc_time;
pc_timer_t update_timer;
pc_timer_t rtc_timer;
} local_t;
static uint8_t nvr_at_inited = 0;
/* Get the current NVR time. */
static void
time_get(nvr_t *nvr, struct tm *tm)
{
const local_t *local = (local_t *) nvr->data;
int8_t temp;
if (nvr->regs[RTC_REGB] & REGB_DM) {
/* NVR is in Binary data mode. */
tm->tm_sec = nvr->regs[RTC_SECONDS];
tm->tm_min = nvr->regs[RTC_MINUTES];
temp = nvr->regs[RTC_HOURS];
tm->tm_wday = (nvr->regs[RTC_DOW] - 1);
tm->tm_mday = nvr->regs[RTC_DOM];
tm->tm_mon = (nvr->regs[RTC_MONTH] - 1);
tm->tm_year = nvr->regs[RTC_YEAR];
if (local->cent != 0xFF)
tm->tm_year += (nvr->regs[local->cent] * 100) - 1900;
} else {
/* NVR is in BCD data mode. */
tm->tm_sec = RTC_DCB(nvr->regs[RTC_SECONDS]);
tm->tm_min = RTC_DCB(nvr->regs[RTC_MINUTES]);
temp = RTC_DCB(nvr->regs[RTC_HOURS]);
tm->tm_wday = (RTC_DCB(nvr->regs[RTC_DOW]) - 1);
tm->tm_mday = RTC_DCB(nvr->regs[RTC_DOM]);
tm->tm_mon = (RTC_DCB(nvr->regs[RTC_MONTH]) - 1);
tm->tm_year = RTC_DCB(nvr->regs[RTC_YEAR]);
if (local->cent != 0xFF)
tm->tm_year += (RTC_DCB(nvr->regs[local->cent]) * 100) - 1900;
}
/* Adjust for 12/24 hour mode. */
if (nvr->regs[RTC_REGB] & REGB_2412)
tm->tm_hour = temp;
else
tm->tm_hour = ((temp & ~RTC_AMPM) % 12) + ((temp & RTC_AMPM) ? 12 : 0);
}
/* Set the current NVR time. */
static void
time_set(nvr_t *nvr, struct tm *tm)
{
const local_t *local = (local_t *) nvr->data;
int year = (tm->tm_year + 1900);
if (nvr->regs[RTC_REGB] & REGB_DM) {
/* NVR is in Binary data mode. */
nvr->regs[RTC_SECONDS] = tm->tm_sec;
nvr->regs[RTC_MINUTES] = tm->tm_min;
nvr->regs[RTC_DOW] = (tm->tm_wday + 1);
nvr->regs[RTC_DOM] = tm->tm_mday;
nvr->regs[RTC_MONTH] = (tm->tm_mon + 1);
nvr->regs[RTC_YEAR] = (year % 100);
if (local->cent != 0xFF)
nvr->regs[local->cent] = (year / 100);
if (nvr->regs[RTC_REGB] & REGB_2412) {
/* NVR is in 24h mode. */
nvr->regs[RTC_HOURS] = tm->tm_hour;
} else {
/* NVR is in 12h mode. */
nvr->regs[RTC_HOURS] = (tm->tm_hour % 12) ? (tm->tm_hour % 12) : 12;
if (tm->tm_hour > 11)
nvr->regs[RTC_HOURS] |= RTC_AMPM;
}
} else {
/* NVR is in BCD data mode. */
nvr->regs[RTC_SECONDS] = RTC_BCD(tm->tm_sec);
nvr->regs[RTC_MINUTES] = RTC_BCD(tm->tm_min);
nvr->regs[RTC_DOW] = RTC_BCD(tm->tm_wday + 1);
nvr->regs[RTC_DOM] = RTC_BCD(tm->tm_mday);
nvr->regs[RTC_MONTH] = RTC_BCD(tm->tm_mon + 1);
nvr->regs[RTC_YEAR] = RTC_BCD(year % 100);
if (local->cent != 0xFF)
nvr->regs[local->cent] = RTC_BCD(year / 100);
if (nvr->regs[RTC_REGB] & REGB_2412) {
/* NVR is in 24h mode. */
nvr->regs[RTC_HOURS] = RTC_BCD(tm->tm_hour);
} else {
/* NVR is in 12h mode. */
nvr->regs[RTC_HOURS] = (tm->tm_hour % 12)
? RTC_BCD(tm->tm_hour % 12)
: RTC_BCD(12);
if (tm->tm_hour > 11)
nvr->regs[RTC_HOURS] |= RTC_AMPM;
}
}
}
/* Check if the current time matches a set alarm time. */
static int8_t
check_alarm(nvr_t *nvr, int8_t addr)
{
return ((nvr->regs[addr + 1] == nvr->regs[addr]) || ((nvr->regs[addr + 1] & AL_DONTCARE) == AL_DONTCARE));
}
/* Check for VIA stuff. */
static int8_t
check_alarm_via(nvr_t *nvr, int8_t addr, int8_t addr_2)
{
const local_t *local = (local_t *) nvr->data;
if (local->cent == RTC_CENTURY_VIA) {
return ((nvr->regs[addr_2] == nvr->regs[addr]) || ((nvr->regs[addr_2] & AL_DONTCARE) == AL_DONTCARE));
} else
return 1;
}
static void
timer_update_irq(nvr_t *nvr)
{
local_t *local = (local_t *) nvr->data;
uint8_t irq = (nvr->regs[RTC_REGB] & nvr->regs[RTC_REGC]) & (REGB_UIE | REGB_AIE | REGB_PIE);
if (irq || (local->irq_state != !!irq)) {
if (irq) {
nvr->regs[RTC_REGC] |= REGC_IRQF;
picintlevel(1 << nvr->irq, &local->irq_state);
if (local->smi_enable) {
smi_raise();
local->smi_status = 1;
}
} else {
nvr->regs[RTC_REGC] &= ~REGC_IRQF;
picintclevel(1 << nvr->irq, &local->irq_state);
}
}
}
/* Update the NVR registers from the internal clock. */
static void
timer_update(void *priv)
{
nvr_t *nvr = (nvr_t *) priv;
local_t *local = (local_t *) nvr->data;
struct tm tm;
if (local->ecount == (244ULL * TIMER_USEC)) {
rtc_tick();
/* Get the current time from the internal clock. */
nvr_time_get(&tm);
/* Update registers with current time. */
time_set(nvr, &tm);
/* Check for any alarms we need to handle. */
if (check_alarm(nvr, RTC_SECONDS) && check_alarm(nvr, RTC_MINUTES) && check_alarm(nvr, RTC_HOURS) &&
check_alarm_via(nvr, RTC_DOM, RTC_ALDAY) && check_alarm_via(nvr, RTC_MONTH, RTC_ALMONTH) /* &&
check_alarm_via(nvr, RTC_DOM, RTC_ALDAY_SIS) && check_alarm_via(nvr, RTC_MONTH, RTC_ALMONT_SIS) */) {
nvr->regs[RTC_REGC] |= REGC_AF;
timer_update_irq(nvr);
}
/* Schedule the end of the update. */
local->ecount = 1984ULL * TIMER_USEC;
timer_set_delay_u64(&local->update_timer, local->ecount);
} else {
/*
* The flag and interrupt should be issued
* on update ended, not started.
*/
nvr->regs[RTC_REGC] |= REGC_UF;
timer_update_irq(nvr);
/* Clear update status. */
local->stat = 0x00;
local->ecount = 0LL;
}
}
static void
timer_load_count(nvr_t *nvr)
{
int c = nvr->regs[RTC_REGA] & REGA_RS;
local_t *local = (local_t *) nvr->data;
timer_disable(&local->rtc_timer);
if ((nvr->regs[RTC_REGA] & 0x70) != 0x20) {
local->state = 0;
return;
}
local->state = 1;
switch (c) {
case 0:
local->state = 0;
break;
case 1:
case 2:
local->count = 1 << (c + 6);
timer_set_delay_u64(&local->rtc_timer, (local->count) * RTCCONST);
break;
default:
local->count = 1 << (c - 1);
timer_set_delay_u64(&local->rtc_timer, (local->count) * RTCCONST);
break;
}
}
static void
timer_intr(void *priv)
{
nvr_t *nvr = (nvr_t *) priv;
const local_t *local = (local_t *) nvr->data;
if (local->state == 1) {
timer_load_count(nvr);
nvr->regs[RTC_REGC] |= REGC_PF;
timer_update_irq(nvr);
}
}
/* Callback from internal clock, another second passed. */
static void
timer_tick(nvr_t *nvr)
{
local_t *local = (local_t *) nvr->data;
/* Only update it there is no SET in progress.
Also avoid updating it is DV2-DV0 are not set to 0, 1, 0. */
if (((nvr->regs[RTC_REGA] & 0x70) == 0x20) && !(nvr->regs[RTC_REGB] & REGB_SET)) {
/* Set the UIP bit, announcing the update. */
local->stat = REGA_UIP;
/* Schedule the actual update. */
local->ecount = 244ULL * TIMER_USEC;
timer_set_delay_u64(&local->update_timer, local->ecount);
}
}
static void
nvr_reg_common_write(uint16_t reg, uint8_t val, nvr_t *nvr, local_t *local)
{
if (local->lock[reg])
return;
if ((reg == 0x2c) && (local->flags & FLAG_AMI_1994_HACK))
nvr->is_new = 0;
if ((reg == 0x2d) && (local->flags & FLAG_AMI_1992_HACK))
nvr->is_new = 0;
if ((reg == 0x52) && (local->flags & FLAG_AMI_1995_HACK))
nvr->is_new = 0;
if ((reg >= 0x38) && (reg <= 0x3f) && local->wp[0])
return;
if ((reg >= 0xb8) && (reg <= 0xbf) && local->wp[1])
return;
if (nvr->regs[reg] != val) {
nvr->regs[reg] = val;
if ((reg >= 0x0d) && ((local->cent == 0xff) || (reg != local->cent)))
nvr_dosave = 1;
}
}
/* This must be exposed because ACPI uses it. */
void
nvr_reg_write(uint16_t reg, uint8_t val, void *priv)
{
nvr_t *nvr = (nvr_t *) priv;
local_t *local = (local_t *) nvr->data;
struct tm tm;
uint8_t old;
old = nvr->regs[reg];
switch (reg) {
case RTC_SECONDS: /* bit 7 of seconds is read-only */
nvr_reg_common_write(reg, val & 0x7f, nvr, local);
break;
case RTC_REGA:
if ((val & nvr->regs[RTC_REGA]) & ~REGA_UIP) {
nvr->regs[RTC_REGA] = (nvr->regs[RTC_REGA] & REGA_UIP) | (val & ~REGA_UIP);
timer_load_count(nvr);
}
break;
case RTC_REGB:
if (((old ^ val) & REGB_SET) && (val & REGB_SET)) {
/* According to the datasheet... */
val &= ~REGB_UIE;
local->stat &= ~REGA_UIP;
}
nvr->regs[RTC_REGB] = val;
timer_update_irq(nvr);
break;
case RTC_REGC: /* R/O */
break;
case RTC_REGD: /* R/O */
/* This is needed for VIA, where writing to this register changes a write-only
bit whose value is read from power management register 42. */
nvr->regs[RTC_REGD] = val & 0x80;
break;
case 0x32:
if ((reg == 0x32) && (local->cent == RTC_CENTURY_VIA) && local->wp_32)
break;
nvr_reg_common_write(reg, val, nvr, local);
break;
default: /* non-RTC registers are just NVRAM */
nvr_reg_common_write(reg, val, nvr, local);
break;
}
if ((reg < RTC_REGA) || ((local->cent != 0xff) && (reg == local->cent))) {
if ((reg != 1) && (reg != 3) && (reg != 5)) {
if ((old != val) && !(time_sync & TIME_SYNC_ENABLED)) {
/* Update internal clock. */
time_get(nvr, &tm);
nvr_time_set(&tm);
// nvr_dosave = 1;
}
}
}
}
/* Write to one of the NVR registers. */
static void
nvr_write(uint16_t addr, uint8_t val, void *priv)
{
nvr_t *nvr = (nvr_t *) priv;
local_t *local = (local_t *) nvr->data;
uint8_t addr_id = (addr & 0x0e) >> 1;
cycles -= ISA_CYCLES(8);
if (local->bank[addr_id] == 0xff)
return;
if (addr & 1) {
#if 0
if (local->bank[addr_id] == 0xff)
return;
#endif
nvr_reg_write(local->addr[addr_id], val, priv);
} else {
local->addr[addr_id] = (val & (nvr->size - 1));
/* Some chipsets use a 256 byte NVRAM but ports 70h and 71h always access only 128 bytes. */
if (addr_id == 0x0) {
local->addr[addr_id] &= 0x7f;
/* Needed for OPTi 82C601/82C602 and NSC PC87306. */
if (local->flags & FLAG_MULTI_BANK)
local->addr[addr_id] |= (0x80 * local->bank[addr_id]);
} else if ((addr_id == 0x1) && (local->flags & FLAG_PIIX4))
local->addr[addr_id] = (local->addr[addr_id] & 0x7f) | 0x80;
if (local->bank[addr_id] > 0)
local->addr[addr_id] = (local->addr[addr_id] & 0x7f) | (0x80 * local->bank[addr_id]);
if (!(local->flags & FLAG_NO_NMI))
nmi_mask = (~val & 0x80);
}
}
/* Get the NVR register index (used for APC). */
uint8_t
nvr_get_index(void *priv, uint8_t addr_id)
{
nvr_t *nvr = (nvr_t *) priv;
local_t *local = (local_t *) nvr->data;
uint8_t ret;
ret = local->addr[addr_id];
return ret;
}
/* Read from one of the NVR registers. */
static uint8_t
nvr_read(uint16_t addr, void *priv)
{
nvr_t *nvr = (nvr_t *) priv;
const local_t *local = (local_t *) nvr->data;
uint8_t ret = 0xff;
uint8_t addr_id = (addr & 0x0e) >> 1;
uint16_t i;
uint16_t checksum = 0x0000;
cycles -= ISA_CYCLES(8);
if (local->bank[addr_id] == 0xff)
ret = 0xff;
else if (addr & 1)
switch (local->addr[addr_id]) {
case RTC_REGA:
ret = (nvr->regs[RTC_REGA] & 0x7f) | local->stat;
break;
case RTC_REGC:
ret = nvr->regs[RTC_REGC] & (REGC_IRQF | REGC_PF | REGC_AF | REGC_UF);
nvr->regs[RTC_REGC] &= ~(REGC_IRQF | REGC_PF | REGC_AF | REGC_UF);
timer_update_irq(nvr);
break;
case RTC_REGD:
/* Bits 6-0 of this register always read 0. Bit 7 is battery state,
we should always return it set, as that means the battery is OK. */
ret = REGD_VRT;
break;
case 0x2c:
if (!nvr->is_new && (local->flags & FLAG_AMI_1994_HACK))
ret = nvr->regs[local->addr[addr_id]] & 0x7f;
else
ret = nvr->regs[local->addr[addr_id]];
break;
case 0x2d:
if (!nvr->is_new && (local->flags & FLAG_AMI_1992_HACK))
ret = nvr->regs[local->addr[addr_id]] & 0xf7;
else
ret = nvr->regs[local->addr[addr_id]];
break;
case 0x2e:
case 0x2f:
if (!nvr->is_new && (local->flags & FLAG_AMI_1992_HACK)) {
for (i = 0x10; i <= 0x2d; i++) {
if (i == 0x2d)
checksum += (nvr->regs[i] & 0xf7);
else
checksum += nvr->regs[i];
}
if (local->addr[addr_id] == 0x2e)
ret = checksum >> 8;
else
ret = checksum & 0xff;
} else if (!nvr->is_new && (local->flags & FLAG_AMI_1994_HACK)) {
for (i = 0x10; i <= 0x2d; i++) {
if (i == 0x2c)
checksum += (nvr->regs[i] & 0x7f);
else
checksum += nvr->regs[i];
}
if (local->addr[addr_id] == 0x2e)
ret = checksum >> 8;
else
ret = checksum & 0xff;
} else
ret = nvr->regs[local->addr[addr_id]];
break;
case 0x3e:
case 0x3f:
if (!nvr->is_new && (local->flags & FLAG_AMI_1995_HACK)) {
/* The checksum at 3E-3F is for 37-3D and 40-7F. */
for (i = 0x37; i <= 0x3d; i++)
checksum += nvr->regs[i];
for (i = 0x40; i <= 0x7f; i++) {
if (i == 0x52)
checksum += (nvr->regs[i] & 0xf3);
else
checksum += nvr->regs[i];
}
if (local->addr[addr_id] == 0x3e)
ret = checksum >> 8;
else
ret = checksum & 0xff;
} else if (!nvr->is_new && (local->flags & FLAG_P6RP4_HACK)) {
/* The checksum at 3E-3F is for 37-3D and 40-51. */
for (i = 0x37; i <= 0x3d; i++)
checksum += nvr->regs[i];
for (i = 0x40; i <= 0x51; i++) {
if (i == 0x43)
checksum += (nvr->regs[i] | 0x02);
else
checksum += nvr->regs[i];
}
if (local->addr[addr_id] == 0x3e)
ret = checksum >> 8;
else
ret = checksum & 0xff;
} else
ret = nvr->regs[local->addr[addr_id]];
break;
case 0x43:
if (!nvr->is_new && (local->flags & FLAG_P6RP4_HACK))
ret = nvr->regs[local->addr[addr_id]] | 0x02;
else
ret = nvr->regs[local->addr[addr_id]];
break;
case 0x52:
if (!nvr->is_new && (local->flags & FLAG_AMI_1995_HACK))
ret = nvr->regs[local->addr[addr_id]] & 0xf3;
else
ret = nvr->regs[local->addr[addr_id]];
break;
default:
if (!(local->lock[local->addr[addr_id]] & 0x02))
ret = nvr->regs[local->addr[addr_id]];
break;
}
else {
ret = local->addr[addr_id];
if (!local->read_addr)
ret &= 0x80;
if (alt_access)
ret = (ret & 0x7f) | (nmi_mask ? 0x00 : 0x80);
}
return ret;
}
/* Secondary NVR write - used by SMC. */
static void
nvr_sec_write(uint16_t addr, uint8_t val, void *priv)
{
nvr_write(0x72 + (addr & 1), val, priv);
}
/* Secondary NVR read - used by SMC. */
static uint8_t
nvr_sec_read(uint16_t addr, void *priv)
{
return nvr_read(0x72 + (addr & 1), priv);
}
/* Reset the RTC state to 1980/01/01 00:00. */
static void
nvr_reset(nvr_t *nvr)
{
const local_t *local = (local_t *) nvr->data;
#if 0
memset(nvr->regs, local->def, RTC_REGS);
#endif
memset(nvr->regs, local->def, nvr->size);
nvr->regs[RTC_DOM] = 1;
nvr->regs[RTC_MONTH] = 1;
nvr->regs[RTC_YEAR] = RTC_BCD(80);
if (local->cent != 0xFF)
nvr->regs[local->cent] = RTC_BCD(19);
nvr->regs[RTC_REGD] = REGD_VRT;
}
/* Process after loading from file. */
static void
nvr_start(nvr_t *nvr)
{
const local_t *local = (local_t *) nvr->data;
struct tm tm;
int default_found = 0;
for (uint16_t i = 0; i < nvr->size; i++) {
if (nvr->regs[i] == local->def)
default_found++;
}
if (default_found == nvr->size)
nvr->regs[0x0e] = 0xff; /* If load failed or it loaded an uninitialized NVR,
mark everything as bad. */
/* Initialize the internal and chip times. */
if (time_sync & TIME_SYNC_ENABLED) {
/* Use the internal clock's time. */
nvr_time_get(&tm);
time_set(nvr, &tm);
} else {
/* Set the internal clock from the chip time. */
time_get(nvr, &tm);
nvr_time_set(&tm);
}
/* Start the RTC. */
nvr->regs[RTC_REGA] = (REGA_RS2 | REGA_RS1);
nvr->regs[RTC_REGB] = REGB_2412;
}
static void
nvr_at_speed_changed(void *priv)
{
nvr_t *nvr = (nvr_t *) priv;
local_t *local = (local_t *) nvr->data;
timer_load_count(nvr);
timer_disable(&local->update_timer);
if (local->ecount > 0ULL)
timer_set_delay_u64(&local->update_timer, local->ecount);
timer_disable(&nvr->onesec_time);
timer_set_delay_u64(&nvr->onesec_time, (10000ULL * TIMER_USEC));
}
void
nvr_at_handler(int set, uint16_t base, nvr_t *nvr)
{
io_handler(set, base, 2,
nvr_read, NULL, NULL, nvr_write, NULL, NULL, nvr);
}
void
nvr_at_index_read_handler(int set, uint16_t base, nvr_t *nvr)
{
io_handler(0, base, 1,
NULL, NULL, NULL, nvr_write, NULL, NULL, nvr);
nvr_at_handler(0, base, nvr);
if (set)
nvr_at_handler(1, base, nvr);
else {
io_handler(1, base, 1,
NULL, NULL, NULL, nvr_write, NULL, NULL, nvr);
io_handler(1, base + 1, 1,
nvr_read, NULL, NULL, nvr_write, NULL, NULL, nvr);
}
}
void
nvr_at_data_port(int set, nvr_t *nvr)
{
io_handler(0, 0x71, 1,
nvr_read, NULL, NULL, nvr_write, NULL, NULL, nvr);
if (set)
io_handler(1, 0x71, 1,
nvr_read, NULL, NULL, nvr_write, NULL, NULL, nvr);
}
void
nvr_at_sec_handler(int set, uint16_t base, nvr_t *nvr)
{
io_handler(set, base, 2,
nvr_sec_read, NULL, NULL, nvr_sec_write, NULL, NULL, nvr);
}
void
nvr_read_addr_set(int set, nvr_t *nvr)
{
local_t *local = (local_t *) nvr->data;
local->read_addr = set;
}
void
nvr_wp_set(int set, int h, nvr_t *nvr)
{
local_t *local = (local_t *) nvr->data;
local->wp[h] = set;
}
void
nvr_via_wp_set(int set, int reg, nvr_t *nvr)
{
local_t *local = (local_t *) nvr->data;
if (reg == 0x0d)
local->wp_0d = set;
else
local->wp_32 = set;
}
void
nvr_bank_set(int base, uint8_t bank, nvr_t *nvr)
{
local_t *local = (local_t *) nvr->data;
local->bank[base] = bank;
}
void
nvr_lock_set(int base, int size, int lock, nvr_t *nvr)
{
local_t *local = (local_t *) nvr->data;
for (int i = 0; i < size; i++)
local->lock[base + i] = lock;
}
void
nvr_irq_set(int irq, nvr_t *nvr)
{
nvr->irq = irq;
}
void
nvr_smi_enable(int enable, nvr_t *nvr)
{
local_t *local = (local_t *) nvr->data;
local->smi_enable = enable;
if (!enable)
local->smi_status = 0;
}
uint8_t
nvr_smi_status(nvr_t *nvr)
{
const local_t *local = (local_t *) nvr->data;
return local->smi_status;
}
void
nvr_smi_status_clear(nvr_t *nvr)
{
local_t *local = (local_t *) nvr->data;
local->smi_status = 0;
}
static void
nvr_at_reset(void *priv)
{
nvr_t *nvr = (nvr_t *) priv;
/* These bits are reset on reset. */
nvr->regs[RTC_REGB] &= ~(REGB_PIE | REGB_AIE | REGB_UIE | REGB_SQWE);
nvr->regs[RTC_REGC] &= ~(REGC_PF | REGC_AF | REGC_UF | REGC_IRQF);
}
static void *
nvr_at_init(const device_t *info)
{
local_t *local;
nvr_t *nvr;
/* Allocate an NVR for this machine. */
nvr = (nvr_t *) malloc(sizeof(nvr_t));
if (nvr == NULL)
return (NULL);
memset(nvr, 0x00, sizeof(nvr_t));
local = (local_t *) malloc(sizeof(local_t));
memset(local, 0x00, sizeof(local_t));
nvr->data = local;
/* This is machine specific. */
nvr->size = machines[machine].nvrmask + 1;
local->lock = (uint8_t *) malloc(nvr->size);
memset(local->lock, 0x00, nvr->size);
local->def = 0xff /*0x00*/;
local->flags = 0x00;
switch (info->local & 0x0f) {
case 0: /* standard AT, no century register */
if (info->local == 32) {
local->flags |= FLAG_P6RP4_HACK;
nvr->irq = 8;
local->cent = RTC_CENTURY_AT;
} else {
nvr->irq = 8;
local->cent = 0xff;
}
break;
case 1: /* standard AT */
case 5: /* AMI WinBIOS 1994 */
case 6: /* AMI BIOS 1995 */
if ((info->local & 0x1f) == 0x11)
local->flags |= FLAG_PIIX4;
else {
local->def = 0x00;
if ((info->local & 0x1f) == 0x15)
local->flags |= FLAG_AMI_1994_HACK;
else if ((info->local & 0x1f) == 0x16)
local->flags |= FLAG_AMI_1995_HACK;
else
local->def = 0xff;
}
nvr->irq = 8;
local->cent = RTC_CENTURY_AT;
break;
case 2: /* PS/1 or PS/2 */
nvr->irq = 8;
local->cent = RTC_CENTURY_PS;
local->def = 0x00;
if (info->local & 0x10)
local->flags |= FLAG_NO_NMI;
break;
case 3: /* Amstrad PC's */
nvr->irq = 1;
local->cent = RTC_CENTURY_AT;
local->def = 0xff;
if (info->local & 0x10)
local->flags |= FLAG_NO_NMI;
break;
case 4: /* IBM AT */
if (info->local & 0x10) {
local->def = 0x00;
local->flags |= FLAG_AMI_1992_HACK;
} else if (info->local == 36)
local->def = 0x00;
else
local->def = 0xff;
nvr->irq = 8;
local->cent = RTC_CENTURY_AT;
break;
case 7: /* VIA VT82C586B */
nvr->irq = 8;
local->cent = RTC_CENTURY_VIA;
break;
case 8: /* Epson Equity LT */
nvr->irq = -1;
local->cent = RTC_CENTURY_ELT;
break;
default:
break;
}
if (info->local & 0x20)
local->def = 0x00;
if (info->local & 0x40)
local->flags |= FLAG_MULTI_BANK;
local->read_addr = 1;
/* Set up any local handlers here. */
nvr->reset = nvr_reset;
nvr->start = nvr_start;
nvr->tick = timer_tick;
/* Initialize the generic NVR. */
nvr_init(nvr);
if (nvr_at_inited == 0) {
/* Start the timers. */
timer_add(&local->update_timer, timer_update, nvr, 0);
timer_add(&local->rtc_timer, timer_intr, nvr, 0);
/* On power on, if the oscillator is disabled, it's reenabled. */
if ((nvr->regs[RTC_REGA] & 0x70) == 0x00)
nvr->regs[RTC_REGA] = (nvr->regs[RTC_REGA] & 0x8f) | 0x20;
nvr_at_reset(nvr);
timer_load_count(nvr);
/* Set up the I/O handler for this device. */
if (info->local == 8) {
io_sethandler(0x11b4, 2,
nvr_read, NULL, NULL, nvr_write, NULL, NULL, nvr);
} else {
io_sethandler(0x0070, 2,
nvr_read, NULL, NULL, nvr_write, NULL, NULL, nvr);
}
if (((info->local & 0x1f) == 0x11) || ((info->local & 0x1f) == 0x17)) {
io_sethandler(0x0072, 2,
nvr_read, NULL, NULL, nvr_write, NULL, NULL, nvr);
}
nvr_at_inited = 1;
}
return nvr;
}
static void
nvr_at_close(void *priv)
{
nvr_t *nvr = (nvr_t *) priv;
local_t *local = (local_t *) nvr->data;
nvr_close();
timer_disable(&local->rtc_timer);
timer_disable(&local->update_timer);
timer_disable(&nvr->onesec_time);
if (nvr != NULL) {
if (nvr->fn != NULL)
free(nvr->fn);
if (nvr->data != NULL)
free(nvr->data);
free(nvr);
}
if (nvr_at_inited == 1)
nvr_at_inited = 0;
}
const device_t at_nvr_old_device = {
.name = "PC/AT NVRAM (No century)",
.internal_name = "at_nvr_old",
.flags = DEVICE_ISA | DEVICE_AT,
.local = 0,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t at_nvr_device = {
.name = "PC/AT NVRAM",
.internal_name = "at_nvr",
.flags = DEVICE_ISA | DEVICE_AT,
.local = 1,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t at_mb_nvr_device = {
.name = "PC/AT NVRAM",
.internal_name = "at_nvr",
.flags = DEVICE_ISA | DEVICE_AT,
.local = 0x40 | 0x20 | 1,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t ps_nvr_device = {
.name = "PS/1 or PS/2 NVRAM",
.internal_name = "ps_nvr",
.flags = DEVICE_PS2,
.local = 2,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t amstrad_nvr_device = {
.name = "Amstrad NVRAM",
.internal_name = "amstrad_nvr",
.flags = DEVICE_ISA | DEVICE_AT,
.local = 3,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t ibmat_nvr_device = {
.name = "IBM AT NVRAM",
.internal_name = "ibmat_nvr",
.flags = DEVICE_ISA | DEVICE_AT,
.local = 4,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t piix4_nvr_device = {
.name = "Intel PIIX4 PC/AT NVRAM",
.internal_name = "piix4_nvr",
.flags = DEVICE_ISA | DEVICE_AT,
.local = 0x10 | 1,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t ps_no_nmi_nvr_device = {
.name = "PS/1 or PS/2 NVRAM (No NMI)",
.internal_name = "ps1_nvr",
.flags = DEVICE_PS2,
.local = 0x10 | 2,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t amstrad_no_nmi_nvr_device = {
.name = "Amstrad NVRAM (No NMI)",
.internal_name = "amstrad_nvr",
.flags = DEVICE_ISA | DEVICE_AT,
.local = 0x10 | 3,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t ami_1992_nvr_device = {
.name = "AMI Color 1992 PC/AT NVRAM",
.internal_name = "ami_1992_nvr",
.flags = DEVICE_ISA | DEVICE_AT,
.local = 0x10 | 4,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t ami_1994_nvr_device = {
.name = "AMI WinBIOS 1994 PC/AT NVRAM",
.internal_name = "ami_1994_nvr",
.flags = DEVICE_ISA | DEVICE_AT,
.local = 0x10 | 5,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t ami_1995_nvr_device = {
.name = "AMI WinBIOS 1995 PC/AT NVRAM",
.internal_name = "ami_1995_nvr",
.flags = DEVICE_ISA | DEVICE_AT,
.local = 0x10 | 6,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t via_nvr_device = {
.name = "VIA PC/AT NVRAM",
.internal_name = "via_nvr",
.flags = DEVICE_ISA | DEVICE_AT,
.local = 0x10 | 7,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t p6rp4_nvr_device = {
.name = "ASUS P/I-P6RP4 PC/AT NVRAM",
.internal_name = "p6rp4_nvr",
.flags = DEVICE_ISA | DEVICE_AT,
.local = 32,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t amstrad_megapc_nvr_device = {
.name = "Amstrad MegaPC NVRAM",
.internal_name = "amstrad_megapc_nvr",
.flags = DEVICE_ISA | DEVICE_AT,
.local = 36,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t elt_nvr_device = {
.name = "Epson Equity LT NVRAM",
.internal_name = "elt_nvr",
.flags = DEVICE_ISA,
.local = 8,
.init = nvr_at_init,
.close = nvr_at_close,
.reset = nvr_at_reset,
{ .available = NULL },
.speed_changed = nvr_at_speed_changed,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/nvr_at.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 13,770 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of Port 92 used by PS/2 machines and 386+
* clones.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <86box/86box.h>
#include <86box/device.h>
#include "cpu.h"
#include <86box/timer.h>
#include <86box/io.h>
#include <86box/keyboard.h>
#include <86box/mem.h>
#include <86box/pit.h>
#include <86box/port_92.h>
#include <86box/plat_unused.h>
#define PORT_92_INV 1
#define PORT_92_WORD 2
#define PORT_92_PCI 4
#define PORT_92_RESET 8
#define PORT_92_A20 16
#define PORT_92_KEY 32
static uint8_t
port_92_readb(uint16_t port, void *priv)
{
uint8_t ret = 0x00;
const port_92_t *dev = (port_92_t *) priv;
if (port == 0x92) {
/* Return bit 1 directly from mem_a20_alt, so the
pin can be reset independently of the device. */
if (dev->flags & PORT_92_KEY)
ret = (dev->reg & ~0x03) | (mem_a20_key & 2) | (cpu_alt_reset & 1);
else
ret = (dev->reg & ~0x03) | (mem_a20_alt & 2) | (cpu_alt_reset & 1);
if (dev->flags & PORT_92_INV)
ret |= 0xfc;
else if (dev->flags & PORT_92_PCI)
ret |= 0x24; /* Intel SIO datasheet says bits 2 and 5 are always 1. */
} else if (dev->flags & PORT_92_INV)
ret = 0xff;
return ret;
}
static uint16_t
port_92_readw(uint16_t port, void *priv)
{
uint16_t ret = 0xffff;
const port_92_t *dev = (port_92_t *) priv;
if (!(dev->flags & PORT_92_PCI))
ret = port_92_readb(port, priv);
return ret;
}
/*
This does the exact same thing as keyboard controller reset.
TODO: ALi M1543(c) behavior.
*/
static void
port_92_pulse(UNUSED(void *priv))
{
softresetx86(); /* Pulse reset! */
cpu_set_edx();
flushmmucache();
cpu_alt_reset = 1;
}
static void
port_92_writeb(uint16_t port, uint8_t val, void *priv)
{
port_92_t *dev = (port_92_t *) priv;
if (port != 0x92)
return;
dev->reg = val & 0x03;
if (dev->flags & PORT_92_KEY) {
mem_a20_key = val & 2;
mem_a20_recalc();
} else if ((mem_a20_alt ^ val) & 2) {
mem_a20_alt = (mem_a20_alt & 0xfd) | (val & 2);
mem_a20_recalc();
}
if ((~cpu_alt_reset & val) & 1)
timer_set_delay_u64(&dev->pulse_timer, dev->pulse_period);
else if (!(val & 1))
timer_disable(&dev->pulse_timer);
cpu_alt_reset = (val & 1);
if (dev->flags & PORT_92_INV)
dev->reg |= 0xfc;
}
static void
port_92_writew(uint16_t port, uint16_t val, void *priv)
{
const port_92_t *dev = (port_92_t *) priv;
if (!(dev->flags & PORT_92_PCI))
port_92_writeb(port, val & 0xff, priv);
}
void
port_92_set_period(void *priv, uint64_t pulse_period)
{
port_92_t *dev = (port_92_t *) priv;
dev->pulse_period = pulse_period;
}
void
port_92_set_features(void *priv, int reset, int a20)
{
port_92_t *dev = (port_92_t *) priv;
dev->flags &= ~(PORT_92_RESET | PORT_92_A20);
if (reset)
dev->flags |= PORT_92_RESET;
timer_disable(&dev->pulse_timer);
if (a20) {
dev->flags |= PORT_92_A20;
mem_a20_alt = (dev->reg & 2);
} else
mem_a20_alt = 0;
mem_a20_recalc();
}
void
port_92_add(void *priv)
{
port_92_t *dev = (port_92_t *) priv;
if (dev->flags & (PORT_92_WORD | PORT_92_PCI))
io_sethandler(0x0092, 2,
port_92_readb, port_92_readw, NULL, port_92_writeb, port_92_writew, NULL, dev);
else
io_sethandler(0x0092, 1,
port_92_readb, NULL, NULL, port_92_writeb, NULL, NULL, dev);
}
void
port_92_remove(void *priv)
{
port_92_t *dev = (port_92_t *) priv;
if (dev->flags & (PORT_92_WORD | PORT_92_PCI))
io_removehandler(0x0092, 2,
port_92_readb, port_92_readw, NULL, port_92_writeb, port_92_writew, NULL, dev);
else
io_removehandler(0x0092, 1,
port_92_readb, NULL, NULL, port_92_writeb, NULL, NULL, dev);
}
static void
port_92_reset(UNUSED(void *priv))
{
cpu_alt_reset = 0;
mem_a20_alt = 0x00;
mem_a20_recalc();
}
static void
port_92_close(void *priv)
{
port_92_t *dev = (port_92_t *) priv;
timer_disable(&dev->pulse_timer);
free(dev);
}
void *
port_92_init(const device_t *info)
{
port_92_t *dev = (port_92_t *) malloc(sizeof(port_92_t));
memset(dev, 0, sizeof(port_92_t));
dev->flags = info->local & 0xff;
timer_add(&dev->pulse_timer, port_92_pulse, dev, 0);
dev->reg = 0;
mem_a20_alt = 0;
mem_a20_recalc();
cpu_alt_reset = 0;
flushmmucache();
port_92_add(dev);
dev->pulse_period = (uint64_t) (4.0 * SYSCLK * (double) (1ULL << 32ULL));
dev->flags |= (PORT_92_RESET | PORT_92_A20);
return dev;
}
const device_t port_92_device = {
.name = "Port 92 Register",
.internal_name = "port_92",
.flags = 0,
.local = 0,
.init = port_92_init,
.close = port_92_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t port_92_key_device = {
.name = "Port 92 Register (using A20 key)",
.internal_name = "port_92_key",
.flags = 0,
.local = PORT_92_KEY,
.init = port_92_init,
.close = port_92_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t port_92_inv_device = {
.name = "Port 92 Register (inverted bits 2-7)",
.internal_name = "port_92_inv",
.flags = 0,
.local = PORT_92_INV,
.init = port_92_init,
.close = port_92_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t port_92_word_device = {
.name = "Port 92 Register (16-bit)",
.internal_name = "port_92_word",
.flags = 0,
.local = PORT_92_WORD,
.init = port_92_init,
.close = port_92_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t port_92_pci_device = {
.name = "Port 92 Register (PCI)",
.internal_name = "port_92_pci",
.flags = 0,
.local = PORT_92_PCI,
.init = port_92_init,
.close = port_92_close,
.reset = port_92_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/port_92.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,217 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the Intel 8253/8254 Programmable Interval
* Timer.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <inttypes.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include "cpu.h"
#include <86box/device.h>
#include <86box/timer.h>
#include <86box/cassette.h>
#include <86box/dma.h>
#include <86box/io.h>
#include <86box/nmi.h>
#include <86box/pic.h>
#include <86box/timer.h>
#include <86box/pit.h>
#include <86box/pit_fast.h>
#include <86box/ppi.h>
#include <86box/machine.h>
#include <86box/sound.h>
#include <86box/snd_speaker.h>
#include <86box/video.h>
#define PIT_PS2 16 /* The PIT is the PS/2's second PIT. */
#define PIT_EXT_IO 32 /* The PIT has externally specified port I/O. */
#define PIT_CUSTOM_CLOCK 64 /* The PIT uses custom clock inputs provided by another provider. */
#define PIT_SECONDARY 128 /* The PIT is secondary (ports 0048-004B). */
#ifdef ENABLE_PIT_FAST_LOG
int pit_fast_do_log = ENABLE_PIT_FAST_LOG;
static void
pit_fast_log(const char *fmt, ...)
{
va_list ap;
if (pit_fast_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define pit_fast_log(fmt, ...)
#endif
static void
pitf_ctr_set_out(ctrf_t *ctr, int out, void *priv)
{
pitf_t *pit = (pitf_t *)priv;
if (ctr == NULL)
return;
if (ctr->out_func != NULL)
ctr->out_func(out, ctr->out, pit);
ctr->out = out;
}
static void
pitf_ctr_set_load_func(void *data, int counter_id, void (*func)(uint8_t new_m, int new_count))
{
if (data == NULL)
return;
pitf_t *pit = (pitf_t *) data;
ctrf_t *ctr = &pit->counters[counter_id];
ctr->load_func = func;
}
static uint16_t
pitf_ctr_get_count(void *data, int counter_id)
{
const pitf_t *pit = (pitf_t *) data;
const ctrf_t *ctr = &pit->counters[counter_id];
return (uint16_t) ctr->l;
}
void
pitf_ctr_set_out_func(void *data, int counter_id, void (*func)(int new_out, int old_out, void *priv))
{
if (data == NULL)
return;
pitf_t *pit = (pitf_t *) data;
ctrf_t *ctr = &pit->counters[counter_id];
ctr->out_func = func;
}
void
pitf_ctr_set_using_timer(void *data, int counter_id, int using_timer)
{
if (tsc > 0)
timer_process();
pitf_t *pit = (pitf_t *) data;
ctrf_t *ctr = &pit->counters[counter_id];
ctr->using_timer = using_timer;
}
static int
pitf_read_timer(ctrf_t *ctr)
{
if (ctr->using_timer && !(ctr->m == 3 && !ctr->gate) && timer_is_enabled(&ctr->timer)) {
int read = (int) ((timer_get_remaining_u64(&ctr->timer)) / ctr->pit_const);
if (ctr->m == 2)
read++;
if (read < 0)
read = 0;
if (read > 0x10000)
read = 0x10000;
if ((ctr->m == 3) && ctr->using_timer)
read <<= 1;
return read;
}
if (ctr->m == 2)
return ctr->count + 1;
return ctr->count;
}
/*Dump timer count back to pit->count[], and disable timer. This should be used
when stopping a PIT timer, to ensure the correct value can be read back.*/
static void
pitf_dump_and_disable_timer(ctrf_t *ctr)
{
if (ctr->using_timer && timer_is_enabled(&ctr->timer)) {
ctr->count = pitf_read_timer(ctr);
if (ctr->m == 2)
ctr->count--; /* Don't store the offset from pitf_read_timer */
timer_disable(&ctr->timer);
}
}
static void
pitf_ctr_load(ctrf_t *ctr, void *priv)
{
pitf_t *pit = (pitf_t *)priv;
int l = ctr->l ? ctr->l : 0x10000;
ctr->newcount = 0;
ctr->disabled = 0;
switch (ctr->m) {
case 0: /*Interrupt on terminal count*/
ctr->count = l;
if (ctr->using_timer)
timer_set_delay_u64(&ctr->timer, (uint64_t) (l * ctr->pit_const));
pitf_ctr_set_out(ctr, 0, pit);
ctr->thit = 0;
ctr->enabled = ctr->gate;
break;
case 1: /*Hardware retriggerable one-shot*/
ctr->enabled = 1;
break;
case 2: /*Rate generator*/
if (ctr->initial) {
ctr->count = l - 1;
if (ctr->using_timer)
timer_set_delay_u64(&ctr->timer, (uint64_t) ((l - 1) * ctr->pit_const));
pitf_ctr_set_out(ctr, 1, pit);
ctr->thit = 0;
}
ctr->enabled = ctr->gate;
break;
case 3: /*Square wave mode*/
if (ctr->initial) {
ctr->count = l;
if (ctr->using_timer)
timer_set_delay_u64(&ctr->timer, (uint64_t) (((l + 1) >> 1) * ctr->pit_const));
else
ctr->newcount = (l & 1);
pitf_ctr_set_out(ctr, 1, pit);
ctr->thit = 0;
}
ctr->enabled = ctr->gate;
break;
case 4: /*Software triggered stobe*/
if (!ctr->thit && !ctr->initial)
ctr->newcount = 1;
else {
ctr->count = l;
if (ctr->using_timer)
timer_set_delay_u64(&ctr->timer, (uint64_t) (l * ctr->pit_const));
pitf_ctr_set_out(ctr, 0, pit);
ctr->thit = 0;
}
ctr->enabled = ctr->gate;
break;
case 5: /*Hardware triggered stobe*/
ctr->enabled = 1;
break;
default:
break;
}
if (ctr->load_func != NULL)
ctr->load_func(ctr->m, l);
ctr->initial = 0;
ctr->running = ctr->enabled && ctr->using_timer && !ctr->disabled;
if (ctr->using_timer && !ctr->running)
pitf_dump_and_disable_timer(ctr);
}
static void
pitf_set_gate_no_timer(ctrf_t *ctr, int gate, void *priv)
{
pitf_t *pit = (pitf_t *)priv;
int l = ctr->l ? ctr->l : 0x10000;
if (ctr->disabled) {
ctr->gate = gate;
return;
}
switch (ctr->m) {
case 0: /*Interrupt on terminal count*/
case 4: /*Software triggered stobe*/
if (ctr->using_timer && !ctr->running)
timer_set_delay_u64(&ctr->timer, (uint64_t) (l * ctr->pit_const));
ctr->enabled = gate;
break;
case 1: /*Hardware retriggerable one-shot*/
case 5: /*Hardware triggered stobe*/
if (gate && !ctr->gate) {
ctr->count = l;
if (ctr->using_timer)
timer_set_delay_u64(&ctr->timer, (uint64_t) (l * ctr->pit_const));
pitf_ctr_set_out(ctr, 0, pit);
ctr->thit = 0;
ctr->enabled = 1;
}
break;
case 2: /*Rate generator*/
if (gate && !ctr->gate) {
ctr->count = l - 1;
if (ctr->using_timer)
timer_set_delay_u64(&ctr->timer, (uint64_t) (l * ctr->pit_const));
pitf_ctr_set_out(ctr, 1, pit);
ctr->thit = 0;
}
ctr->enabled = gate;
break;
case 3: /*Square wave mode*/
if (gate && !ctr->gate) {
ctr->count = l;
if (ctr->using_timer)
timer_set_delay_u64(&ctr->timer, (uint64_t) (((l + 1) >> 1) * ctr->pit_const));
else
ctr->newcount = (l & 1);
pitf_ctr_set_out(ctr, 1, pit);
ctr->thit = 0;
}
ctr->enabled = gate;
break;
default:
break;
}
ctr->gate = gate;
ctr->running = ctr->enabled && ctr->using_timer && !ctr->disabled;
if (ctr->using_timer && !ctr->running)
pitf_dump_and_disable_timer(ctr);
}
void
pitf_ctr_set_gate(void *data, int counter_id, int gate)
{
pitf_t *pit = (pitf_t *) data;
ctrf_t *ctr = &pit->counters[counter_id];
if (ctr->disabled) {
ctr->gate = gate;
return;
}
pitf_set_gate_no_timer(ctr, gate, pit);
}
static void
pitf_over(ctrf_t *ctr, void *priv)
{
pitf_t *pit = (pitf_t *)priv;
int l = ctr->l ? ctr->l : 0x10000;
if (ctr->disabled) {
ctr->count += 0xffff;
if (ctr->using_timer)
timer_advance_u64(&ctr->timer, (uint64_t) (0xffff * ctr->pit_const));
return;
}
switch (ctr->m) {
case 0: /*Interrupt on terminal count*/
case 1: /*Hardware retriggerable one-shot*/
if (!ctr->thit)
pitf_ctr_set_out(ctr, 1, pit);
ctr->thit = 1;
ctr->count += 0xffff;
if (ctr->using_timer)
timer_advance_u64(&ctr->timer, (uint64_t) (0xffff * ctr->pit_const));
break;
case 2: /*Rate generator*/
ctr->count += l;
if (ctr->using_timer)
timer_advance_u64(&ctr->timer, (uint64_t) (l * ctr->pit_const));
pitf_ctr_set_out(ctr, 0, pit);
pitf_ctr_set_out(ctr, 1, pit);
break;
case 3: /*Square wave mode*/
if (ctr->out) {
pitf_ctr_set_out(ctr, 0, pit);
if (ctr->using_timer) {
ctr->count += (l >> 1);
timer_advance_u64(&ctr->timer, (uint64_t) ((l >> 1) * ctr->pit_const));
} else {
ctr->count += l;
ctr->newcount = (l & 1);
}
} else {
pitf_ctr_set_out(ctr, 1, pit);
ctr->count += ((l + 1) >> 1);
if (ctr->using_timer) {
ctr->count += (l >> 1);
timer_advance_u64(&ctr->timer, (uint64_t) (((l + 1) >> 1) * ctr->pit_const));
} else {
ctr->count += l;
ctr->newcount = (l & 1);
}
}
#if 0
if (!t)
pclog("pit_over: square wave mode c=%x %lli %f\n", pit.c[t], tsc, ctr->pit_const);
#endif
break;
case 4: /*Software triggered strove*/
if (!ctr->thit) {
pitf_ctr_set_out(ctr, 0, pit);
pitf_ctr_set_out(ctr, 1, pit);
}
if (ctr->newcount) {
ctr->newcount = 0;
ctr->count += l;
if (ctr->using_timer)
timer_advance_u64(&ctr->timer, (uint64_t) (l * ctr->pit_const));
} else {
ctr->thit = 1;
ctr->count += 0xffff;
if (ctr->using_timer)
timer_advance_u64(&ctr->timer, (uint64_t) (0xffff * ctr->pit_const));
}
break;
case 5: /*Hardware triggered strove*/
if (!ctr->thit) {
pitf_ctr_set_out(ctr, 0, pit);
pitf_ctr_set_out(ctr, 1, pit);
}
ctr->thit = 1;
ctr->count += 0xffff;
if (ctr->using_timer)
timer_advance_u64(&ctr->timer, (uint64_t) (0xffff * ctr->pit_const));
break;
default:
break;
}
ctr->running = ctr->enabled && ctr->using_timer && !ctr->disabled;
if (ctr->using_timer && !ctr->running)
pitf_dump_and_disable_timer(ctr);
}
static __inline void
pitf_ctr_latch_count(ctrf_t *ctr)
{
ctr->rl = pitf_read_timer(ctr);
#if 0
pclog("Timer latch %f %04X %04X\n",pit->c[0],pit->rl[0],pit->l[0]);
pit->ctrl |= 0x30;
#endif
ctr->rereadlatch = 0;
ctr->rm = 3;
ctr->latched = 1;
}
static __inline void
pitf_ctr_latch_status(ctrf_t *ctr)
{
ctr->read_status = (ctr->ctrl & 0x3f) | (ctr->out ? 0x80 : 0);
ctr->do_read_status = 1;
}
static void
pitf_write(uint16_t addr, uint8_t val, void *priv)
{
pitf_t *dev = (pitf_t *) priv;
int t = (addr & 3);
ctrf_t *ctr;
pit_fast_log("[%04X:%08X] pit_write(%04X, %02X, %08X)\n", CS, cpu_state.pc, addr, val, priv);
cycles -= ISA_CYCLES(8);
switch (addr & 3) {
case 3: /* control */
t = val >> 6;
if (t == 3) {
if (dev->flags & PIT_8254) {
/* This is 8254-only. */
if (!(val & 0x20)) {
if (val & 2)
pitf_ctr_latch_count(&dev->counters[0]);
if (val & 4)
pitf_ctr_latch_count(&dev->counters[1]);
if (val & 8)
pitf_ctr_latch_count(&dev->counters[2]);
pit_fast_log("PIT %i: Initiated readback command\n", t);
}
if (!(val & 0x10)) {
if (val & 2)
pitf_ctr_latch_status(&dev->counters[0]);
if (val & 4)
pitf_ctr_latch_status(&dev->counters[1]);
if (val & 8)
pitf_ctr_latch_status(&dev->counters[2]);
}
}
} else {
dev->ctrl = val;
ctr = &dev->counters[t];
if (!(dev->ctrl & 0x30)) {
pitf_ctr_latch_count(ctr);
dev->ctrl |= 0x30;
pit_fast_log("PIT %i: Initiated latched read, %i bytes latched\n",
t, ctr->latched);
} else {
ctr->ctrl = val;
ctr->rm = ctr->wm = (ctr->ctrl >> 4) & 3;
ctr->m = (val >> 1) & 7;
if (ctr->m > 5)
ctr->m &= 3;
if (!(ctr->rm)) {
ctr->rm = 3;
ctr->rl = pitf_read_timer(ctr);
}
ctr->rereadlatch = 1;
ctr->initial = 1;
if (!ctr->m)
pitf_ctr_set_out(ctr, 0, dev);
else
pitf_ctr_set_out(ctr, 1, dev);
ctr->disabled = 1;
pit_fast_log("PIT %i: M = %i, RM/WM = %i, Out = %i\n", t, ctr->m, ctr->rm, ctr->out);
}
ctr->thit = 0;
}
break;
case 0:
case 1:
case 2: /* the actual timers */
ctr = &dev->counters[t];
switch (ctr->wm) {
case 1:
ctr->l = val;
pitf_ctr_load(ctr, dev);
break;
case 2:
ctr->l = (val << 8);
pitf_ctr_load(ctr, dev);
break;
case 0:
ctr->l &= 0xFF;
ctr->l |= (val << 8);
pitf_ctr_load(ctr, dev);
ctr->wm = 3;
break;
case 3:
ctr->l &= 0xFF00;
ctr->l |= val;
ctr->wm = 0;
break;
default:
break;
}
break;
default:
break;
}
}
uint8_t
pitf_read_reg(void *priv, uint8_t reg)
{
pitf_t *dev = (pitf_t *) priv;
uint8_t ret = 0xff;
switch (reg) {
case 0x00:
case 0x02:
case 0x04:
ret = dev->counters[reg >> 1].l & 0xff;
break;
case 0x01:
case 0x03:
case 0x05:
ret = (dev->counters[reg >> 1].l >> 8) & 0xff;
break;
case 0x06:
ret = dev->ctrl;
break;
case 0x07:
/* The SiS 551x datasheet is unclear about how exactly
this register is structured.
Update: But the SiS 5571 datasheet is clear. */
ret = (dev->counters[0].rm & 0x80) ? 0x01 : 0x00;
ret |= (dev->counters[1].rm & 0x80) ? 0x02 : 0x00;
ret |= (dev->counters[2].rm & 0x80) ? 0x04 : 0x00;
ret |= (dev->counters[0].wm & 0x80) ? 0x08 : 0x00;
ret |= (dev->counters[1].wm & 0x80) ? 0x10 : 0x00;
ret |= (dev->counters[2].wm & 0x80) ? 0x20 : 0x00;
break;
}
return ret;
}
static uint8_t
pitf_read(uint16_t addr, void *priv)
{
pitf_t *dev = (pitf_t *) priv;
uint8_t ret = 0xff;
int t = (addr & 3);
ctrf_t *ctr;
cycles -= ISA_CYCLES(8);
switch (addr & 3) {
case 3: /* Control. */
/* This is 8254-only, 8253 returns 0x00. */
ret = (dev->flags & PIT_8254) ? dev->ctrl : 0x00;
break;
case 0:
case 1:
case 2: /* The actual timers. */
ctr = &dev->counters[t];
if (ctr->do_read_status) {
ctr->do_read_status = 0;
ret = ctr->read_status;
break;
}
if (ctr->rereadlatch && !ctr->latched) {
ctr->rereadlatch = 0;
ctr->rl = pitf_read_timer(ctr);
}
switch (ctr->rm) {
case 0:
ret = ctr->rl >> 8;
ctr->rm = 3;
ctr->latched = 0;
ctr->rereadlatch = 1;
break;
case 1:
ret = (ctr->rl) & 0xFF;
ctr->latched = 0;
ctr->rereadlatch = 1;
break;
case 2:
ret = (ctr->rl) >> 8;
ctr->latched = 0;
ctr->rereadlatch = 1;
break;
case 3:
ret = (ctr->rl) & 0xFF;
if (ctr->m & 0x80)
ctr->m &= 7;
else
ctr->rm = 0;
break;
default:
break;
}
break;
default:
break;
}
pit_fast_log("[%04X:%08X] pit_read(%04X, %08X) = %02X\n", CS, cpu_state.pc, addr, priv, ret);
return ret;
}
static void
pitf_timer_over(void *priv)
{
ctrf_t *ctr = (ctrf_t *) priv;
pit_t *pit = (pit_t *)ctr->priv;
pitf_over(ctr, pit);
}
void
pitf_ctr_clock(void *data, int counter_id)
{
pitf_t *pit = (pitf_t *) data;
ctrf_t *ctr = &pit->counters[counter_id];
if (ctr->thit || !ctr->enabled)
return;
if (ctr->using_timer)
return;
if ((ctr->m == 3) && ctr->newcount) {
ctr->count -= ctr->out ? 1 : 3;
ctr->newcount = 0;
} else
ctr->count -= (ctr->m == 3) ? 2 : 1;
if (!ctr->count)
pitf_over(ctr, pit);
}
static void
ctr_reset(ctrf_t *ctr)
{
ctr->ctrl = 0;
ctr->m = 0;
ctr->gate = 0;
ctr->l = 0xffff;
ctr->thit = 1;
ctr->using_timer = 1;
}
static void
pitf_reset(pitf_t *dev)
{
memset(dev, 0, sizeof(pitf_t));
for (uint8_t i = 0; i < NUM_COUNTERS; i++)
ctr_reset(&dev->counters[i]);
/* Disable speaker gate. */
dev->counters[2].gate = 0;
}
void
pitf_set_pit_const(void *data, uint64_t pit_const)
{
pitf_t *pit = (pitf_t *) data;
ctrf_t *ctr;
for (uint8_t i = 0; i < NUM_COUNTERS; i++) {
ctr = &pit->counters[i];
ctr->pit_const = pit_const;
}
}
static void
pitf_speed_changed(void *priv)
{
pitf_set_pit_const(priv, PITCONST);
}
static void
pitf_close(void *priv)
{
pitf_t *dev = (pitf_t *) priv;
if (dev == pit_devs[0].data)
pit_devs[0].data = NULL;
if (dev == pit_devs[1].data)
pit_devs[1].data = NULL;
if (dev != NULL)
free(dev);
}
void
pitf_handler(int set, uint16_t base, int size, void *priv)
{
io_handler(set, base, size, pitf_read, NULL, NULL, pitf_write, NULL, NULL, priv);
}
static void *
pitf_init(const device_t *info)
{
pitf_t *dev = (pitf_t *) malloc(sizeof(pitf_t));
pitf_reset(dev);
pitf_set_pit_const(dev, PITCONST);
dev->flags = info->local;
if (!(dev->flags & PIT_PS2) && !(dev->flags & PIT_CUSTOM_CLOCK)) {
for (int i = 0; i < NUM_COUNTERS; i++) {
ctrf_t *ctr = &dev->counters[i];
ctr->priv = dev;
timer_add(&ctr->timer, pitf_timer_over, (void *) ctr, 0);
}
}
if (!(dev->flags & PIT_EXT_IO)) {
io_sethandler((dev->flags & PIT_SECONDARY) ? 0x0048 : 0x0040, 0x0004,
pitf_read, NULL, NULL, pitf_write, NULL, NULL, dev);
}
return dev;
}
const device_t i8253_fast_device = {
.name = "Intel 8253/8253-5 Programmable Interval Timer",
.internal_name = "i8253_fast",
.flags = DEVICE_ISA | DEVICE_PIT,
.local = PIT_8253,
.init = pitf_init,
.close = pitf_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = pitf_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t i8254_fast_device = {
.name = "Intel 8254 Programmable Interval Timer",
.internal_name = "i8254_fast",
.flags = DEVICE_ISA | DEVICE_PIT,
.local = PIT_8254,
.init = pitf_init,
.close = pitf_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = pitf_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t i8254_sec_fast_device = {
.name = "Intel 8254 Programmable Interval Timer (Secondary)",
.internal_name = "i8254_sec_fast",
.flags = DEVICE_ISA,
.local = PIT_8254 | PIT_SECONDARY,
.init = pitf_init,
.close = pitf_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = pitf_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t i8254_ext_io_fast_device = {
.name = "Intel 8254 Programmable Interval Timer (External I/O)",
.internal_name = "i8254_ext_io_fast",
.flags = DEVICE_ISA,
.local = PIT_8254 | PIT_EXT_IO,
.init = pitf_init,
.close = pitf_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t i8254_ps2_fast_device = {
.name = "Intel 8254 Programmable Interval Timer (PS/2)",
.internal_name = "i8254_ps2_fast",
.flags = DEVICE_ISA,
.local = PIT_8254 | PIT_PS2 | PIT_EXT_IO,
.init = pitf_init,
.close = pitf_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = pitf_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const pit_intf_t pit_fast_intf = {
&pitf_read,
&pitf_write,
&pitf_ctr_get_count,
&pitf_ctr_set_gate,
&pitf_ctr_set_using_timer,
&pitf_ctr_set_out_func,
&pitf_ctr_set_load_func,
&pitf_ctr_clock,
&pitf_set_pit_const,
NULL,
};
``` | /content/code_sandbox/src/pit_fast.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 6,638 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the Intel DMA controllers.
*
*
*
* Authors: Sarah Walker, <path_to_url
* Miran Grca, <mgrca8@gmail.com>
* Fred N. van Kempen, <decwiz@yahoo.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include "cpu.h"
#include "x86.h"
#include <86box/machine.h>
#include <86box/mca.h>
#include <86box/mem.h>
#include <86box/io.h>
#include <86box/pic.h>
#include <86box/dma.h>
#include <86box/plat_unused.h>
dma_t dma[8];
uint8_t dma_e;
uint8_t dma_m;
static uint8_t dmaregs[3][16];
static int dma_wp[2];
static uint8_t dma_stat;
static uint8_t dma_stat_rq;
static uint8_t dma_stat_rq_pc;
static uint8_t dma_stat_adv_pend;
static uint8_t dma_command[2];
static uint8_t dma_req_is_soft;
static uint8_t dma_advanced;
static uint8_t dma_at;
static uint8_t dma_buffer[65536];
static uint16_t dma_sg_base;
static uint16_t dma16_buffer[65536];
static uint32_t dma_mask;
static struct dma_ps2_t {
int xfr_command;
int xfr_channel;
int byte_ptr;
int is_ps2;
} dma_ps2;
#define DMA_PS2_IOA (1 << 0)
#define DMA_PS2_AUTOINIT (1 << 1)
#define DMA_PS2_XFER_MEM_TO_IO (1 << 2)
#define DMA_PS2_XFER_IO_TO_MEM (3 << 2)
#define DMA_PS2_XFER_MASK (3 << 2)
#define DMA_PS2_DEC2 (1 << 4)
#define DMA_PS2_SIZE16 (1 << 6)
#ifdef ENABLE_DMA_LOG
int dma_do_log = ENABLE_DMA_LOG;
static void
dma_log(const char *fmt, ...)
{
va_list ap;
if (dma_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define dma_log(fmt, ...)
#endif
static void dma_ps2_run(int channel);
int
dma_get_drq(int channel)
{
return !!(dma_stat_rq_pc & (1 << channel));
}
void
dma_set_drq(int channel, int set)
{
dma_stat_rq_pc &= ~(1 << channel);
if (set)
dma_stat_rq_pc |= (1 << channel);
}
static int
dma_transfer_size(dma_t *dev)
{
return dev->transfer_mode & 0xff;
}
static void
dma_sg_next_addr(dma_t *dev)
{
int ts = dma_transfer_size(dev);
dma_bm_read(dev->ptr_cur, (uint8_t *) &(dev->addr), 4, ts);
dma_bm_read(dev->ptr_cur + 4, (uint8_t *) &(dev->count), 4, ts);
dma_log("DMA S/G DWORDs: %08X %08X\n", dev->addr, dev->count);
dev->eot = dev->count >> 31;
dev->count &= 0xfffe;
dev->cb = (uint16_t) dev->count;
dev->cc = dev->count;
if (!dev->count)
dev->count = 65536;
if (ts == 2)
dev->addr &= 0xfffffffe;
dev->ab = dev->addr & dma_mask;
dev->ac = dev->addr & dma_mask;
dev->page = dev->page_l = (dev->ac >> 16) & 0xff;
dev->page_h = (dev->ac >> 24) & 0xff;
dev->ptr_cur += 8;
}
static void
dma_block_transfer(int channel)
{
int bit16 = (channel >= 4);
if (dma_advanced)
bit16 = !!(dma_transfer_size(&(dma[channel])) == 2);
dma_req_is_soft = 1;
for (uint16_t i = 0; i <= dma[channel].cb; i++) {
if ((dma[channel].mode & 0x8c) == 0x84) {
if (bit16)
dma_channel_write(channel, dma16_buffer[i]);
else
dma_channel_write(channel, dma_buffer[i]);
} else if ((dma[channel].mode & 0x8c) == 0x88) {
if (bit16)
dma16_buffer[i] = dma_channel_read(channel);
else
dma_buffer[i] = dma_channel_read(channel);
}
}
dma_req_is_soft = 0;
}
static void
dma_mem_to_mem_transfer(void)
{
int i;
if ((dma[0].mode & 0x0c) != 0x08)
fatal("DMA memory to memory transfer: channel 0 mode not read\n");
if ((dma[1].mode & 0x0c) != 0x04)
fatal("DMA memory to memory transfer: channel 1 mode not write\n");
dma_req_is_soft = 1;
for (i = 0; i <= dma[0].cb; i++)
dma_buffer[i] = dma_channel_read(0);
for (i = 0; i <= dma[1].cb; i++)
dma_channel_write(1, dma_buffer[i]);
dma_req_is_soft = 0;
}
static void
dma_sg_write(uint16_t port, uint8_t val, void *priv)
{
dma_t *dev = (dma_t *) priv;
dma_log("DMA S/G BYTE write: %04X %02X\n", port, val);
port &= 0xff;
if (port < 0x20)
port &= 0xf8;
else
port &= 0xe3;
switch (port) {
case 0x00:
dma_log("DMA S/G Cmd : val = %02X, old = %02X\n", val, dev->sg_command);
if ((val & 1) && !(dev->sg_command & 1)) { /*Start*/
#ifdef ENABLE_DMA_LOG
dma_log("DMA S/G start\n");
#endif
dev->ptr_cur = dev->ptr;
dma_sg_next_addr(dev);
dev->sg_status = (dev->sg_status & 0xf7) | 0x01;
}
if (!(val & 1) && (dev->sg_command & 1)) { /*Stop*/
#ifdef ENABLE_DMA_LOG
dma_log("DMA S/G stop\n");
#endif
dev->sg_status &= ~0x81;
}
dev->sg_command = val;
break;
case 0x20:
dev->ptr = (dev->ptr & 0xffffff00) | (val & 0xfc);
dev->ptr %= (mem_size * 1024);
dev->ptr0 = val;
break;
case 0x21:
dev->ptr = (dev->ptr & 0xffff00fc) | (val << 8);
dev->ptr %= (mem_size * 1024);
break;
case 0x22:
dev->ptr = (dev->ptr & 0xff00fffc) | (val << 16);
dev->ptr %= (mem_size * 1024);
break;
case 0x23:
dev->ptr = (dev->ptr & 0x00fffffc) | (val << 24);
dev->ptr %= (mem_size * 1024);
break;
default:
break;
}
}
static void
dma_sg_writew(uint16_t port, uint16_t val, void *priv)
{
dma_t *dev = (dma_t *) priv;
dma_log("DMA S/G WORD write: %04X %04X\n", port, val);
port &= 0xff;
if (port < 0x20)
port &= 0xf8;
else
port &= 0xe3;
switch (port) {
case 0x00:
dma_sg_write(port, val & 0xff, priv);
break;
case 0x20:
dev->ptr = (dev->ptr & 0xffff0000) | (val & 0xfffc);
dev->ptr %= (mem_size * 1024);
dev->ptr0 = val & 0xff;
break;
case 0x22:
dev->ptr = (dev->ptr & 0x0000fffc) | (val << 16);
dev->ptr %= (mem_size * 1024);
break;
default:
break;
}
}
static void
dma_sg_writel(uint16_t port, uint32_t val, void *priv)
{
dma_t *dev = (dma_t *) priv;
dma_log("DMA S/G DWORD write: %04X %08X\n", port, val);
port &= 0xff;
if (port < 0x20)
port &= 0xf8;
else
port &= 0xe3;
switch (port) {
case 0x00:
dma_sg_write(port, val & 0xff, priv);
break;
case 0x20:
dev->ptr = (val & 0xfffffffc);
dev->ptr %= (mem_size * 1024);
dev->ptr0 = val & 0xff;
break;
default:
break;
}
}
static uint8_t
dma_sg_read(uint16_t port, void *priv)
{
const dma_t *dev = (dma_t *) priv;
uint8_t ret = 0xff;
port &= 0xff;
if (port < 0x20)
port &= 0xf8;
else
port &= 0xe3;
switch (port) {
case 0x08:
ret = (dev->sg_status & 0x01);
if (dev->eot)
ret |= 0x80;
if ((dev->sg_command & 0xc0) == 0x40)
ret |= 0x20;
if (dev->ab != 0x00000000)
ret |= 0x08;
if (dev->ac != 0x00000000)
ret |= 0x04;
break;
case 0x20:
ret = dev->ptr0;
break;
case 0x21:
ret = dev->ptr >> 8;
break;
case 0x22:
ret = dev->ptr >> 16;
break;
case 0x23:
ret = dev->ptr >> 24;
break;
default:
break;
}
dma_log("DMA S/G BYTE read : %04X %02X\n", port, ret);
return ret;
}
static uint16_t
dma_sg_readw(uint16_t port, void *priv)
{
const dma_t *dev = (dma_t *) priv;
uint16_t ret = 0xffff;
port &= 0xff;
if (port < 0x20)
port &= 0xf8;
else
port &= 0xe3;
switch (port) {
case 0x08:
ret = (uint16_t) dma_sg_read(port, priv);
break;
case 0x20:
ret = dev->ptr0 | (dev->ptr & 0xff00);
break;
case 0x22:
ret = dev->ptr >> 16;
break;
default:
break;
}
dma_log("DMA S/G WORD read : %04X %04X\n", port, ret);
return ret;
}
static uint32_t
dma_sg_readl(uint16_t port, void *priv)
{
const dma_t *dev = (dma_t *) priv;
uint32_t ret = 0xffffffff;
port &= 0xff;
if (port < 0x20)
port &= 0xf8;
else
port &= 0xe3;
switch (port) {
case 0x08:
ret = (uint32_t) dma_sg_read(port, priv);
break;
case 0x20:
ret = dev->ptr0 | (dev->ptr & 0xffffff00);
break;
default:
break;
}
dma_log("DMA S/G DWORD read : %04X %08X\n", port, ret);
return ret;
}
static void
dma_ext_mode_write(uint16_t addr, uint8_t val, UNUSED(void *priv))
{
int channel = (val & 0x03);
if (addr == 0x4d6)
channel |= 4;
dma[channel].ext_mode = val & 0x7c;
switch ((val > 2) & 0x03) {
case 0x00:
dma[channel].transfer_mode = 0x0101;
break;
case 0x01:
dma[channel].transfer_mode = 0x0202;
break;
case 0x02: /* 0x02 is reserved. */
/* Logic says this should be an undocumented mode that counts by words,
but is 8-bit I/O, thus only transferring every second byte. */
dma[channel].transfer_mode = 0x0201;
break;
case 0x03:
dma[channel].transfer_mode = 0x0102;
break;
default:
break;
}
}
static uint8_t
dma_sg_int_status_read(UNUSED(uint16_t addr), UNUSED(void *priv))
{
uint8_t ret = 0x00;
for (uint8_t i = 0; i < 8; i++) {
if (i != 4)
ret = (!!(dma[i].sg_status & 8)) << i;
}
return ret;
}
static uint8_t
dma_read(uint16_t addr, UNUSED(void *priv))
{
int channel = (addr >> 1) & 3;
int count;
uint8_t ret = (dmaregs[0][addr & 0xf]);
switch (addr & 0xf) {
case 0:
case 2:
case 4:
case 6: /*Address registers*/
dma_wp[0] ^= 1;
if (dma_wp[0])
ret = (dma[channel].ac & 0xff);
else
ret = ((dma[channel].ac >> 8) & 0xff);
break;
case 1:
case 3:
case 5:
case 7: /*Count registers*/
dma_wp[0] ^= 1;
count = dma[channel].cc/* + 1*/;
if (dma_wp[0])
ret = count & 0xff;
else
ret = count >> 8;
break;
case 8: /*Status register*/
ret = dma_stat_rq_pc & 0xf;
ret <<= 4;
ret |= dma_stat & 0xf;
dma_stat &= ~0xf;
break;
case 0xd: /*Temporary register*/
ret = 0x00;
break;
default:
break;
}
dma_log("DMA: [R] %04X = %02X\n", addr, ret);
return ret;
}
static void
dma_write(uint16_t addr, uint8_t val, UNUSED(void *priv))
{
int channel = (addr >> 1) & 3;
dma_log("DMA: [W] %04X = %02X\n", addr, val);
dmaregs[0][addr & 0xf] = val;
switch (addr & 0xf) {
case 0:
case 2:
case 4:
case 6: /*Address registers*/
dma_wp[0] ^= 1;
if (dma_wp[0])
dma[channel].ab = (dma[channel].ab & 0xffffff00 & dma_mask) | val;
else
dma[channel].ab = (dma[channel].ab & 0xffff00ff & dma_mask) | (val << 8);
dma[channel].ac = dma[channel].ab;
return;
case 1:
case 3:
case 5:
case 7: /*Count registers*/
dma_wp[0] ^= 1;
if (dma_wp[0])
dma[channel].cb = (dma[channel].cb & 0xff00) | val;
else
dma[channel].cb = (dma[channel].cb & 0x00ff) | (val << 8);
dma[channel].cc = dma[channel].cb;
return;
case 8: /*Control register*/
dma_command[0] = val;
#ifdef ENABLE_DMA_LOG
if (val & 0x01)
dma_log("[%08X:%04X] Memory-to-memory enable\n", CS, cpu_state.pc);
#endif
return;
case 9: /*Request register */
channel = (val & 3);
if (val & 4) {
dma_stat_rq_pc |= (1 << channel);
if ((channel == 0) && (dma_command[0] & 0x01)) {
dma_log("Memory to memory transfer start\n");
dma_mem_to_mem_transfer();
} else
dma_block_transfer(channel);
} else
dma_stat_rq_pc &= ~(1 << channel);
break;
case 0xa: /*Mask*/
channel = (val & 3);
if (val & 4)
dma_m |= (1 << channel);
else
dma_m &= ~(1 << channel);
return;
case 0xb: /*Mode*/
channel = (val & 3);
dma[channel].mode = val;
if (dma_ps2.is_ps2) {
dma[channel].ps2_mode &= ~0x1c;
if (val & 0x20)
dma[channel].ps2_mode |= 0x10;
if ((val & 0xc) == 8)
dma[channel].ps2_mode |= 4;
else if ((val & 0xc) == 4)
dma[channel].ps2_mode |= 0xc;
}
return;
case 0xc: /*Clear FF*/
dma_wp[0] = 0;
return;
case 0xd: /*Master clear*/
dma_wp[0] = 0;
dma_m |= 0xf;
dma_stat_rq_pc &= ~0x0f;
return;
case 0xe: /*Clear mask*/
dma_m &= 0xf0;
return;
case 0xf: /*Mask write*/
dma_m = (dma_m & 0xf0) | (val & 0xf);
return;
default:
break;
}
}
static uint8_t
dma_ps2_read(uint16_t addr, UNUSED(void *priv))
{
const dma_t *dma_c = &dma[dma_ps2.xfr_channel];
uint8_t temp = 0xff;
switch (addr) {
case 0x1a:
switch (dma_ps2.xfr_command) {
case 2: /*Address*/
case 3:
switch (dma_ps2.byte_ptr) {
case 0:
temp = dma_c->ac & 0xff;
dma_ps2.byte_ptr = 1;
break;
case 1:
temp = (dma_c->ac >> 8) & 0xff;
dma_ps2.byte_ptr = 2;
break;
case 2:
temp = (dma_c->ac >> 16) & 0xff;
dma_ps2.byte_ptr = 0;
break;
default:
break;
}
break;
case 4: /*Count*/
case 5:
if (dma_ps2.byte_ptr)
temp = dma_c->cc >> 8;
else
temp = dma_c->cc & 0xff;
dma_ps2.byte_ptr = (dma_ps2.byte_ptr + 1) & 1;
break;
case 6: /*Read DMA status*/
if (dma_ps2.byte_ptr) {
temp = ((dma_stat_rq & 0xf0) >> 4) | (dma_stat & 0xf0);
dma_stat &= ~0xf0;
dma_stat_rq &= ~0xf0;
} else {
temp = (dma_stat_rq & 0xf) | ((dma_stat & 0xf) << 4);
dma_stat &= ~0xf;
dma_stat_rq &= ~0xf;
}
dma_ps2.byte_ptr = (dma_ps2.byte_ptr + 1) & 1;
break;
case 7: /*Mode*/
temp = dma_c->ps2_mode;
break;
case 8: /*Arbitration Level*/
temp = dma_c->arb_level;
break;
default:
fatal("Bad XFR Read command %i channel %i\n", dma_ps2.xfr_command, dma_ps2.xfr_channel);
}
break;
default:
break;
}
return temp;
}
static void
dma_ps2_write(uint16_t addr, uint8_t val, UNUSED(void *priv))
{
dma_t *dma_c = &dma[dma_ps2.xfr_channel];
uint8_t mode;
switch (addr) {
case 0x18:
dma_ps2.xfr_channel = val & 0x7;
dma_ps2.xfr_command = val >> 4;
dma_ps2.byte_ptr = 0;
switch (dma_ps2.xfr_command) {
case 9: /*Set DMA mask*/
dma_m |= (1 << dma_ps2.xfr_channel);
break;
case 0xa: /*Reset DMA mask*/
dma_m &= ~(1 << dma_ps2.xfr_channel);
break;
case 0xb:
if (!(dma_m & (1 << dma_ps2.xfr_channel)))
dma_ps2_run(dma_ps2.xfr_channel);
break;
default:
break;
}
break;
case 0x1a:
switch (dma_ps2.xfr_command) {
case 0: /*I/O address*/
if (dma_ps2.byte_ptr)
dma_c->io_addr = (dma_c->io_addr & 0x00ff) | (val << 8);
else
dma_c->io_addr = (dma_c->io_addr & 0xff00) | val;
dma_ps2.byte_ptr = (dma_ps2.byte_ptr + 1) & 1;
break;
case 2: /*Address*/
switch (dma_ps2.byte_ptr) {
case 0:
dma_c->ac = (dma_c->ac & 0xffff00) | val;
dma_ps2.byte_ptr = 1;
break;
case 1:
dma_c->ac = (dma_c->ac & 0xff00ff) | (val << 8);
dma_ps2.byte_ptr = 2;
break;
case 2:
dma_c->ac = (dma_c->ac & 0x00ffff) | (val << 16);
dma_ps2.byte_ptr = 0;
break;
default:
break;
}
dma_c->ab = dma_c->ac;
break;
case 4: /*Count*/
if (dma_ps2.byte_ptr)
dma_c->cc = (dma_c->cc & 0xff) | (val << 8);
else
dma_c->cc = (dma_c->cc & 0xff00) | val;
dma_ps2.byte_ptr = (dma_ps2.byte_ptr + 1) & 1;
dma_c->cb = dma_c->cc;
break;
case 7: /*Mode register*/
mode = 0;
if (val & DMA_PS2_DEC2)
mode |= 0x20;
if ((val & DMA_PS2_XFER_MASK) == DMA_PS2_XFER_MEM_TO_IO)
mode |= 8;
else if ((val & DMA_PS2_XFER_MASK) == DMA_PS2_XFER_IO_TO_MEM)
mode |= 4;
dma_c->mode = (dma_c->mode & ~0x2c) | mode;
if (val & DMA_PS2_AUTOINIT)
dma_c->mode |= 0x10;
dma_c->ps2_mode = val;
dma_c->size = val & DMA_PS2_SIZE16;
break;
case 8: /*Arbitration Level*/
dma_c->arb_level = val;
break;
default:
fatal("Bad XFR command %i channel %i val %02x\n", dma_ps2.xfr_command, dma_ps2.xfr_channel, val);
}
break;
default:
break;
}
}
static uint8_t
dma16_read(uint16_t addr, UNUSED(void *priv))
{
int channel = ((addr >> 2) & 3) + 4;
#ifdef ENABLE_DMA_LOG
uint16_t port = addr;
#endif
uint8_t ret;
int count;
addr >>= 1;
ret = dmaregs[1][addr & 0xf];
switch (addr & 0xf) {
case 0:
case 2:
case 4:
case 6: /*Address registers*/
dma_wp[1] ^= 1;
if (dma_ps2.is_ps2) {
if (dma_wp[1])
ret = (dma[channel].ac);
else
ret = ((dma[channel].ac >> 8) & 0xff);
} else if (dma_wp[1])
ret = ((dma[channel].ac >> 1) & 0xff);
else
ret = ((dma[channel].ac >> 9) & 0xff);
break;
case 1:
case 3:
case 5:
case 7: /*Count registers*/
dma_wp[1] ^= 1;
count = dma[channel].cc/* + 1*/;
// if (count > dma[channel].cb)
// count = 0x0000;
if (dma_wp[1])
ret = count & 0xff;
else
ret = count >> 8;
break;
case 8: /*Status register*/
ret = (dma_stat_rq_pc & 0xf0);
ret |= dma_stat >> 4;
dma_stat &= ~0xf0;
break;
default:
break;
}
dma_log("dma16_read(%08X) = %02X\n", port, ret);
return ret;
}
static void
dma16_write(uint16_t addr, uint8_t val, UNUSED(void *priv))
{
int channel = ((addr >> 2) & 3) + 4;
dma_log("dma16_write(%08X, %02X)\n", addr, val);
addr >>= 1;
dmaregs[1][addr & 0xf] = val;
switch (addr & 0xf) {
case 0:
case 2:
case 4:
case 6: /*Address registers*/
dma_wp[1] ^= 1;
if (dma_ps2.is_ps2) {
if (dma_wp[1])
dma[channel].ab = (dma[channel].ab & 0xffffff00 & dma_mask) | val;
else
dma[channel].ab = (dma[channel].ab & 0xffff00ff & dma_mask) | (val << 8);
} else {
if (dma_wp[1])
dma[channel].ab = (dma[channel].ab & 0xfffffe00 & dma_mask) | (val << 1);
else
dma[channel].ab = (dma[channel].ab & 0xfffe01ff & dma_mask) | (val << 9);
}
dma[channel].ac = dma[channel].ab;
return;
case 1:
case 3:
case 5:
case 7: /*Count registers*/
dma_wp[1] ^= 1;
if (dma_wp[1])
dma[channel].cb = (dma[channel].cb & 0xff00) | val;
else
dma[channel].cb = (dma[channel].cb & 0x00ff) | (val << 8);
dma[channel].cc = dma[channel].cb;
return;
case 8: /*Control register*/
return;
case 9: /*Request register */
channel = (val & 3) + 4;
if (val & 4) {
dma_stat_rq_pc |= (1 << channel);
dma_block_transfer(channel);
} else
dma_stat_rq_pc &= ~(1 << channel);
break;
case 0xa: /*Mask*/
channel = (val & 3);
if (val & 4)
dma_m |= (0x10 << channel);
else
dma_m &= ~(0x10 << channel);
return;
case 0xb: /*Mode*/
channel = (val & 3) + 4;
dma[channel].mode = val;
if (dma_ps2.is_ps2) {
dma[channel].ps2_mode &= ~0x1c;
if (val & 0x20)
dma[channel].ps2_mode |= 0x10;
if ((val & 0xc) == 8)
dma[channel].ps2_mode |= 4;
else if ((val & 0xc) == 4)
dma[channel].ps2_mode |= 0xc;
}
return;
case 0xc: /*Clear FF*/
dma_wp[1] = 0;
return;
case 0xd: /*Master clear*/
dma_wp[1] = 0;
dma_m |= 0xf0;
dma_stat_rq_pc &= ~0xf0;
return;
case 0xe: /*Clear mask*/
dma_m &= 0x0f;
return;
case 0xf: /*Mask write*/
dma_m = (dma_m & 0x0f) | ((val & 0xf) << 4);
return;
default:
break;
}
}
#define CHANNELS \
{ \
8, 2, 3, 1, 8, 8, 8, 0 \
}
static void
dma_page_write(uint16_t addr, uint8_t val, UNUSED(void *priv))
{
uint8_t convert[8] = CHANNELS;
dma_log("DMA: [W] %04X = %02X\n", addr, val);
#ifdef USE_DYNAREC
if ((addr == 0x84) && cpu_use_dynarec)
update_tsc();
#endif
addr &= 0x0f;
dmaregs[2][addr] = val;
if (addr >= 8)
addr = convert[addr & 0x07] | 4;
else
addr = convert[addr & 0x07];
if (addr < 8) {
dma[addr].page_l = val;
if (addr > 4) {
dma[addr].page = val & 0xfe;
dma[addr].ab = (dma[addr].ab & 0xff01ffff & dma_mask) | (dma[addr].page << 16);
dma[addr].ac = (dma[addr].ac & 0xff01ffff & dma_mask) | (dma[addr].page << 16);
} else {
dma[addr].page = dma_at ? val : val & 0xf;
dma[addr].ab = (dma[addr].ab & 0xff00ffff & dma_mask) | (dma[addr].page << 16);
dma[addr].ac = (dma[addr].ac & 0xff00ffff & dma_mask) | (dma[addr].page << 16);
}
}
}
static uint8_t
dma_page_read(uint16_t addr, UNUSED(void *priv))
{
uint8_t convert[8] = CHANNELS;
uint8_t ret = 0xff;
if (((addr & 0xfffc) == 0x80) && (CS == 0xf000) &&
((cpu_state.pc & 0xfffffff8) == 0x00007278) &&
!strcmp(machine_get_internal_name(), "megapc")) switch (addr) {
/* The Amstrad MegaPC Quadtel BIOS times a sequence of:
mov ax,di
div bx
And expects this value to be at least 0x06e0 for 20 MHz,
and at least 0x0898 for 25 MHz, everything below 0x06e0
is assumed to be 16 MHz. Given that for some reason, this
does not occur on 86Box, we have to work around it here,
we return 0x0580 for 16 MHz, because it logically follows
in the sequence (0x06e0 = 0x0898 * (20 / 25), and
0x0580 = 0x06e0 * (16 / 20)). */
case 0x0081:
if (cpu_busspeed >= 25000000)
ret = 0x98;
else if (cpu_busspeed >= 20000000)
ret = 0xe0;
else
ret = 0x80;
break;
case 0x0082:
if (cpu_busspeed >= 25000000)
ret = 0x08;
else if (cpu_busspeed >= 20000000)
ret = 0x06;
else
ret = 0x05;
break;
} else {
addr &= 0x0f;
ret = dmaregs[2][addr];
if (addr >= 8)
addr = convert[addr & 0x07] | 4;
else
addr = convert[addr & 0x07];
if (addr < 8)
ret = dma[addr].page_l;
}
dma_log("DMA: [R] %04X = %02X\n", addr, ret);
return ret;
}
static void
dma_high_page_write(uint16_t addr, uint8_t val, UNUSED(void *priv))
{
uint8_t convert[8] = CHANNELS;
addr &= 0x0f;
if (addr >= 8)
addr = convert[addr & 0x07] | 4;
else
addr = convert[addr & 0x07];
if (addr < 8) {
dma[addr].page_h = val;
dma[addr].ab = ((dma[addr].ab & 0xffffff) | (dma[addr].page << 24)) & dma_mask;
dma[addr].ac = ((dma[addr].ac & 0xffffff) | (dma[addr].page << 24)) & dma_mask;
}
}
static uint8_t
dma_high_page_read(uint16_t addr, UNUSED(void *priv))
{
uint8_t convert[8] = CHANNELS;
uint8_t ret = 0xff;
addr &= 0x0f;
if (addr >= 8)
addr = convert[addr & 0x07] | 4;
else
addr = convert[addr & 0x07];
if (addr < 8)
ret = dma[addr].page_h;
return ret;
}
void
dma_set_params(uint8_t advanced, uint32_t mask)
{
dma_advanced = advanced;
dma_mask = mask;
}
void
dma_set_mask(uint32_t mask)
{
dma_mask = mask;
for (uint8_t i = 0; i < 8; i++) {
dma[i].ab &= mask;
dma[i].ac &= mask;
}
}
void
dma_set_at(uint8_t at)
{
dma_at = at;
}
void
dma_reset(void)
{
int c;
dma_wp[0] = dma_wp[1] = 0;
dma_m = 0;
dma_e = 0xff;
for (c = 0; c < 16; c++)
dmaregs[0][c] = dmaregs[1][c] = 0;
for (c = 0; c < 8; c++) {
memset(&(dma[c]), 0x00, sizeof(dma_t));
dma[c].size = (c & 4) ? 1 : 0;
dma[c].transfer_mode = (c & 4) ? 0x0202 : 0x0101;
}
dma_stat = 0x00;
dma_stat_rq = 0x00;
dma_stat_rq_pc = 0x00;
dma_stat_adv_pend = 0x00;
dma_req_is_soft = 0;
dma_advanced = 0;
memset(dma_buffer, 0x00, sizeof(dma_buffer));
memset(dma16_buffer, 0x00, sizeof(dma16_buffer));
dma_remove_sg();
dma_sg_base = 0x0400;
dma_mask = 0x00ffffff;
dma_at = is286;
}
void
dma_remove_sg(void)
{
io_removehandler(dma_sg_base + 0x0a, 0x01,
dma_sg_int_status_read, NULL, NULL,
NULL, NULL, NULL,
NULL);
for (uint8_t i = 0; i < 8; i++) {
io_removehandler(dma_sg_base + 0x10 + i, 0x01,
dma_sg_read, dma_sg_readw, dma_sg_readl,
dma_sg_write, dma_sg_writew, dma_sg_writel,
&dma[i]);
io_removehandler(dma_sg_base + 0x18 + i, 0x01,
dma_sg_read, dma_sg_readw, dma_sg_readl,
dma_sg_write, dma_sg_writew, dma_sg_writel,
&dma[i]);
io_removehandler(dma_sg_base + 0x20 + i, 0x04,
dma_sg_read, dma_sg_readw, dma_sg_readl,
dma_sg_write, dma_sg_writew, dma_sg_writel,
&dma[i]);
}
}
void
dma_set_sg_base(uint8_t sg_base)
{
dma_sg_base = sg_base << 8;
io_sethandler(dma_sg_base + 0x0a, 0x01,
dma_sg_int_status_read, NULL, NULL,
NULL, NULL, NULL,
NULL);
for (uint8_t i = 0; i < 8; i++) {
io_sethandler(dma_sg_base + 0x10 + i, 0x01,
dma_sg_read, dma_sg_readw, dma_sg_readl,
dma_sg_write, dma_sg_writew, dma_sg_writel,
&dma[i]);
io_sethandler(dma_sg_base + 0x18 + i, 0x01,
dma_sg_read, dma_sg_readw, dma_sg_readl,
dma_sg_write, dma_sg_writew, dma_sg_writel,
&dma[i]);
io_sethandler(dma_sg_base + 0x20 + i, 0x04,
dma_sg_read, dma_sg_readw, dma_sg_readl,
dma_sg_write, dma_sg_writew, dma_sg_writel,
&dma[i]);
}
}
void
dma_ext_mode_init(void)
{
io_sethandler(0x040b, 0x01,
NULL, NULL, NULL, dma_ext_mode_write, NULL, NULL, NULL);
io_sethandler(0x04d6, 0x01,
NULL, NULL, NULL, dma_ext_mode_write, NULL, NULL, NULL);
}
void
dma_high_page_init(void)
{
io_sethandler(0x0480, 8,
dma_high_page_read, NULL, NULL, dma_high_page_write, NULL, NULL, NULL);
}
void
dma_init(void)
{
dma_reset();
io_sethandler(0x0000, 16,
dma_read, NULL, NULL, dma_write, NULL, NULL, NULL);
io_sethandler(0x0080, 8,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
dma_ps2.is_ps2 = 0;
}
void
dma16_init(void)
{
dma_reset();
io_sethandler(0x00C0, 32,
dma16_read, NULL, NULL, dma16_write, NULL, NULL, NULL);
io_sethandler(0x0088, 8,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
}
void
dma_alias_set(void)
{
io_sethandler(0x0090, 2,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
io_sethandler(0x0093, 13,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
}
void
dma_alias_set_piix(void)
{
io_sethandler(0x0090, 1,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
io_sethandler(0x0094, 3,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
io_sethandler(0x0098, 1,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
io_sethandler(0x009C, 3,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
}
void
dma_alias_remove(void)
{
io_removehandler(0x0090, 2,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
io_removehandler(0x0093, 13,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
}
void
dma_alias_remove_piix(void)
{
io_removehandler(0x0090, 1,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
io_removehandler(0x0094, 3,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
io_removehandler(0x0098, 1,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
io_removehandler(0x009C, 3,
dma_page_read, NULL, NULL, dma_page_write, NULL, NULL, NULL);
}
void
ps2_dma_init(void)
{
dma_reset();
io_sethandler(0x0018, 1,
dma_ps2_read, NULL, NULL, dma_ps2_write, NULL, NULL, NULL);
io_sethandler(0x001a, 1,
dma_ps2_read, NULL, NULL, dma_ps2_write, NULL, NULL, NULL);
dma_ps2.is_ps2 = 1;
}
extern void dma_bm_read(uint32_t PhysAddress, uint8_t *DataRead, uint32_t TotalSize, int TransferSize);
extern void dma_bm_write(uint32_t PhysAddress, const uint8_t *DataWrite, uint32_t TotalSize, int TransferSize);
static int
dma_sg(uint8_t *data, int transfer_length, int out, void *priv)
{
dma_t *dev = (dma_t *) priv;
#ifdef ENABLE_DMA_LOG
char *sop;
#endif
int force_end = 0;
int buffer_pos = 0;
#ifdef ENABLE_DMA_LOG
sop = out ? "Read" : "Writ";
#endif
if (!(dev->sg_status & 1))
return 2; /*S/G disabled*/
dma_log("DMA S/G %s: %i bytes\n", out ? "write" : "read", transfer_length);
while (1) {
if (dev->count <= transfer_length) {
dma_log("%sing %i bytes to %08X\n", sop, dev->count, dev->addr);
if (out)
dma_bm_read(dev->addr, (uint8_t *) (data + buffer_pos), dev->count, 4);
else
dma_bm_write(dev->addr, (uint8_t *) (data + buffer_pos), dev->count, 4);
transfer_length -= dev->count;
buffer_pos += dev->count;
} else {
dma_log("%sing %i bytes to %08X\n", sop, transfer_length, dev->addr);
if (out)
dma_bm_read(dev->addr, (uint8_t *) (data + buffer_pos), transfer_length, 4);
else
dma_bm_write(dev->addr, (uint8_t *) (data + buffer_pos), transfer_length, 4);
/* Increase addr and decrease count so that resumed transfers do not mess up. */
dev->addr += transfer_length;
dev->count -= transfer_length;
transfer_length = 0;
force_end = 1;
}
if (force_end) {
dma_log("Total transfer length smaller than sum of all blocks, partial block\n");
return 1; /* This block has exhausted the data to transfer and it was smaller than the count, break. */
} else {
if (!transfer_length && !dev->eot) {
dma_log("Total transfer length smaller than sum of all blocks, full block\n");
return 1; /* We have exhausted the data to transfer but there's more blocks left, break. */
} else if (transfer_length && dev->eot) {
dma_log("Total transfer length greater than sum of all blocks\n");
return 4; /* There is data left to transfer but we have reached EOT - return with error. */
} else if (dev->eot) {
dma_log("Regular EOT\n");
return 5; /* We have regularly reached EOT - clear status and break. */
} else {
/* We have more to transfer and there are blocks left, get next block. */
dma_sg_next_addr(dev);
}
}
}
}
uint8_t
_dma_read(uint32_t addr, dma_t *dma_c)
{
uint8_t temp = 0;
if (dma_advanced) {
if (dma_c->sg_status & 1)
dma_c->sg_status = (dma_c->sg_status & 0x0f) | (dma_sg(&temp, 1, 1, dma_c) << 4);
else
dma_bm_read(addr, &temp, 1, dma_transfer_size(dma_c));
} else
temp = mem_readb_phys(addr);
return temp;
}
static uint16_t
_dma_readw(uint32_t addr, dma_t *dma_c)
{
uint16_t temp = 0;
if (dma_advanced) {
if (dma_c->sg_status & 1)
dma_c->sg_status = (dma_c->sg_status & 0x0f) | (dma_sg((uint8_t *) &temp, 2, 1, dma_c) << 4);
else
dma_bm_read(addr, (uint8_t *) &temp, 2, dma_transfer_size(dma_c));
} else
temp = _dma_read(addr, dma_c) | (_dma_read(addr + 1, dma_c) << 8);
return temp;
}
static void
_dma_write(uint32_t addr, uint8_t val, dma_t *dma_c)
{
if (dma_advanced) {
if (dma_c->sg_status & 1)
dma_c->sg_status = (dma_c->sg_status & 0x0f) | (dma_sg(&val, 1, 0, dma_c) << 4);
else
dma_bm_write(addr, &val, 1, dma_transfer_size(dma_c));
} else {
mem_writeb_phys(addr, val);
if (dma_at)
mem_invalidate_range(addr, addr);
}
}
static void
_dma_writew(uint32_t addr, uint16_t val, dma_t *dma_c)
{
if (dma_advanced) {
if (dma_c->sg_status & 1)
dma_c->sg_status = (dma_c->sg_status & 0x0f) | (dma_sg((uint8_t *) &val, 2, 0, dma_c) << 4);
else
dma_bm_write(addr, (uint8_t *) &val, 2, dma_transfer_size(dma_c));
} else {
_dma_write(addr, val & 0xff, dma_c);
_dma_write(addr + 1, val >> 8, dma_c);
}
}
static void
dma_retreat(dma_t *dma_c)
{
int as = dma_c->transfer_mode >> 8;
if (dma->sg_status & 1) {
dma_c->ac = (dma_c->ac - as) & dma_mask;
dma_c->page = dma_c->page_l = (dma_c->ac >> 16) & 0xff;
dma_c->page_h = (dma_c->ac >> 24) & 0xff;
} else if (as == 2)
dma_c->ac = ((dma_c->ac & 0xfffe0000) & dma_mask) | ((dma_c->ac - as) & 0x1ffff);
else
dma_c->ac = ((dma_c->ac & 0xffff0000) & dma_mask) | ((dma_c->ac - as) & 0xffff);
}
void
dma_advance(dma_t *dma_c)
{
int as = dma_c->transfer_mode >> 8;
if (dma->sg_status & 1) {
dma_c->ac = (dma_c->ac + as) & dma_mask;
dma_c->page = dma_c->page_l = (dma_c->ac >> 16) & 0xff;
dma_c->page_h = (dma_c->ac >> 24) & 0xff;
} else if (as == 2)
dma_c->ac = ((dma_c->ac & 0xfffe0000) & dma_mask) | ((dma_c->ac + as) & 0x1ffff);
else
dma_c->ac = ((dma_c->ac & 0xffff0000) & dma_mask) | ((dma_c->ac + as) & 0xffff);
}
int
dma_channel_readable(int channel)
{
dma_t *dma_c = &dma[channel];
int ret = 1;
if (channel < 4) {
if (dma_command[0] & 0x04)
ret = 0;
} else {
if (dma_command[1] & 0x04)
ret = 0;
}
if (!(dma_e & (1 << channel)))
ret = 0;
if ((dma_m & (1 << channel)) && !dma_req_is_soft)
ret = 0;
if ((dma_c->mode & 0xC) != 8)
ret = 0;
return ret;
}
int
dma_channel_read_only(int channel)
{
dma_t *dma_c = &dma[channel];
uint16_t temp;
if (channel < 4) {
if (dma_command[0] & 0x04)
return (DMA_NODATA);
} else {
if (dma_command[1] & 0x04)
return (DMA_NODATA);
}
if (!(dma_e & (1 << channel)))
return (DMA_NODATA);
if ((dma_m & (1 << channel)) && !dma_req_is_soft)
return (DMA_NODATA);
if ((dma_c->mode & 0xC) != 8)
return (DMA_NODATA);
dma_channel_advance(channel);
if (!dma_at && !channel)
refreshread();
if (!dma_c->size) {
temp = _dma_read(dma_c->ac, dma_c);
if (dma_c->mode & 0x20) {
if (dma_ps2.is_ps2)
dma_c->ac--;
else if (dma_advanced)
dma_retreat(dma_c);
else
dma_c->ac = (dma_c->ac & 0xffff0000 & dma_mask) | ((dma_c->ac - 1) & 0xffff);
} else {
if (dma_ps2.is_ps2)
dma_c->ac++;
else if (dma_advanced)
dma_advance(dma_c);
else
dma_c->ac = (dma_c->ac & 0xffff0000 & dma_mask) | ((dma_c->ac + 1) & 0xffff);
}
} else {
temp = _dma_readw(dma_c->ac, dma_c);
if (dma_c->mode & 0x20) {
if (dma_ps2.is_ps2)
dma_c->ac -= 2;
else if (dma_advanced)
dma_retreat(dma_c);
else
dma_c->ac = (dma_c->ac & 0xfffe0000 & dma_mask) | ((dma_c->ac - 2) & 0x1ffff);
} else {
if (dma_ps2.is_ps2)
dma_c->ac += 2;
else if (dma_advanced)
dma_advance(dma_c);
else
dma_c->ac = (dma_c->ac & 0xfffe0000 & dma_mask) | ((dma_c->ac + 2) & 0x1ffff);
}
}
dma_stat_rq |= (1 << channel);
dma_stat_adv_pend |= (1 << channel);
return temp;
}
int
dma_channel_advance(int channel)
{
dma_t *dma_c = &dma[channel];
int tc = 0;
if (dma_stat_adv_pend & (1 << channel)) {
dma_c->cc--;
if (dma_c->cc < 0) {
if (dma_advanced && (dma_c->sg_status & 1) && !(dma_c->sg_status & 6))
dma_sg_next_addr(dma_c);
else {
tc = 1;
if (dma_c->mode & 0x10) { /*Auto-init*/
dma_c->cc = dma_c->cb;
dma_c->ac = dma_c->ab;
} else
dma_m |= (1 << channel);
dma_stat |= (1 << channel);
}
}
if (tc) {
if (dma_advanced && (dma_c->sg_status & 1) && ((dma_c->sg_command & 0xc0) == 0x40)) {
picint(1 << 13);
dma_c->sg_status |= 8;
}
}
dma_stat_adv_pend &= ~(1 << channel);
}
return tc;
}
int
dma_channel_read(int channel)
{
dma_t *dma_c = &dma[channel];
uint16_t temp;
int tc = 0;
if (channel < 4) {
if (dma_command[0] & 0x04)
return (DMA_NODATA);
} else {
if (dma_command[1] & 0x04)
return (DMA_NODATA);
}
if (!(dma_e & (1 << channel)))
return (DMA_NODATA);
if ((dma_m & (1 << channel)) && !dma_req_is_soft)
return (DMA_NODATA);
if ((dma_c->mode & 0xC) != 8)
return (DMA_NODATA);
if (dma_stat_adv_pend & (1 << channel))
dma_channel_advance(channel);
if (!dma_at && !channel)
refreshread();
if (!dma_c->size) {
temp = _dma_read(dma_c->ac, dma_c);
if (dma_c->mode & 0x20) {
if (dma_ps2.is_ps2)
dma_c->ac--;
else if (dma_advanced)
dma_retreat(dma_c);
else
dma_c->ac = (dma_c->ac & 0xffff0000 & dma_mask) | ((dma_c->ac - 1) & 0xffff);
} else {
if (dma_ps2.is_ps2)
dma_c->ac++;
else if (dma_advanced)
dma_advance(dma_c);
else
dma_c->ac = (dma_c->ac & 0xffff0000 & dma_mask) | ((dma_c->ac + 1) & 0xffff);
}
} else {
temp = _dma_readw(dma_c->ac, dma_c);
if (dma_c->mode & 0x20) {
if (dma_ps2.is_ps2)
dma_c->ac -= 2;
else if (dma_advanced)
dma_retreat(dma_c);
else
dma_c->ac = (dma_c->ac & 0xfffe0000 & dma_mask) | ((dma_c->ac - 2) & 0x1ffff);
} else {
if (dma_ps2.is_ps2)
dma_c->ac += 2;
else if (dma_advanced)
dma_advance(dma_c);
else
dma_c->ac = (dma_c->ac & 0xfffe0000 & dma_mask) | ((dma_c->ac + 2) & 0x1ffff);
}
}
dma_stat_rq |= (1 << channel);
dma_c->cc--;
if (dma_c->cc < 0) {
if (dma_advanced && (dma_c->sg_status & 1) && !(dma_c->sg_status & 6))
dma_sg_next_addr(dma_c);
else {
tc = 1;
if (dma_c->mode & 0x10) { /*Auto-init*/
dma_c->cc = dma_c->cb;
dma_c->ac = dma_c->ab;
} else
dma_m |= (1 << channel);
dma_stat |= (1 << channel);
}
}
if (tc) {
if (dma_advanced && (dma_c->sg_status & 1) && ((dma_c->sg_command & 0xc0) == 0x40)) {
picint(1 << 13);
dma_c->sg_status |= 8;
}
return (temp | DMA_OVER);
}
return temp;
}
int
dma_channel_write(int channel, uint16_t val)
{
dma_t *dma_c = &dma[channel];
if (channel < 4) {
if (dma_command[0] & 0x04)
return (DMA_NODATA);
} else {
if (dma_command[1] & 0x04)
return (DMA_NODATA);
}
if (!(dma_e & (1 << channel)))
return (DMA_NODATA);
if ((dma_m & (1 << channel)) && !dma_req_is_soft)
return (DMA_NODATA);
if ((dma_c->mode & 0xC) != 4)
return (DMA_NODATA);
if (!dma_c->size) {
_dma_write(dma_c->ac, val & 0xff, dma_c);
if (dma_c->mode & 0x20) {
if (dma_ps2.is_ps2)
dma_c->ac--;
else if (dma_advanced)
dma_retreat(dma_c);
else
dma_c->ac = (dma_c->ac & 0xffff0000 & dma_mask) | ((dma_c->ac - 1) & 0xffff);
} else {
if (dma_ps2.is_ps2)
dma_c->ac++;
else if (dma_advanced)
dma_advance(dma_c);
else
dma_c->ac = (dma_c->ac & 0xffff0000 & dma_mask) | ((dma_c->ac + 1) & 0xffff);
}
} else {
_dma_writew(dma_c->ac, val, dma_c);
if (dma_c->mode & 0x20) {
if (dma_ps2.is_ps2)
dma_c->ac -= 2;
else if (dma_advanced)
dma_retreat(dma_c);
else
dma_c->ac = (dma_c->ac & 0xfffe0000 & dma_mask) | ((dma_c->ac - 2) & 0x1ffff);
dma_c->ac = (dma_c->ac & 0xfffe0000 & dma_mask) | ((dma_c->ac - 2) & 0x1ffff);
} else {
if (dma_ps2.is_ps2)
dma_c->ac += 2;
else if (dma_advanced)
dma_advance(dma_c);
else
dma_c->ac = (dma_c->ac & 0xfffe0000 & dma_mask) | ((dma_c->ac + 2) & 0x1ffff);
}
}
dma_stat_rq |= (1 << channel);
dma_stat_adv_pend &= ~(1 << channel);
dma_c->cc--;
if (dma_c->cc < 0) {
if (dma_advanced && (dma_c->sg_status & 1) && !(dma_c->sg_status & 6))
dma_sg_next_addr(dma_c);
else {
if (dma_c->mode & 0x10) { /*Auto-init*/
dma_c->cc = dma_c->cb;
dma_c->ac = dma_c->ab;
} else
dma_m |= (1 << channel);
dma_stat |= (1 << channel);
}
}
if (dma_m & (1 << channel)) {
if (dma_advanced && (dma_c->sg_status & 1) && ((dma_c->sg_command & 0xc0) == 0x40)) {
picint(1 << 13);
dma_c->sg_status |= 8;
}
return DMA_OVER;
}
return 0;
}
static void
dma_ps2_run(int channel)
{
dma_t *dma_c = &dma[channel];
switch (dma_c->ps2_mode & DMA_PS2_XFER_MASK) {
case DMA_PS2_XFER_MEM_TO_IO:
do {
if (!dma_c->size) {
uint8_t temp = _dma_read(dma_c->ac, dma_c);
outb(dma_c->io_addr, temp);
if (dma_c->ps2_mode & DMA_PS2_DEC2)
dma_c->ac--;
else
dma_c->ac++;
} else {
uint16_t temp = _dma_readw(dma_c->ac, dma_c);
outw(dma_c->io_addr, temp);
if (dma_c->ps2_mode & DMA_PS2_DEC2)
dma_c->ac -= 2;
else
dma_c->ac += 2;
}
dma_stat_rq |= (1 << channel);
dma_c->cc--;
} while (dma_c->cc > 0);
dma_stat |= (1 << channel);
break;
case DMA_PS2_XFER_IO_TO_MEM:
do {
if (!dma_c->size) {
uint8_t temp = inb(dma_c->io_addr);
_dma_write(dma_c->ac, temp, dma_c);
if (dma_c->ps2_mode & DMA_PS2_DEC2)
dma_c->ac--;
else
dma_c->ac++;
} else {
uint16_t temp = inw(dma_c->io_addr);
_dma_writew(dma_c->ac, temp, dma_c);
if (dma_c->ps2_mode & DMA_PS2_DEC2)
dma_c->ac -= 2;
else
dma_c->ac += 2;
}
dma_stat_rq |= (1 << channel);
dma_c->cc--;
} while (dma_c->cc > 0);
ps2_cache_clean();
dma_stat |= (1 << channel);
break;
default: /*Memory verify*/
do {
if (!dma_c->size) {
if (dma_c->ps2_mode & DMA_PS2_DEC2)
dma_c->ac--;
else
dma_c->ac++;
} else {
if (dma_c->ps2_mode & DMA_PS2_DEC2)
dma_c->ac -= 2;
else
dma_c->ac += 2;
}
dma_stat_rq |= (1 << channel);
dma->cc--;
} while (dma->cc > 0);
dma_stat |= (1 << channel);
break;
}
}
int
dma_mode(int channel)
{
return (dma[channel].mode);
}
/* DMA Bus Master Page Read/Write */
void
dma_bm_read(uint32_t PhysAddress, uint8_t *DataRead, uint32_t TotalSize, int TransferSize)
{
uint32_t n;
uint32_t n2;
uint8_t bytes[4] = { 0, 0, 0, 0 };
n = TotalSize & ~(TransferSize - 1);
n2 = TotalSize - n;
/* Do the divisible block, if there is one. */
if (n) {
for (uint32_t i = 0; i < n; i += TransferSize)
mem_read_phys((void *) &(DataRead[i]), PhysAddress + i, TransferSize);
}
/* Do the non-divisible block, if there is one. */
if (n2) {
mem_read_phys((void *) bytes, PhysAddress + n, TransferSize);
memcpy((void *) &(DataRead[n]), bytes, n2);
}
}
void
dma_bm_write(uint32_t PhysAddress, const uint8_t *DataWrite, uint32_t TotalSize, int TransferSize)
{
uint32_t n;
uint32_t n2;
uint8_t bytes[4] = { 0, 0, 0, 0 };
n = TotalSize & ~(TransferSize - 1);
n2 = TotalSize - n;
/* Do the divisible block, if there is one. */
if (n) {
for (uint32_t i = 0; i < n; i += TransferSize)
mem_write_phys((void *) &(DataWrite[i]), PhysAddress + i, TransferSize);
}
/* Do the non-divisible block, if there is one. */
if (n2) {
mem_read_phys((void *) bytes, PhysAddress + n, TransferSize);
memcpy(bytes, (void *) &(DataWrite[n]), n2);
mem_write_phys((void *) bytes, PhysAddress + n, TransferSize);
}
if (dma_at)
mem_invalidate_range(PhysAddress, PhysAddress + TotalSize - 1);
}
``` | /content/code_sandbox/src/dma.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 15,016 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the Intel 8253/8254 Programmable Interval
* Timer.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <inttypes.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include "cpu.h"
#include <86box/device.h>
#include <86box/timer.h>
#include <86box/cassette.h>
#include <86box/dma.h>
#include <86box/io.h>
#include <86box/nmi.h>
#include <86box/pic.h>
#include <86box/timer.h>
#include <86box/pit.h>
#include <86box/pit_fast.h>
#include <86box/ppi.h>
#include <86box/machine.h>
#include <86box/sound.h>
#include <86box/snd_speaker.h>
#include <86box/video.h>
#include <86box/plat_unused.h>
pit_intf_t pit_devs[2];
double cpuclock;
double PITCONSTD;
double PAS16CONSTD;
double PAS16CONST2D;
double PASSCSICONSTD;
double SYSCLK;
double isa_timing;
double bus_timing;
double pci_timing;
double agp_timing;
double PCICLK;
double AGPCLK;
uint64_t PITCONST;
uint64_t PAS16CONST;
uint64_t PAS16CONST2;
uint64_t PASSCSICONST;
uint64_t ISACONST;
uint64_t CGACONST;
uint64_t MDACONST;
uint64_t HERCCONST;
uint64_t VGACONST1;
uint64_t VGACONST2;
uint64_t RTCCONST;
uint64_t ACPICONST;
int refresh_at_enable = 1;
int io_delay = 5;
int64_t firsttime = 1;
#define PIT_PS2 16 /* The PIT is the PS/2's second PIT. */
#define PIT_EXT_IO 32 /* The PIT has externally specified port I/O. */
#define PIT_CUSTOM_CLOCK 64 /* The PIT uses custom clock inputs provided by another provider. */
#define PIT_SECONDARY 128 /* The PIT is secondary (ports 0048-004B). */
#ifdef ENABLE_PIT_LOG
int pit_do_log = ENABLE_PIT_LOG;
static void
pit_log(const char *fmt, ...)
{
va_list ap;
if (pit_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define pit_log(fmt, ...)
#endif
static void
ctr_set_out(ctr_t *ctr, int out, void *priv)
{
pit_t *pit = (pit_t *)priv;
if (ctr == NULL)
return;
if (ctr->out_func != NULL)
ctr->out_func(out, ctr->out, pit);
ctr->out = out;
}
static void
ctr_decrease_count(ctr_t *ctr)
{
if (ctr->bcd) {
ctr->units--;
if (ctr->units == -1) {
ctr->units = -7;
ctr->tens--;
if (ctr->tens == -1) {
ctr->tens = -7;
ctr->hundreds--;
if (ctr->hundreds == -1) {
ctr->hundreds = -7;
ctr->thousands--;
if (ctr->thousands == -1) {
ctr->thousands = -7;
ctr->myriads--;
if (ctr->myriads == -1)
ctr->myriads = -7; /* 0 - 1 should wrap around to 9999. */
}
}
}
}
} else
ctr->count = (ctr->count - 1) & 0xffff;
}
static void
ctr_load_count(ctr_t *ctr)
{
int l = ctr->l ? ctr->l : 0x10000;
ctr->count = l;
pit_log("ctr->count = %i\n", l);
ctr->null_count = 0;
ctr->newcount = !!(l & 1);
/* Undocumented feature - writing MSB after reload after writing LSB causes an instant reload. */
ctr->incomplete = !!(ctr->wm & 0x80);
}
static void
ctr_tick(ctr_t *ctr, void *priv)
{
pit_t *pit = (pit_t *)priv;
uint8_t state = ctr->state;
if ((state & 0x03) == 0x01) {
/* This is true for all modes */
ctr_load_count(ctr);
ctr->state++;
if (((ctr->m & 0x07) == 0x01) && (ctr->state == 2))
ctr_set_out(ctr, 0, pit);
} else switch (ctr->m & 0x07) {
case 0:
/* Interrupt on terminal count */
switch (state) {
case 2:
if (ctr->gate && (ctr->count >= 1)) {
ctr_decrease_count(ctr);
if (ctr->count < 1) {
ctr->state = 3;
ctr_set_out(ctr, 1, pit);
}
}
break;
case 3:
ctr_decrease_count(ctr);
break;
default:
break;
}
break;
case 1:
/* Hardware retriggerable one-shot */
switch (state) {
case 2:
if (ctr->count >= 1) {
ctr_decrease_count(ctr);
if (ctr->count < 1) {
ctr->state = 3;
ctr_set_out(ctr, 1, pit);
}
}
break;
case 3:
case 6:
ctr_decrease_count(ctr);
break;
default:
break;
}
break;
case 2:
case 6:
/* Rate generator */
switch (state) {
case 3:
ctr_load_count(ctr);
ctr->state = 2;
ctr_set_out(ctr, 1, pit);
break;
case 2:
if (ctr->gate == 0)
break;
else if (ctr->count >= 2) {
ctr_decrease_count(ctr);
if (ctr->count < 2) {
ctr->state = 3;
ctr_set_out(ctr, 0, pit);
}
}
break;
default:
break;
}
break;
case 3:
case 7:
/* Square wave mode */
switch (state) {
case 2:
if (ctr->gate == 0)
break;
else if (ctr->count >= 0) {
if (ctr->bcd) {
ctr_decrease_count(ctr);
if (!ctr->newcount)
ctr_decrease_count(ctr);
} else
ctr->count -= (ctr->newcount ? 1 : 2);
if (ctr->count < 0) {
ctr_set_out(ctr, 0, pit);
ctr_load_count(ctr);
ctr->state = 3;
} else if (ctr->newcount)
ctr->newcount = 0;
}
break;
case 3:
if (ctr->gate == 0)
break;
else if (ctr->count >= 0) {
if (ctr->bcd) {
ctr_decrease_count(ctr);
ctr_decrease_count(ctr);
if (ctr->newcount)
ctr_decrease_count(ctr);
} else
ctr->count -= (ctr->newcount ? 3 : 2);
if (ctr->count < 0) {
ctr_set_out(ctr, 1, pit);
ctr_load_count(ctr);
ctr->state = 2;
} else if (ctr->newcount)
ctr->newcount = 0;
}
break;
default:
break;
}
break;
case 4:
case 5:
/* Software triggered strobe */
/* Hardware triggered strobe */
if ((ctr->gate != 0) || (ctr->m != 4)) {
switch (state) {
case 0:
case 6:
ctr_decrease_count(ctr);
break;
case 2:
if (ctr->count >= 1) {
ctr_decrease_count(ctr);
if (ctr->count < 1) {
ctr->state = 3;
ctr_set_out(ctr, 0, pit);
}
}
break;
case 3:
ctr->state = 0;
ctr_set_out(ctr, 1, pit);
break;
default:
break;
}
}
break;
default:
break;
}
}
void
ctr_clock(void *data, int counter_id)
{
pit_t *pit = (pit_t *) data;
ctr_t *ctr = &pit->counters[counter_id];
/* FIXME: Is this even needed? */
if ((ctr->state == 3) && (ctr->m != 2) && (ctr->m != 3))
return;
if (ctr->using_timer)
return;
ctr_tick(ctr, pit);
}
static void
ctr_set_state_1(ctr_t *ctr)
{
uint8_t mode = (ctr->m & 0x03);
int do_reload = !!ctr->incomplete || (mode == 0) || (ctr->state == 0);
ctr->incomplete = 0;
if (do_reload)
ctr->state = 1 + ((mode == 1) << 2);
}
static void
ctr_load(ctr_t *ctr)
{
if (ctr->l == 1) {
/* Count of 1 is illegal in modes 2 and 3. What happens here was
determined experimentally. */
if (ctr->m == 2)
ctr->l = 2;
else if (ctr->m == 3)
ctr->l = 0;
}
if (ctr->using_timer)
ctr->latch = 1;
else
ctr_set_state_1(ctr);
if (ctr->load_func != NULL)
ctr->load_func(ctr->m, ctr->l ? ctr->l : 0x10000);
pit_log("Counter loaded, state = %i, gate = %i, latch = %i\n", ctr->state, ctr->gate, ctr->latch);
}
static __inline void
ctr_latch_status(ctr_t *ctr)
{
ctr->read_status = (ctr->ctrl & 0x3f) | (ctr->out ? 0x80 : 0) | (ctr->null_count ? 0x40 : 0);
ctr->do_read_status = 1;
}
static __inline void
ctr_latch_count(ctr_t *ctr)
{
int count = (ctr->latch || (ctr->state == 1)) ? ctr->l : ctr->count;
switch (ctr->rm & 0x03) {
case 0x00:
/* This should never happen. */
break;
case 0x01:
/* Latch bits 0-7 only. */
ctr->rl = ((count << 8) & 0xff00) | (count & 0xff);
ctr->latched = 1;
break;
case 0x02:
/* Latch bit 8-15 only. */
ctr->rl = (count & 0xff00) | ((count >> 8) & 0xff);
ctr->latched = 1;
break;
case 0x03:
/* Latch all 16 bits. */
ctr->rl = count;
ctr->latched = 2;
break;
default:
break;
}
pit_log("rm = %x, latched counter = %04X\n", ctr->rm & 0x03, ctr->rl & 0xffff);
}
uint16_t
pit_ctr_get_count(void *data, int counter_id)
{
const pit_t *pit = (pit_t *) data;
const ctr_t *ctr = &pit->counters[counter_id];
return (uint16_t) ctr->l;
}
void
pit_ctr_set_load_func(void *data, int counter_id, void (*func)(uint8_t new_m, int new_count))
{
if (data == NULL)
return;
pit_t *pit = (pit_t *) data;
ctr_t *ctr = &pit->counters[counter_id];
ctr->load_func = func;
}
void
pit_ctr_set_out_func(void *data, int counter_id, void (*func)(int new_out, int old_out, void *priv))
{
if (data == NULL)
return;
pit_t *pit = (pit_t *) data;
ctr_t *ctr = &pit->counters[counter_id];
ctr->out_func = func;
}
void
pit_ctr_set_gate(void *data, int counter_id, int gate)
{
pit_t *pit = (pit_t *) data;
ctr_t *ctr = &pit->counters[counter_id];
int old = ctr->gate;
uint8_t mode = ctr->m & 3;
switch (mode) {
case 1:
case 2:
case 3:
case 5:
case 6:
case 7:
if (!old && gate) {
/* Here we handle the rising edges. */
if (mode & 1) {
if (mode != 1)
ctr_set_out(ctr, 1, pit);
ctr->state = 1;
} else if (mode == 2)
ctr->state = 3;
} else if (old && !gate) {
/* Here we handle the lowering edges. */
if (mode & 2)
ctr_set_out(ctr, 1, pit);
}
break;
default:
break;
}
ctr->gate = gate;
}
static __inline void
pit_ctr_set_clock_common(ctr_t *ctr, int clock, void *priv)
{
pit_t *pit = (pit_t *)priv;
int old = ctr->clock;
ctr->clock = clock;
if (ctr->using_timer && ctr->latch) {
if (old && !ctr->clock) {
ctr_set_state_1(ctr);
ctr->latch = 0;
}
} else if (ctr->using_timer && !ctr->latch) {
if (ctr->state == 1) {
if (!old && ctr->clock)
ctr->s1_det = 1; /* Rising edge. */
else if (old && !ctr->clock) {
ctr->s1_det++; /* Falling edge. */
if (ctr->s1_det >= 2) {
ctr->s1_det = 0;
ctr_tick(ctr, pit);
}
}
} else if (old && !ctr->clock)
ctr_tick(ctr, pit);
}
}
void
pit_ctr_set_clock(ctr_t *ctr, int clock, void *priv)
{
pit_ctr_set_clock_common(ctr, clock, priv);
}
void
pit_ctr_set_using_timer(void *data, int counter_id, int using_timer)
{
if (tsc > 0)
timer_process();
pit_t *pit = (pit_t *) data;
ctr_t *ctr = &pit->counters[counter_id];
ctr->using_timer = using_timer;
}
static void
pit_timer_over(void *priv)
{
pit_t *dev = (pit_t *) priv;
dev->clock ^= 1;
for (uint8_t i = 0; i < NUM_COUNTERS; i++)
pit_ctr_set_clock_common(&dev->counters[i], dev->clock, dev);
timer_advance_u64(&dev->callback_timer, dev->pit_const >> 1ULL);
}
static void
pit_write(uint16_t addr, uint8_t val, void *priv)
{
pit_t *dev = (pit_t *) priv;
int t = (addr & 3);
ctr_t *ctr;
if ((dev->flags & (PIT_8254 | PIT_EXT_IO))) {
pit_log("[%04X:%08X] pit_write(%04X, %02X, %08X)\n", CS, cpu_state.pc, addr, val, priv);
}
switch (addr & 3) {
case 3: /* control */
t = val >> 6;
if (t == 3) {
if (dev->flags & PIT_8254) {
/* This is 8254-only. */
if (!(val & 0x20)) {
if (val & 2)
ctr_latch_count(&dev->counters[0]);
if (val & 4)
ctr_latch_count(&dev->counters[1]);
if (val & 8)
ctr_latch_count(&dev->counters[2]);
if ((dev->flags & (PIT_8254 | PIT_EXT_IO))) {
pit_log("PIT %i: Initiated readback command\n", t);
}
}
if (!(val & 0x10)) {
if (val & 2)
ctr_latch_status(&dev->counters[0]);
if (val & 4)
ctr_latch_status(&dev->counters[1]);
if (val & 8)
ctr_latch_status(&dev->counters[2]);
}
}
} else {
dev->ctrl = val;
ctr = &dev->counters[t];
if (!(dev->ctrl & 0x30)) {
ctr_latch_count(ctr);
if ((dev->flags & (PIT_8254 | PIT_EXT_IO))) {
pit_log("PIT %i: Initiated latched read, %i bytes latched\n",
t, ctr->latched);
}
} else {
ctr->ctrl = val;
ctr->rm = ctr->wm = (ctr->ctrl >> 4) & 3;
ctr->m = (val >> 1) & 7;
if (ctr->m > 5)
ctr->m &= 3;
ctr->null_count = 1;
ctr->bcd = (ctr->ctrl & 0x01);
ctr_set_out(ctr, !!ctr->m, dev);
ctr->state = 0;
if (ctr->latched) {
if ((dev->flags & (PIT_8254 | PIT_EXT_IO))) {
pit_log("PIT %i: Reload while counter is latched\n", t);
}
ctr->rl--;
}
if ((dev->flags & (PIT_8254 | PIT_EXT_IO))) {
pit_log("PIT %i: M = %i, RM/WM = %i, State = %i, Out = %i\n", t, ctr->m, ctr->rm, ctr->state, ctr->out);
}
}
}
break;
case 0:
case 1:
case 2: /* the actual timers */
ctr = &dev->counters[t];
switch (ctr->wm) {
case 0:
/* This should never happen. */
break;
case 1:
ctr->l = val;
ctr->lback = ctr->l;
ctr->lback2 = ctr->l;
if ((dev->flags & (PIT_8254 | PIT_EXT_IO))) {
pit_log("PIT %i (1): Written byte %02X, latch now %04X\n", t, val, ctr->l);
}
if (ctr->m == 0)
ctr_set_out(ctr, 0, dev);
ctr_load(ctr);
break;
case 2:
ctr->l = (val << 8);
ctr->lback = ctr->l;
ctr->lback2 = ctr->l;
if ((dev->flags & (PIT_8254 | PIT_EXT_IO))) {
pit_log("PIT %i (2): Written byte %02X, latch now %04X\n", t, val, ctr->l);
}
if (ctr->m == 0)
ctr_set_out(ctr, 0, dev);
ctr_load(ctr);
break;
case 3:
case 0x83:
if (ctr->wm & 0x80) {
ctr->l = (ctr->l & 0x00ff) | (val << 8);
ctr->lback = ctr->l;
ctr->lback2 = ctr->l;
if ((dev->flags & (PIT_8254 | PIT_EXT_IO))) {
pit_log("PIT %i (0x83): Written high byte %02X, latch now %04X\n", t, val, ctr->l);
}
ctr_load(ctr);
} else {
ctr->l = (ctr->l & 0xff00) | val;
ctr->lback = ctr->l;
ctr->lback2 = ctr->l;
if ((dev->flags & (PIT_8254 | PIT_EXT_IO))) {
pit_log("PIT %i (3): Written low byte %02X, latch now %04X\n", t, val, ctr->l);
}
if (ctr->m == 0) {
ctr->state = 0;
ctr_set_out(ctr, 0, dev);
}
}
if (ctr->wm & 0x80)
ctr->wm &= ~0x80;
else
ctr->wm |= 0x80;
break;
default:
break;
}
break;
default:
break;
}
}
extern uint8_t *ram;
uint8_t
pit_read_reg(void *priv, uint8_t reg)
{
pit_t *dev = (pit_t *) priv;
uint8_t ret = 0xff;
switch (reg) {
case 0x00:
case 0x02:
case 0x04:
ret = dev->counters[reg >> 1].l & 0xff;
break;
case 0x01:
case 0x03:
case 0x05:
ret = (dev->counters[reg >> 1].l >> 8) & 0xff;
break;
case 0x06:
ret = dev->ctrl;
break;
case 0x07:
/* The SiS 551x datasheet is unclear about how exactly
this register is structured.
Update: But the SiS 5571 datasheet is clear. */
ret = (dev->counters[0].rm & 0x80) ? 0x01 : 0x00;
ret |= (dev->counters[1].rm & 0x80) ? 0x02 : 0x00;
ret |= (dev->counters[2].rm & 0x80) ? 0x04 : 0x00;
ret |= (dev->counters[0].wm & 0x80) ? 0x08 : 0x00;
ret |= (dev->counters[1].wm & 0x80) ? 0x10 : 0x00;
ret |= (dev->counters[2].wm & 0x80) ? 0x20 : 0x00;
break;
}
return ret;
}
static uint8_t
pit_read(uint16_t addr, void *priv)
{
pit_t *dev = (pit_t *) priv;
uint8_t ret = 0xff;
int count;
int t = (addr & 3);
ctr_t *ctr;
switch (addr & 3) {
case 3: /* Control. */
/* This is 8254-only, 8253 returns 0x00. */
ret = (dev->flags & PIT_8254) ? dev->ctrl : 0x00;
break;
case 0:
case 1:
case 2: /* The actual timers. */
ctr = &dev->counters[t];
if (ctr->do_read_status) {
ctr->do_read_status = 0;
ret = ctr->read_status;
break;
}
count = (ctr->state == 1) ? ctr->l : ctr->count;
if (ctr->latched) {
ret = (ctr->rl) >> ((ctr->rm & 0x80) ? 8 : 0);
if (ctr->rm & 0x80)
ctr->rm &= ~0x80;
else
ctr->rm |= 0x80;
ctr->latched--;
} else
switch (ctr->rm) {
case 0:
case 0x80:
ret = 0x00;
break;
case 1:
ret = count & 0xff;
break;
case 2:
ret = count >> 8;
break;
case 3:
case 0x83:
/* Yes, wm is correct here - this is to ensure correct readout while the
count is being written. */
if (ctr->wm & 0x80)
ret = ~(ctr->l & 0xff);
else
ret = count >> ((ctr->rm & 0x80) ? 8 : 0);
if (ctr->rm & 0x80)
ctr->rm &= ~0x80;
else
ctr->rm |= 0x80;
break;
default:
break;
}
break;
default:
break;
}
if ((dev->flags & (PIT_8254 | PIT_EXT_IO))) {
pit_log("[%04X:%08X] pit_read(%04X, %08X) = %02X\n", CS, cpu_state.pc, addr, priv, ret);
}
return ret;
}
void
pit_irq0_timer_ps2(int new_out, int old_out, UNUSED(void *priv))
{
if (new_out && !old_out) {
picint(1);
pit_devs[1].set_gate(pit_devs[1].data, 0, 1);
}
if (!new_out)
picintc(1);
if (!new_out && old_out)
pit_devs[1].ctr_clock(pit_devs[1].data, 0);
}
void
pit_refresh_timer_xt(int new_out, int old_out, UNUSED(void *priv))
{
if (new_out && !old_out)
dma_channel_read(0);
}
void
pit_refresh_timer_at(int new_out, int old_out, UNUSED(void *priv))
{
if (refresh_at_enable && new_out && !old_out)
ppi.pb ^= 0x10;
}
void
pit_speaker_timer(int new_out, UNUSED(int old_out), UNUSED(void *priv))
{
int l;
if (cassette != NULL)
pc_cas_set_out(cassette, new_out);
speaker_update();
uint16_t count = pit_devs[0].get_count(pit_devs[0].data, 2);
l = count ? count : 0x10000;
if (l < 25)
speakon = 0;
else
speakon = new_out;
ppispeakon = new_out;
}
void
pit_nmi_timer_ps2(int new_out, UNUSED(int old_out), UNUSED(void *priv))
{
nmi = new_out;
if (nmi)
nmi_auto_clear = 1;
}
static void
ctr_reset(ctr_t *ctr)
{
ctr->ctrl = 0;
ctr->m = 0;
ctr->gate = 0;
ctr->l = 0xffff;
ctr->using_timer = 1;
ctr->state = 0;
ctr->null_count = 1;
ctr->latch = 0;
ctr->s1_det = 0;
ctr->l_det = 0;
}
void
pit_device_reset(pit_t *dev)
{
dev->clock = 0;
for (uint8_t i = 0; i < NUM_COUNTERS; i++)
ctr_reset(&dev->counters[i]);
}
void
pit_reset(pit_t *dev)
{
memset(dev, 0, sizeof(pit_t));
dev->clock = 0;
for (uint8_t i = 0; i < NUM_COUNTERS; i++)
ctr_reset(&dev->counters[i]);
/* Disable speaker gate. */
dev->counters[2].gate = 0;
}
void
pit_handler(int set, uint16_t base, int size, void *priv)
{
io_handler(set, base, size, pit_read, NULL, NULL, pit_write, NULL, NULL, priv);
}
void
pit_set_pit_const(void *data, uint64_t pit_const)
{
pit_t *pit = (pit_t *) data;
pit->pit_const = pit_const;
}
static void
pit_speed_changed(void *priv)
{
pit_set_pit_const(priv, PITCONST);
}
static void
pit_close(void *priv)
{
pit_t *dev = (pit_t *) priv;
if (dev == pit_devs[0].data)
pit_devs[0].data = NULL;
if (dev == pit_devs[1].data)
pit_devs[1].data = NULL;
if (dev != NULL)
free(dev);
}
static void *
pit_init(const device_t *info)
{
pit_t *dev = (pit_t *) malloc(sizeof(pit_t));
pit_reset(dev);
pit_set_pit_const(dev, PITCONST);
if (!(dev->flags & PIT_PS2) && !(dev->flags & PIT_CUSTOM_CLOCK)) {
timer_add(&dev->callback_timer, pit_timer_over, (void *) dev, 0);
timer_set_delay_u64(&dev->callback_timer, dev->pit_const >> 1ULL);
}
dev->flags = info->local;
dev->dev_priv = NULL;
if (!(dev->flags & PIT_EXT_IO)) {
io_sethandler((dev->flags & PIT_SECONDARY) ? 0x0048 : 0x0040, 0x0004,
pit_read, NULL, NULL, pit_write, NULL, NULL, dev);
}
return dev;
}
const device_t i8253_device = {
.name = "Intel 8253/8253-5 Programmable Interval Timer",
.internal_name = "i8253",
.flags = DEVICE_ISA | DEVICE_PIT,
.local = PIT_8253,
.init = pit_init,
.close = pit_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = pit_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t i8253_ext_io_device = {
.name = "Intel 8253 Programmable Interval Timer (External I/O)",
.internal_name = "i8253_ext_io",
.flags = DEVICE_ISA,
.local = PIT_8253 | PIT_EXT_IO,
.init = pit_init,
.close = pit_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t i8254_device = {
.name = "Intel 8254 Programmable Interval Timer",
.internal_name = "i8254",
.flags = DEVICE_ISA | DEVICE_PIT,
.local = PIT_8254,
.init = pit_init,
.close = pit_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = pit_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t i8254_sec_device = {
.name = "Intel 8254 Programmable Interval Timer (Secondary)",
.internal_name = "i8254_sec",
.flags = DEVICE_ISA,
.local = PIT_8254 | PIT_SECONDARY,
.init = pit_init,
.close = pit_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = pit_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t i8254_ext_io_device = {
.name = "Intel 8254 Programmable Interval Timer (External I/O)",
.internal_name = "i8254_ext_io",
.flags = DEVICE_ISA,
.local = PIT_8254 | PIT_EXT_IO,
.init = pit_init,
.close = pit_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t i8254_ps2_device = {
.name = "Intel 8254 Programmable Interval Timer (PS/2)",
.internal_name = "i8254_ps2",
.flags = DEVICE_ISA,
.local = PIT_8254 | PIT_PS2 | PIT_EXT_IO,
.init = pit_init,
.close = pit_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = pit_speed_changed,
.force_redraw = NULL,
.config = NULL
};
pit_t *
pit_common_init(int type, void (*out0)(int new_out, int old_out, void *priv), void (*out1)(int new_out, int old_out, void *priv))
{
void *pit;
pit_intf_t *pit_intf = &pit_devs[0];
switch (type) {
default:
case PIT_8253:
pit = device_add(&i8253_device);
*pit_intf = pit_classic_intf;
break;
case PIT_8254:
pit = device_add(&i8254_device);
*pit_intf = pit_classic_intf;
break;
case PIT_8253_FAST:
pit = device_add(&i8253_fast_device);
*pit_intf = pit_fast_intf;
break;
case PIT_8254_FAST:
pit = device_add(&i8254_fast_device);
*pit_intf = pit_fast_intf;
break;
}
pit_intf->data = pit;
for (uint8_t i = 0; i < 3; i++) {
pit_intf->set_gate(pit_intf->data, i, 1);
pit_intf->set_using_timer(pit_intf->data, i, 1);
}
pit_intf->set_out_func(pit_intf->data, 0, out0);
pit_intf->set_out_func(pit_intf->data, 1, out1);
pit_intf->set_out_func(pit_intf->data, 2, pit_speaker_timer);
pit_intf->set_load_func(pit_intf->data, 2, speaker_set_count);
pit_intf->set_gate(pit_intf->data, 2, 0);
return pit;
}
pit_t *
pit_ps2_init(int type)
{
void *pit;
pit_intf_t *ps2_pit = &pit_devs[1];
switch (type) {
default:
case PIT_8254:
pit = device_add(&i8254_ps2_device);
*ps2_pit = pit_classic_intf;
break;
case PIT_8254_FAST:
pit = device_add(&i8254_ps2_fast_device);
*ps2_pit = pit_fast_intf;
break;
}
ps2_pit->data = pit;
ps2_pit->set_gate(ps2_pit->data, 0, 0);
for (int i = 0; i < 3; i++) {
ps2_pit->set_using_timer(ps2_pit->data, i, 0);
}
io_sethandler(0x0044, 0x0001, ps2_pit->read, NULL, NULL, ps2_pit->write, NULL, NULL, pit);
io_sethandler(0x0047, 0x0001, ps2_pit->read, NULL, NULL, ps2_pit->write, NULL, NULL, pit);
pit_devs[0].set_out_func(pit_devs[0].data, 0, pit_irq0_timer_ps2);
ps2_pit->set_out_func(ps2_pit->data, 0, pit_nmi_timer_ps2);
return pit;
}
void
pit_change_pas16_consts(double prescale)
{
PAS16CONST = (uint64_t) ((PAS16CONSTD / prescale) * (double) (1ULL << 32));
PAS16CONST2 = (uint64_t) ((PAS16CONST2D / prescale) * (double) (1ULL << 32));
}
void
pit_set_clock(uint32_t clock)
{
/* Set default CPU/crystal clock and xt_cpu_multi. */
if (cpu_s->cpu_type >= CPU_286) {
uint32_t remainder = (clock % 100000000);
if (remainder == 66666666)
cpuclock = (double) (clock - remainder) + (200000000.0 / 3.0);
else if (remainder == 33333333)
cpuclock = (double) (clock - remainder) + (100000000.0 / 3.0);
else
cpuclock = (double) clock;
PITCONSTD = (cpuclock / 1193182.0);
PITCONST = (uint64_t) (PITCONSTD * (double) (1ULL << 32));
#ifdef IMPRECISE_CGACONST
CGACONST = (uint64_t) ((cpuclock / (19687503.0 / 11.0)) * (double) (1ULL << 32));
#else
CGACONST = (uint64_t) ((cpuclock / (157500000.0 / 88.0)) * (double) (1ULL << 32));
#endif
ISACONST = (uint64_t) ((cpuclock / (double) cpu_isa_speed) * (double) (1ULL << 32));
xt_cpu_multi = 1ULL;
} else {
cpuclock = (157500000.0 / 11.0);
PITCONSTD = 12.0;
PITCONST = (12ULL << 32ULL);
CGACONST = (8ULL << 32ULL);
xt_cpu_multi = 3ULL;
switch (cpu_s->rspeed) {
case 7159092:
if (cpu_s->cpu_flags & CPU_ALTERNATE_XTAL) {
cpuclock = 28636368.0;
xt_cpu_multi = 4ULL;
} else
xt_cpu_multi = 2ULL;
break;
case 8000000:
cpuclock = 24000000.0;
break;
case 9545456:
cpuclock = 28636368.0;
break;
case 10000000:
cpuclock = 30000000.0;
break;
case 12000000:
cpuclock = 36000000.0;
break;
case 16000000:
cpuclock = 48000000.0;
break;
default:
if (cpu_s->cpu_flags & CPU_ALTERNATE_XTAL) {
cpuclock = 28636368.0;
xt_cpu_multi = 6ULL;
}
break;
}
if (cpuclock == 28636368.0) {
PITCONSTD = 24.0;
PITCONST = (24ULL << 32LL);
CGACONST = (16ULL << 32LL);
} else if (cpuclock != 14318184.0) {
PITCONSTD = (cpuclock / 1193182.0);
PITCONST = (uint64_t) (PITCONSTD * (double) (1ULL << 32));
#ifdef IMPRECISE_CGACONST
CGACONST = (uint64_t) ((cpuclock / (19687503.0 / 11.0)) * (double) (1ULL << 32));
#else
CGACONST = (uint64_t) ((cpuclock / (157500000.0 / 88.0)) * (double) (1ULL << 32));
#endif
}
ISACONST = (1ULL << 32ULL);
}
xt_cpu_multi <<= 32ULL;
/* Delay for empty I/O ports. */
io_delay = (int) round(((double) cpu_s->rspeed) / 3000000.0);
#ifdef WRONG_MDACONST
MDACONST = (uint64_t) (cpuclock / 2032125.0 * (double) (1ULL << 32));
#else
MDACONST = (uint64_t) (cpuclock / (16257000.0 / 9.0) * (double) (1ULL << 32));
#endif
HERCCONST = MDACONST;
VGACONST1 = (uint64_t) (cpuclock / 25175000.0 * (double) (1ULL << 32));
VGACONST2 = (uint64_t) (cpuclock / 28322000.0 * (double) (1ULL << 32));
RTCCONST = (uint64_t) (cpuclock / 32768.0 * (double) (1ULL << 32));
TIMER_USEC = (uint64_t) ((cpuclock / 1000000.0) * (double) (1ULL << 32));
PAS16CONSTD = (cpuclock / 441000.0);
PAS16CONST = (uint64_t) (PAS16CONSTD * (double) (1ULL << 32));
PAS16CONST2D = (cpuclock / 1008000.0);
PAS16CONST2 = (uint64_t) (PAS16CONST2D * (double) (1ULL << 32));
PASSCSICONSTD = (cpuclock / (28224000.0 / 14.0));
PASSCSICONST = (uint64_t) (PASSCSICONSTD * (double) (1ULL << 32));
isa_timing = (cpuclock / (double) cpu_isa_speed);
if (cpu_64bitbus)
bus_timing = (cpuclock / (cpu_busspeed / 2));
else
bus_timing = (cpuclock / cpu_busspeed);
pci_timing = (cpuclock / (double) cpu_pci_speed);
agp_timing = (cpuclock / (double) cpu_agp_speed);
/* PCICLK in us for use with timer_on_auto(). */
PCICLK = pci_timing / (cpuclock / 1000000.0);
AGPCLK = agp_timing / (cpuclock / 1000000.0);
if (cpu_busspeed >= 30000000)
SYSCLK = bus_timing * 4.0;
else
SYSCLK = bus_timing * 3.0;
video_update_timing();
device_speed_changed();
}
const pit_intf_t pit_classic_intf = {
&pit_read,
&pit_write,
&pit_ctr_get_count,
&pit_ctr_set_gate,
&pit_ctr_set_using_timer,
&pit_ctr_set_out_func,
&pit_ctr_set_load_func,
&ctr_clock,
&pit_set_pit_const,
NULL,
};
``` | /content/code_sandbox/src/pit.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 9,938 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Universal Serial Bus emulation (currently dummy UHCI and
* OHCI).
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/io.h>
#include <86box/mem.h>
#include <86box/usb.h>
#include "cpu.h"
#include <86box/plat_unused.h>
#ifdef ENABLE_USB_LOG
int usb_do_log = ENABLE_USB_LOG;
static void
usb_log(const char *fmt, ...)
{
va_list ap;
if (usb_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define usb_log(fmt, ...)
#endif
static uint8_t
uhci_reg_read(uint16_t addr, void *priv)
{
const usb_t *dev = (usb_t *) priv;
uint8_t ret;
const uint8_t *regs = dev->uhci_io;
addr &= 0x0000001f;
ret = regs[addr];
return ret;
}
static void
uhci_reg_write(uint16_t addr, uint8_t val, void *priv)
{
usb_t *dev = (usb_t *) priv;
uint8_t *regs = dev->uhci_io;
addr &= 0x0000001f;
switch (addr) {
case 0x02:
regs[0x02] &= ~(val & 0x3f);
break;
case 0x04:
regs[0x04] = (val & 0x0f);
break;
case 0x09:
regs[0x09] = (val & 0xf0);
break;
case 0x0a:
case 0x0b:
regs[addr] = val;
break;
case 0x0c:
regs[0x0c] = (val & 0x7f);
break;
default:
break;
}
}
static void
uhci_reg_writew(uint16_t addr, uint16_t val, void *priv)
{
usb_t *dev = (usb_t *) priv;
uint16_t *regs = (uint16_t *) dev->uhci_io;
addr &= 0x0000001f;
switch (addr) {
case 0x00:
if ((val & 0x0001) && !(regs[0x00] & 0x0001))
regs[0x01] &= ~0x20;
else if (!(val & 0x0001))
regs[0x01] |= 0x20;
regs[0x00] = (val & 0x00ff);
break;
case 0x06:
regs[0x03] = (val & 0x07ff);
break;
case 0x10:
case 0x12:
regs[addr >> 1] = ((regs[addr >> 1] & 0xedbb) | (val & 0x1244)) & ~(val & 0x080a);
break;
default:
uhci_reg_write(addr, val & 0xff, priv);
uhci_reg_write(addr + 1, (val >> 8) & 0xff, priv);
break;
}
}
void
uhci_update_io_mapping(usb_t *dev, uint8_t base_l, uint8_t base_h, int enable)
{
if (dev->uhci_enable && (dev->uhci_io_base != 0x0000))
io_removehandler(dev->uhci_io_base, 0x20, uhci_reg_read, NULL, NULL, uhci_reg_write, uhci_reg_writew, NULL, dev);
dev->uhci_io_base = base_l | (base_h << 8);
dev->uhci_enable = enable;
if (dev->uhci_enable && (dev->uhci_io_base != 0x0000))
io_sethandler(dev->uhci_io_base, 0x20, uhci_reg_read, NULL, NULL, uhci_reg_write, uhci_reg_writew, NULL, dev);
}
static uint8_t
ohci_mmio_read(uint32_t addr, void *priv)
{
const usb_t *dev = (usb_t *) priv;
uint8_t ret = 0x00;
addr &= 0x00000fff;
ret = dev->ohci_mmio[addr];
if (addr == 0x101)
ret = (ret & 0xfe) | (!!mem_a20_key);
return ret;
}
static void
ohci_mmio_write(uint32_t addr, uint8_t val, void *priv)
{
usb_t *dev = (usb_t *) priv;
uint8_t old;
addr &= 0x00000fff;
switch (addr) {
case 0x04:
if ((val & 0xc0) == 0x00) {
/* UsbReset */
dev->ohci_mmio[0x56] = dev->ohci_mmio[0x5a] = 0x16;
}
break;
case 0x08: /* HCCOMMANDSTATUS */
/* bit OwnershipChangeRequest triggers an ownership change (SMM <-> OS) */
if (val & 0x08) {
dev->ohci_mmio[0x0f] = 0x40;
if ((dev->ohci_mmio[0x13] & 0xc0) == 0xc0)
smi_raise();
}
/* bit HostControllerReset must be cleared for the controller to be seen as initialized */
if (val & 0x01) {
memset(dev->ohci_mmio, 0x00, 4096);
dev->ohci_mmio[0x00] = 0x10;
dev->ohci_mmio[0x01] = 0x01;
dev->ohci_mmio[0x48] = 0x02;
val &= ~0x01;
}
break;
case 0x0c:
dev->ohci_mmio[addr] &= ~(val & 0x7f);
return;
case 0x0d:
case 0x0e:
return;
case 0x0f:
dev->ohci_mmio[addr] &= ~(val & 0x40);
return;
case 0x3b:
dev->ohci_mmio[addr] = (val & 0x80);
return;
case 0x39:
case 0x41:
dev->ohci_mmio[addr] = (val & 0x3f);
return;
case 0x45:
dev->ohci_mmio[addr] = (val & 0x0f);
return;
case 0x3a:
case 0x3e:
case 0x3f:
case 0x42:
case 0x43:
case 0x46:
case 0x47:
case 0x48:
case 0x4a:
return;
case 0x49:
dev->ohci_mmio[addr] = (val & 0x1b);
if (val & 0x02) {
dev->ohci_mmio[0x55] |= 0x01;
dev->ohci_mmio[0x59] |= 0x01;
}
return;
case 0x4b:
dev->ohci_mmio[addr] = (val & 0x03);
return;
case 0x4c:
case 0x4e:
dev->ohci_mmio[addr] = (val & 0x06);
if ((addr == 0x4c) && !(val & 0x04)) {
if (!(dev->ohci_mmio[0x58] & 0x01))
dev->ohci_mmio[0x5a] |= 0x01;
dev->ohci_mmio[0x58] |= 0x01;
}
if ((addr == 0x4c) && !(val & 0x02)) {
if (!(dev->ohci_mmio[0x54] & 0x01))
dev->ohci_mmio[0x56] |= 0x01;
dev->ohci_mmio[0x54] |= 0x01;
}
return;
case 0x4d:
case 0x4f:
return;
case 0x50:
if (val & 0x01) {
if ((dev->ohci_mmio[0x49] & 0x03) == 0x00) {
dev->ohci_mmio[0x55] &= ~0x01;
dev->ohci_mmio[0x54] &= ~0x17;
dev->ohci_mmio[0x56] &= ~0x17;
dev->ohci_mmio[0x59] &= ~0x01;
dev->ohci_mmio[0x58] &= ~0x17;
dev->ohci_mmio[0x5a] &= ~0x17;
} else if ((dev->ohci_mmio[0x49] & 0x03) == 0x01) {
if (!(dev->ohci_mmio[0x4e] & 0x02)) {
dev->ohci_mmio[0x55] &= ~0x01;
dev->ohci_mmio[0x54] &= ~0x17;
dev->ohci_mmio[0x56] &= ~0x17;
}
if (!(dev->ohci_mmio[0x4e] & 0x04)) {
dev->ohci_mmio[0x59] &= ~0x01;
dev->ohci_mmio[0x58] &= ~0x17;
dev->ohci_mmio[0x5a] &= ~0x17;
}
}
}
return;
case 0x51:
if (val & 0x80)
dev->ohci_mmio[addr] |= 0x80;
return;
case 0x52:
dev->ohci_mmio[addr] &= ~(val & 0x02);
if (val & 0x01) {
if ((dev->ohci_mmio[0x49] & 0x03) == 0x00) {
dev->ohci_mmio[0x55] |= 0x01;
dev->ohci_mmio[0x59] |= 0x01;
} else if ((dev->ohci_mmio[0x49] & 0x03) == 0x01) {
if (!(dev->ohci_mmio[0x4e] & 0x02))
dev->ohci_mmio[0x55] |= 0x01;
if (!(dev->ohci_mmio[0x4e] & 0x04))
dev->ohci_mmio[0x59] |= 0x01;
}
}
return;
case 0x53:
if (val & 0x80)
dev->ohci_mmio[0x51] &= ~0x80;
return;
case 0x54:
case 0x58:
old = dev->ohci_mmio[addr];
if (val & 0x10) {
if (old & 0x01) {
dev->ohci_mmio[addr] |= 0x10;
/* TODO: The clear should be on a 10 ms timer. */
dev->ohci_mmio[addr] &= ~0x10;
dev->ohci_mmio[addr + 2] |= 0x10;
} else
dev->ohci_mmio[addr + 2] |= 0x01;
}
if (val & 0x08)
dev->ohci_mmio[addr] &= ~0x04;
if (val & 0x04)
dev->ohci_mmio[addr] |= 0x04;
if (val & 0x02) {
if (old & 0x01)
dev->ohci_mmio[addr] |= 0x02;
else
dev->ohci_mmio[addr + 2] |= 0x01;
}
if (val & 0x01) {
if (old & 0x01)
dev->ohci_mmio[addr] &= ~0x02;
else
dev->ohci_mmio[addr + 2] |= 0x01;
}
if (!(dev->ohci_mmio[addr] & 0x04) && (old & 0x04))
dev->ohci_mmio[addr + 2] |= 0x04;
#if 0
if (!(dev->ohci_mmio[addr] & 0x02))
dev->ohci_mmio[addr + 2] |= 0x02;
#endif
return;
case 0x55:
if ((val & 0x02) && ((dev->ohci_mmio[0x49] & 0x03) == 0x00) && (dev->ohci_mmio[0x4e] & 0x02)) {
dev->ohci_mmio[addr] &= ~0x01;
dev->ohci_mmio[0x54] &= ~0x17;
dev->ohci_mmio[0x56] &= ~0x17;
}
if ((val & 0x01) && ((dev->ohci_mmio[0x49] & 0x03) == 0x00) && (dev->ohci_mmio[0x4e] & 0x02)) {
dev->ohci_mmio[addr] |= 0x01;
dev->ohci_mmio[0x58] &= ~0x17;
dev->ohci_mmio[0x5a] &= ~0x17;
}
return;
case 0x59:
if ((val & 0x02) && ((dev->ohci_mmio[0x49] & 0x03) == 0x00) && (dev->ohci_mmio[0x4e] & 0x04))
dev->ohci_mmio[addr] &= ~0x01;
if ((val & 0x01) && ((dev->ohci_mmio[0x49] & 0x03) == 0x00) && (dev->ohci_mmio[0x4e] & 0x04))
dev->ohci_mmio[addr] |= 0x01;
return;
case 0x56:
case 0x5a:
dev->ohci_mmio[addr] &= ~(val & 0x1f);
return;
case 0x57:
case 0x5b:
return;
default:
break;
}
dev->ohci_mmio[addr] = val;
}
void
ohci_update_mem_mapping(usb_t *dev, uint8_t base1, uint8_t base2, uint8_t base3, int enable)
{
if (dev->ohci_enable && (dev->ohci_mem_base != 0x00000000))
mem_mapping_disable(&dev->ohci_mmio_mapping);
dev->ohci_mem_base = ((base1 << 8) | (base2 << 16) | (base3 << 24)) & 0xfffff000;
dev->ohci_enable = enable;
if (dev->ohci_enable && (dev->ohci_mem_base != 0x00000000))
mem_mapping_set_addr(&dev->ohci_mmio_mapping, dev->ohci_mem_base, 0x1000);
}
static void
usb_reset(void *priv)
{
usb_t *dev = (usb_t *) priv;
memset(dev->uhci_io, 0x00, 128);
dev->uhci_io[0x0c] = 0x40;
dev->uhci_io[0x10] = dev->uhci_io[0x12] = 0x80;
memset(dev->ohci_mmio, 0x00, 4096);
dev->ohci_mmio[0x00] = 0x10;
dev->ohci_mmio[0x01] = 0x01;
dev->ohci_mmio[0x48] = 0x02;
io_removehandler(dev->uhci_io_base, 0x20, uhci_reg_read, NULL, NULL, uhci_reg_write, uhci_reg_writew, NULL, dev);
dev->uhci_enable = 0;
mem_mapping_disable(&dev->ohci_mmio_mapping);
dev->ohci_enable = 0;
}
static void
usb_close(void *priv)
{
usb_t *dev = (usb_t *) priv;
free(dev);
}
static void *
usb_init(UNUSED(const device_t *info))
{
usb_t *dev;
dev = (usb_t *) malloc(sizeof(usb_t));
if (dev == NULL)
return (NULL);
memset(dev, 0x00, sizeof(usb_t));
memset(dev->uhci_io, 0x00, 128);
dev->uhci_io[0x0c] = 0x40;
dev->uhci_io[0x10] = dev->uhci_io[0x12] = 0x80;
memset(dev->ohci_mmio, 0x00, 4096);
dev->ohci_mmio[0x00] = 0x10;
dev->ohci_mmio[0x01] = 0x01;
dev->ohci_mmio[0x48] = 0x02;
mem_mapping_add(&dev->ohci_mmio_mapping, 0, 0,
ohci_mmio_read, NULL, NULL,
ohci_mmio_write, NULL, NULL,
NULL, MEM_MAPPING_EXTERNAL, dev);
usb_reset(dev);
return dev;
}
const device_t usb_device = {
.name = "Universal Serial Bus",
.internal_name = "usb",
.flags = DEVICE_PCI,
.local = 0,
.init = usb_init,
.close = usb_close,
.reset = usb_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/usb.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 4,330 |
```c
/*
* Generic FIFO component, implemented as a circular buffer.
*
*
* This program is free software; you can redistribute it and/or
* as published by the Free Software Foundation; either version
*
* with this program; if not, see <path_to_url
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <wchar.h>
#include <assert.h>
#include <86box/86box.h>
#include <86box/fifo8.h>
void
fifo8_reset(Fifo8 *fifo)
{
fifo->num = 0;
fifo->head = 0;
}
void
fifo8_create(Fifo8 *fifo, uint32_t capacity)
{
fifo->data = (uint8_t *) calloc(1, capacity);
fifo->capacity = capacity;
fifo8_reset(fifo);
}
void
fifo8_destroy(Fifo8 *fifo)
{
if (fifo->data) {
free(fifo->data);
fifo->data = NULL;
}
}
void
fifo8_push(Fifo8 *fifo, uint8_t data)
{
assert(fifo->num < fifo->capacity);
fifo->data[(fifo->head + fifo->num) % fifo->capacity] = data;
fifo->num++;
}
void
fifo8_push_all(Fifo8 *fifo, const uint8_t *data, uint32_t num)
{
uint32_t start;
uint32_t avail;
assert((fifo->num + num) <= fifo->capacity);
start = (fifo->head + fifo->num) % fifo->capacity;
if (start + num <= fifo->capacity) {
memcpy(&fifo->data[start], data, num);
} else {
avail = fifo->capacity - start;
memcpy(&fifo->data[start], data, avail);
memcpy(&fifo->data[0], &data[avail], num - avail);
}
fifo->num += num;
}
uint8_t
fifo8_pop(Fifo8 *fifo)
{
uint8_t ret;
assert(fifo->num > 0);
ret = fifo->data[fifo->head++];
fifo->head %= fifo->capacity;
fifo->num--;
return ret;
}
static const uint8_t
*fifo8_peekpop_buf(Fifo8 *fifo, uint32_t max, uint32_t *numptr, int do_pop)
{
uint8_t *ret;
uint32_t num;
assert((max > 0) && (max <= fifo->num));
num = MIN(fifo->capacity - fifo->head, max);
ret = &fifo->data[fifo->head];
if (do_pop) {
fifo->head += num;
fifo->head %= fifo->capacity;
fifo->num -= num;
}
if (numptr)
*numptr = num;
return ret;
}
const uint8_t
*fifo8_peek_bufptr(Fifo8 *fifo, uint32_t max, uint32_t *numptr)
{
return fifo8_peekpop_buf(fifo, max, numptr, 0);
}
const uint8_t
*fifo8_pop_bufptr(Fifo8 *fifo, uint32_t max, uint32_t *numptr)
{
return fifo8_peekpop_buf(fifo, max, numptr, 1);
}
uint32_t
fifo8_pop_buf(Fifo8 *fifo, uint8_t *dest, uint32_t destlen)
{
const uint8_t *buf;
uint32_t n1, n2 = 0;
uint32_t len;
if (destlen == 0)
return 0;
len = destlen;
buf = fifo8_pop_bufptr(fifo, len, &n1);
if (dest)
memcpy(dest, buf, n1);
/* Add FIFO wraparound if needed */
len -= n1;
len = MIN(len, fifo8_num_used(fifo));
if (len) {
buf = fifo8_pop_bufptr(fifo, len, &n2);
if (dest) {
memcpy(&dest[n1], buf, n2);
}
}
return n1 + n2;
}
void
fifo8_drop(Fifo8 *fifo, uint32_t len)
{
len -= fifo8_pop_buf(fifo, NULL, len);
assert(len == 0);
}
int
fifo8_is_empty(Fifo8 *fifo)
{
return (fifo->num == 0);
}
int
fifo8_is_full(Fifo8 *fifo)
{
return (fifo->num == fifo->capacity);
}
uint32_t
fifo8_num_free(Fifo8 *fifo)
{
return fifo->capacity - fifo->num;
}
uint32_t
fifo8_num_used(Fifo8 *fifo)
{
return fifo->num;
}
``` | /content/code_sandbox/src/fifo8.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,053 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* A better random number generation, used for floppy weak bits
* and network MAC address generation.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdint.h>
#include <stdlib.h>
#include <86box/random.h>
#if !(defined(__i386__) || defined(__x86_64__))
# include <time.h>
#endif
uint32_t preconst = 0x6ED9EBA1;
static __inline uint32_t
rotl32c(uint32_t x, uint32_t n)
{
#if 0
assert (n<32);
#endif
return (x << n) | (x >> (-n & 31));
}
static __inline uint32_t
rotr32c(uint32_t x, uint32_t n)
{
#if 0
assert (n<32);
#endif
return (x >> n) | (x << (-n & 31));
}
#define ROTATE_LEFT rotl32c
#define ROTATE_RIGHT rotr32c
static __inline unsigned long long
rdtsc(void)
{
#if defined(__i386__) || defined(__x86_64__)
unsigned int hi;
unsigned int lo;
# ifdef _MSC_VER
__asm {
rdtsc
mov hi, edx ; EDX:EAX is already standard return!!
mov lo, eax
}
# else
__asm__ __volatile__("rdtsc"
: "=a"(lo), "=d"(hi));
# endif
return ((unsigned long long) lo) | (((unsigned long long) hi) << 32);
#else
return time(NULL);
#endif
}
static uint32_t
RDTSC(void)
{
return (uint32_t) (rdtsc());
}
static void
random_twist(uint32_t *val)
{
*val = ROTATE_LEFT(*val, rand() % 32);
*val ^= 0x5A827999;
*val = ROTATE_RIGHT(*val, rand() % 32);
*val ^= 0x4ED32706;
}
uint8_t
random_generate(void)
{
uint16_t r = 0;
r = (RDTSC() ^ ROTATE_LEFT(preconst, rand() % 32)) % 256;
random_twist(&preconst);
return (r & 0xff);
}
void
random_init(void)
{
uint32_t seed = RDTSC();
srand(seed);
return;
}
``` | /content/code_sandbox/src/random.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 614 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Intel UPI-42/MCS-48 microcontroller emulation.
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <86box/plat_unused.h>
#ifdef UPI42_STANDALONE
# define fatal(...) \
{ \
upi42_log(__VA_ARGS__); \
abort(); \
}
# define upi42_log(...) \
{ \
printf(__VA_ARGS__); \
fflush(stdout); \
}
#else
# include <stdarg.h>
# define HAVE_STDARG_H
# include <86box/86box.h>
# include <86box/device.h>
# include <86box/io.h>
# include <86box/timer.h>
# ifdef ENABLE_UPI42_LOG
int upi42_do_log = ENABLE_UPI42_LOG;
void
upi42_log(const char *fmt, ...)
{
va_list ap;
if (upi42_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
# else
# define upi42_log(fmt, ...)
# endif
#endif
#define UPI42_REG(upi42, r, op) ((upi42->psw & 0x10) ? (upi42->ram[24 + ((r) &7)] op) : (upi42->ram[(r) &7] op))
#define UPI42_ROM_SHIFT 0 /* actually the mask */
#define UPI42_RAM_SHIFT 16 /* actually the mask */
#define UPI42_TYPE_MCS (0 << 24)
#define UPI42_TYPE_UPI (1 << 24)
#define UPI42_EXT_C42 (1 << 25)
#define UPI42_8048 ((1023 << UPI42_ROM_SHIFT) | (63 << UPI42_RAM_SHIFT) | UPI42_TYPE_MCS)
#define UPI42_8049 ((2047 << UPI42_ROM_SHIFT) | (127 << UPI42_RAM_SHIFT) | UPI42_TYPE_MCS)
#define UPI42_8041 ((1023 << UPI42_ROM_SHIFT) | (127 << UPI42_RAM_SHIFT) | UPI42_TYPE_UPI)
#define UPI42_8042 ((2047 << UPI42_ROM_SHIFT) | (255 << UPI42_RAM_SHIFT) | UPI42_TYPE_UPI)
#define UPI42_80C42 ((4095 << UPI42_ROM_SHIFT) | (255 << UPI42_RAM_SHIFT) | UPI42_TYPE_UPI | UPI42_EXT_C42)
typedef struct _upi42_ {
int (*ops[256])(struct _upi42_ *upi42, uint32_t fetchdat);
uint32_t type;
uint8_t ram[256], *rom, /* memory */
ports_in[8], ports_out[8], /* I/O ports */
dbb_in, dbb_out; /* UPI-42 data buffer */
uint8_t rammask, /* RAM mask */
a, /* accumulator */
t, /* timer counter */
psw, /* program status word */
sts; /* UPI-42 status */
uint16_t pc, rommask; /* program counter and ROM mask */
unsigned int prescaler : 5, tf : 1, skip_timer_inc : 1, /* timer/counter */
run_timer : 1, run_counter : 1, tcnti : 1, /* timer/counter enables */
i : 1, i_raise : 1, tcnti_raise : 1, irq_mask : 1, /* interrupts */
t0 : 1, t1 : 1, /* T0/T1 signals */
flags : 1, dbf : 1, suspend : 1; /* UPI-42 flags */
int cycs; /* cycle counter */
#ifndef UPI42_STANDALONE
uint8_t ram_index;
uint16_t rom_index;
#endif
} upi42_t;
static inline void
upi42_mirror_f0(upi42_t *upi42)
{
/* Update status register F0 flag to match PSW F0 flag. */
upi42->sts = ((upi42->psw & 0x20) >> 3) | (upi42->sts & ~0x04);
}
static int
upi42_op_MOV_A_Rr(upi42_t *upi42, uint32_t fetchdat)
{
upi42->a = UPI42_REG(upi42, fetchdat, );
return 1;
}
static int
upi42_op_MOV_Rr_A(upi42_t *upi42, uint32_t fetchdat)
{
UPI42_REG(upi42, fetchdat, = upi42->a);
return 1;
}
static int
upi42_op_MOV_A_indRr(upi42_t *upi42, uint32_t fetchdat)
{
upi42->a = upi42->ram[upi42->ram[fetchdat & 1] & upi42->rammask];
return 1;
}
static int
upi42_op_MOV_indRr_A(upi42_t *upi42, uint32_t fetchdat)
{
upi42->ram[upi42->ram[fetchdat & 1] & upi42->rammask] = upi42->a;
return 1;
}
static int
upi42_op_MOV_Rr_imm(upi42_t *upi42, uint32_t fetchdat)
{
UPI42_REG(upi42, fetchdat, = fetchdat >> 8);
upi42->cycs--;
return 2;
}
static int
upi42_op_MOV_indRr_imm(upi42_t *upi42, uint32_t fetchdat)
{
upi42->ram[upi42->ram[fetchdat & 1] & upi42->rammask] = fetchdat >> 8;
upi42->cycs--;
return 2;
}
static int
upi42_op_MOV_A_imm(upi42_t *upi42, uint32_t fetchdat)
{
upi42->a = fetchdat >> 8;
upi42->cycs--;
return 2;
}
static int
upi42_op_MOV_A_PSW(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->a = upi42->psw;
upi42_mirror_f0(upi42);
return 1;
}
static int
upi42_op_MOV_PSW_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->psw = upi42->a;
upi42_mirror_f0(upi42);
return 1;
}
static int
upi42_op_MOV_A_T(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->a = upi42->t;
return 1;
}
static int
upi42_op_MOV_T_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->t = upi42->a;
return 1;
}
static int
upi42_op_MOV_STS_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->sts = (upi42->a & 0xf0) | (upi42->sts & 0x0f);
return 1;
}
static int
upi42_op_MOVP_A_indA(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->a = upi42->rom[(upi42->pc & 0xff00) | upi42->a];
upi42->cycs--;
return 1;
}
static int
upi42_op_MOVP3_A_indA(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->a = upi42->rom[0x300 | upi42->a];
upi42->cycs--;
return 1;
}
static int
upi42_op_XCH_A_Rr(upi42_t *upi42, uint32_t fetchdat)
{
uint8_t temp = upi42->a;
upi42->a = UPI42_REG(upi42, fetchdat, );
UPI42_REG(upi42, fetchdat, = temp);
return 1;
}
static int
upi42_op_XCH_A_indRr(upi42_t *upi42, uint32_t fetchdat)
{
uint8_t temp = upi42->a;
uint8_t addr = upi42->ram[fetchdat & 1] & upi42->rammask;
upi42->a = upi42->ram[addr];
upi42->ram[addr] = temp;
return 1;
}
static int
upi42_op_XCHD_A_indRr(upi42_t *upi42, uint32_t fetchdat)
{
uint8_t temp = upi42->a;
uint8_t addr = upi42->ram[fetchdat & 1] & upi42->rammask;
upi42->a = (upi42->a & 0xf0) | (upi42->ram[addr] & 0x0f);
upi42->ram[addr] = (upi42->ram[addr] & 0xf0) | (temp & 0x0f);
return 1;
}
static int
upi42_op_SWAP_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->a = (upi42->a << 4) | (upi42->a >> 4);
return 1;
}
static int
upi42_op_IN_A_Pp(upi42_t *upi42, uint32_t fetchdat)
{
int port = fetchdat & 3;
upi42->a = upi42->ports_in[port] & upi42->ports_out[port];
upi42->cycs--;
return 1;
}
static int
upi42_op_IN_A_DBB(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->a = upi42->dbb_in;
upi42->sts &= ~0x02; /* clear IBF */
return 1;
}
static int
upi42_op_OUTL_Pp_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->ports_out[fetchdat & 3] = upi42->a;
upi42->cycs--;
return 1;
}
static int
upi42_op_OUT_DBB_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->dbb_out = upi42->a;
upi42->sts |= 0x01; /* set OBF */
return 1;
}
static int
upi42_op_MOVD_A_Pp(upi42_t *upi42, uint32_t fetchdat)
{
int port = 4 | (fetchdat & 3);
upi42->a = (upi42->ports_in[port] & upi42->ports_out[port]) & 0x0f;
upi42->cycs--;
return 1;
}
static int
upi42_op_MOVD_Pp_A(upi42_t *upi42, uint32_t fetchdat)
{
upi42->ports_out[4 | (fetchdat & 3)] = upi42->a & 0x0f;
upi42->cycs--;
return 1;
}
static int
upi42_op_ANL_A_Rr(upi42_t *upi42, uint32_t fetchdat)
{
upi42->a &= UPI42_REG(upi42, fetchdat, );
return 1;
}
static int
upi42_op_ORL_A_Rr(upi42_t *upi42, uint32_t fetchdat)
{
upi42->a |= UPI42_REG(upi42, fetchdat, );
return 1;
}
static int
upi42_op_XRL_A_Rr(upi42_t *upi42, uint32_t fetchdat)
{
upi42->a ^= UPI42_REG(upi42, fetchdat, );
return 1;
}
static int
upi42_op_ANL_A_indRr(upi42_t *upi42, uint32_t fetchdat)
{
upi42->a &= upi42->ram[upi42->ram[fetchdat & 1] & upi42->rammask];
return 1;
}
static int
upi42_op_ORL_A_indRr(upi42_t *upi42, uint32_t fetchdat)
{
upi42->a |= upi42->ram[upi42->ram[fetchdat & 1] & upi42->rammask];
return 1;
}
static int
upi42_op_XRL_A_indRr(upi42_t *upi42, uint32_t fetchdat)
{
upi42->a ^= upi42->ram[upi42->ram[fetchdat & 1] & upi42->rammask];
return 1;
}
static int
upi42_op_ANL_A_imm(upi42_t *upi42, uint32_t fetchdat)
{
upi42->a &= fetchdat >> 8;
upi42->cycs--;
return 2;
}
static int
upi42_op_ORL_A_imm(upi42_t *upi42, uint32_t fetchdat)
{
upi42->a |= fetchdat >> 8;
upi42->cycs--;
return 2;
}
static int
upi42_op_XRL_A_imm(upi42_t *upi42, uint32_t fetchdat)
{
upi42->a ^= fetchdat >> 8;
upi42->cycs--;
return 2;
}
static int
upi42_op_ANL_Pp_imm(upi42_t *upi42, uint32_t fetchdat)
{
upi42->ports_out[fetchdat & 3] &= fetchdat >> 8;
upi42->cycs--;
return 2;
}
static int
upi42_op_ORL_Pp_imm(upi42_t *upi42, uint32_t fetchdat)
{
upi42->ports_out[fetchdat & 3] |= fetchdat >> 8;
upi42->cycs--;
return 2;
}
static int
upi42_op_ANLD_Pp_A(upi42_t *upi42, uint32_t fetchdat)
{
upi42->ports_out[4 | (fetchdat & 3)] &= upi42->a;
upi42->cycs--;
return 1;
}
static int
upi42_op_ORLD_Pp_A(upi42_t *upi42, uint32_t fetchdat)
{
upi42->ports_out[4 | (fetchdat & 3)] |= upi42->a;
upi42->cycs--;
return 1;
}
static int
upi42_op_RR_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->a = (upi42->a << 7) | (upi42->a >> 1);
return 1;
}
static int
upi42_op_RL_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->a = (upi42->a >> 7) | (upi42->a << 1);
return 1;
}
static int
upi42_op_RRC_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
uint8_t temp = upi42->a;
upi42->a = (upi42->psw & 0x80) | (temp >> 1);
upi42->psw = (temp << 7) | (upi42->psw & ~0x80);
return 1;
}
static int
upi42_op_RLC_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
uint8_t temp = upi42->a;
upi42->a = (temp << 1) | (upi42->psw >> 7);
upi42->psw = (temp & 0x80) | (upi42->psw & ~0x80);
return 1;
}
static int
upi42_op_INC_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->a++;
return 1;
}
static int
upi42_op_INC_Rr(upi42_t *upi42, uint32_t fetchdat)
{
UPI42_REG(upi42, fetchdat, ++);
return 1;
}
static int
upi42_op_INC_indRr(upi42_t *upi42, uint32_t fetchdat)
{
upi42->ram[upi42->ram[fetchdat & 1] & upi42->rammask]++;
return 1;
}
static int
upi42_op_DEC_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->a--;
return 1;
}
static int
upi42_op_DEC_Rr(upi42_t *upi42, uint32_t fetchdat)
{
UPI42_REG(upi42, fetchdat, --);
return 1;
}
static int
upi42_op_DJNZ_Rr_imm(upi42_t *upi42, uint32_t fetchdat)
{
upi42->cycs--;
UPI42_REG(upi42, fetchdat, --);
if (UPI42_REG(upi42, fetchdat, )) {
upi42->pc = (upi42->pc & 0xff00) | ((fetchdat >> 8) & 0xff);
return 0;
} else {
return 2;
}
}
static int
upi42_op_ADD_A_Rr(upi42_t *upi42, uint32_t fetchdat)
{
int res = upi42->a + UPI42_REG(upi42, fetchdat, );
upi42->a = res;
upi42->psw = ((res >> 1) & 0x80) | (upi42->psw & ~0x80);
return 1;
}
static int
upi42_op_ADDC_A_Rr(upi42_t *upi42, uint32_t fetchdat)
{
int res = upi42->a + (upi42->psw >> 7) + UPI42_REG(upi42, fetchdat, );
upi42->a = res;
upi42->psw = ((res >> 1) & 0x80) | (upi42->psw & ~0x80);
return 1;
}
static int
upi42_op_ADD_A_indRr(upi42_t *upi42, uint32_t fetchdat)
{
int res = upi42->a + upi42->ram[UPI42_REG(upi42, fetchdat, ) & upi42->rammask];
upi42->a = res;
upi42->psw = ((res >> 1) & 0x80) | (upi42->psw & ~0x80);
return 1;
}
static int
upi42_op_ADDC_A_indRr(upi42_t *upi42, uint32_t fetchdat)
{
int res = upi42->a + (upi42->psw >> 7) + upi42->ram[UPI42_REG(upi42, fetchdat, ) & upi42->rammask];
upi42->a = res;
upi42->psw = ((res >> 1) & 0x80) | (upi42->psw & ~0x80);
return 1;
}
static int
upi42_op_ADD_A_imm(upi42_t *upi42, uint32_t fetchdat)
{
int res = upi42->a + (fetchdat >> 8);
upi42->a = res;
upi42->psw = ((res >> 1) & 0x80) | (upi42->psw & ~0x80);
upi42->cycs--;
return 2;
}
static int
upi42_op_ADDC_A_imm(upi42_t *upi42, uint32_t fetchdat)
{
int res = upi42->a + (upi42->psw >> 7) + (fetchdat >> 8);
upi42->a = res;
upi42->psw = ((res >> 1) & 0x80) | (upi42->psw & ~0x80);
upi42->cycs--;
return 2;
}
static int
upi42_op_CLR_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->a = 0;
return 1;
}
static int
upi42_op_CPL_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->a = ~upi42->a;
return 1;
}
static int
upi42_op_DA_A(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
if (((upi42->a & 0x0f) > 9) || (upi42->psw & 0x40))
upi42->a += 6;
if (((upi42->a >> 4) > 9) || (upi42->psw & 0x80)) {
int res = upi42->a + (6 << 4);
upi42->a = res;
upi42->psw = ((res >> 1) & 0x80) | (upi42->psw & ~0x80);
}
return 1;
}
static int
upi42_op_CLR_C(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->psw &= ~0x80;
return 1;
}
static int
upi42_op_CPL_C(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->psw ^= 0x80;
return 1;
}
static int
upi42_op_CLR_F0(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->psw &= ~0x20;
upi42_mirror_f0(upi42);
return 1;
}
static int
upi42_op_CPL_F0(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->psw ^= 0x20;
upi42_mirror_f0(upi42);
return 1;
}
static int
upi42_op_CLR_F1(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->sts &= ~0x08;
return 1;
}
static int
upi42_op_CPL_F1(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->sts ^= 0x08;
return 1;
}
static int
upi42_op_EN_I(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->i = 1;
upi42->skip_timer_inc = 1;
return 1;
}
static int
upi42_op_DIS_I(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->i = 0;
upi42->skip_timer_inc = 1;
return 1;
}
static int
upi42_op_EN_TCNTI(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->tcnti = 1;
return 1;
}
static int
upi42_op_DIS_TCNTI(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->tcnti = upi42->tcnti_raise = 0;
return 1;
}
static int
upi42_op_STRT_T(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->run_timer = 1;
upi42->prescaler = 0;
upi42->skip_timer_inc = 1;
return 1;
}
static int
upi42_op_STRT_CNT(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->run_counter = 1;
upi42->skip_timer_inc = 1;
return 1;
}
static int
upi42_op_STOP_TCNT(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->run_timer = upi42->run_counter = 0;
upi42->skip_timer_inc = 1;
return 1;
}
static int
upi42_op_SEL_PMB0(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->dbf = 0;
return 1;
}
static int
upi42_op_SEL_PMB1(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->dbf = 1;
return 1;
}
static int
upi42_op_SEL_RB0(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->psw &= ~0x10;
return 1;
}
static int
upi42_op_SEL_RB1(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->psw |= 0x10;
return 1;
}
static int
upi42_op_NOP(UNUSED(upi42_t *upi42), UNUSED(uint32_t fetchdat))
{
return 1;
}
static int
upi42_op_CALL_imm(upi42_t *upi42, uint32_t fetchdat)
{
/* Push new frame onto stack. */
uint8_t sp = (upi42->psw & 0x07) << 1;
upi42->ram[8 + sp++] = upi42->pc + 2; /* stack frame format is undocumented! */
upi42->ram[8 + sp++] = (upi42->psw & 0xf0) | ((upi42->pc >> 8) & 0x07);
upi42->psw = (upi42->psw & 0xf8) | (sp >> 1);
/* Load new program counter. */
upi42->pc = (upi42->dbf << 11) | ((fetchdat << 3) & 0x0700) | ((fetchdat >> 8) & 0x00ff);
upi42->cycs--;
return 0;
}
static int
upi42_op_RET(upi42_t *upi42, uint32_t fetchdat)
{
/* Pop frame off the stack. */
uint8_t sp = (upi42->psw & 0x07) << 1;
uint8_t frame1 = upi42->ram[8 + --sp];
uint8_t frame0 = upi42->ram[8 + --sp];
upi42->psw = (upi42->psw & 0xf8) | (sp >> 1);
/* Load new program counter. */
upi42->pc = ((frame1 & 0x0f) << 8) | frame0;
/* Load new Program Status Word and unmask interrupts if this is RETR. */
if (fetchdat & 0x10) {
upi42->psw = (frame1 & 0xf0) | (upi42->psw & 0x0f);
upi42_mirror_f0(upi42);
upi42->irq_mask = 0;
}
upi42->cycs--;
return 0;
}
static int
upi42_op_JMP_imm(upi42_t *upi42, uint32_t fetchdat)
{
upi42->pc = (upi42->dbf << 11) | ((fetchdat << 3) & 0x0700) | ((fetchdat >> 8) & 0x00ff);
upi42->cycs--;
return 0;
}
static int
upi42_op_JMPP_indA(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->pc = (upi42->pc & 0xff00) | upi42->a;
upi42->cycs--;
return 0;
}
#define UPI42_COND_JMP_IMM(insn, cond, post) \
static int \
upi42_op_##insn##_imm(upi42_t *upi42, uint32_t fetchdat) \
{ \
if (cond) \
upi42->pc = (upi42->pc & 0xff00) | ((fetchdat >> 8) & 0x00ff); \
post; \
upi42->cycs--; \
return 2 * !(cond); \
}
UPI42_COND_JMP_IMM(JC, upi42->psw & 0x80, )
UPI42_COND_JMP_IMM(JNC, !(upi42->psw & 0x80), )
UPI42_COND_JMP_IMM(JZ, !upi42->a, )
UPI42_COND_JMP_IMM(JNZ, upi42->a, )
UPI42_COND_JMP_IMM(JT0, upi42->t0, )
UPI42_COND_JMP_IMM(JNT0, !upi42->t0, )
UPI42_COND_JMP_IMM(JT1, upi42->t1, )
UPI42_COND_JMP_IMM(JNT1, !upi42->t1, )
UPI42_COND_JMP_IMM(JF0, upi42->psw & 0x20, )
UPI42_COND_JMP_IMM(JF1, upi42->sts & 0x08, )
UPI42_COND_JMP_IMM(JTF, !upi42->tf, upi42->tf = 0)
UPI42_COND_JMP_IMM(JBb, upi42->a & (1 << ((fetchdat >> 5) & 7)), )
UPI42_COND_JMP_IMM(JNIBF, !(upi42->sts & 0x02), )
UPI42_COND_JMP_IMM(JOBF, upi42->sts & 0x01, )
static int
upi42_op_EN_A20(UNUSED(upi42_t *upi42), UNUSED(uint32_t fetchdat))
{
/* Enable fast A20 until reset. */
return 1;
}
static int
upi42_op_EN_DMA(UNUSED(upi42_t *upi42), UNUSED(uint32_t fetchdat))
{
return 1;
}
static int
upi42_op_EN_FLAGS(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
upi42->flags = 1;
return 1;
}
static int
upi42_op_SUSPEND(upi42_t *upi42, UNUSED(uint32_t fetchdat))
{
/* Inhibit execution until reset. */
upi42->suspend = 1;
return 1;
}
static const int (*ops_80c42[256])(upi42_t *upi42, uint32_t fetchdat) = {
// clang-format off
/* 0 / 8 */ /* 1 / 9 */ /* 2 / a */ /* 3 / b */ /* 4 / c */ /* 5 / d */ /* 6 / e */ /* 7 / f */
/* 00 */ upi42_op_NOP, NULL, upi42_op_OUT_DBB_A, upi42_op_ADD_A_imm, upi42_op_JMP_imm, upi42_op_EN_I, NULL, upi42_op_DEC_A,
/* 08 */ upi42_op_IN_A_Pp, upi42_op_IN_A_Pp, upi42_op_IN_A_Pp, NULL, upi42_op_MOVD_A_Pp, upi42_op_MOVD_A_Pp, upi42_op_MOVD_A_Pp, upi42_op_MOVD_A_Pp,
/* 10 */ upi42_op_INC_indRr, upi42_op_INC_indRr, upi42_op_JBb_imm, upi42_op_ADDC_A_imm, upi42_op_CALL_imm, upi42_op_DIS_I, upi42_op_JTF_imm, upi42_op_INC_A,
/* 18 */ upi42_op_INC_Rr, upi42_op_INC_Rr, upi42_op_INC_Rr, upi42_op_INC_Rr, upi42_op_INC_Rr, upi42_op_INC_Rr, upi42_op_INC_Rr, upi42_op_INC_Rr,
/* 20 */ upi42_op_XCH_A_indRr, upi42_op_XCH_A_indRr, upi42_op_IN_A_DBB, upi42_op_MOV_A_imm, upi42_op_JMP_imm, upi42_op_EN_TCNTI, upi42_op_JNT0_imm, upi42_op_CLR_A,
/* 28 */ upi42_op_XCH_A_Rr, upi42_op_XCH_A_Rr, upi42_op_XCH_A_Rr, upi42_op_XCH_A_Rr, upi42_op_XCH_A_Rr, upi42_op_XCH_A_Rr, upi42_op_XCH_A_Rr, upi42_op_XCH_A_Rr,
/* 30 */ upi42_op_XCHD_A_indRr, upi42_op_XCHD_A_indRr, upi42_op_JBb_imm, upi42_op_EN_A20, upi42_op_CALL_imm, upi42_op_DIS_TCNTI, upi42_op_JT0_imm, upi42_op_CPL_A,
/* 38 */ upi42_op_OUTL_Pp_A, upi42_op_OUTL_Pp_A, upi42_op_OUTL_Pp_A, upi42_op_OUTL_Pp_A, upi42_op_MOVD_Pp_A, upi42_op_MOVD_Pp_A, upi42_op_MOVD_Pp_A, upi42_op_MOVD_Pp_A,
/* 40 */ upi42_op_ORL_A_indRr, upi42_op_ORL_A_indRr, upi42_op_MOV_A_T, upi42_op_ORL_A_imm, upi42_op_JMP_imm, upi42_op_STRT_CNT, upi42_op_JNT1_imm, upi42_op_SWAP_A,
/* 48 */ upi42_op_ORL_A_Rr, upi42_op_ORL_A_Rr, upi42_op_ORL_A_Rr, upi42_op_ORL_A_Rr, upi42_op_ORL_A_Rr, upi42_op_ORL_A_Rr, upi42_op_ORL_A_Rr, upi42_op_ORL_A_Rr,
/* 50 */ upi42_op_ANL_A_indRr, upi42_op_ANL_A_indRr, upi42_op_JBb_imm, upi42_op_ANL_A_imm, upi42_op_CALL_imm, upi42_op_STRT_T, upi42_op_JT1_imm, upi42_op_DA_A,
/* 58 */ upi42_op_ANL_A_Rr, upi42_op_ANL_A_Rr, upi42_op_ANL_A_Rr, upi42_op_ANL_A_Rr, upi42_op_ANL_A_Rr, upi42_op_ANL_A_Rr, upi42_op_ANL_A_Rr, upi42_op_ANL_A_Rr,
/* 60 */ upi42_op_ADD_A_indRr, upi42_op_ADD_A_indRr, upi42_op_MOV_T_A, upi42_op_SEL_PMB0, upi42_op_JMP_imm, upi42_op_STOP_TCNT, NULL, upi42_op_RRC_A,
/* 68 */ upi42_op_ADD_A_Rr, upi42_op_ADD_A_Rr, upi42_op_ADD_A_Rr, upi42_op_ADD_A_Rr, upi42_op_ADD_A_Rr, upi42_op_ADD_A_Rr, upi42_op_ADD_A_Rr, upi42_op_ADD_A_Rr,
/* 70 */ upi42_op_ADDC_A_indRr, upi42_op_ADDC_A_indRr, upi42_op_JBb_imm, upi42_op_SEL_PMB1, upi42_op_CALL_imm, NULL, upi42_op_JF1_imm, upi42_op_RR_A,
/* 78 */ upi42_op_ADDC_A_Rr, upi42_op_ADDC_A_Rr, upi42_op_ADDC_A_Rr, upi42_op_ADDC_A_Rr, upi42_op_ADDC_A_Rr, upi42_op_ADDC_A_Rr, upi42_op_ADDC_A_Rr, upi42_op_ADDC_A_Rr,
/* 80 */ NULL, NULL, upi42_op_SUSPEND, upi42_op_RET, upi42_op_JMP_imm, upi42_op_CLR_F0, upi42_op_JOBF_imm, NULL,
/* 88 */ upi42_op_ORL_Pp_imm, upi42_op_ORL_Pp_imm, upi42_op_ORL_Pp_imm, upi42_op_ORL_Pp_imm, upi42_op_ORLD_Pp_A, upi42_op_ORLD_Pp_A, upi42_op_ORLD_Pp_A, upi42_op_ORLD_Pp_A,
/* 90 */ upi42_op_MOV_STS_A, NULL, upi42_op_JBb_imm, upi42_op_RET, upi42_op_CALL_imm, upi42_op_CPL_F0, upi42_op_JNZ_imm, upi42_op_CLR_C,
/* 98 */ upi42_op_ANL_Pp_imm, upi42_op_ANL_Pp_imm, upi42_op_ANL_Pp_imm, upi42_op_ANL_Pp_imm, upi42_op_ANLD_Pp_A, upi42_op_ANLD_Pp_A, upi42_op_ANLD_Pp_A, upi42_op_ANLD_Pp_A,
/* a0 */ upi42_op_MOV_indRr_A, upi42_op_MOV_indRr_A, NULL, upi42_op_MOVP_A_indA, upi42_op_JMP_imm, upi42_op_CLR_F1, NULL, upi42_op_CPL_C,
/* a8 */ upi42_op_MOV_Rr_A, upi42_op_MOV_Rr_A, upi42_op_MOV_Rr_A, upi42_op_MOV_Rr_A, upi42_op_MOV_Rr_A, upi42_op_MOV_Rr_A, upi42_op_MOV_Rr_A, upi42_op_MOV_Rr_A,
/* b0 */ upi42_op_MOV_indRr_imm,upi42_op_MOV_indRr_imm,upi42_op_JBb_imm, upi42_op_JMPP_indA, upi42_op_CALL_imm, upi42_op_CPL_F1, upi42_op_JF0_imm, NULL,
/* b8 */ upi42_op_MOV_Rr_imm, upi42_op_MOV_Rr_imm, upi42_op_MOV_Rr_imm, upi42_op_MOV_Rr_imm, upi42_op_MOV_Rr_imm, upi42_op_MOV_Rr_imm, upi42_op_MOV_Rr_imm, upi42_op_MOV_Rr_imm,
/* c0 */ NULL, NULL, NULL, NULL, upi42_op_JMP_imm, NULL, upi42_op_JZ_imm, upi42_op_MOV_A_PSW,
/* c8 */ upi42_op_DEC_Rr, upi42_op_DEC_Rr, upi42_op_DEC_Rr, upi42_op_DEC_Rr, upi42_op_DEC_Rr, upi42_op_DEC_Rr, upi42_op_DEC_Rr, upi42_op_DEC_Rr,
/* d0 */ upi42_op_XRL_A_indRr, upi42_op_XRL_A_indRr, upi42_op_JBb_imm, upi42_op_XRL_A_imm, upi42_op_CALL_imm, NULL, upi42_op_JNIBF_imm, upi42_op_MOV_PSW_A,
/* d8 */ upi42_op_XRL_A_Rr, upi42_op_XRL_A_Rr, upi42_op_XRL_A_Rr, upi42_op_XRL_A_Rr, upi42_op_XRL_A_Rr, upi42_op_XRL_A_Rr, upi42_op_XRL_A_Rr, upi42_op_XRL_A_Rr,
/* e0 */ NULL, NULL, upi42_op_SUSPEND, upi42_op_MOVP3_A_indA, upi42_op_JMP_imm, upi42_op_EN_DMA, upi42_op_JNC_imm, upi42_op_RL_A,
/* e8 */ upi42_op_DJNZ_Rr_imm, upi42_op_DJNZ_Rr_imm, upi42_op_DJNZ_Rr_imm, upi42_op_DJNZ_Rr_imm, upi42_op_DJNZ_Rr_imm, upi42_op_DJNZ_Rr_imm, upi42_op_DJNZ_Rr_imm, upi42_op_DJNZ_Rr_imm,
/* f0 */ upi42_op_MOV_A_indRr, upi42_op_MOV_A_indRr, upi42_op_JBb_imm, NULL, upi42_op_CALL_imm, upi42_op_EN_FLAGS, upi42_op_JC_imm, upi42_op_RLC_A,
/* f8 */ upi42_op_MOV_A_Rr, upi42_op_MOV_A_Rr, upi42_op_MOV_A_Rr, upi42_op_MOV_A_Rr, upi42_op_MOV_A_Rr, upi42_op_MOV_A_Rr, upi42_op_MOV_A_Rr, upi42_op_MOV_A_Rr
// clang-format on
};
static void
upi42_exec(void *priv)
{
upi42_t *upi42 = (upi42_t *) priv;
/* Skip everything if we're suspended, or just process timer if we're in a multi-cycle instruction. */
if (upi42->suspend)
return;
else if (++upi42->cycs < 0)
goto timer;
/* Trigger interrupt if requested. */
if (upi42->irq_mask) {
/* Masked, we're currently in an ISR. */
} else if (upi42->i_raise) {
/* External interrupt. Higher priority than the timer interrupt. */
upi42->irq_mask = 1;
upi42->i_raise = 0;
upi42->pc -= 2;
upi42->cycs++;
upi42_op_CALL_imm(upi42, 3 << 8);
return;
} else if (upi42->tcnti_raise) {
/* Timer interrupt. */
upi42->irq_mask = 1;
upi42->tcnti_raise = 0;
upi42->pc -= 2;
upi42->cycs++;
upi42_op_CALL_imm(upi42, 7 << 8);
return;
}
/* Fetch instruction. */
uint32_t fetchdat = *((uint32_t *) &upi42->rom[upi42->pc]);
/* Decode instruction. */
uint8_t insn = fetchdat & 0xff;
if (upi42->ops[insn]) {
/* Execute instruction. */
int pc_inc = upi42->ops[insn](upi42, fetchdat);
/* Increment lower 11 bits of the program counter. */
upi42->pc = (upi42->pc & 0xf800) | ((upi42->pc + pc_inc) & 0x07ff);
/* Decrement cycle counter. Multi-cycle instructions also decrement within their code. */
upi42->cycs--;
} else {
fatal("UPI42: Unknown opcode %02X (%08X)\n", insn, fetchdat);
return;
}
timer:
/* Process timer. */
if (!upi42->run_timer) {
/* Timer disabled. */
} else if (upi42->skip_timer_inc) {
/* Some instructions don't increment the timer. */
upi42->skip_timer_inc = 0;
} else {
/* Increment counter once the prescaler overflows,
and set timer flag once the main value overflows. */
if ((++upi42->prescaler == 0) && (++upi42->t == 0)) {
upi42->tf = 1;
/* Fire counter interrupt if enabled. */
if (upi42->tcnti)
upi42->tcnti_raise = 1;
}
}
}
uint8_t
upi42_port_read(void *priv, int port)
{
const upi42_t *upi42 = (upi42_t *) priv;
/* Read base port value. */
port &= 7;
uint8_t ret = upi42->ports_in[port] & upi42->ports_out[port];
/* Apply special meanings. */
switch (port) {
default:
break;
}
upi42_log("UPI42: port_read(%d) = %02X\n", port, ret);
return ret;
}
void
upi42_port_write(void *priv, int port, uint8_t val)
{
upi42_t *upi42 = (upi42_t *) priv;
port &= 7;
upi42_log("UPI42: port_write(%d, %02X)\n", port, val);
/* Set input level. */
upi42->ports_in[port] = val;
}
/* NOTE: The dbb/sts/cmd functions use I/O handler signatures; port is ignored. */
uint8_t
upi42_dbb_read(UNUSED(uint16_t port), void *priv)
{
upi42_t *upi42 = (upi42_t *) priv;
uint8_t ret = upi42->dbb_out;
upi42_log("UPI42: dbb_read(%04X) = %02X\n", port, ret);
upi42->sts &= ~0x01; /* clear OBF */
return ret;
}
void
upi42_dbb_write(UNUSED(uint16_t port), uint8_t val, void *priv)
{
upi42_t *upi42 = (upi42_t *) priv;
upi42_log("UPI42: dbb_write(%04X, %02X)\n", port, val);
upi42->dbb_in = val;
upi42->sts = (upi42->sts & ~0x08) | 0x02; /* clear F1 and set IBF */
if (upi42->i) /* fire IBF interrupt if enabled */
upi42->i_raise = 1;
}
uint8_t
upi42_sts_read(UNUSED(uint16_t port), void *priv)
{
const upi42_t *upi42 = (upi42_t *) priv;
uint8_t ret = upi42->sts;
upi42_log("UPI42: sts_read(%04X) = %02X\n", port, ret);
return ret;
}
void
upi42_cmd_write(UNUSED(uint16_t port), uint8_t val, void *priv)
{
upi42_t *upi42 = (upi42_t *) priv;
upi42_log("UPI42: cmd_write(%04X, %02X)\n", port, val);
upi42->dbb_in = val;
upi42->sts |= 0x0a; /* set F1 and IBF */
if (upi42->i) /* fire IBF interrupt if enabled */
upi42->i_raise = 1;
}
void
upi42_reset(upi42_t *upi42)
{
upi42->pc = 0; /* program counter */
upi42->psw = 0; /* stack pointer, register bank and F0 */
upi42->dbf = 0; /* ROM bank */
upi42->i = 0; /* external interrupt */
upi42->tcnti = 0; /* timer/counter interrupt */
upi42->tf = 0; /* timer flag */
upi42->sts = 0; /* F1 */
upi42->flags = 0; /* UPI-42 buffer interrupts */
upi42->suspend = 0; /* 80C42 suspend flag */
}
void
upi42_do_init(upi32_t type, uint8_t *rom)
{
memset(upi42, 0x00, sizeof(upi42_t));
upi42->rom = rom;
/* Set chip type. */
upi42->type = type;
upi42->rommask = type >> UPI42_ROM_SHIFT;
upi42->rammask = type >> UPI42_RAM_SHIFT;
/* Build instruction table. */
memcpy(upi42->ops, ops_80c42, sizeof(ops_80c42));
if (!(type & UPI42_EXT_C42)) {
/* Remove 80C42-only instructions. */
upi42->ops[0x33] = NULL; /* EN A20 */
upi42->ops[0x63] = NULL; /* SEL PMB0 */
upi42->ops[0x73] = NULL; /* SEL PMB1 */
upi42->ops[0x42] = NULL; /* SUSPEND */
upi42->ops[0xe2] = NULL; /* SUSPEND */
}
memset(upi42_t->ports_in, 0xff, sizeof(upi42_t->ports_in));
upi42_t->t0 = 1;
upi42_t->t1 = 1;
}
void *
upi42_init(uint32_t type, uint8_t *rom)
{
/* Allocate state structure. */
upi42_t *upi42 = (upi42_t *) malloc(sizeof(upi42_t));
upi42_do_init(type, rom);
return upi42;
}
#ifdef UPI42_STANDALONE
static const char *flags_8042[] = { "OBF", "IBF", "F0", "F1", "ST4", "ST5", "ST6", "ST7" };
int
main(int argc, char **argv)
{
/* Check arguments. */
if (argc < 2) {
upi42_log("Specify a ROM file to execute.\n");
return 1;
}
/* Load ROM. */
uint8_t rom[4096] = { 0 };
FILE *fp = fopen(argv[1], "rb");
if (!fp) {
upi42_log("Could not read ROM file.\n");
return 2;
}
size_t rom_size = fread(rom, sizeof(rom[0]), sizeof(rom), fp);
fclose(fp);
/* Determine chip type from ROM. */
upi42_log("%d-byte ROM, ", rom_size);
uint32_t type;
switch (rom_size) {
case 0 ... 1024:
upi42_log("emulating 8041");
type = UPI42_8041;
break;
case 1025 ... 2048:
upi42_log("emulating 8042");
type = UPI42_8042;
break;
case 2049 ... 4096:
upi42_log("emulating 80C42");
type = UPI42_80C42;
break;
default:
upi42_log("unknown!\n");
return 3;
}
upi42_log(".\n");
/* Initialize emulator. */
upi42_t *upi42 = (upi42_t *) upi42_init(type, rom);
/* Start execution. */
char cmd, cmd_buf[256];
int val, go_until = -1;
while (1) {
/* Output status. */
upi42_log("PC=%04X I=%02X(%02X) A=%02X", upi42->pc, upi42->rom[upi42->pc], upi42->rom[upi42->pc + 1], upi42->a);
for (val = 0; val < 8; val++)
upi42_log(" R%d=%02X", val, UPI42_REG(upi42, val, ));
upi42_log(" T=%02X PSW=%02X TF=%d I=%d TCNTI=%d", upi42->t, upi42->psw, upi42->tf, upi42->i, upi42->tcnti);
if (type & UPI42_TYPE_UPI) {
upi42_log(" STS=%02X", upi42->sts);
for (val = 0; val < 8; val++) {
if (upi42->sts & (1 << val)) {
upi42_log(" [%s]", flags_8042[val]);
} else {
upi42_log(" %s ", flags_8042[val]);
}
}
}
upi42_log("\n");
/* Break for command only if stepping. */
if ((go_until < 0) || (upi42->pc == go_until)) {
retry:
go_until = -1;
upi42_log("> ");
/* Read command. */
cmd = '\0';
scanf("%c", &cmd);
/* Execute command. */
switch (cmd) {
case 'c': /* write command */
if (scanf("%X%*c", &val, &cmd_buf))
upi42_cmd_write(0, val, upi42);
goto retry;
case 'd': /* write data */
if (scanf("%X%*c", &val, &cmd_buf))
upi42_dbb_write(0, val, upi42);
goto retry;
case 'g': /* go until */
if (!scanf("%X%*c", &go_until, &cmd_buf))
go_until = -1;
break;
case 'r': /* read data */
upi42_dbb_read(0, upi42); /* return value will be logged */
goto skip_and_retry;
case 'q': /* exit */
return 0;
case '\r': /* step */
case '\n':
case '\0':
break;
default:
upi42_log("Monitor commands:\n");
upi42_log("- Return (no command) - Step execution\n");
upi42_log("- q (or Ctrl+C) - Exit\n");
upi42_log("- gXXXX - Execute until PC is hex value XXXX\n");
upi42_log("- dXX - Write hex value XX to data port\n");
upi42_log("- cXX - Write hex value XX to command port\n");
upi42_log("- r - Read from data port and reset OBF\n");
skip_and_retry:
scanf("%*c", &cmd_buf);
goto retry;
}
}
/* Execute a cycle. */
upi42_exec(upi42);
}
return 0;
}
#else
static void
upi42_write(uint16_t port, uint8_t val, void *priv)
{
upi42_t *upi42 = (upi42_t *) priv;
uint32_t temp_type;
uint8_t *temp_rom;
int i;
switch (port) {
/* Write to data port. */
case 0x0060:
case 0x0160:
upi42_dbb_write(0, val, upi42);
break;
/* RAM Index. */
case 0x0162:
upi42->ram_index = val & upi42->rammask;
break;
/* RAM. */
case 0x0163:
upi42->ram[upi42->ram_index & upi42->rammask] = val;
break;
/* Write to command port. */
case 0x0064:
case 0x0164:
upi42_cmd_write(0, val, upi42);
break;
/* Input ports. */
case 0x0180 ... 0x0187:
upi42->ports_in[addr & 0x0007] = val;
break;
/* Output ports. */
case 0x0188 ... 0x018f:
upi42->ports_out[addr & 0x0007] = val;
break;
/* 4 = T0, 5 = T1. */
case 0x0194:
upi42->t0 = (val >> 4) & 0x01;
upi42->t1 = (val >> 5) & 0x01;
break;
/* Program counter. */
case 0x0196:
upi42->pc = (upi42->pc & 0xff00) | val;
break;
case 0x0197:
upi42->pc = (upi42->pc & 0x00ff) | (val << 8);
break;
/* Input data buffer. */
case 0x019a:
upi42->dbb_in = val;
break;
/* Output data buffer. */
case 0x019b:
upi42->dbb_out = val;
break;
/* ROM Index. */
case 0x01a0:
upi42->rom_index = (upi42->rom_index & 0xff00) | val;
break;
case 0x01a1:
upi42->rom_index = (upi42->rom_index & 0x00ff) | (val << 8);
break;
/* Hard reset. */
case 0x01a2:
temp_type = upi42->type;
temp_rom = upi42->rom;
upi42_do_init(temp_type, temp_rom);
break;
/* Soft reset. */
case 0x01a3:
upi42_reset(upi42);
break;
/* ROM. */
case 0x01a4:
upi42->rom[upi42->rom_index & upi42->rommask] = val;
break;
case 0x01a5:
upi42->rom[(upi42->rom_index + 1) & upi42->rommask] = val;
break;
case 0x01a6:
upi42->rom[(upi42->rom_index + 2) & upi42->rommask] = val;
break;
case 0x01a7:
upi42->rom[(upi42->rom_index + 3) & upi42->rommask] = val;
break;
/* Pause. */
case 0x01a8:
break;
/* Resume. */
case 0x01a9:
break;
/* Bus master ROM: 0 = direction (0 = to memory, 1 = from memory). */
case 0x01aa:
if (val & 0x01) {
for (i = 0; i <= upi42->rommask; i += 4)
*(uint32_t *) &(upi42->rom[i]) = mem_readl_phys(upi42->ram_addr + i);
} else {
for (i = 0; i <= upi42->rommask; i += 4)
mem_writel_phys(upi42->ram_addr + i, *(uint32_t *) &(upi42->rom[i]));
}
upi42->bm_stat = (val & 0x01) | 0x02;
break;
}
}
static uint8_t
upi42_read(uint16_t port, void *priv)
{
upi42_t *upi42 = (upi42_t *) priv;
uint8_t ret = 0xff;
switch (port) {
/* Type. */
case 0x015c:
ret = upi42->type & 0xff;
break;
case 0x015d:
ret = upi42->type >> 8;
break;
case 0x015e:
ret = upi42->type >> 16;
break;
case 0x015f:
ret = upi42->type >> 24;
break;
/* Read from data port and reset OBF. */
case 0x0060:
case 0x0160:
ret = upi42->dbb_out;
upi42->sts &= ~0x01; /* clear OBF */
break;
/* RAM Mask. */
case 0x0161:
ret = upi42->rammask;
break;
/* RAM Index. */
case 0x0162:
ret = upi42->ram_index;
break;
/* RAM. */
case 0x0163:
ret = upi42->ram[upi42->ram_index & upi42->rammask];
break;
/* Read status. */
case 0x0064:
case 0x0164:
ret = upi42->sts;
break;
/* Input ports. */
case 0x0180 ... 0x0187:
ret = upi42->ports_in[addr & 0x0007];
break;
/* Output ports. */
case 0x0188 ... 0x018f:
ret = upi42->ports_out[addr & 0x0007];
break;
/* Accumulator. */
case 0x0190:
ret = upi42->a;
break;
/* Timer counter. */
case 0x0191:
ret = upi42->t;
break;
/* Program status word. */
case 0x0192:
ret = upi42->psw;
break;
/* 0-4 = Prescaler, 5 = TF, 6 = Skip Timer Inc, 7 = Run Timer. */
case 0x0193:
ret = (upi42->prescaler & 0x1f) || ((upi42->tf & 0x01) << 5) || ((upi42->skip_timer_inc & 0x01) << 6) || ((upi42->run_timer & 0x01) << 7);
break;
/* 0 = I, 1 = I Raise, 2 = TCNTI Raise, 3 = IRQ Mask, 4 = T0, 5 = T1, 6 = Flags, 7 = DBF. */
case 0x0194:
ret = (upi42->i & 0x01) || ((upi42->i_raise & 0x01) << 1) || ((upi42->tcnti_raise & 0x01) << 2) || ((upi42->irq_mask & 0x01) << 3) || ((upi42->t0 & 0x01) << 4) || ((upi42->t1 & 0x01) << 5) || ((upi42->flags & 0x01) << 6) || ((upi42->dbf & 0x01) << 7);
break;
/* 0 = Suspend. */
case 0x0195:
ret = (upi42->suspend & 0x01);
break;
/* Program counter. */
case 0x0196:
ret = upi42->pc & 0xff;
break;
case 0x0197:
ret = upi42->pc >> 8;
break;
/* ROM Mask. */
case 0x0198:
ret = upi42->rommask & 0xff;
break;
case 0x0199:
ret = upi42->rommask >> 8;
break;
/* Input data buffer. */
case 0x019a:
ret = upi42->dbb_in;
break;
/* Output data buffer. */
case 0x019b:
ret = upi42->dbb_out;
break;
/* Cycle counter. */
case 0x019c:
ret = upi42->cycs & 0xff;
break;
case 0x019d:
ret = upi42->cycs >> 8;
break;
case 0x019e:
ret = upi42->cycs >> 16;
break;
case 0x019f:
ret = upi42->cycs >> 24;
break;
/* ROM Index. */
case 0x01a0:
ret = upi42->rom_index & 0xff;
break;
case 0x01a1:
ret = upi42->rom_index >> 8;
break;
/* ROM. */
case 0x01a4:
ret = upi42->rom[upi42->rom_index & upi42->rommask];
break;
case 0x01a5:
ret = upi42->rom[(upi42->rom_index + 1) & upi42->rommask];
break;
case 0x01a6:
ret = upi42->rom[(upi42->rom_index + 2) & upi42->rommask];
break;
case 0x01a7:
ret = upi42->rom[(upi42->rom_index + 3) & upi42->rommask];
break;
/* Bus master status: 0 = direction, 1 = finished. */
case 0x01ab:
ret = upi42->bm_stat;
break;
}
return ret;
}
#endif
``` | /content/code_sandbox/src/upi42.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 15,385 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Handling of the PS/2 series CMOS devices.
*
*
*
* Authors: Fred N. van Kempen, <decwiz@yahoo.com>
* Sarah Walker, <path_to_url
*
*
* This program is free software; you can redistribute it and/or modify
* (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
*
* along with this program; if not, write to the:
*
* Free Software Foundation, Inc.
* 59 Temple Place - Suite 330
* Boston, MA 02111-1307
* USA.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <86box/86box.h>
#include <86box/machine.h>
#include <86box/device.h>
#include <86box/io.h>
#include <86box/mem.h>
#include <86box/timer.h>
#include <86box/nvr.h>
#include <86box/nvr_ps2.h>
#include <86box/rom.h>
typedef struct ps2_nvr_t {
int addr;
uint8_t *ram;
int size;
char *fn;
} ps2_nvr_t;
static uint8_t
ps2_nvr_read(uint16_t port, void *priv)
{
const ps2_nvr_t *nvr = (ps2_nvr_t *) priv;
uint8_t ret = 0xff;
switch (port) {
case 0x74:
ret = nvr->addr & 0xff;
break;
case 0x75:
ret = nvr->addr >> 8;
break;
case 0x76:
ret = nvr->ram[nvr->addr];
break;
default:
break;
}
return ret;
}
static void
ps2_nvr_write(uint16_t port, uint8_t val, void *priv)
{
ps2_nvr_t *nvr = (ps2_nvr_t *) priv;
switch (port) {
case 0x74:
nvr->addr = (nvr->addr & 0x1f00) | val;
break;
case 0x75:
nvr->addr = (nvr->addr & 0xff) | ((val & 0x1f) << 8);
break;
case 0x76:
nvr->ram[nvr->addr] = val;
break;
default:
break;
}
}
static void *
ps2_nvr_init(const device_t *info)
{
ps2_nvr_t *nvr;
FILE *fp = NULL;
int c;
nvr = (ps2_nvr_t *) malloc(sizeof(ps2_nvr_t));
memset(nvr, 0x00, sizeof(ps2_nvr_t));
if (info->local)
nvr->size = 2048;
else
nvr->size = 8192;
/* Set up the NVR file's name. */
c = strlen(machine_get_internal_name()) + 9;
nvr->fn = (char *) malloc(c + 1);
sprintf(nvr->fn, "%s_sec.nvr", machine_get_internal_name());
io_sethandler(0x0074, 3,
ps2_nvr_read, NULL, NULL, ps2_nvr_write, NULL, NULL, nvr);
fp = nvr_fopen(nvr->fn, "rb");
nvr->ram = (uint8_t *) malloc(nvr->size);
memset(nvr->ram, 0xff, nvr->size);
if (fp != NULL) {
if (fread(nvr->ram, 1, nvr->size, fp) != nvr->size)
fatal("ps2_nvr_init(): Error reading EEPROM data\n");
fclose(fp);
}
return nvr;
}
static void
ps2_nvr_close(void *priv)
{
ps2_nvr_t *nvr = (ps2_nvr_t *) priv;
FILE *fp = NULL;
fp = nvr_fopen(nvr->fn, "wb");
if (fp != NULL) {
(void) fwrite(nvr->ram, nvr->size, 1, fp);
fclose(fp);
}
if (nvr->ram != NULL)
free(nvr->ram);
free(nvr);
}
const device_t ps2_nvr_device = {
.name = "PS/2 Secondary NVRAM for PS/2 Models 70-80",
.internal_name = "ps2_nvr",
.flags = 0,
.local = 0,
.init = ps2_nvr_init,
.close = ps2_nvr_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t ps2_nvr_55ls_device = {
.name = "PS/2 Secondary NVRAM for PS/2 Models 55LS-65SX",
.internal_name = "ps2_nvr_55ls",
.flags = 0,
.local = 1,
.init = ps2_nvr_init,
.close = ps2_nvr_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/nvr_ps2.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,339 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Configuration file handler.
*
*
*
* Authors: Sarah Walker, <path_to_url
* Miran Grca, <mgrca8@gmail.com>
* Fred N. van Kempen, <decwiz@yahoo.com>
* Overdoze,
* David Hrdlika, <hrdlickadavid@outlook.com>
*
*
* NOTE: Forcing config files to be in Unicode encoding breaks
* it on Windows XP, and possibly also Vista. Use the
* -DANSI_CFG for use on these systems.
*/
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include "cpu.h"
#include <86box/device.h>
#include <86box/timer.h>
#include <86box/cassette.h>
#include <86box/cartridge.h>
#include <86box/nvr.h>
#include <86box/ini.h>
#include <86box/config.h>
#include <86box/isamem.h>
#include <86box/isartc.h>
#include <86box/lpt.h>
#include <86box/serial.h>
#include <86box/hdd.h>
#include <86box/hdc.h>
#include <86box/hdc_ide.h>
#include <86box/fdd.h>
#include <86box/fdc.h>
#include <86box/fdc_ext.h>
#include <86box/gameport.h>
#include <86box/serial.h>
#include <86box/serial_passthrough.h>
#include <86box/machine.h>
#include <86box/mouse.h>
#include <86box/thread.h>
#include <86box/network.h>
#include <86box/scsi.h>
#include <86box/scsi_device.h>
#include <86box/cdrom.h>
#include <86box/cdrom_interface.h>
#include <86box/zip.h>
#include <86box/mo.h>
#include <86box/sound.h>
#include <86box/midi.h>
#include <86box/snd_mpu401.h>
#include <86box/video.h>
#include <86box/path.h>
#include <86box/plat.h>
#include <86box/plat_dir.h>
#include <86box/ui.h>
#include <86box/snd_opl.h>
#include <86box/version.h>
static int cx;
static int cy;
static int cw;
static int ch;
static ini_t config;
#ifdef ENABLE_CONFIG_LOG
int config_do_log = ENABLE_CONFIG_LOG;
static void
config_log(const char *fmt, ...)
{
va_list ap;
if (config_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define config_log(fmt, ...)
#endif
/* Load "General" section. */
static void
load_general(void)
{
ini_section_t cat = ini_find_section(config, "General");
char temp[512];
char *p;
vid_resize = ini_section_get_int(cat, "vid_resize", 0);
if (vid_resize & ~3)
vid_resize &= 3;
memset(temp, '\0', sizeof(temp));
p = ini_section_get_string(cat, "vid_renderer", "default");
vid_api = plat_vidapi(p);
ini_section_delete_var(cat, "vid_api");
video_fullscreen_scale = ini_section_get_int(cat, "video_fullscreen_scale", 1);
video_fullscreen_first = ini_section_get_int(cat, "video_fullscreen_first", 1);
video_filter_method = ini_section_get_int(cat, "video_filter_method", 1);
force_43 = !!ini_section_get_int(cat, "force_43", 0);
scale = ini_section_get_int(cat, "scale", 1);
if (scale > 9)
scale = 9;
dpi_scale = ini_section_get_int(cat, "dpi_scale", 1);
enable_overscan = !!ini_section_get_int(cat, "enable_overscan", 0);
vid_cga_contrast = !!ini_section_get_int(cat, "vid_cga_contrast", 0);
video_grayscale = ini_section_get_int(cat, "video_grayscale", 0);
video_graytype = ini_section_get_int(cat, "video_graytype", 0);
rctrl_is_lalt = ini_section_get_int(cat, "rctrl_is_lalt", 0);
update_icons = ini_section_get_int(cat, "update_icons", 1);
window_remember = ini_section_get_int(cat, "window_remember", 0);
if (!window_remember && !(vid_resize & 2))
window_w = window_h = window_x = window_y = 0;
if (vid_resize & 2) {
p = ini_section_get_string(cat, "window_fixed_res", NULL);
if (p == NULL)
p = "120x120";
sscanf(p, "%ix%i", &fixed_size_x, &fixed_size_y);
if (fixed_size_x < 120)
fixed_size_x = 120;
if (fixed_size_x > 2048)
fixed_size_x = 2048;
if (fixed_size_y < 120)
fixed_size_y = 120;
if (fixed_size_y > 2048)
fixed_size_y = 2048;
} else {
ini_section_delete_var(cat, "window_fixed_res");
fixed_size_x = fixed_size_y = 120;
}
sound_gain = ini_section_get_int(cat, "sound_gain", 0);
kbd_req_capture = ini_section_get_int(cat, "kbd_req_capture", 0);
hide_status_bar = ini_section_get_int(cat, "hide_status_bar", 0);
hide_tool_bar = ini_section_get_int(cat, "hide_tool_bar", 0);
confirm_reset = ini_section_get_int(cat, "confirm_reset", 1);
confirm_exit = ini_section_get_int(cat, "confirm_exit", 1);
confirm_save = ini_section_get_int(cat, "confirm_save", 1);
p = ini_section_get_string(cat, "language", NULL);
if (p != NULL)
lang_id = plat_language_code(p);
mouse_sensitivity = ini_section_get_double(cat, "mouse_sensitivity", 1.0);
if (mouse_sensitivity < 0.1)
mouse_sensitivity = 0.1;
else if (mouse_sensitivity > 2.0)
mouse_sensitivity = 2.0;
p = ini_section_get_string(cat, "iconset", NULL);
if (p != NULL)
strcpy(icon_set, p);
else
strcpy(icon_set, "");
enable_discord = !!ini_section_get_int(cat, "enable_discord", 0);
open_dir_usr_path = ini_section_get_int(cat, "open_dir_usr_path", 0);
video_framerate = ini_section_get_int(cat, "video_gl_framerate", -1);
video_vsync = ini_section_get_int(cat, "video_gl_vsync", 0);
strncpy(video_shader, ini_section_get_string(cat, "video_gl_shader", ""), sizeof(video_shader) - 1);
window_remember = ini_section_get_int(cat, "window_remember", 0);
if (window_remember) {
p = ini_section_get_string(cat, "window_coordinates", NULL);
if (p == NULL)
p = "0, 0, 0, 0";
sscanf(p, "%i, %i, %i, %i", &cw, &ch, &cx, &cy);
} else
cw = ch = cx = cy = 0;
ini_section_delete_var(cat, "window_coordinates");
do_auto_pause = ini_section_get_int(cat, "do_auto_pause", 0);
p = ini_section_get_string(cat, "uuid", NULL);
if (p != NULL)
strncpy(uuid, p, sizeof(uuid) - 1);
else
strncpy(uuid, "", sizeof(uuid) - 1);
}
/* Load monitor section. */
static void
load_monitor(int monitor_index)
{
ini_section_t cat;
char name[512];
char temp[512];
const char * p = NULL;
monitor_settings_t *ms = &monitor_settings[monitor_index];
sprintf(name, "Monitor #%i", monitor_index + 1);
sprintf(temp, "%i, %i, %i, %i", cx, cy, cw, ch);
cat = ini_find_section(config, name);
p = ini_section_get_string(cat, "window_coordinates", temp);
if (window_remember) {
sscanf(p, "%i, %i, %i, %i", &ms->mon_window_x, &ms->mon_window_y,
&ms->mon_window_w, &ms->mon_window_h);
ms->mon_window_maximized = !!ini_section_get_int(cat, "window_maximized", 0);
} else
ms->mon_window_maximized = 0;
}
/* Load "Machine" section. */
static void
load_machine(void)
{
ini_section_t cat = ini_find_section(config, "Machine");
const char *p;
const char *migrate_from = NULL;
int c;
int i;
int j;
int speed;
double multi;
p = ini_section_get_string(cat, "machine", NULL);
if (p != NULL) {
migrate_from = p;
/* Migrate renamed machines. */
if (!strcmp(p, "430nx"))
machine = machine_get_machine_from_internal_name("586ip");
else if (!strcmp(p, "586mc1"))
machine = machine_get_machine_from_internal_name("586is");
else {
machine = machine_get_machine_from_internal_name(p);
migrate_from = NULL;
}
} else
machine = 0;
if (machine >= machine_count())
machine = machine_count() - 1;
/* Copy NVR files when migrating a machine to a new internal name. */
if (migrate_from) {
char old_fn[256];
strcpy(old_fn, migrate_from);
strcat(old_fn, ".");
c = strlen(old_fn);
char new_fn[256];
strcpy(new_fn, machines[machine].internal_name);
strcat(new_fn, ".");
i = strlen(new_fn);
/* Iterate through NVR files. */
DIR *dirp = opendir(nvr_path("."));
if (dirp) {
struct dirent *entry;
while ((entry = readdir(dirp))) {
/* Check if this file corresponds to the old name. */
if (strncmp(entry->d_name, old_fn, c))
continue;
/* Add extension to the new name. */
strcpy(&new_fn[i], &entry->d_name[c]);
/* Only copy if a file with the new name doesn't already exist. */
FILE *g = nvr_fopen(new_fn, "rb");
if (!g) {
FILE *f = nvr_fopen(entry->d_name, "rb");
g = nvr_fopen(new_fn, "wb");
uint8_t buf[4096];
while ((j = fread(buf, 1, sizeof(buf), f)))
fwrite(buf, 1, j, g);
fclose(f);
}
fclose(g);
}
}
}
cpu_override = ini_section_get_int(cat, "cpu_override", 0);
cpu_override_interpreter = ini_section_get_int(cat, "cpu_override_interpreter", 0);
cpu_f = NULL;
p = ini_section_get_string(cat, "cpu_family", NULL);
if (p) {
/* Migrate CPU family changes. */
if ((!strcmp(machines[machine].internal_name, "deskpro386") ||
!strcmp(machines[machine].internal_name, "deskpro386_05_1988")))
cpu_f = cpu_get_family("i386dx_deskpro386");
else
cpu_f = cpu_get_family(p);
if (cpu_f && !cpu_family_is_eligible(cpu_f, machine)) /* only honor eligible families */
cpu_f = NULL;
}
if (cpu_f) {
speed = ini_section_get_int(cat, "cpu_speed", 0);
multi = ini_section_get_double(cat, "cpu_multi", 0);
/* Find the configured CPU. */
cpu = 0;
c = 0;
i = 256;
while (cpu_f->cpus[cpu].cpu_type) {
if (cpu_is_eligible(cpu_f, cpu, machine)) {
/* Skip ineligible CPUs. */
if ((cpu_f->cpus[cpu].rspeed == speed) && (cpu_f->cpus[cpu].multi == multi))
/* Exact speed/multiplier match. */
break;
else if ((cpu_f->cpus[cpu].rspeed >= speed) && (i == 256))
/* Closest speed match. */
i = cpu;
c = cpu; /* store fastest eligible CPU */
}
cpu++;
}
if (!cpu_f->cpus[cpu].cpu_type)
/* if no exact match was found, use closest matching faster CPU or fastest eligible CPU. */
cpu = MIN(i, c);
} else {
/* Default, find first eligible family. */
c = 0;
while (!cpu_family_is_eligible(&cpu_families[c], machine)) {
if (cpu_families[c++].package == 0) {
/* End of list. */
fatal("No eligible CPU families for the selected machine\n");
return;
}
}
cpu_f = (cpu_family_t *) &cpu_families[c];
/* Find first eligible CPU in that family. */
cpu = 0;
while (!cpu_is_eligible(cpu_f, cpu, machine)) {
if (cpu_f->cpus[cpu++].cpu_type == 0) {
/* End of list. */
cpu = 0;
break;
}
}
}
cpu_s = (CPU *) &cpu_f->cpus[cpu];
cpu_waitstates = ini_section_get_int(cat, "cpu_waitstates", 0);
p = ini_section_get_string(cat, "fpu_type", "none");
fpu_type = fpu_get_type(cpu_f, cpu, p);
mem_size = ini_section_get_int(cat, "mem_size", 64);
if (mem_size > machine_get_max_ram(machine))
mem_size = machine_get_max_ram(machine);
cpu_use_dynarec = !!ini_section_get_int(cat, "cpu_use_dynarec", 0);
fpu_softfloat = !!ini_section_get_int(cat, "fpu_softfloat", 0);
if ((fpu_type != FPU_NONE) && machine_has_flags(machine, MACHINE_SOFTFLOAT_ONLY))
fpu_softfloat = 1;
p = ini_section_get_string(cat, "time_sync", NULL);
if (p != NULL) {
if (!strcmp(p, "disabled"))
time_sync = TIME_SYNC_DISABLED;
else if (!strcmp(p, "local"))
time_sync = TIME_SYNC_ENABLED;
else if (!strcmp(p, "utc") || !strcmp(p, "gmt"))
time_sync = TIME_SYNC_ENABLED | TIME_SYNC_UTC;
else
time_sync = TIME_SYNC_ENABLED;
} else
time_sync = !!ini_section_get_int(cat, "enable_sync", 1);
pit_mode = ini_section_get_int(cat, "pit_mode", -1);
}
/* Load "Video" section. */
static void
load_video(void)
{
ini_section_t cat = ini_find_section(config, "Video");
char *p;
int free_p = 0;
if (machine_has_flags(machine, MACHINE_VIDEO_ONLY)) {
ini_section_delete_var(cat, "gfxcard");
gfxcard[0] = VID_INTERNAL;
} else {
p = ini_section_get_string(cat, "gfxcard", NULL);
if (p == NULL) {
if (machine_has_flags(machine, MACHINE_VIDEO)) {
p = (char *) malloc((strlen("internal") + 1) * sizeof(char));
strcpy(p, "internal");
} else {
p = (char *) malloc((strlen("none") + 1) * sizeof(char));
strcpy(p, "none");
}
free_p = 1;
} else if (!strcmp(p, "c&t_69000")) {
p = (char *) malloc((strlen("chips_69000") + 1) * sizeof(char));
strcpy(p, "chips_69000");
free_p = 1;
}
gfxcard[0] = video_get_video_from_internal_name(p);
if (free_p) {
free(p);
p = NULL;
free_p = 0;
}
}
if (((gfxcard[0] == VID_INTERNAL) && machine_has_flags(machine, MACHINE_VIDEO_8514A)) ||
video_card_get_flags(gfxcard[0]) == VIDEO_FLAG_TYPE_8514)
ini_section_delete_var(cat, "8514a");
if (((gfxcard[0] == VID_INTERNAL) && machine_has_flags(machine, MACHINE_VIDEO_XGA)) ||
video_card_get_flags(gfxcard[0]) == VIDEO_FLAG_TYPE_XGA)
ini_section_delete_var(cat, "xga");
voodoo_enabled = !!ini_section_get_int(cat, "voodoo", 0);
ibm8514_standalone_enabled = !!ini_section_get_int(cat, "8514a", 0);
ibm8514_active = ibm8514_standalone_enabled;
xga_standalone_enabled = !!ini_section_get_int(cat, "xga", 0);
xga_active = xga_standalone_enabled;
show_second_monitors = !!ini_section_get_int(cat, "show_second_monitors", 1);
video_fullscreen_scale_maximized = !!ini_section_get_int(cat, "video_fullscreen_scale_maximized", 0);
// TODO
for (uint8_t i = 1; i < GFXCARD_MAX; i ++) {
p = ini_section_get_string(cat, "gfxcard_2", NULL);
if (!p)
p = "none";
gfxcard[i] = video_get_video_from_internal_name(p);
}
}
/* Load "Input Devices" section. */
static void
load_input_devices(void)
{
ini_section_t cat = ini_find_section(config, "Input devices");
char temp[512];
int c;
int d;
char *p;
p = ini_section_get_string(cat, "mouse_type", NULL);
if (p != NULL)
mouse_type = mouse_get_from_internal_name(p);
else
mouse_type = 0;
p = ini_section_get_string(cat, "joystick_type", NULL);
if (p != NULL) {
joystick_type = joystick_get_from_internal_name(p);
if (!joystick_type) {
/* Try to read an integer for backwards compatibility with old configs */
if (!strcmp(p, "0"))
/* Workaround for ini_section_get_int returning 0 on non-integer data */
joystick_type = joystick_get_from_internal_name("2axis_2button");
else {
c = ini_section_get_int(cat, "joystick_type", 8);
switch (c) {
case JS_TYPE_2AXIS_4BUTTON:
joystick_type = joystick_get_from_internal_name("2axis_4button");
break;
case JS_TYPE_2AXIS_6BUTTON:
joystick_type = joystick_get_from_internal_name("2axis_6button");
break;
case JS_TYPE_2AXIS_8BUTTON:
joystick_type = joystick_get_from_internal_name("2axis_8button");
break;
case JS_TYPE_4AXIS_4BUTTON:
joystick_type = joystick_get_from_internal_name("4axis_4button");
break;
case JS_TYPE_CH_FLIGHTSTICK_PRO:
joystick_type = joystick_get_from_internal_name("ch_flightstick_pro");
break;
case JS_TYPE_SIDEWINDER_PAD:
joystick_type = joystick_get_from_internal_name("sidewinder_pad");
break;
case JS_TYPE_THRUSTMASTER_FCS:
joystick_type = joystick_get_from_internal_name("thrustmaster_fcs");
break;
default:
joystick_type = JS_TYPE_NONE;
break;
}
}
}
} else
joystick_type = JS_TYPE_NONE;
for (c = 0; c < joystick_get_max_joysticks(joystick_type); c++) {
sprintf(temp, "joystick_%i_nr", c);
joystick_state[c].plat_joystick_nr = ini_section_get_int(cat, temp, 0);
if (joystick_state[c].plat_joystick_nr) {
for (d = 0; d < joystick_get_axis_count(joystick_type); d++) {
sprintf(temp, "joystick_%i_axis_%i", c, d);
joystick_state[c].axis_mapping[d] = ini_section_get_int(cat, temp, d);
}
for (d = 0; d < joystick_get_button_count(joystick_type); d++) {
sprintf(temp, "joystick_%i_button_%i", c, d);
joystick_state[c].button_mapping[d] = ini_section_get_int(cat, temp, d);
}
for (d = 0; d < joystick_get_pov_count(joystick_type); d++) {
sprintf(temp, "joystick_%i_pov_%i", c, d);
p = ini_section_get_string(cat, temp, "0, 0");
joystick_state[c].pov_mapping[d][0] = joystick_state[c].pov_mapping[d][1] = 0;
sscanf(p, "%i, %i", &joystick_state[c].pov_mapping[d][0],
&joystick_state[c].pov_mapping[d][1]);
}
}
}
tablet_tool_type = !!ini_section_get_int(cat, "tablet_tool_type", 1);
}
/* Load "Sound" section. */
static void
load_sound(void)
{
ini_section_t cat = ini_find_section(config, "Sound");
char temp[512];
char *p;
p = ini_section_get_string(cat, "sndcard", NULL);
if (p != NULL)
sound_card_current[0] = sound_card_get_from_internal_name(p);
else
sound_card_current[0] = 0;
p = ini_section_get_string(cat, "sndcard2", NULL);
if (p != NULL)
sound_card_current[1] = sound_card_get_from_internal_name(p);
else
sound_card_current[1] = 0;
p = ini_section_get_string(cat, "sndcard3", NULL);
if (p != NULL)
sound_card_current[2] = sound_card_get_from_internal_name(p);
else
sound_card_current[2] = 0;
p = ini_section_get_string(cat, "sndcard4", NULL);
if (p != NULL)
sound_card_current[3] = sound_card_get_from_internal_name(p);
else
sound_card_current[3] = 0;
p = ini_section_get_string(cat, "midi_device", NULL);
if (p != NULL)
midi_output_device_current = midi_out_device_get_from_internal_name(p);
else
midi_output_device_current = 0;
p = ini_section_get_string(cat, "midi_in_device", NULL);
if (p != NULL)
midi_input_device_current = midi_in_device_get_from_internal_name(p);
else
midi_input_device_current = 0;
mpu401_standalone_enable = !!ini_section_get_int(cat, "mpu401_standalone", 0);
/* Backwards compatibility for standalone SSI-2001, CMS and GUS from v3.11 and older. */
const char *legacy_cards[][2] = {
{"ssi2001", "ssi2001"},
{ "gameblaster", "cms" },
{ "gus", "gus" }
};
for (int i = 0, j = 0; i < (sizeof(legacy_cards) / sizeof(legacy_cards[0])); i++) {
if (ini_section_get_int(cat, legacy_cards[i][0], 0) == 1) {
/* Migrate to the first available sound card slot. */
for (; j < (sizeof(sound_card_current) / sizeof(sound_card_current[0])); j++) {
if (!sound_card_current[j]) {
sound_card_current[j] = sound_card_get_from_internal_name(legacy_cards[i][1]);
break;
}
}
}
}
memset(temp, '\0', sizeof(temp));
p = ini_section_get_string(cat, "sound_type", "float");
if (strlen(p) > 511)
fatal("load_sound(): strlen(p) > 511\n");
else
strncpy(temp, p, 511);
if (!strcmp(temp, "float") || !strcmp(temp, "1"))
sound_is_float = 1;
else
sound_is_float = 0;
p = ini_section_get_string(cat, "fm_driver", "nuked");
if (!strcmp(p, "ymfm")) {
fm_driver = FM_DRV_YMFM;
} else {
fm_driver = FM_DRV_NUKED;
}
}
/* Load "Network" section. */
static void
load_network(void)
{
ini_section_t cat = ini_find_section(config, "Network");
char * p;
char temp[512];
uint16_t c = 0;
uint16_t min = 0;
netcard_conf_t *nc = &net_cards_conf[c];
/* Handle legacy configuration which supported only one NIC */
p = ini_section_get_string(cat, "net_card", NULL);
if (p != NULL) {
nc->device_num = network_card_get_from_internal_name(p);
p = ini_section_get_string(cat, "net_type", NULL);
if (p != NULL) {
if (!strcmp(p, "pcap") || !strcmp(p, "1"))
nc->net_type = NET_TYPE_PCAP;
else if (!strcmp(p, "slirp") || !strcmp(p, "2"))
nc->net_type = NET_TYPE_SLIRP;
else if (!strcmp(p, "vde") || !strcmp(p, "2"))
nc->net_type = NET_TYPE_VDE;
else
nc->net_type = NET_TYPE_NONE;
} else
nc->net_type = NET_TYPE_NONE;
p = ini_section_get_string(cat, "net_host_device", NULL);
if (p != NULL) {
if (nc->net_type == NET_TYPE_PCAP) {
if ((network_dev_to_id(p) == -1) || (network_ndev == 1)) {
if (network_ndev == 1)
ui_msgbox_header(MBX_ERROR, plat_get_string(STRING_PCAP_ERROR_NO_DEVICES), plat_get_string(STRING_PCAP_ERROR_DESC));
else if (network_dev_to_id(p) == -1)
ui_msgbox_header(MBX_ERROR, plat_get_string(STRING_PCAP_ERROR_INVALID_DEVICE), plat_get_string(STRING_PCAP_ERROR_DESC));
strcpy(nc->host_dev_name, "none");
} else
strncpy(nc->host_dev_name, p, sizeof(nc->host_dev_name) - 1);
} else
strncpy(nc->host_dev_name, p, sizeof(nc->host_dev_name) - 1);
} else
strcpy(nc->host_dev_name, "none");
min++;
}
ini_section_delete_var(cat, "net_card");
ini_section_delete_var(cat, "net_type");
ini_section_delete_var(cat, "net_host_device");
for (c = min; c < NET_CARD_MAX; c++) {
nc = &net_cards_conf[c];
sprintf(temp, "net_%02i_card", c + 1);
p = ini_section_get_string(cat, temp, NULL);
if (p != NULL)
nc->device_num = network_card_get_from_internal_name(p);
else
nc->device_num = 0;
sprintf(temp, "net_%02i_net_type", c + 1);
p = ini_section_get_string(cat, temp, NULL);
if (p != NULL) {
if (!strcmp(p, "pcap") || !strcmp(p, "1"))
nc->net_type = NET_TYPE_PCAP;
else if (!strcmp(p, "slirp") || !strcmp(p, "2"))
nc->net_type = NET_TYPE_SLIRP;
else if (!strcmp(p, "vde") || !strcmp(p, "2"))
nc->net_type = NET_TYPE_VDE;
else
nc->net_type = NET_TYPE_NONE;
} else
nc->net_type = NET_TYPE_NONE;
sprintf(temp, "net_%02i_host_device", c + 1);
p = ini_section_get_string(cat, temp, NULL);
if (p != NULL) {
if (nc->net_type == NET_TYPE_PCAP) {
if ((network_dev_to_id(p) == -1) || (network_ndev == 1)) {
if (network_ndev == 1)
ui_msgbox_header(MBX_ERROR, plat_get_string(STRING_PCAP_ERROR_NO_DEVICES), plat_get_string(STRING_PCAP_ERROR_DESC));
else if (network_dev_to_id(p) == -1)
ui_msgbox_header(MBX_ERROR, plat_get_string(STRING_PCAP_ERROR_INVALID_DEVICE), plat_get_string(STRING_PCAP_ERROR_DESC));
strcpy(nc->host_dev_name, "none");
} else
strncpy(nc->host_dev_name, p, sizeof(nc->host_dev_name) - 1);
} else
strncpy(nc->host_dev_name, p, sizeof(nc->host_dev_name) - 1);
} else
strcpy(nc->host_dev_name, "none");
sprintf(temp, "net_%02i_link", c + 1);
nc->link_state = ini_section_get_int(cat, temp,
(NET_LINK_10_HD | NET_LINK_10_FD |
NET_LINK_100_HD | NET_LINK_100_FD |
NET_LINK_1000_HD | NET_LINK_1000_FD));
}
}
/* Load "Ports" section. */
static void
load_ports(void)
{
ini_section_t cat = ini_find_section(config, "Ports (COM & LPT)");
char *p;
char temp[512];
int c;
memset(temp, 0, sizeof(temp));
for (c = 0; c < SERIAL_MAX; c++) {
sprintf(temp, "serial%d_enabled", c + 1);
com_ports[c].enabled = !!ini_section_get_int(cat, temp, (c >= 2) ? 0 : 1);
sprintf(temp, "serial%d_passthrough_enabled", c + 1);
serial_passthrough_enabled[c] = !!ini_section_get_int(cat, temp, 0);
if (serial_passthrough_enabled[c])
config_log("Serial Port %d: passthrough enabled.\n\n", c + 1);
}
for (c = 0; c < PARALLEL_MAX; c++) {
sprintf(temp, "lpt%d_enabled", c + 1);
lpt_ports[c].enabled = !!ini_section_get_int(cat, temp, (c == 0) ? 1 : 0);
sprintf(temp, "lpt%d_device", c + 1);
p = ini_section_get_string(cat, temp, "none");
lpt_ports[c].device = lpt_device_get_from_internal_name(p);
}
}
/* Load "Storage Controllers" section. */
static void
load_storage_controllers(void)
{
ini_section_t cat = ini_find_section(config, "Storage controllers");
ini_section_t migration_cat;
char *p;
char temp[512];
int c;
int min = 0;
int free_p = 0;
for (c = min; c < SCSI_CARD_MAX; c++) {
sprintf(temp, "scsicard_%d", c + 1);
p = ini_section_get_string(cat, temp, NULL);
if (p != NULL)
scsi_card_current[c] = scsi_card_get_from_internal_name(p);
else
scsi_card_current[c] = 0;
}
p = ini_section_get_string(cat, "fdc", NULL);
#if 1
if (p != NULL)
fdc_current[0] = fdc_card_get_from_internal_name(p);
else
fdc_current[0] = FDC_INTERNAL;
#else
if (p == NULL) {
if (machine_has_flags(machine, MACHINE_FDC)) {
p = (char *) malloc((strlen("internal") + 1) * sizeof(char));
strcpy(p, "internal");
} else {
p = (char *) malloc((strlen("none") + 1) * sizeof(char));
strcpy(p, "none");
}
free_p = 1;
}
fdc_current[0] = fdc_card_get_from_internal_name(p);
if (free_p) {
free(p);
p = NULL;
free_p = 0;
}
#endif
p = ini_section_get_string(cat, "hdc", NULL);
if (p == NULL) {
if (machine_has_flags(machine, MACHINE_HDC)) {
p = (char *) malloc((strlen("internal") + 1) * sizeof(char));
strcpy(p, "internal");
} else {
p = (char *) malloc((strlen("none") + 1) * sizeof(char));
strcpy(p, "none");
}
free_p = 1;
}
/* Migrate renamed and merged cards. */
if (!strcmp(p, "xtide_plus")) {
hdc_current[0] = hdc_get_from_internal_name("xtide");
migration_cat = ini_find_or_create_section(config, "PC/XT XTIDE");
ini_section_set_string(migration_cat, "bios", "xt_plus");
} else if (!strcmp(p, "xtide_at_386")) {
hdc_current[0] = hdc_get_from_internal_name("xtide_at");
migration_cat = ini_find_or_create_section(config, "PC/AT XTIDE");
ini_section_set_string(migration_cat, "bios", "at_386");
} else
hdc_current[0] = hdc_get_from_internal_name(p);
if (free_p) {
free(p);
p = NULL;
}
p = ini_section_get_string(cat, "cdrom_interface", NULL);
if (p != NULL)
cdrom_interface_current = cdrom_interface_get_from_internal_name(p);
if (free_p) {
free(p);
p = NULL;
free_p = 0;
}
ide_ter_enabled = !!ini_section_get_int(cat, "ide_ter", 0);
ide_qua_enabled = !!ini_section_get_int(cat, "ide_qua", 0);
if (machine_has_bus(machine, MACHINE_BUS_CASSETTE))
cassette_enable = !!ini_section_get_int(cat, "cassette_enabled", 0);
else
cassette_enable = 0;
p = ini_section_get_string(cat, "cassette_file", "");
if (strlen(p) > 511)
fatal("load_storage_controllers(): strlen(p) > 511\n");
else
strncpy(cassette_fname, p, 511);
p = ini_section_get_string(cat, "cassette_mode", "");
if (strlen(p) > 511)
fatal("load_storage_controllers(): strlen(p) > 511\n");
else
strncpy(cassette_mode, p, 511);
cassette_pos = ini_section_get_int(cat, "cassette_position", 0);
cassette_srate = ini_section_get_int(cat, "cassette_srate", 44100);
cassette_append = !!ini_section_get_int(cat, "cassette_append", 0);
cassette_pcm = ini_section_get_int(cat, "cassette_pcm", 0);
cassette_ui_writeprot = !!ini_section_get_int(cat, "cassette_writeprot", 0);
for (c = 0; c < 2; c++) {
sprintf(temp, "cartridge_%02i_fn", c + 1);
p = ini_section_get_string(cat, temp, "");
if (!strcmp(p, usr_path))
p[0] = 0x00;
if (p[0] != 0x00) {
if (path_abs(p)) {
if (strlen(p) > 511)
fatal("load_storage_controllers(): strlen(p) > 511 (cart_fns[%i])\n", c);
else
strncpy(cart_fns[c], p, 511);
} else
path_append_filename(cart_fns[c], usr_path, p);
path_normalize(cart_fns[c]);
}
}
lba_enhancer_enabled = !!ini_section_get_int(cat, "lba_enhancer_enabled", 0);
}
/* Load "Hard Disks" section. */
static void
load_hard_disks(void)
{
ini_section_t cat = ini_find_section(config, "Hard disks");
char temp[512];
char tmp2[512];
char s[512];
char *p;
uint32_t max_spt;
uint32_t max_hpc;
uint32_t max_tracks;
uint32_t board = 0;
uint32_t dev = 0;
memset(temp, '\0', sizeof(temp));
for (uint8_t c = 0; c < HDD_NUM; c++) {
sprintf(temp, "hdd_%02i_parameters", c + 1);
p = ini_section_get_string(cat, temp, "0, 0, 0, 0, none");
sscanf(p, "%u, %u, %u, %i, %s",
&hdd[c].spt, &hdd[c].hpc, &hdd[c].tracks, (int *) &hdd[c].wp, s);
hdd[c].bus = hdd_string_to_bus(s, 0);
switch (hdd[c].bus) {
default:
case HDD_BUS_DISABLED:
max_spt = max_hpc = max_tracks = 0;
break;
case HDD_BUS_MFM:
max_spt = 26; /* 26 for RLL */
max_hpc = 15;
max_tracks = 2047;
break;
case HDD_BUS_XTA:
max_spt = 63;
max_hpc = 16;
max_tracks = 1023;
break;
case HDD_BUS_ESDI:
max_spt = 99;
max_hpc = 16;
max_tracks = 266305;
break;
case HDD_BUS_IDE:
max_spt = 255;
max_hpc = 255;
max_tracks = 266305;
break;
case HDD_BUS_SCSI:
case HDD_BUS_ATAPI:
max_spt = 255;
max_hpc = 255;
max_tracks = 266305;
break;
}
if (hdd[c].spt > max_spt)
hdd[c].spt = max_spt;
if (hdd[c].hpc > max_hpc)
hdd[c].hpc = max_hpc;
if (hdd[c].tracks > max_tracks)
hdd[c].tracks = max_tracks;
sprintf(temp, "hdd_%02i_speed", c + 1);
switch (hdd[c].bus) {
case HDD_BUS_IDE:
case HDD_BUS_ESDI:
case HDD_BUS_ATAPI:
case HDD_BUS_SCSI:
sprintf(tmp2, "1997_5400rpm");
break;
default:
sprintf(tmp2, "ramdisk");
break;
}
p = ini_section_get_string(cat, temp, tmp2);
hdd[c].speed_preset = hdd_preset_get_from_internal_name(p);
/* MFM/RLL */
sprintf(temp, "hdd_%02i_mfm_channel", c + 1);
if (hdd[c].bus == HDD_BUS_MFM)
hdd[c].mfm_channel = !!ini_section_get_int(cat, temp, c & 1);
else
ini_section_delete_var(cat, temp);
/* XTA */
sprintf(temp, "hdd_%02i_xta_channel", c + 1);
if (hdd[c].bus == HDD_BUS_XTA)
hdd[c].xta_channel = !!ini_section_get_int(cat, temp, c & 1);
else
ini_section_delete_var(cat, temp);
/* ESDI */
sprintf(temp, "hdd_%02i_esdi_channel", c + 1);
if (hdd[c].bus == HDD_BUS_ESDI)
hdd[c].esdi_channel = !!ini_section_get_int(cat, temp, c & 1);
else
ini_section_delete_var(cat, temp);
/* IDE */
sprintf(temp, "hdd_%02i_ide_channel", c + 1);
if ((hdd[c].bus == HDD_BUS_IDE) || (hdd[c].bus == HDD_BUS_ATAPI)) {
sprintf(tmp2, "%01u:%01u", c >> 1, c & 1);
p = ini_section_get_string(cat, temp, tmp2);
sscanf(p, "%01u:%01u", &board, &dev);
board &= 3;
dev &= 1;
hdd[c].ide_channel = (board << 1) + dev;
if (hdd[c].ide_channel > 7)
hdd[c].ide_channel = 7;
} else {
ini_section_delete_var(cat, temp);
}
/* SCSI */
if (hdd[c].bus == HDD_BUS_SCSI) {
sprintf(temp, "hdd_%02i_scsi_location", c + 1);
sprintf(tmp2, "%01u:%02u", SCSI_BUS_MAX, c + 2);
p = ini_section_get_string(cat, temp, tmp2);
sscanf(p, "%01u:%02u", &board, &dev);
if (board >= SCSI_BUS_MAX) {
/* Invalid bus - check legacy ID */
sprintf(temp, "hdd_%02i_scsi_id", c + 1);
hdd[c].scsi_id = ini_section_get_int(cat, temp, c + 2);
if (hdd[c].scsi_id > 15)
hdd[c].scsi_id = 15;
} else {
board %= SCSI_BUS_MAX;
dev &= 15;
hdd[c].scsi_id = (board << 4) + dev;
}
} else {
sprintf(temp, "hdd_%02i_scsi_location", c + 1);
ini_section_delete_var(cat, temp);
}
sprintf(temp, "hdd_%02i_scsi_id", c + 1);
ini_section_delete_var(cat, temp);
memset(hdd[c].fn, 0x00, sizeof(hdd[c].fn));
sprintf(temp, "hdd_%02i_fn", c + 1);
p = ini_section_get_string(cat, temp, "");
/*
* NOTE:
* When loading differencing VHDs, the absolute path is required.
* So we should not convert absolute paths to relative. -sards
*/
if (!strcmp(p, usr_path))
p[0] = 0x00;
if (p[0] != 0x00) {
if (path_abs(p)) {
if (strlen(p) > 511)
fatal("load_hard_disks(): strlen(p) > 511 (hdd[%i].fn)\n", c);
else
strncpy(hdd[c].fn, p, 511);
} else
path_append_filename(hdd[c].fn, usr_path, p);
path_normalize(hdd[c].fn);
}
sprintf(temp, "hdd_%02i_vhd_blocksize", c + 1);
hdd[c].vhd_blocksize = ini_section_get_int(cat, temp, 0);
sprintf(temp, "hdd_%02i_vhd_parent", c + 1);
p = ini_section_get_string(cat, temp, "");
strncpy(hdd[c].vhd_parent, p, sizeof(hdd[c].vhd_parent) - 1);
/* If disk is empty or invalid, mark it for deletion. */
if (!hdd_is_valid(c)) {
sprintf(temp, "hdd_%02i_parameters", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "hdd_%02i_preide_channels", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "hdd_%02i_ide_channels", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "hdd_%02i_scsi_id", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "hdd_%02i_fn", c + 1);
ini_section_delete_var(cat, temp);
}
sprintf(temp, "hdd_%02i_mfm_channel", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "hdd_%02i_ide_channel", c + 1);
ini_section_delete_var(cat, temp);
}
}
/* Load "Floppy and CD-ROM Drives" section. */
static void
load_floppy_and_cdrom_drives(void)
{
ini_section_t cat = ini_find_section(config, "Floppy and CD-ROM drives");
char temp[512];
char tmp2[512];
char *p;
char s[512];
unsigned int board = 0;
unsigned int dev = 0;
int c;
int d = 0;
memset(temp, 0x00, sizeof(temp));
for (c = 0; c < FDD_NUM; c++) {
sprintf(temp, "fdd_%02i_type", c + 1);
p = ini_section_get_string(cat, temp, (c < 2) ? "525_2dd" : "none");
fdd_set_type(c, fdd_get_from_internal_name(p));
if (fdd_get_type(c) > 13)
fdd_set_type(c, 13);
sprintf(temp, "fdd_%02i_fn", c + 1);
p = ini_section_get_string(cat, temp, "");
if (!strcmp(p, usr_path))
p[0] = 0x00;
if (p[0] != 0x00) {
if (path_abs(p)) {
if (strlen(p) > 511)
fatal("load_floppy_and_cdrom_drives(): strlen(p) > 511 (floppyfns[%i])\n", c);
else
strncpy(floppyfns[c], p, 511);
} else
path_append_filename(floppyfns[c], usr_path, p);
path_normalize(floppyfns[c]);
}
#if defined(ENABLE_CONFIG_LOG) && (ENABLE_CONFIG_LOG == 2)
if (*p != '\0')
config_log("Floppy%d: %ls\n", c, floppyfns[c]);
#endif
sprintf(temp, "fdd_%02i_writeprot", c + 1);
ui_writeprot[c] = !!ini_section_get_int(cat, temp, 0);
sprintf(temp, "fdd_%02i_turbo", c + 1);
fdd_set_turbo(c, !!ini_section_get_int(cat, temp, 0));
sprintf(temp, "fdd_%02i_check_bpb", c + 1);
fdd_set_check_bpb(c, !!ini_section_get_int(cat, temp, 1));
/* Check whether each value is default, if yes, delete it so that only
non-default values will later be saved. */
if (fdd_get_type(c) == ((c < 2) ? 2 : 0)) {
sprintf(temp, "fdd_%02i_type", c + 1);
ini_section_delete_var(cat, temp);
}
if (strlen(floppyfns[c]) == 0) {
sprintf(temp, "fdd_%02i_fn", c + 1);
ini_section_delete_var(cat, temp);
}
if (ui_writeprot[c] == 0) {
sprintf(temp, "fdd_%02i_writeprot", c + 1);
ini_section_delete_var(cat, temp);
}
if (fdd_get_turbo(c) == 0) {
sprintf(temp, "fdd_%02i_turbo", c + 1);
ini_section_delete_var(cat, temp);
}
if (fdd_get_check_bpb(c) == 1) {
sprintf(temp, "fdd_%02i_check_bpb", c + 1);
ini_section_delete_var(cat, temp);
}
for (int i = 0; i < MAX_PREV_IMAGES; i++) {
fdd_image_history[c][i] = (char *) calloc((MAX_IMAGE_PATH_LEN + 1) << 1, sizeof(char));
sprintf(temp, "fdd_%02i_image_history_%02i", c + 1, i + 1);
p = ini_section_get_string(cat, temp, NULL);
if (p) {
if (path_abs(p)) {
if (strlen(p) > (MAX_IMAGE_PATH_LEN - 1))
fatal("load_floppy_and_cdrom_drives(): strlen(p) > 2047 "
"(fdd_image_history[%i][%i])\n", c, i);
else
snprintf(fdd_image_history[c][i], (MAX_IMAGE_PATH_LEN - 1), "%s", p);
} else
snprintf(fdd_image_history[c][i], (MAX_IMAGE_PATH_LEN - 1), "%s%s%s", usr_path,
path_get_slash(usr_path), p);
path_normalize(fdd_image_history[c][i]);
}
}
}
memset(temp, 0x00, sizeof(temp));
for (c = 0; c < CDROM_NUM; c++) {
sprintf(temp, "cdrom_%02i_host_drive", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "cdrom_%02i_parameters", c + 1);
p = ini_section_get_string(cat, temp, NULL);
if (p != NULL)
sscanf(p, "%01u, %s", &d, s);
else if (c == 0)
/* If this is the first drive, unmute the audio. */
sscanf("1, none", "%01u, %s", &d, s);
else
sscanf("0, none", "%01u, %s", &d, s);
cdrom[c].sound_on = d;
cdrom[c].bus_type = hdd_string_to_bus(s, 1);
sprintf(temp, "cdrom_%02i_speed", c + 1);
cdrom[c].speed = ini_section_get_int(cat, temp, 8);
sprintf(temp, "cdrom_%02i_type", c + 1);
p = ini_section_get_string(cat, temp, (c == 1) ? "86BOX_CD-ROM_1.00" : "none");
cdrom_set_type(c, cdrom_get_from_internal_name(p));
if (cdrom_get_type(c) > KNOWN_CDROM_DRIVE_TYPES)
cdrom_set_type(c, KNOWN_CDROM_DRIVE_TYPES);
ini_section_delete_var(cat, temp);
/* Default values, needed for proper operation of the Settings dialog. */
cdrom[c].ide_channel = cdrom[c].scsi_device_id = c + 2;
if (cdrom[c].bus_type == CDROM_BUS_ATAPI) {
sprintf(temp, "cdrom_%02i_ide_channel", c + 1);
sprintf(tmp2, "%01u:%01u", (c + 2) >> 1, (c + 2) & 1);
p = ini_section_get_string(cat, temp, tmp2);
sscanf(p, "%01u:%01u", &board, &dev);
board &= 3;
dev &= 1;
cdrom[c].ide_channel = (board << 1) + dev;
if (cdrom[c].ide_channel > 7)
cdrom[c].ide_channel = 7;
} else if (cdrom[c].bus_type == CDROM_BUS_SCSI) {
sprintf(temp, "cdrom_%02i_scsi_location", c + 1);
sprintf(tmp2, "%01u:%02u", SCSI_BUS_MAX, c + 2);
p = ini_section_get_string(cat, temp, tmp2);
sscanf(p, "%01u:%02u", &board, &dev);
if (board >= SCSI_BUS_MAX) {
/* Invalid bus - check legacy ID */
sprintf(temp, "cdrom_%02i_scsi_id", c + 1);
cdrom[c].scsi_device_id = ini_section_get_int(cat, temp, c + 2);
if (cdrom[c].scsi_device_id > 15)
cdrom[c].scsi_device_id = 15;
} else {
board %= SCSI_BUS_MAX;
dev &= 15;
cdrom[c].scsi_device_id = (board << 4) + dev;
}
}
if (cdrom[c].bus_type != CDROM_BUS_ATAPI) {
sprintf(temp, "cdrom_%02i_ide_channel", c + 1);
ini_section_delete_var(cat, temp);
}
if (cdrom[c].bus_type != CDROM_BUS_SCSI) {
sprintf(temp, "cdrom_%02i_scsi_location", c + 1);
ini_section_delete_var(cat, temp);
}
sprintf(temp, "cdrom_%02i_scsi_id", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "cdrom_%02i_image_path", c + 1);
p = ini_section_get_string(cat, temp, "");
if (!strcmp(p, usr_path))
p[0] = 0x00;
if (p[0] != 0x00) {
if (path_abs(p)) {
if (strlen(p) > 511)
fatal("load_floppy_and_cdrom_drives(): strlen(p) > 511 (cdrom[%i].image_path)\n", c);
else
strncpy(cdrom[c].image_path, p, 511);
} else
path_append_filename(cdrom[c].image_path, usr_path, p);
path_normalize(cdrom[c].image_path);
}
for (int i = 0; i < MAX_PREV_IMAGES; i++) {
cdrom[c].image_history[i] = (char *) calloc((MAX_IMAGE_PATH_LEN + 1) << 1, sizeof(char));
sprintf(temp, "cdrom_%02i_image_history_%02i", c + 1, i + 1);
p = ini_section_get_string(cat, temp, NULL);
if (p) {
if (path_abs(p)) {
if (strlen(p) > (MAX_IMAGE_PATH_LEN - 1))
fatal("load_floppy_and_cdrom_drives(): strlen(p) > 2047 "
"(cdrom[%i].image_history[%i])\n", c, i);
else
snprintf(cdrom[c].image_history[i], (MAX_IMAGE_PATH_LEN - 1), "%s", p);
} else
snprintf(cdrom[c].image_history[i], (MAX_IMAGE_PATH_LEN - 1), "%s%s%s", usr_path,
path_get_slash(usr_path), p);
path_normalize(cdrom[c].image_history[i]);
}
}
/* If the CD-ROM is disabled, delete all its variables. */
if (cdrom[c].bus_type == CDROM_BUS_DISABLED) {
sprintf(temp, "cdrom_%02i_parameters", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "cdrom_%02i_ide_channel", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "cdrom_%02i_scsi_id", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "cdrom_%02i_image_path", c + 1);
ini_section_delete_var(cat, temp);
for (int i = 0; i < MAX_PREV_IMAGES; i++) {
sprintf(temp, "cdrom_%02i_image_history_%02i", c + 1, i + 1);
ini_section_delete_var(cat, temp);
}
}
sprintf(temp, "cdrom_%02i_iso_path", c + 1);
ini_section_delete_var(cat, temp);
}
}
/* Load "Other Removable Devices" section. */
static void
load_other_removable_devices(void)
{
ini_section_t cat = ini_find_section(config, "Other removable devices");
char temp[512];
char tmp2[512];
char *p;
char s[512];
unsigned int board = 0;
unsigned int dev = 0;
int c;
memset(temp, 0x00, sizeof(temp));
for (c = 0; c < ZIP_NUM; c++) {
sprintf(temp, "zip_%02i_parameters", c + 1);
p = ini_section_get_string(cat, temp, NULL);
if (p != NULL)
sscanf(p, "%01u, %s", &zip_drives[c].is_250, s);
else
sscanf("0, none", "%01u, %s", &zip_drives[c].is_250, s);
zip_drives[c].bus_type = hdd_string_to_bus(s, 1);
/* Default values, needed for proper operation of the Settings dialog. */
zip_drives[c].ide_channel = zip_drives[c].scsi_device_id = c + 2;
if (zip_drives[c].bus_type == ZIP_BUS_ATAPI) {
sprintf(temp, "zip_%02i_ide_channel", c + 1);
sprintf(tmp2, "%01u:%01u", (c + 2) >> 1, (c + 2) & 1);
p = ini_section_get_string(cat, temp, tmp2);
sscanf(p, "%01u:%01u", &board, &dev);
board &= 3;
dev &= 1;
zip_drives[c].ide_channel = (board << 1) + dev;
if (zip_drives[c].ide_channel > 7)
zip_drives[c].ide_channel = 7;
} else if (zip_drives[c].bus_type == ZIP_BUS_SCSI) {
sprintf(temp, "zip_%02i_scsi_location", c + 1);
sprintf(tmp2, "%01u:%02u", SCSI_BUS_MAX, c + 2);
p = ini_section_get_string(cat, temp, tmp2);
sscanf(p, "%01u:%02u", &board, &dev);
if (board >= SCSI_BUS_MAX) {
/* Invalid bus - check legacy ID */
sprintf(temp, "zip_%02i_scsi_id", c + 1);
zip_drives[c].scsi_device_id = ini_section_get_int(cat, temp, c + 2);
if (zip_drives[c].scsi_device_id > 15)
zip_drives[c].scsi_device_id = 15;
} else {
board %= SCSI_BUS_MAX;
dev &= 15;
zip_drives[c].scsi_device_id = (board << 4) + dev;
}
}
if (zip_drives[c].bus_type != ZIP_BUS_ATAPI) {
sprintf(temp, "zip_%02i_ide_channel", c + 1);
ini_section_delete_var(cat, temp);
}
if (zip_drives[c].bus_type != ZIP_BUS_SCSI) {
sprintf(temp, "zip_%02i_scsi_location", c + 1);
ini_section_delete_var(cat, temp);
}
sprintf(temp, "zip_%02i_scsi_id", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "zip_%02i_image_path", c + 1);
p = ini_section_get_string(cat, temp, "");
if (!strcmp(p, usr_path))
p[0] = 0x00;
if (p[0] != 0x00) {
if (path_abs(p)) {
if (strlen(p) > 511)
fatal("load_other_removable_devices(): strlen(p) > 511 (zip_drives[%i].image_path)\n",
c);
else
strncpy(zip_drives[c].image_path, p, 511);
} else
path_append_filename(zip_drives[c].image_path, usr_path, p);
path_normalize(zip_drives[c].image_path);
}
for (int i = 0; i < MAX_PREV_IMAGES; i++) {
zip_drives[c].image_history[i] = (char *) calloc((MAX_IMAGE_PATH_LEN + 1) << 1, sizeof(char));
sprintf(temp, "zip_%02i_image_history_%02i", c + 1, i + 1);
p = ini_section_get_string(cat, temp, NULL);
if (p) {
if (path_abs(p)) {
if (strlen(p) > (MAX_IMAGE_PATH_LEN - 1))
fatal("load_other_removable_devices(): strlen(p) > 2047 "
"(zip_drives[%i].image_history[%i])\n", c, i);
else
snprintf(zip_drives[c].image_history[i], (MAX_IMAGE_PATH_LEN - 1), "%s", p);
} else
snprintf(zip_drives[c].image_history[i], (MAX_IMAGE_PATH_LEN - 1), "%s%s%s", usr_path,
path_get_slash(usr_path), p);
path_normalize(zip_drives[c].image_history[i]);
}
}
/* If the ZIP drive is disabled, delete all its variables. */
if (zip_drives[c].bus_type == ZIP_BUS_DISABLED) {
sprintf(temp, "zip_%02i_parameters", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "zip_%02i_ide_channel", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "zip_%02i_scsi_id", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "zip_%02i_image_path", c + 1);
ini_section_delete_var(cat, temp);
for (int i = 0; i < MAX_PREV_IMAGES; i++) {
sprintf(temp, "zip_%02i_image_history_%02i", c + 1, i + 1);
ini_section_delete_var(cat, temp);
}
}
}
memset(temp, 0x00, sizeof(temp));
for (c = 0; c < MO_NUM; c++) {
sprintf(temp, "mo_%02i_parameters", c + 1);
p = ini_section_get_string(cat, temp, NULL);
if (p != NULL)
sscanf(p, "%u, %s", &mo_drives[c].type, s);
else
sscanf("00, none", "%u, %s", &mo_drives[c].type, s);
mo_drives[c].bus_type = hdd_string_to_bus(s, 1);
/* Default values, needed for proper operation of the Settings dialog. */
mo_drives[c].ide_channel = mo_drives[c].scsi_device_id = c + 2;
if (mo_drives[c].bus_type == MO_BUS_ATAPI) {
sprintf(temp, "mo_%02i_ide_channel", c + 1);
sprintf(tmp2, "%01u:%01u", (c + 2) >> 1, (c + 2) & 1);
p = ini_section_get_string(cat, temp, tmp2);
sscanf(p, "%01u:%01u", &board, &dev);
board &= 3;
dev &= 1;
mo_drives[c].ide_channel = (board << 1) + dev;
if (mo_drives[c].ide_channel > 7)
mo_drives[c].ide_channel = 7;
} else if (mo_drives[c].bus_type == MO_BUS_SCSI) {
sprintf(temp, "mo_%02i_scsi_location", c + 1);
sprintf(tmp2, "%01u:%02u", SCSI_BUS_MAX, c + 2);
p = ini_section_get_string(cat, temp, tmp2);
sscanf(p, "%01u:%02u", &board, &dev);
if (board >= SCSI_BUS_MAX) {
/* Invalid bus - check legacy ID */
sprintf(temp, "mo_%02i_scsi_id", c + 1);
mo_drives[c].scsi_device_id = ini_section_get_int(cat, temp, c + 2);
if (mo_drives[c].scsi_device_id > 15)
mo_drives[c].scsi_device_id = 15;
} else {
board %= SCSI_BUS_MAX;
dev &= 15;
mo_drives[c].scsi_device_id = (board << 4) + dev;
}
}
if (mo_drives[c].bus_type != MO_BUS_ATAPI) {
sprintf(temp, "mo_%02i_ide_channel", c + 1);
ini_section_delete_var(cat, temp);
}
if (mo_drives[c].bus_type != MO_BUS_SCSI) {
sprintf(temp, "mo_%02i_scsi_location", c + 1);
ini_section_delete_var(cat, temp);
}
sprintf(temp, "mo_%02i_scsi_id", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "mo_%02i_image_path", c + 1);
p = ini_section_get_string(cat, temp, "");
if (!strcmp(p, usr_path))
p[0] = 0x00;
if (p[0] != 0x00) {
if (path_abs(p)) {
if (strlen(p) > 511)
fatal("load_other_removable_devices(): strlen(p) > 511 (mo_drives[%i].image_path)\n",
c);
else
strncpy(mo_drives[c].image_path, p, 511);
} else
path_append_filename(mo_drives[c].image_path, usr_path, p);
path_normalize(mo_drives[c].image_path);
}
for (int i = 0; i < MAX_PREV_IMAGES; i++) {
mo_drives[c].image_history[i] = (char *) calloc((MAX_IMAGE_PATH_LEN + 1) << 1, sizeof(char));
sprintf(temp, "mo_%02i_image_history_%02i", c + 1, i + 1);
p = ini_section_get_string(cat, temp, NULL);
if (p) {
if (path_abs(p)) {
if (strlen(p) > (MAX_IMAGE_PATH_LEN - 1))
fatal("load_other_removable_devices(): strlen(p) > 2047 "
"(mo_drives[%i].image_history[%i])\n", c, i);
else
snprintf(mo_drives[c].image_history[i], (MAX_IMAGE_PATH_LEN - 1), "%s", p);
} else
snprintf(mo_drives[c].image_history[i], (MAX_IMAGE_PATH_LEN - 1), "%s%s%s", usr_path,
path_get_slash(usr_path), p);
path_normalize(mo_drives[c].image_history[i]);
}
}
/* If the MO drive is disabled, delete all its variables. */
if (mo_drives[c].bus_type == MO_BUS_DISABLED) {
sprintf(temp, "mo_%02i_parameters", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "mo_%02i_ide_channel", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "mo_%02i_scsi_id", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "mo_%02i_image_path", c + 1);
ini_section_delete_var(cat, temp);
for (int i = 0; i < MAX_PREV_IMAGES; i++) {
sprintf(temp, "mo_%02i_image_history_%02i", c + 1, i + 1);
ini_section_delete_var(cat, temp);
}
}
}
}
/* Load "Other Peripherals" section. */
static void
load_other_peripherals(void)
{
ini_section_t cat = ini_find_section(config, "Other peripherals");
char *p;
char temp[512];
bugger_enabled = !!ini_section_get_int(cat, "bugger_enabled", 0);
postcard_enabled = !!ini_section_get_int(cat, "postcard_enabled", 0);
unittester_enabled = !!ini_section_get_int(cat, "unittester_enabled", 0);
novell_keycard_enabled = !!ini_section_get_int(cat, "novell_keycard_enabled", 0);
for (uint8_t c = 0; c < ISAMEM_MAX; c++) {
sprintf(temp, "isamem%d_type", c);
p = ini_section_get_string(cat, temp, "none");
isamem_type[c] = isamem_get_from_internal_name(p);
}
p = ini_section_get_string(cat, "isartc_type", "none");
isartc_type = isartc_get_from_internal_name(p);
}
/* Load the specified or a default configuration file. */
void
config_load(void)
{
int i;
ini_section_t c;
config_log("Loading config file '%s'..\n", cfg_path);
memset(hdd, 0, sizeof(hard_disk_t));
memset(cdrom, 0, sizeof(cdrom_t) * CDROM_NUM);
#ifdef USE_IOCTL
memset(cdrom_ioctl, 0, sizeof(cdrom_ioctl_t) * CDROM_NUM);
#endif
memset(zip_drives, 0, sizeof(zip_drive_t));
config = ini_read(cfg_path);
if (!config) {
config = ini_new();
config_changed = 1;
cpu_f = (cpu_family_t *) &cpu_families[0];
cpu = 0;
kbd_req_capture = 0;
hide_status_bar = 0;
hide_tool_bar = 0;
scale = 1;
machine = machine_get_machine_from_internal_name("ibmpc");
dpi_scale = 1;
do_auto_pause = 0;
cpu_override_interpreter = 0;
fpu_type = fpu_get_type(cpu_f, cpu, "none");
gfxcard[0] = video_get_video_from_internal_name("cga");
vid_api = plat_vidapi("default");
vid_resize = 0;
video_fullscreen_first = 1;
video_fullscreen_scale = 1;
time_sync = TIME_SYNC_ENABLED;
hdc_current[0] = hdc_get_from_internal_name("none");
com_ports[0].enabled = 1;
com_ports[1].enabled = 1;
for (i = 2; i < SERIAL_MAX; i++)
com_ports[i].enabled = 0;
lpt_ports[0].enabled = 1;
for (i = 1; i < PARALLEL_MAX; i++)
lpt_ports[i].enabled = 0;
for (i = 0; i < FDD_NUM; i++) {
if (i < 2)
fdd_set_type(i, 2);
else
fdd_set_type(i, 0);
fdd_set_turbo(i, 0);
fdd_set_check_bpb(i, 1);
}
/* Unmute the CD audio on the first CD-ROM drive. */
cdrom[0].sound_on = 1;
mem_size = 64;
isartc_type = 0;
for (i = 0; i < ISAMEM_MAX; i++)
isamem_type[i] = 0;
cassette_enable = 1;
memset(cassette_fname, 0x00, sizeof(cassette_fname));
memcpy(cassette_mode, "load", strlen("load") + 1);
cassette_pos = 0;
cassette_srate = 44100;
cassette_append = 0;
cassette_pcm = 0;
cassette_ui_writeprot = 0;
config_log("Config file not present or invalid!\n");
} else {
load_general(); /* General */
for (i = 0; i < MONITORS_NUM; i++)
load_monitor(i); /* Monitors */
load_machine(); /* Machine */
load_video(); /* Video */
load_input_devices(); /* Input devices */
load_sound(); /* Sound */
load_network(); /* Network */
load_ports(); /* Ports (COM & LPT) */
load_storage_controllers(); /* Storage controllers */
load_hard_disks(); /* Hard disks */
load_floppy_and_cdrom_drives(); /* Floppy and CD-ROM drives */
load_other_removable_devices(); /* Other removable devices */
load_other_peripherals(); /* Other peripherals */
/* Migrate renamed device configurations. */
c = ini_find_section(config, "MDA");
if (c != NULL)
ini_rename_section(c, "IBM MDA");
c = ini_find_section(config, "CGA");
if (c != NULL)
ini_rename_section(c, "IBM CGA");
c = ini_find_section(config, "EGA");
if (c != NULL)
ini_rename_section(c, "IBM EGA");
c = ini_find_section(config, "3DFX Voodoo Graphics");
if (c != NULL)
ini_rename_section(c, "3Dfx Voodoo Graphics");
c = ini_find_section(config, "3dfx Voodoo Banshee");
if (c != NULL)
ini_rename_section(c, "3Dfx Voodoo Banshee");
/* Mark the configuration as changed. */
config_changed = 1;
config_log("Config loaded.\n\n");
}
video_copy = (video_grayscale || invert_display) ? video_transform_copy : memcpy;
}
/* Save "General" section. */
static void
save_general(void)
{
ini_section_t cat = ini_find_or_create_section(config, "General");
char temp[512];
char buffer[512] = { 0 };
const char *va_name;
ini_section_set_int(cat, "vid_resize", vid_resize);
if (vid_resize == 0)
ini_section_delete_var(cat, "vid_resize");
va_name = plat_vidapi_name(vid_api);
if (!strcmp(va_name, "default"))
ini_section_delete_var(cat, "vid_renderer");
else
ini_section_set_string(cat, "vid_renderer", va_name);
if (video_fullscreen_scale == 1)
ini_section_delete_var(cat, "video_fullscreen_scale");
else
ini_section_set_int(cat, "video_fullscreen_scale", video_fullscreen_scale);
if (video_fullscreen_first == 1)
ini_section_delete_var(cat, "video_fullscreen_first");
else
ini_section_set_int(cat, "video_fullscreen_first", video_fullscreen_first);
if (video_filter_method == 1)
ini_section_delete_var(cat, "video_filter_method");
else
ini_section_set_int(cat, "video_filter_method", video_filter_method);
if (force_43 == 0)
ini_section_delete_var(cat, "force_43");
else
ini_section_set_int(cat, "force_43", force_43);
if (scale == 1)
ini_section_delete_var(cat, "scale");
else
ini_section_set_int(cat, "scale", scale);
if (dpi_scale == 1)
ini_section_delete_var(cat, "dpi_scale");
else
ini_section_set_int(cat, "dpi_scale", dpi_scale);
if (enable_overscan == 0)
ini_section_delete_var(cat, "enable_overscan");
else
ini_section_set_int(cat, "enable_overscan", enable_overscan);
if (vid_cga_contrast == 0)
ini_section_delete_var(cat, "vid_cga_contrast");
else
ini_section_set_int(cat, "vid_cga_contrast", vid_cga_contrast);
if (video_grayscale == 0)
ini_section_delete_var(cat, "video_grayscale");
else
ini_section_set_int(cat, "video_grayscale", video_grayscale);
if (video_graytype == 0)
ini_section_delete_var(cat, "video_graytype");
else
ini_section_set_int(cat, "video_graytype", video_graytype);
if (rctrl_is_lalt == 0)
ini_section_delete_var(cat, "rctrl_is_lalt");
else
ini_section_set_int(cat, "rctrl_is_lalt", rctrl_is_lalt);
if (update_icons == 1)
ini_section_delete_var(cat, "update_icons");
else
ini_section_set_int(cat, "update_icons", update_icons);
if (window_remember)
ini_section_set_int(cat, "window_remember", window_remember);
else
ini_section_delete_var(cat, "window_remember");
if (vid_resize & 2) {
sprintf(temp, "%ix%i", fixed_size_x, fixed_size_y);
ini_section_set_string(cat, "window_fixed_res", temp);
} else
ini_section_delete_var(cat, "window_fixed_res");
if (sound_gain != 0)
ini_section_set_int(cat, "sound_gain", sound_gain);
else
ini_section_delete_var(cat, "sound_gain");
if (kbd_req_capture != 0)
ini_section_set_int(cat, "kbd_req_capture", kbd_req_capture);
else
ini_section_delete_var(cat, "kbd_req_capture");
if (hide_status_bar != 0)
ini_section_set_int(cat, "hide_status_bar", hide_status_bar);
else
ini_section_delete_var(cat, "hide_status_bar");
if (hide_tool_bar != 0)
ini_section_set_int(cat, "hide_tool_bar", hide_tool_bar);
else
ini_section_delete_var(cat, "hide_tool_bar");
if (confirm_reset != 1)
ini_section_set_int(cat, "confirm_reset", confirm_reset);
else
ini_section_delete_var(cat, "confirm_reset");
if (confirm_exit != 1)
ini_section_set_int(cat, "confirm_exit", confirm_exit);
else
ini_section_delete_var(cat, "confirm_exit");
if (confirm_save != 1)
ini_section_set_int(cat, "confirm_save", confirm_save);
else
ini_section_delete_var(cat, "confirm_save");
if (mouse_sensitivity != 1.0)
ini_section_set_double(cat, "mouse_sensitivity", mouse_sensitivity);
else
ini_section_delete_var(cat, "mouse_sensitivity");
if (lang_id == DEFAULT_LANGUAGE)
ini_section_delete_var(cat, "language");
else {
plat_language_code_r(lang_id, buffer, 511);
ini_section_set_string(cat, "language", buffer);
}
if (!strcmp(icon_set, ""))
ini_section_delete_var(cat, "iconset");
else
ini_section_set_string(cat, "iconset", icon_set);
if (enable_discord)
ini_section_set_int(cat, "enable_discord", enable_discord);
else
ini_section_delete_var(cat, "enable_discord");
if (open_dir_usr_path)
ini_section_set_int(cat, "open_dir_usr_path", open_dir_usr_path);
else
ini_section_delete_var(cat, "open_dir_usr_path");
if (video_framerate != -1)
ini_section_set_int(cat, "video_gl_framerate", video_framerate);
else
ini_section_delete_var(cat, "video_gl_framerate");
if (video_vsync != 0)
ini_section_set_int(cat, "video_gl_vsync", video_vsync);
else
ini_section_delete_var(cat, "video_gl_vsync");
if (strlen(video_shader) > 0)
ini_section_set_string(cat, "video_gl_shader", video_shader);
else
ini_section_delete_var(cat, "video_gl_shader");
if (do_auto_pause)
ini_section_set_int(cat, "do_auto_pause", do_auto_pause);
else
ini_section_delete_var(cat, "do_auto_pause");
char cpu_buf[128] = { 0 };
plat_get_cpu_string(cpu_buf, 128);
ini_section_set_string(cat, "host_cpu", cpu_buf);
if (EMU_BUILD_NUM != 0)
ini_section_set_int(cat, "emu_build_num", EMU_BUILD_NUM);
else
ini_section_delete_var(cat, "emu_build_num");
if (strnlen(uuid, sizeof(uuid) - 1) > 0)
ini_section_set_string(cat, "uuid", uuid);
else
ini_section_delete_var(cat, "uuid");
ini_delete_section_if_empty(config, cat);
}
/* Save monitor section. */
static void
save_monitor(int monitor_index)
{
ini_section_t cat;
char name[sizeof("Monitor #") + 12] = { [0] = 0 };
char temp[512];
monitor_settings_t *ms = &monitor_settings[monitor_index];
snprintf(name, sizeof(name), "Monitor #%i", monitor_index + 1);
cat = ini_find_or_create_section(config, name);
if (window_remember) {
sprintf(temp, "%i, %i, %i, %i", ms->mon_window_x, ms->mon_window_y,
ms->mon_window_w, ms->mon_window_h);
ini_section_set_string(cat, "window_coordinates", temp);
if (ms->mon_window_maximized != 0)
ini_section_set_int(cat, "window_maximized", ms->mon_window_maximized);
else
ini_section_delete_var(cat, "window_maximized");
} else {
ini_section_delete_var(cat, "window_coordinates");
ini_section_delete_var(cat, "window_maximized");
}
ini_delete_section_if_empty(config, cat);
}
/* Save "Machine" section. */
static void
save_machine(void)
{
ini_section_t cat = ini_find_or_create_section(config, "Machine");
const char *p;
p = machine_get_internal_name();
ini_section_set_string(cat, "machine", p);
ini_section_set_string(cat, "cpu_family", cpu_f->internal_name);
ini_section_set_uint(cat, "cpu_speed", cpu_f->cpus[cpu].rspeed);
ini_section_set_double(cat, "cpu_multi", cpu_f->cpus[cpu].multi);
if (cpu_override)
ini_section_set_int(cat, "cpu_override", cpu_override);
else
ini_section_delete_var(cat, "cpu_override");
if (cpu_override_interpreter)
ini_section_set_int(cat, "cpu_override_interpreter", cpu_override_interpreter);
else
ini_section_delete_var(cat, "cpu_override_interpreter");
/* Downgrade compatibility with the previous CPU model system. */
ini_section_delete_var(cat, "cpu_manufacturer");
ini_section_delete_var(cat, "cpu");
if (cpu_waitstates == 0)
ini_section_delete_var(cat, "cpu_waitstates");
else
ini_section_set_int(cat, "cpu_waitstates", cpu_waitstates);
if (fpu_type == 0)
ini_section_delete_var(cat, "fpu_type");
else
ini_section_set_string(cat, "fpu_type", fpu_get_internal_name(cpu_f, cpu, fpu_type));
/* Write the mem_size explicitly to the setttings in order to help managers
to display it without having the actual machine table. */
ini_section_delete_var(cat, "mem_size");
ini_section_set_int(cat, "mem_size", mem_size);
ini_section_set_int(cat, "cpu_use_dynarec", cpu_use_dynarec);
ini_section_set_int(cat, "fpu_softfloat", fpu_softfloat);
if (time_sync & TIME_SYNC_ENABLED)
if (time_sync & TIME_SYNC_UTC)
ini_section_set_string(cat, "time_sync", "utc");
else
ini_section_set_string(cat, "time_sync", "local");
else
ini_section_set_string(cat, "time_sync", "disabled");
if (pit_mode == -1)
ini_section_delete_var(cat, "pit_mode");
else
ini_section_set_int(cat, "pit_mode", pit_mode);
ini_delete_section_if_empty(config, cat);
}
/* Save "Video" section. */
static void
save_video(void)
{
ini_section_t cat = ini_find_or_create_section(config, "Video");
ini_section_set_string(cat, "gfxcard",
video_get_internal_name(gfxcard[0]));
if (voodoo_enabled == 0)
ini_section_delete_var(cat, "voodoo");
else
ini_section_set_int(cat, "voodoo", voodoo_enabled);
if (ibm8514_standalone_enabled == 0)
ini_section_delete_var(cat, "8514a");
else
ini_section_set_int(cat, "8514a", ibm8514_standalone_enabled);
if (xga_standalone_enabled == 0)
ini_section_delete_var(cat, "xga");
else
ini_section_set_int(cat, "xga", xga_standalone_enabled);
// TODO
for (uint8_t i = 1; i < GFXCARD_MAX; i ++) {
if (gfxcard[i] == 0)
ini_section_delete_var(cat, "gfxcard_2");
else
ini_section_set_string(cat, "gfxcard_2", video_get_internal_name(gfxcard[i]));
}
if (show_second_monitors == 1)
ini_section_delete_var(cat, "show_second_monitors");
else
ini_section_set_int(cat, "show_second_monitors", show_second_monitors);
if (video_fullscreen_scale_maximized == 0)
ini_section_delete_var(cat, "video_fullscreen_scale_maximized");
else
ini_section_set_int(cat, "video_fullscreen_scale_maximized", video_fullscreen_scale_maximized);
ini_delete_section_if_empty(config, cat);
}
/* Save "Input Devices" section. */
static void
save_input_devices(void)
{
ini_section_t cat = ini_find_or_create_section(config, "Input devices");
char temp[512];
char tmp2[512];
int c;
int d;
ini_section_set_string(cat, "mouse_type", mouse_get_internal_name(mouse_type));
if (!joystick_type) {
ini_section_delete_var(cat, "joystick_type");
for (c = 0; c < 16; c++) {
sprintf(tmp2, "joystick_%i_nr", c);
ini_section_delete_var(cat, tmp2);
for (d = 0; d < 16; d++) {
sprintf(tmp2, "joystick_%i_axis_%i", c, d);
ini_section_delete_var(cat, tmp2);
}
for (d = 0; d < 16; d++) {
sprintf(tmp2, "joystick_%i_button_%i", c, d);
ini_section_delete_var(cat, tmp2);
}
for (d = 0; d < 16; d++) {
sprintf(tmp2, "joystick_%i_pov_%i", c, d);
ini_section_delete_var(cat, tmp2);
}
}
} else {
ini_section_set_string(cat, "joystick_type", joystick_get_internal_name(joystick_type));
for (c = 0; c < joystick_get_max_joysticks(joystick_type); c++) {
sprintf(tmp2, "joystick_%i_nr", c);
ini_section_set_int(cat, tmp2, joystick_state[c].plat_joystick_nr);
if (joystick_state[c].plat_joystick_nr) {
for (d = 0; d < joystick_get_axis_count(joystick_type); d++) {
sprintf(tmp2, "joystick_%i_axis_%i", c, d);
ini_section_set_int(cat, tmp2, joystick_state[c].axis_mapping[d]);
}
for (d = 0; d < joystick_get_button_count(joystick_type); d++) {
sprintf(tmp2, "joystick_%i_button_%i", c, d);
ini_section_set_int(cat, tmp2, joystick_state[c].button_mapping[d]);
}
for (d = 0; d < joystick_get_pov_count(joystick_type); d++) {
sprintf(tmp2, "joystick_%i_pov_%i", c, d);
sprintf(temp, "%i, %i", joystick_state[c].pov_mapping[d][0], joystick_state[c].pov_mapping[d][1]);
ini_section_set_string(cat, tmp2, temp);
}
}
}
}
if (tablet_tool_type != 1) {
ini_section_set_int(cat, "tablet_tool_type", tablet_tool_type);
} else {
ini_section_delete_var(cat, "tablet_tool_type");
}
ini_delete_section_if_empty(config, cat);
}
/* Save "Sound" section. */
static void
save_sound(void)
{
ini_section_t cat = ini_find_or_create_section(config, "Sound");
if (sound_card_current[0] == 0)
ini_section_delete_var(cat, "sndcard");
else
ini_section_set_string(cat, "sndcard", sound_card_get_internal_name(sound_card_current[0]));
if (sound_card_current[1] == 0)
ini_section_delete_var(cat, "sndcard2");
else
ini_section_set_string(cat, "sndcard2", sound_card_get_internal_name(sound_card_current[1]));
if (sound_card_current[2] == 0)
ini_section_delete_var(cat, "sndcard3");
else
ini_section_set_string(cat, "sndcard3", sound_card_get_internal_name(sound_card_current[2]));
if (sound_card_current[3] == 0)
ini_section_delete_var(cat, "sndcard4");
else
ini_section_set_string(cat, "sndcard4", sound_card_get_internal_name(sound_card_current[3]));
if (!strcmp(midi_out_device_get_internal_name(midi_output_device_current), "none"))
ini_section_delete_var(cat, "midi_device");
else
ini_section_set_string(cat, "midi_device", midi_out_device_get_internal_name(midi_output_device_current));
if (!strcmp(midi_in_device_get_internal_name(midi_input_device_current), "none"))
ini_section_delete_var(cat, "midi_in_device");
else
ini_section_set_string(cat, "midi_in_device", midi_in_device_get_internal_name(midi_input_device_current));
if (mpu401_standalone_enable == 0)
ini_section_delete_var(cat, "mpu401_standalone");
else
ini_section_set_int(cat, "mpu401_standalone", mpu401_standalone_enable);
/* Downgrade compatibility for standalone SSI-2001, CMS and GUS from v3.11 and older. */
const char *legacy_cards[][2] = {
{"ssi2001", "ssi2001"},
{ "gameblaster", "cms" },
{ "gus", "gus" }
};
for (int i = 0; i < (sizeof(legacy_cards) / sizeof(legacy_cards[0])); i++) {
int card_id = sound_card_get_from_internal_name(legacy_cards[i][1]);
for (int j = 0; j < (sizeof(sound_card_current) / sizeof(sound_card_current[0])); j++) {
if (sound_card_current[j] == card_id) {
/* A special value of 2 still enables the cards on older versions,
but lets newer versions know that they've already been migrated. */
ini_section_set_int(cat, legacy_cards[i][0], 2);
card_id = 0; /* mark as found */
break;
}
}
if (card_id > 0) /* not found */
ini_section_delete_var(cat, legacy_cards[i][0]);
}
if (sound_is_float == 1)
ini_section_delete_var(cat, "sound_type");
else
ini_section_set_string(cat, "sound_type", (sound_is_float == 1) ? "float" : "int16");
ini_section_set_string(cat, "fm_driver", (fm_driver == FM_DRV_NUKED) ? "nuked" : "ymfm");
ini_delete_section_if_empty(config, cat);
}
/* Save "Network" section. */
static void
save_network(void)
{
char temp[512];
ini_section_t cat = ini_find_or_create_section(config, "Network");
netcard_conf_t *nc;
ini_section_delete_var(cat, "net_type");
ini_section_delete_var(cat, "net_host_device");
ini_section_delete_var(cat, "net_card");
for (uint8_t c = 0; c < NET_CARD_MAX; c++) {
nc = &net_cards_conf[c];
sprintf(temp, "net_%02i_card", c + 1);
if (nc->device_num == 0)
ini_section_delete_var(cat, temp);
else
ini_section_set_string(cat, temp, network_card_get_internal_name(nc->device_num));
sprintf(temp, "net_%02i_net_type", c + 1);
switch(nc->net_type) {
case NET_TYPE_NONE:
ini_section_delete_var(cat, temp);
break;
case NET_TYPE_SLIRP:
ini_section_set_string(cat, temp, "slirp");
break;
case NET_TYPE_PCAP:
ini_section_set_string(cat, temp, "pcap");
break;
case NET_TYPE_VDE:
ini_section_set_string(cat, temp, "vde");
break;
default:
break;
}
sprintf(temp, "net_%02i_host_device", c + 1);
if (nc->host_dev_name[0] != '\0') {
if (!strcmp(nc->host_dev_name, "none"))
ini_section_delete_var(cat, temp);
else
ini_section_set_string(cat, temp, nc->host_dev_name);
} else
ini_section_delete_var(cat, temp);
sprintf(temp, "net_%02i_link", c + 1);
if (nc->link_state == (NET_LINK_10_HD | NET_LINK_10_FD |
NET_LINK_100_HD | NET_LINK_100_FD |
NET_LINK_1000_HD | NET_LINK_1000_FD))
ini_section_delete_var(cat, temp);
else
ini_section_set_int(cat, temp, nc->link_state);
}
ini_delete_section_if_empty(config, cat);
}
/* Save "Ports" section. */
static void
save_ports(void)
{
ini_section_t cat = ini_find_or_create_section(config, "Ports (COM & LPT)");
char temp[512];
int c;
int d;
for (c = 0; c < SERIAL_MAX; c++) {
sprintf(temp, "serial%d_enabled", c + 1);
if (((c < 2) && com_ports[c].enabled) || ((c >= 2) && !com_ports[c].enabled))
ini_section_delete_var(cat, temp);
else
ini_section_set_int(cat, temp, com_ports[c].enabled);
sprintf(temp, "serial%d_passthrough_enabled", c + 1);
if (serial_passthrough_enabled[c]) {
ini_section_set_int(cat, temp, 1);
} else {
ini_section_delete_var(cat, temp);
}
}
for (c = 0; c < PARALLEL_MAX; c++) {
sprintf(temp, "lpt%d_enabled", c + 1);
d = (c == 0) ? 1 : 0;
if (lpt_ports[c].enabled == d)
ini_section_delete_var(cat, temp);
else
ini_section_set_int(cat, temp, lpt_ports[c].enabled);
sprintf(temp, "lpt%d_device", c + 1);
if (lpt_ports[c].device == 0)
ini_section_delete_var(cat, temp);
else
ini_section_set_string(cat, temp,
lpt_device_get_internal_name(lpt_ports[c].device));
}
ini_delete_section_if_empty(config, cat);
}
/* Save "Storage Controllers" section. */
static void
save_storage_controllers(void)
{
ini_section_t cat = ini_find_or_create_section(config, "Storage controllers");
char temp[512];
int c;
ini_section_delete_var(cat, "scsicard");
for (c = 0; c < SCSI_CARD_MAX; c++) {
sprintf(temp, "scsicard_%d", c + 1);
if (scsi_card_current[c] == 0)
ini_section_delete_var(cat, temp);
else
ini_section_set_string(cat, temp,
scsi_card_get_internal_name(scsi_card_current[c]));
}
if (fdc_current[0] == FDC_INTERNAL)
ini_section_delete_var(cat, "fdc");
else
ini_section_set_string(cat, "fdc",
fdc_card_get_internal_name(fdc_current[0]));
ini_section_set_string(cat, "hdc",
hdc_get_internal_name(hdc_current[0]));
if (cdrom_interface_current == 0)
ini_section_delete_var(cat, "cdrom_interface");
else
ini_section_set_string(cat, "cdrom_interface",
cdrom_interface_get_internal_name(cdrom_interface_current));
if (ide_ter_enabled == 0)
ini_section_delete_var(cat, "ide_ter");
else
ini_section_set_int(cat, "ide_ter", ide_ter_enabled);
if (ide_qua_enabled == 0)
ini_section_delete_var(cat, "ide_qua");
else
ini_section_set_int(cat, "ide_qua", ide_qua_enabled);
ini_delete_section_if_empty(config, cat);
if (cassette_enable == 0)
ini_section_delete_var(cat, "cassette_enabled");
else
ini_section_set_int(cat, "cassette_enabled", cassette_enable);
if (strlen(cassette_fname) == 0)
ini_section_delete_var(cat, "cassette_file");
else
ini_section_set_string(cat, "cassette_file", cassette_fname);
if (strlen(cassette_mode) == 0)
ini_section_delete_var(cat, "cassette_mode");
else
ini_section_set_string(cat, "cassette_mode", cassette_mode);
if (cassette_pos == 0)
ini_section_delete_var(cat, "cassette_position");
else
ini_section_set_int(cat, "cassette_position", cassette_pos);
if (cassette_srate == 44100)
ini_section_delete_var(cat, "cassette_srate");
else
ini_section_set_int(cat, "cassette_srate", cassette_srate);
if (cassette_append == 0)
ini_section_delete_var(cat, "cassette_append");
else
ini_section_set_int(cat, "cassette_append", cassette_append);
if (cassette_pcm == 0)
ini_section_delete_var(cat, "cassette_pcm");
else
ini_section_set_int(cat, "cassette_pcm", cassette_pcm);
if (cassette_ui_writeprot == 0)
ini_section_delete_var(cat, "cassette_writeprot");
else
ini_section_set_int(cat, "cassette_writeprot", cassette_ui_writeprot);
for (c = 0; c < 2; c++) {
sprintf(temp, "cartridge_%02i_fn", c + 1);
if (strlen(cart_fns[c]) == 0)
ini_section_delete_var(cat, temp);
else
ini_section_set_string(cat, temp, cart_fns[c]);
}
if (lba_enhancer_enabled == 0)
ini_section_delete_var(cat, "lba_enhancer_enabled");
else
ini_section_set_int(cat, "lba_enhancer_enabled", 1);
}
/* Save "Other Peripherals" section. */
static void
save_other_peripherals(void)
{
ini_section_t cat = ini_find_or_create_section(config, "Other peripherals");
char temp[512];
if (bugger_enabled == 0)
ini_section_delete_var(cat, "bugger_enabled");
else
ini_section_set_int(cat, "bugger_enabled", bugger_enabled);
if (postcard_enabled == 0)
ini_section_delete_var(cat, "postcard_enabled");
else
ini_section_set_int(cat, "postcard_enabled", postcard_enabled);
if (unittester_enabled == 0)
ini_section_delete_var(cat, "unittester_enabled");
else
ini_section_set_int(cat, "unittester_enabled", unittester_enabled);
if (novell_keycard_enabled == 0)
ini_section_delete_var(cat, "novell_keycard_enabled");
else
ini_section_set_int(cat, "novell_keycard_enabled", novell_keycard_enabled);
for (uint8_t c = 0; c < ISAMEM_MAX; c++) {
sprintf(temp, "isamem%d_type", c);
if (isamem_type[c] == 0)
ini_section_delete_var(cat, temp);
else
ini_section_set_string(cat, temp,
isamem_get_internal_name(isamem_type[c]));
}
if (isartc_type == 0)
ini_section_delete_var(cat, "isartc_type");
else
ini_section_set_string(cat, "isartc_type",
isartc_get_internal_name(isartc_type));
ini_delete_section_if_empty(config, cat);
}
/* Save "Hard Disks" section. */
static void
save_hard_disks(void)
{
ini_section_t cat = ini_find_or_create_section(config, "Hard disks");
char temp[32];
char tmp2[512];
char *p;
memset(temp, 0x00, sizeof(temp));
for (uint8_t c = 0; c < HDD_NUM; c++) {
sprintf(temp, "hdd_%02i_parameters", c + 1);
if (hdd_is_valid(c)) {
p = hdd_bus_to_string(hdd[c].bus, 0);
sprintf(tmp2, "%u, %u, %u, %i, %s",
hdd[c].spt, hdd[c].hpc, hdd[c].tracks, hdd[c].wp, p);
ini_section_set_string(cat, temp, tmp2);
} else {
ini_section_delete_var(cat, temp);
}
sprintf(temp, "hdd_%02i_mfm_channel", c + 1);
if (hdd_is_valid(c) && (hdd[c].bus == HDD_BUS_MFM))
ini_section_set_int(cat, temp, hdd[c].mfm_channel);
else
ini_section_delete_var(cat, temp);
sprintf(temp, "hdd_%02i_xta_channel", c + 1);
if (hdd_is_valid(c) && (hdd[c].bus == HDD_BUS_XTA))
ini_section_set_int(cat, temp, hdd[c].xta_channel);
else
ini_section_delete_var(cat, temp);
sprintf(temp, "hdd_%02i_esdi_channel", c + 1);
if (hdd_is_valid(c) && (hdd[c].bus == HDD_BUS_ESDI))
ini_section_set_int(cat, temp, hdd[c].esdi_channel);
else
ini_section_delete_var(cat, temp);
sprintf(temp, "hdd_%02i_ide_channel", c + 1);
if (!hdd_is_valid(c) || ((hdd[c].bus != HDD_BUS_IDE) && (hdd[c].bus != HDD_BUS_ATAPI)))
ini_section_delete_var(cat, temp);
else {
sprintf(tmp2, "%01u:%01u", hdd[c].ide_channel >> 1, hdd[c].ide_channel & 1);
ini_section_set_string(cat, temp, tmp2);
}
sprintf(temp, "hdd_%02i_scsi_id", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "hdd_%02i_scsi_location", c + 1);
if (hdd[c].bus != HDD_BUS_SCSI)
ini_section_delete_var(cat, temp);
else {
sprintf(tmp2, "%01u:%02u", hdd[c].scsi_id >> 4,
hdd[c].scsi_id & 15);
ini_section_set_string(cat, temp, tmp2);
}
sprintf(temp, "hdd_%02i_fn", c + 1);
if (hdd_is_valid(c) && (strlen(hdd[c].fn) != 0)) {
path_normalize(hdd[c].fn);
if (!strnicmp(hdd[c].fn, usr_path, strlen(usr_path)))
ini_section_set_string(cat, temp, &hdd[c].fn[strlen(usr_path)]);
else
ini_section_set_string(cat, temp, hdd[c].fn);
} else
ini_section_delete_var(cat, temp);
sprintf(temp, "hdd_%02i_vhd_blocksize", c + 1);
if (hdd_is_valid(c) && (hdd[c].vhd_blocksize > 0))
ini_section_set_int(cat, temp, hdd[c].vhd_blocksize);
else
ini_section_delete_var(cat, temp);
sprintf(temp, "hdd_%02i_vhd_parent", c + 1);
if (hdd_is_valid(c) && hdd[c].vhd_parent[0]) {
path_normalize(hdd[c].vhd_parent);
ini_section_set_string(cat, temp, hdd[c].vhd_parent);
} else
ini_section_delete_var(cat, temp);
sprintf(temp, "hdd_%02i_speed", c + 1);
if (!hdd_is_valid(c) || ((hdd[c].bus != HDD_BUS_ESDI) && (hdd[c].bus != HDD_BUS_IDE) &&
(hdd[c].bus != HDD_BUS_SCSI) && (hdd[c].bus != HDD_BUS_ATAPI)))
ini_section_delete_var(cat, temp);
else
ini_section_set_string(cat, temp, hdd_preset_get_internal_name(hdd[c].speed_preset));
}
ini_delete_section_if_empty(config, cat);
}
/* Save "Floppy Drives" section. */
static void
save_floppy_and_cdrom_drives(void)
{
ini_section_t cat = ini_find_or_create_section(config, "Floppy and CD-ROM drives");
char temp[512];
char tmp2[512];
int c;
for (c = 0; c < FDD_NUM; c++) {
sprintf(temp, "fdd_%02i_type", c + 1);
if (fdd_get_type(c) == ((c < 2) ? 2 : 0))
ini_section_delete_var(cat, temp);
else
ini_section_set_string(cat, temp,
fdd_get_internal_name(fdd_get_type(c)));
sprintf(temp, "fdd_%02i_fn", c + 1);
if (strlen(floppyfns[c]) == 0) {
ini_section_delete_var(cat, temp);
ui_writeprot[c] = 0;
sprintf(temp, "fdd_%02i_writeprot", c + 1);
ini_section_delete_var(cat, temp);
} else {
path_normalize(floppyfns[c]);
if (!strnicmp(floppyfns[c], usr_path, strlen(usr_path)))
ini_section_set_string(cat, temp, &floppyfns[c][strlen(usr_path)]);
else
ini_section_set_string(cat, temp, floppyfns[c]);
}
sprintf(temp, "fdd_%02i_writeprot", c + 1);
if (ui_writeprot[c] == 0)
ini_section_delete_var(cat, temp);
else
ini_section_set_int(cat, temp, ui_writeprot[c]);
sprintf(temp, "fdd_%02i_turbo", c + 1);
if (fdd_get_turbo(c) == 0)
ini_section_delete_var(cat, temp);
else
ini_section_set_int(cat, temp, fdd_get_turbo(c));
sprintf(temp, "fdd_%02i_check_bpb", c + 1);
if (fdd_get_check_bpb(c) == 1)
ini_section_delete_var(cat, temp);
else
ini_section_set_int(cat, temp, fdd_get_check_bpb(c));
for (int i = 0; i < MAX_PREV_IMAGES; i++) {
sprintf(temp, "fdd_%02i_image_history_%02i", c + 1, i + 1);
if ((fdd_image_history[c][i] == 0) || strlen(fdd_image_history[c][i]) == 0)
ini_section_delete_var(cat, temp);
else {
path_normalize(fdd_image_history[c][i]);
if (!strnicmp(fdd_image_history[c][i], usr_path, strlen(usr_path)))
ini_section_set_string(cat, temp, &fdd_image_history[c][i][strlen(usr_path)]);
else
ini_section_set_string(cat, temp, fdd_image_history[c][i]);
}
}
}
for (c = 0; c < CDROM_NUM; c++) {
sprintf(temp, "cdrom_%02i_host_drive", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "cdrom_%02i_speed", c + 1);
if ((cdrom[c].bus_type == 0) || (cdrom[c].speed == 8))
ini_section_delete_var(cat, temp);
else
ini_section_set_int(cat, temp, cdrom[c].speed);
sprintf(temp, "cdrom_%02i_type", c + 1);
if ((cdrom[c].bus_type == 0) || (cdrom[c].bus_type == CDROM_BUS_MITSUMI))
ini_section_delete_var(cat, temp);
else
ini_section_set_string(cat, temp,
cdrom_get_internal_name(cdrom_get_type(c)));
sprintf(temp, "cdrom_%02i_parameters", c + 1);
if (cdrom[c].bus_type == 0)
ini_section_delete_var(cat, temp);
else {
/* In case one wants an ATAPI drive on SCSI and vice-versa. */
if ((cdrom_drive_types[cdrom_get_type(c)].bus_type != BUS_TYPE_BOTH) &&
(cdrom_drive_types[cdrom_get_type(c)].bus_type != cdrom[c].bus_type))
cdrom[c].bus_type = cdrom_drive_types[cdrom_get_type(c)].bus_type;
sprintf(tmp2, "%u, %s", cdrom[c].sound_on,
hdd_bus_to_string(cdrom[c].bus_type, 1));
ini_section_set_string(cat, temp, tmp2);
}
sprintf(temp, "cdrom_%02i_ide_channel", c + 1);
if (cdrom[c].bus_type != CDROM_BUS_ATAPI)
ini_section_delete_var(cat, temp);
else {
sprintf(tmp2, "%01u:%01u", cdrom[c].ide_channel >> 1,
cdrom[c].ide_channel & 1);
ini_section_set_string(cat, temp, tmp2);
}
sprintf(temp, "cdrom_%02i_scsi_id", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "cdrom_%02i_scsi_location", c + 1);
if (cdrom[c].bus_type != CDROM_BUS_SCSI)
ini_section_delete_var(cat, temp);
else {
sprintf(tmp2, "%01u:%02u", cdrom[c].scsi_device_id >> 4,
cdrom[c].scsi_device_id & 15);
ini_section_set_string(cat, temp, tmp2);
}
sprintf(temp, "cdrom_%02i_image_path", c + 1);
if ((cdrom[c].bus_type == 0) || (strlen(cdrom[c].image_path) == 0))
ini_section_delete_var(cat, temp);
else {
path_normalize(cdrom[c].image_path);
if (!strnicmp(cdrom[c].image_path, usr_path, strlen(usr_path)))
ini_section_set_string(cat, temp, &cdrom[c].image_path[strlen(usr_path)]);
else
ini_section_set_string(cat, temp, cdrom[c].image_path);
}
for (int i = 0; i < MAX_PREV_IMAGES; i++) {
sprintf(temp, "cdrom_%02i_image_history_%02i", c + 1, i + 1);
if ((cdrom[c].image_history[i] == 0) || strlen(cdrom[c].image_history[i]) == 0)
ini_section_delete_var(cat, temp);
else {
path_normalize(cdrom[c].image_history[i]);
if (!strnicmp(cdrom[c].image_history[i], usr_path, strlen(usr_path)))
ini_section_set_string(cat, temp, &cdrom[c].image_history[i][strlen(usr_path)]);
else
ini_section_set_string(cat, temp, cdrom[c].image_history[i]);
}
}
}
ini_delete_section_if_empty(config, cat);
}
/* Save "Other Removable Devices" section. */
static void
save_other_removable_devices(void)
{
ini_section_t cat = ini_find_or_create_section(config, "Other removable devices");
char temp[512];
char tmp2[512];
int c;
for (c = 0; c < ZIP_NUM; c++) {
sprintf(temp, "zip_%02i_parameters", c + 1);
if (zip_drives[c].bus_type == 0) {
ini_section_delete_var(cat, temp);
} else {
sprintf(tmp2, "%u, %s", zip_drives[c].is_250,
hdd_bus_to_string(zip_drives[c].bus_type, 1));
ini_section_set_string(cat, temp, tmp2);
}
sprintf(temp, "zip_%02i_ide_channel", c + 1);
if (zip_drives[c].bus_type != ZIP_BUS_ATAPI)
ini_section_delete_var(cat, temp);
else {
sprintf(tmp2, "%01u:%01u", zip_drives[c].ide_channel >> 1,
zip_drives[c].ide_channel & 1);
ini_section_set_string(cat, temp, tmp2);
}
sprintf(temp, "zip_%02i_scsi_id", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "zip_%02i_scsi_location", c + 1);
if (zip_drives[c].bus_type != ZIP_BUS_SCSI)
ini_section_delete_var(cat, temp);
else {
sprintf(tmp2, "%01u:%02u", zip_drives[c].scsi_device_id >> 4,
zip_drives[c].scsi_device_id & 15);
ini_section_set_string(cat, temp, tmp2);
}
sprintf(temp, "zip_%02i_image_path", c + 1);
if ((zip_drives[c].bus_type == 0) || (strlen(zip_drives[c].image_path) == 0))
ini_section_delete_var(cat, temp);
else {
path_normalize(zip_drives[c].image_path);
if (!strnicmp(zip_drives[c].image_path, usr_path, strlen(usr_path)))
ini_section_set_string(cat, temp, &zip_drives[c].image_path[strlen(usr_path)]);
else
ini_section_set_string(cat, temp, zip_drives[c].image_path);
}
}
for (c = 0; c < MO_NUM; c++) {
sprintf(temp, "mo_%02i_parameters", c + 1);
if (mo_drives[c].bus_type == 0) {
ini_section_delete_var(cat, temp);
} else {
sprintf(tmp2, "%u, %s", mo_drives[c].type,
hdd_bus_to_string(mo_drives[c].bus_type, 1));
ini_section_set_string(cat, temp, tmp2);
}
sprintf(temp, "mo_%02i_ide_channel", c + 1);
if (mo_drives[c].bus_type != MO_BUS_ATAPI)
ini_section_delete_var(cat, temp);
else {
sprintf(tmp2, "%01u:%01u", mo_drives[c].ide_channel >> 1,
mo_drives[c].ide_channel & 1);
ini_section_set_string(cat, temp, tmp2);
}
sprintf(temp, "mo_%02i_scsi_id", c + 1);
ini_section_delete_var(cat, temp);
sprintf(temp, "mo_%02i_scsi_location", c + 1);
if (mo_drives[c].bus_type != MO_BUS_SCSI)
ini_section_delete_var(cat, temp);
else {
sprintf(tmp2, "%01u:%02u", mo_drives[c].scsi_device_id >> 4,
mo_drives[c].scsi_device_id & 15);
ini_section_set_string(cat, temp, tmp2);
}
sprintf(temp, "mo_%02i_image_path", c + 1);
if ((mo_drives[c].bus_type == 0) || (strlen(mo_drives[c].image_path) == 0))
ini_section_delete_var(cat, temp);
else {
path_normalize(mo_drives[c].image_path);
if (!strnicmp(mo_drives[c].image_path, usr_path, strlen(usr_path)))
ini_section_set_string(cat, temp, &mo_drives[c].image_path[strlen(usr_path)]);
else
ini_section_set_string(cat, temp, mo_drives[c].image_path);
}
}
ini_delete_section_if_empty(config, cat);
}
void
config_save(void)
{
save_general(); /* General */
for (uint8_t i = 0; i < MONITORS_NUM; i++)
save_monitor(i); /* Monitors */
save_machine(); /* Machine */
save_video(); /* Video */
save_input_devices(); /* Input devices */
save_sound(); /* Sound */
save_network(); /* Network */
save_ports(); /* Ports (COM & LPT) */
save_storage_controllers(); /* Storage controllers */
save_hard_disks(); /* Hard disks */
save_floppy_and_cdrom_drives(); /* Floppy and CD-ROM drives */
save_other_removable_devices(); /* Other removable devices */
save_other_peripherals(); /* Other peripherals */
ini_write(config, cfg_path);
}
ini_t
config_get_ini(void)
{
return config;
}
``` | /content/code_sandbox/src/config.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 26,508 |
```c
/* This can also serve as a sample PCI device. */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/io.h>
#include <86box/pci.h>
#include <86box/pci_dummy.h>
#include <86box/plat_fallthrough.h>
#include <86box/plat_unused.h>
typedef struct pci_dummy_t {
uint8_t pci_regs[256];
bar_t pci_bar[2];
uint8_t pci_slot;
uint8_t irq_state;
uint8_t interrupt_on;
uint8_t irq_level;
} pci_dummy_t;
static void
pci_dummy_interrupt(int set, pci_dummy_t *dev)
{
if (set != dev->irq_level) {
if (set)
pci_set_irq(dev->pci_slot, PCI_INTA, &dev->irq_state);
else
pci_clear_irq(dev->pci_slot, PCI_INTA, &dev->irq_state);
}
dev->irq_level = set;
}
static uint8_t
pci_dummy_read(uint16_t port, void *priv)
{
pci_dummy_t *dev = (pci_dummy_t *) priv;
uint8_t ret = 0xff;
switch (port & 0x20) {
case 0x00:
ret = 0x1a;
break;
case 0x01:
ret = 0x07;
break;
case 0x02:
ret = 0x0b;
break;
case 0x03:
ret = 0xab;
break;
case 0x04:
ret = dev->pci_regs[0x3c];
break;
case 0x05:
ret = dev->pci_regs[0x3d];
break;
case 0x06:
ret = dev->interrupt_on;
if (dev->interrupt_on) {
pci_dummy_interrupt(0, dev);
dev->interrupt_on = 0;
}
break;
default:
break;
}
return ret;
}
static uint16_t
pci_dummy_readw(uint16_t port, void *priv)
{
return pci_dummy_read(port, priv);
}
static uint32_t
pci_dummy_readl(uint16_t port, void *priv)
{
return pci_dummy_read(port, priv);
}
static void
pci_dummy_write(uint16_t port, UNUSED(uint8_t val), void *priv)
{
pci_dummy_t *dev = (pci_dummy_t *) priv;
switch (port & 0x20) {
case 0x06:
if (!dev->interrupt_on) {
dev->interrupt_on = 1;
pci_dummy_interrupt(1, dev);
}
break;
default:
break;
}
}
static void
pci_dummy_writew(uint16_t port, uint16_t val, void *priv)
{
pci_dummy_write(port, val & 0xFF, priv);
}
static void
pci_dummy_writel(uint16_t port, uint32_t val, void *priv)
{
pci_dummy_write(port, val & 0xFF, priv);
}
static void
pci_dummy_io_remove(pci_dummy_t *dev)
{
io_removehandler(dev->pci_bar[0].addr, 0x0020, pci_dummy_read, pci_dummy_readw, pci_dummy_readl, pci_dummy_write, pci_dummy_writew, pci_dummy_writel, dev);
}
static void
pci_dummy_io_set(pci_dummy_t *dev)
{
io_sethandler(dev->pci_bar[0].addr, 0x0020, pci_dummy_read, pci_dummy_readw, pci_dummy_readl, pci_dummy_write, pci_dummy_writew, pci_dummy_writel, dev);
}
static uint8_t
pci_dummy_pci_read(int func, int addr, void *priv)
{
const pci_dummy_t *dev = (pci_dummy_t *) priv;
uint8_t ret = 0xff;
if (func == 0x00)
switch (addr) {
case 0x00:
case 0x2c:
ret = 0x1a;
break;
case 0x01:
case 0x2d:
ret = 0x07;
break;
case 0x02:
case 0x2e:
ret = 0x0b;
break;
case 0x03:
case 0x2f:
ret = 0xab;
break;
case 0x04: /* PCI_COMMAND_LO */
case 0x05: /* PCI_COMMAND_HI */
case 0x06: /* PCI_STATUS_LO */
case 0x07: /* PCI_STATUS_HI */
case 0x0a:
case 0x0b:
case 0x3c: /* PCI_ILR */
ret = dev->pci_regs[addr];
break;
case 0x08: /* Techncially, revision, but we return the slot here. */
ret = dev->pci_slot;
break;
case 0x10: /* PCI_BAR 7:5 */
ret = (dev->pci_bar[0].addr_regs[0] & 0xe0) | 0x01;
break;
case 0x11: /* PCI_BAR 15:8 */
ret = dev->pci_bar[0].addr_regs[1];
break;
case 0x3d: /* PCI_IPR */
ret = PCI_INTA;
break;
default:
ret = 0x00;
break;
}
#if 0
pclog("AB0B:071A: PCI_Read(%d, %04X) = %02X\n", func, addr, ret);
#endif
return ret;
}
static void
pci_dummy_pci_write(int func, int addr, uint8_t val, void *priv)
{
pci_dummy_t *dev = (pci_dummy_t *) priv;
uint8_t valxor;
#if 0
pclog("AB0B:071A: PCI_Write(%d, %04X, %02X)\n", func, addr, val);
#endif
if (func == 0x00)
switch (addr) {
case 0x04: /* PCI_COMMAND_LO */
valxor = (val & 0x03) ^ dev->pci_regs[addr];
if (valxor & PCI_COMMAND_IO) {
pci_dummy_io_remove(dev);
if ((dev->pci_bar[0].addr != 0) && (val & PCI_COMMAND_IO))
pci_dummy_io_set(dev);
}
dev->pci_regs[addr] = val & 0x03;
break;
case 0x10: /* PCI_BAR */
val &= 0xe0; /* 0xe0 acc to RTL DS */
fallthrough;
case 0x11: /* PCI_BAR */
/* Remove old I/O. */
pci_dummy_io_remove(dev);
/* Set new I/O as per PCI request. */
dev->pci_bar[0].addr_regs[addr & 3] = val;
/* Then let's calculate the new I/O base. */
dev->pci_bar[0].addr &= 0xffe0;
/* Log the new base. */
// pclog("AB0B:071A: PCI: new I/O base is %04X\n", dev->pci_bar[0].addr);
/* We're done, so get out of the here. */
if (dev->pci_regs[4] & PCI_COMMAND_IO) {
if ((dev->pci_bar[0].addr) != 0)
pci_dummy_io_set(dev);
}
break;
case 0x3c: /* PCI_ILR */
pclog("AB0B:071A Device %02X: IRQ now: %i\n", dev->pci_slot, val);
dev->pci_regs[addr] = val;
return;
default:
break;
}
}
static void
pci_dummy_reset(void *priv)
{
pci_dummy_t *dev = (pci_dummy_t *) priv;
/* Lower the IRQ. */
pci_dummy_interrupt(0, dev);
/* Disable I/O and memory accesses. */
pci_dummy_pci_write(0x00, 0x04, 0x00, dev);
/* Zero all the registers. */
memset(dev, 0x00, sizeof(pci_dummy_t));
}
static void
pci_dummy_close(void *priv)
{
pci_dummy_t *dev = (pci_dummy_t *) priv;
free(dev);
}
static void *
pci_dummy_card_init(UNUSED(const device_t *info))
{
pci_dummy_t *dev = (pci_dummy_t *) calloc(1, sizeof(pci_dummy_t));
pci_add_card(PCI_ADD_NORMAL, pci_dummy_pci_read, pci_dummy_pci_write, dev, &dev->pci_slot);
return dev;
}
const device_t pci_dummy_device = {
.name = "Dummy Device (PCI)",
.internal_name = "pci_dummy",
.flags = DEVICE_PCI,
.local = 0,
.init = pci_dummy_card_init,
.close = pci_dummy_close,
.reset = pci_dummy_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
void
pci_dummy_init(int min_slot, int max_slot, int nb_slot, int sb_slot)
{
int j = 1;
for (int i = min_slot; i <= max_slot; i++) {
if ((i != nb_slot) && (i != sb_slot)) {
pci_register_slot(i, PCI_CARD_NORMAL, 1, 3, 2, 4);
device_add_inst(&pci_dummy_device, j);
j++;
}
}
}
``` | /content/code_sandbox/src/pci_dummy.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,171 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Advanced Power Management emulation.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include "cpu.h"
#include <86box/device.h>
#include <86box/io.h>
#include <86box/apm.h>
#ifdef ENABLE_APM_LOG
int apm_do_log = ENABLE_APM_LOG;
static void
apm_log(const char *fmt, ...)
{
va_list ap;
if (apm_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define apm_log(fmt, ...)
#endif
void
apm_set_do_smi(apm_t *dev, uint8_t do_smi)
{
dev->do_smi = do_smi;
}
static void
apm_out(uint16_t port, uint8_t val, void *priv)
{
apm_t *dev = (apm_t *) priv;
apm_log("[%04X:%08X] APM write: %04X = %02X (BX = %04X, CX = %04X)\n", CS, cpu_state.pc, port, val, BX, CX);
port &= 0x0001;
if (port == 0x0000) {
dev->cmd = val;
if (dev->do_smi)
smi_raise();
} else
dev->stat = val;
}
static uint8_t
apm_in(uint16_t port, void *priv)
{
const apm_t *dev = (apm_t *) priv;
uint8_t ret = 0xff;
port &= 0x0001;
if (port == 0x0000)
ret = dev->cmd;
else
ret = dev->stat;
apm_log("[%04X:%08X] APM read: %04X = %02X\n", CS, cpu_state.pc, port, ret);
return ret;
}
static void
apm_reset(void *priv)
{
apm_t *dev = (apm_t *) priv;
dev->cmd = dev->stat = 0x00;
}
static void
apm_close(void *priv)
{
apm_t *dev = (apm_t *) priv;
free(dev);
}
static void *
apm_init(const device_t *info)
{
apm_t *dev = (apm_t *) malloc(sizeof(apm_t));
memset(dev, 0, sizeof(apm_t));
if (info->local == 0)
io_sethandler(0x00b2, 0x0002, apm_in, NULL, NULL, apm_out, NULL, NULL, dev);
return dev;
}
const device_t apm_device = {
.name = "Advanced Power Management",
.internal_name = "apm",
.flags = 0,
.local = 0,
.init = apm_init,
.close = apm_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t apm_pci_device = {
.name = "Advanced Power Management (PCI)",
.internal_name = "apm_pci",
.flags = DEVICE_PCI,
.local = 0,
.init = apm_init,
.close = apm_close,
.reset = apm_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t apm_pci_acpi_device = {
.name = "Advanced Power Management (PCI)",
.internal_name = "apm_pci_acpi",
.flags = DEVICE_PCI,
.local = 1,
.init = apm_init,
.close = apm_close,
.reset = apm_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/apm.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,022 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implement I/O ports and their operations.
*
*
*
* Authors: Sarah Walker, <path_to_url
* Miran Grca, <mgrca8@gmail.com>
* Fred N. van Kempen, <decwiz@yahoo.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/io.h>
#include <86box/timer.h>
#include "cpu.h"
#include <86box/m_amstrad.h>
#include <86box/pci.h>
#define NPORTS 65536 /* PC/AT supports 64K ports */
typedef struct _io_ {
uint8_t (*inb)(uint16_t addr, void *priv);
uint16_t (*inw)(uint16_t addr, void *priv);
uint32_t (*inl)(uint16_t addr, void *priv);
void (*outb)(uint16_t addr, uint8_t val, void *priv);
void (*outw)(uint16_t addr, uint16_t val, void *priv);
void (*outl)(uint16_t addr, uint32_t val, void *priv);
void *priv;
struct _io_ *prev, *next;
} io_t;
typedef struct {
uint8_t enable;
uint16_t base;
uint16_t size;
void (*func)(int size, uint16_t addr, uint8_t write, uint8_t val, void *priv);
void *priv;
} io_trap_t;
int initialized = 0;
io_t *io[NPORTS];
io_t *io_last[NPORTS];
#ifdef ENABLE_IO_LOG
int io_do_log = ENABLE_IO_LOG;
static void
io_log(const char *fmt, ...)
{
va_list ap;
if (io_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define io_log(fmt, ...)
#endif
void
io_init(void)
{
int c;
io_t *p;
io_t *q;
if (!initialized) {
for (c = 0; c < NPORTS; c++)
io[c] = io_last[c] = NULL;
initialized = 1;
}
for (c = 0; c < NPORTS; c++) {
if (io_last[c]) {
/* Port c has at least one handler. */
p = io_last[c];
/* After this loop, p will have the pointer to the first handler. */
while (p) {
q = p->prev;
free(p);
p = q;
}
p = NULL;
}
/* io[c] should be NULL. */
io[c] = io_last[c] = NULL;
}
}
void
io_sethandler_common(uint16_t base, int size,
uint8_t (*inb)(uint16_t addr, void *priv),
uint16_t (*inw)(uint16_t addr, void *priv),
uint32_t (*inl)(uint16_t addr, void *priv),
void (*outb)(uint16_t addr, uint8_t val, void *priv),
void (*outw)(uint16_t addr, uint16_t val, void *priv),
void (*outl)(uint16_t addr, uint32_t val, void *priv),
void *priv, int step)
{
io_t *p;
io_t *q = NULL;
for (int c = 0; c < size; c += step) {
p = io_last[base + c];
q = (io_t *) malloc(sizeof(io_t));
memset(q, 0, sizeof(io_t));
if (p) {
p->next = q;
q->prev = p;
} else {
io[base + c] = q;
q->prev = NULL;
}
q->inb = inb;
q->inw = inw;
q->inl = inl;
q->outb = outb;
q->outw = outw;
q->outl = outl;
q->priv = priv;
q->next = NULL;
io_last[base + c] = q;
}
}
void
io_removehandler_common(uint16_t base, int size,
uint8_t (*inb)(uint16_t addr, void *priv),
uint16_t (*inw)(uint16_t addr, void *priv),
uint32_t (*inl)(uint16_t addr, void *priv),
void (*outb)(uint16_t addr, uint8_t val, void *priv),
void (*outw)(uint16_t addr, uint16_t val, void *priv),
void (*outl)(uint16_t addr, uint32_t val, void *priv),
void *priv, int step)
{
io_t *p;
io_t *q;
for (int c = 0; c < size; c += step) {
p = io[base + c];
if (!p)
continue;
while (p) {
q = p->next;
if ((p->inb == inb) && (p->inw == inw) && (p->inl == inl) && (p->outb == outb) && (p->outw == outw) && (p->outl == outl) && (p->priv == priv)) {
if (p->prev)
p->prev->next = p->next;
else
io[base + c] = p->next;
if (p->next)
p->next->prev = p->prev;
else
io_last[base + c] = p->prev;
free(p);
p = NULL;
break;
}
p = q;
}
}
}
void
io_handler_common(int set, uint16_t base, int size,
uint8_t (*inb)(uint16_t addr, void *priv),
uint16_t (*inw)(uint16_t addr, void *priv),
uint32_t (*inl)(uint16_t addr, void *priv),
void (*outb)(uint16_t addr, uint8_t val, void *priv),
void (*outw)(uint16_t addr, uint16_t val, void *priv),
void (*outl)(uint16_t addr, uint32_t val, void *priv),
void *priv, int step)
{
if (set)
io_sethandler_common(base, size, inb, inw, inl, outb, outw, outl, priv, step);
else
io_removehandler_common(base, size, inb, inw, inl, outb, outw, outl, priv, step);
}
void
io_sethandler(uint16_t base, int size,
uint8_t (*inb)(uint16_t addr, void *priv),
uint16_t (*inw)(uint16_t addr, void *priv),
uint32_t (*inl)(uint16_t addr, void *priv),
void (*outb)(uint16_t addr, uint8_t val, void *priv),
void (*outw)(uint16_t addr, uint16_t val, void *priv),
void (*outl)(uint16_t addr, uint32_t val, void *priv),
void *priv)
{
io_sethandler_common(base, size, inb, inw, inl, outb, outw, outl, priv, 1);
}
void
io_removehandler(uint16_t base, int size,
uint8_t (*inb)(uint16_t addr, void *priv),
uint16_t (*inw)(uint16_t addr, void *priv),
uint32_t (*inl)(uint16_t addr, void *priv),
void (*outb)(uint16_t addr, uint8_t val, void *priv),
void (*outw)(uint16_t addr, uint16_t val, void *priv),
void (*outl)(uint16_t addr, uint32_t val, void *priv),
void *priv)
{
io_removehandler_common(base, size, inb, inw, inl, outb, outw, outl, priv, 1);
}
void
io_handler(int set, uint16_t base, int size,
uint8_t (*inb)(uint16_t addr, void *priv),
uint16_t (*inw)(uint16_t addr, void *priv),
uint32_t (*inl)(uint16_t addr, void *priv),
void (*outb)(uint16_t addr, uint8_t val, void *priv),
void (*outw)(uint16_t addr, uint16_t val, void *priv),
void (*outl)(uint16_t addr, uint32_t val, void *priv),
void *priv)
{
io_handler_common(set, base, size, inb, inw, inl, outb, outw, outl, priv, 1);
}
void
io_sethandler_interleaved(uint16_t base, int size,
uint8_t (*inb)(uint16_t addr, void *priv),
uint16_t (*inw)(uint16_t addr, void *priv),
uint32_t (*inl)(uint16_t addr, void *priv),
void (*outb)(uint16_t addr, uint8_t val, void *priv),
void (*outw)(uint16_t addr, uint16_t val, void *priv),
void (*outl)(uint16_t addr, uint32_t val, void *priv),
void *priv)
{
io_sethandler_common(base, size, inb, inw, inl, outb, outw, outl, priv, 2);
}
void
io_removehandler_interleaved(uint16_t base, int size,
uint8_t (*inb)(uint16_t addr, void *priv),
uint16_t (*inw)(uint16_t addr, void *priv),
uint32_t (*inl)(uint16_t addr, void *priv),
void (*outb)(uint16_t addr, uint8_t val, void *priv),
void (*outw)(uint16_t addr, uint16_t val, void *priv),
void (*outl)(uint16_t addr, uint32_t val, void *priv),
void *priv)
{
io_removehandler_common(base, size, inb, inw, inl, outb, outw, outl, priv, 2);
}
void
io_handler_interleaved(int set, uint16_t base, int size,
uint8_t (*inb)(uint16_t addr, void *priv),
uint16_t (*inw)(uint16_t addr, void *priv),
uint32_t (*inl)(uint16_t addr, void *priv),
void (*outb)(uint16_t addr, uint8_t val, void *priv),
void (*outw)(uint16_t addr, uint16_t val, void *priv),
void (*outl)(uint16_t addr, uint32_t val, void *priv),
void *priv)
{
io_handler_common(set, base, size, inb, inw, inl, outb, outw, outl, priv, 2);
}
#ifdef USE_DEBUG_REGS_486
extern int trap;
/* Set trap for I/O address breakpoints. */
void
io_debug_check_addr(uint16_t addr)
{
int i = 0;
int set_trap = 0;
if (!(dr[7] & 0xFF))
return;
if (!(cr4 & 0x8))
return; /* No I/O debug trap. */
for (i = 0; i < 4; i++) {
uint16_t dr_addr = dr[i] & 0xFFFF;
int breakpoint_enabled = !!(dr[7] & (0x3 << (2 * i)));
int len_type_pair = ((dr[7] >> 16) & (0xF << (4 * i))) >> (4 * i);
if (!breakpoint_enabled)
continue;
if ((len_type_pair & 3) != 2)
continue;
switch ((len_type_pair >> 2) & 3)
{
case 0x00:
if (dr_addr == addr) {
set_trap = 1;
dr[6] |= (1 << i);
}
break;
case 0x01:
if ((dr_addr & ~1) == addr || ((dr_addr & ~1) + 1) == (addr + 1)) {
set_trap = 1;
dr[6] |= (1 << i);
}
break;
case 0x03:
dr_addr &= ~3;
if (addr >= dr_addr && addr < (dr_addr + 4)) {
set_trap = 1;
dr[6] |= (1 << i);
}
break;
}
}
if (set_trap)
trap |= 4;
}
#endif
uint8_t
inb(uint16_t port)
{
uint8_t ret = 0xff;
io_t *p;
io_t *q;
int found = 0;
#ifdef ENABLE_IO_LOG
int qfound = 0;
#endif
#ifdef USE_DEBUG_REGS_486
io_debug_check_addr(port);
#endif
if ((pci_flags & FLAG_CONFIG_IO_ON) && (port >= pci_base) && (port < (pci_base + pci_size))) {
ret = pci_read(port, NULL);
found = 1;
#ifdef ENABLE_IO_LOG
qfound = 1;
#endif
} else if ((pci_flags & FLAG_CONFIG_DEV0_IO_ON) && (port >= 0xc000) && (port < 0xc100)) {
ret = pci_read(port, NULL);
found = 1;
#ifdef ENABLE_IO_LOG
qfound = 1;
#endif
} else {
p = io[port];
while (p) {
q = p->next;
if (p->inb) {
ret &= p->inb(port, p->priv);
found |= 1;
#ifdef ENABLE_IO_LOG
qfound++;
#endif
}
p = q;
}
}
if (amstrad_latch & 0x80000000) {
if (port & 0x80)
amstrad_latch = AMSTRAD_NOLATCH | 0x80000000;
else if (port & 0x4000)
amstrad_latch = AMSTRAD_SW10 | 0x80000000;
else
amstrad_latch = AMSTRAD_SW9 | 0x80000000;
}
if (!found)
cycles -= io_delay;
/* TriGem 486-BIOS MHz output. */
#if 0
if (port == 0x1ed)
ret = 0xfe;
#endif
io_log("[%04X:%08X] (%i, %i, %04i) in b(%04X) = %02X\n", CS, cpu_state.pc, in_smm, found, qfound, port, ret);
return ret;
}
void
outb(uint16_t port, uint8_t val)
{
io_t *p;
io_t *q;
int found = 0;
#ifdef ENABLE_IO_LOG
int qfound = 0;
#endif
#ifdef USE_DEBUG_REGS_486
io_debug_check_addr(port);
#endif
if ((pci_flags & FLAG_CONFIG_IO_ON) && (port >= pci_base) && (port < (pci_base + pci_size))) {
pci_write(port, val, NULL);
found = 1;
#ifdef ENABLE_IO_LOG
qfound = 1;
#endif
} else if ((pci_flags & FLAG_CONFIG_DEV0_IO_ON) && (port >= 0xc000) && (port < 0xc100)) {
pci_write(port, val, NULL);
found = 1;
#ifdef ENABLE_IO_LOG
qfound = 1;
#endif
} else {
p = io[port];
while (p) {
q = p->next;
if (p->outb) {
p->outb(port, val, p->priv);
found |= 1;
#ifdef ENABLE_IO_LOG
qfound++;
#endif
}
p = q;
}
}
if (!found) {
cycles -= io_delay;
#ifdef USE_DYNAREC
if (cpu_use_dynarec && ((port == 0xeb) || (port == 0xed)))
update_tsc();
#endif
}
io_log("[%04X:%08X] (%i, %i, %04i) outb(%04X, %02X)\n", CS, cpu_state.pc, in_smm, found, qfound, port, val);
return;
}
uint16_t
inw(uint16_t port)
{
io_t *p;
io_t *q;
uint16_t ret = 0xffff;
int found = 0;
#ifdef ENABLE_IO_LOG
int qfound = 0;
#endif
uint8_t ret8[2];
#ifdef USE_DEBUG_REGS_486
io_debug_check_addr(port);
#endif
if ((pci_flags & FLAG_CONFIG_IO_ON) && (port >= pci_base) && (port < (pci_base + pci_size))) {
ret = pci_readw(port, NULL);
found = 2;
#ifdef ENABLE_IO_LOG
qfound = 1;
#endif
} else if ((pci_flags & FLAG_CONFIG_DEV0_IO_ON) && (port >= 0xc000) && (port < 0xc100)) {
ret = pci_readw(port, NULL);
found = 2;
#ifdef ENABLE_IO_LOG
qfound = 1;
#endif
} else {
p = io[port];
while (p) {
q = p->next;
if (p->inw) {
ret &= p->inw(port, p->priv);
found |= 2;
#ifdef ENABLE_IO_LOG
qfound++;
#endif
}
p = q;
}
ret8[0] = ret & 0xff;
ret8[1] = (ret >> 8) & 0xff;
for (uint8_t i = 0; i < 2; i++) {
p = io[(port + i) & 0xffff];
while (p) {
q = p->next;
if (p->inb && !p->inw) {
ret8[i] &= p->inb(port + i, p->priv);
found |= 1;
#ifdef ENABLE_IO_LOG
qfound++;
#endif
}
p = q;
}
}
ret = (ret8[1] << 8) | ret8[0];
}
if (amstrad_latch & 0x80000000) {
if (port & 0x80)
amstrad_latch = AMSTRAD_NOLATCH | 0x80000000;
else if (port & 0x4000)
amstrad_latch = AMSTRAD_SW10 | 0x80000000;
else
amstrad_latch = AMSTRAD_SW9 | 0x80000000;
}
if (!found)
cycles -= io_delay;
io_log("[%04X:%08X] (%i, %i, %04i) in w(%04X) = %04X\n", CS, cpu_state.pc, in_smm, found, qfound, port, ret);
return ret;
}
void
outw(uint16_t port, uint16_t val)
{
io_t *p;
io_t *q;
int found = 0;
#ifdef ENABLE_IO_LOG
int qfound = 0;
#endif
#ifdef USE_DEBUG_REGS_486
io_debug_check_addr(port);
#endif
if ((pci_flags & FLAG_CONFIG_IO_ON) && (port >= pci_base) && (port < (pci_base + pci_size))) {
pci_writew(port, val, NULL);
found = 2;
#ifdef ENABLE_IO_LOG
qfound = 1;
#endif
} else if ((pci_flags & FLAG_CONFIG_DEV0_IO_ON) && (port >= 0xc000) && (port < 0xc100)) {
pci_writew(port, val, NULL);
found = 2;
#ifdef ENABLE_IO_LOG
qfound = 1;
#endif
} else {
p = io[port];
while (p) {
q = p->next;
if (p->outw) {
p->outw(port, val, p->priv);
found |= 2;
#ifdef ENABLE_IO_LOG
qfound++;
#endif
}
p = q;
}
for (uint8_t i = 0; i < 2; i++) {
p = io[(port + i) & 0xffff];
while (p) {
q = p->next;
if (p->outb && !p->outw) {
p->outb(port + i, val >> (i << 3), p->priv);
found |= 1;
#ifdef ENABLE_IO_LOG
qfound++;
#endif
}
p = q;
}
}
}
if (!found) {
cycles -= io_delay;
#ifdef USE_DYNAREC
if (cpu_use_dynarec && ((port == 0xeb) || (port == 0xed)))
update_tsc();
#endif
}
io_log("[%04X:%08X] (%i, %i, %04i) outw(%04X, %04X)\n", CS, cpu_state.pc, in_smm, found, qfound, port, val);
return;
}
uint32_t
inl(uint16_t port)
{
io_t *p;
io_t *q;
uint32_t ret = 0xffffffff;
uint16_t ret16[2];
uint8_t ret8[4];
int found = 0;
#ifdef ENABLE_IO_LOG
int qfound = 0;
#endif
#ifdef USE_DEBUG_REGS_486
io_debug_check_addr(port);
#endif
if ((pci_flags & FLAG_CONFIG_IO_ON) && (port >= pci_base) && (port < (pci_base + pci_size))) {
ret = pci_readl(port, NULL);
found = 4;
#ifdef ENABLE_IO_LOG
qfound = 1;
#endif
} else if ((pci_flags & FLAG_CONFIG_DEV0_IO_ON) && (port >= 0xc000) && (port < 0xc100)) {
ret = pci_readl(port, NULL);
found = 4;
#ifdef ENABLE_IO_LOG
qfound = 1;
#endif
} else {
p = io[port];
while (p) {
q = p->next;
if (p->inl) {
ret &= p->inl(port, p->priv);
found |= 4;
#ifdef ENABLE_IO_LOG
qfound++;
#endif
}
p = q;
}
ret16[0] = ret & 0xffff;
ret16[1] = (ret >> 16) & 0xffff;
p = io[port & 0xffff];
while (p) {
q = p->next;
if (p->inw && !p->inl) {
ret16[0] &= p->inw(port, p->priv);
found |= 2;
#ifdef ENABLE_IO_LOG
qfound++;
#endif
}
p = q;
}
p = io[(port + 2) & 0xffff];
while (p) {
q = p->next;
if (p->inw && !p->inl) {
ret16[1] &= p->inw(port + 2, p->priv);
found |= 2;
#ifdef ENABLE_IO_LOG
qfound++;
#endif
}
p = q;
}
ret = (ret16[1] << 16) | ret16[0];
ret8[0] = ret & 0xff;
ret8[1] = (ret >> 8) & 0xff;
ret8[2] = (ret >> 16) & 0xff;
ret8[3] = (ret >> 24) & 0xff;
for (uint8_t i = 0; i < 4; i++) {
p = io[(port + i) & 0xffff];
while (p) {
q = p->next;
if (p->inb && !p->inw && !p->inl) {
ret8[i] &= p->inb(port + i, p->priv);
found |= 1;
#ifdef ENABLE_IO_LOG
qfound++;
#endif
}
p = q;
}
}
ret = (ret8[3] << 24) | (ret8[2] << 16) | (ret8[1] << 8) | ret8[0];
}
if (amstrad_latch & 0x80000000) {
if (port & 0x80)
amstrad_latch = AMSTRAD_NOLATCH | 0x80000000;
else if (port & 0x4000)
amstrad_latch = AMSTRAD_SW10 | 0x80000000;
else
amstrad_latch = AMSTRAD_SW9 | 0x80000000;
}
if (!found)
cycles -= io_delay;
io_log("[%04X:%08X] (%i, %i, %04i) in l(%04X) = %08X\n", CS, cpu_state.pc, in_smm, found, qfound, port, ret);
return ret;
}
void
outl(uint16_t port, uint32_t val)
{
io_t *p;
io_t *q;
int found = 0;
#ifdef ENABLE_IO_LOG
int qfound = 0;
#endif
int i = 0;
#ifdef USE_DEBUG_REGS_486
io_debug_check_addr(port);
#endif
if ((pci_flags & FLAG_CONFIG_IO_ON) && (port >= pci_base) && (port < (pci_base + pci_size))) {
pci_writel(port, val, NULL);
found = 4;
#ifdef ENABLE_IO_LOG
qfound = 1;
#endif
} else if ((pci_flags & FLAG_CONFIG_DEV0_IO_ON) && (port >= 0xc000) && (port < 0xc100)) {
pci_writel(port, val, NULL);
found = 4;
#ifdef ENABLE_IO_LOG
qfound = 1;
#endif
} else {
p = io[port];
if (p) {
while (p) {
q = p->next;
if (p->outl) {
p->outl(port, val, p->priv);
found |= 4;
#ifdef ENABLE_IO_LOG
qfound++;
#endif
}
p = q;
}
}
for (i = 0; i < 4; i += 2) {
p = io[(port + i) & 0xffff];
while (p) {
q = p->next;
if (p->outw && !p->outl) {
p->outw(port + i, val >> (i << 3), p->priv);
found |= 2;
#ifdef ENABLE_IO_LOG
qfound++;
#endif
}
p = q;
}
}
for (i = 0; i < 4; i++) {
p = io[(port + i) & 0xffff];
while (p) {
q = p->next;
if (p->outb && !p->outw && !p->outl) {
p->outb(port + i, val >> (i << 3), p->priv);
found |= 1;
#ifdef ENABLE_IO_LOG
qfound++;
#endif
}
p = q;
}
}
}
if (!found) {
cycles -= io_delay;
#ifdef USE_DYNAREC
if (cpu_use_dynarec && ((port == 0xeb) || (port == 0xed)))
update_tsc();
#endif
}
io_log("[%04X:%08X] (%i, %i, %04i) outl(%04X, %08X)\n", CS, cpu_state.pc, in_smm, found, qfound, port, val);
return;
}
static uint8_t
io_trap_readb(uint16_t addr, void *priv)
{
io_trap_t *trap = (io_trap_t *) priv;
trap->func(1, addr, 0, 0, trap->priv);
return 0xff;
}
static uint16_t
io_trap_readw(uint16_t addr, void *priv)
{
io_trap_t *trap = (io_trap_t *) priv;
trap->func(2, addr, 0, 0, trap->priv);
return 0xffff;
}
static uint32_t
io_trap_readl(uint16_t addr, void *priv)
{
io_trap_t *trap = (io_trap_t *) priv;
trap->func(4, addr, 0, 0, trap->priv);
return 0xffffffff;
}
static void
io_trap_writeb(uint16_t addr, uint8_t val, void *priv)
{
io_trap_t *trap = (io_trap_t *) priv;
trap->func(1, addr, 1, val, trap->priv);
}
static void
io_trap_writew(uint16_t addr, uint16_t val, void *priv)
{
io_trap_t *trap = (io_trap_t *) priv;
trap->func(2, addr, 1, val, trap->priv);
}
static void
io_trap_writel(uint16_t addr, uint32_t val, void *priv)
{
io_trap_t *trap = (io_trap_t *) priv;
trap->func(4, addr, 1, val, trap->priv);
}
void *
io_trap_add(void (*func)(int size, uint16_t addr, uint8_t write, uint8_t val, void *priv),
void *priv)
{
/* Instantiate new I/O trap. */
io_trap_t *trap = (io_trap_t *) malloc(sizeof(io_trap_t));
trap->enable = 0;
trap->base = trap->size = 0;
trap->func = func;
trap->priv = priv;
return trap;
}
void
io_trap_remap(void *handle, int enable, uint16_t addr, uint16_t size)
{
io_trap_t *trap = (io_trap_t *) handle;
if (!trap)
return;
io_log("I/O: Remapping trap from %04X-%04X (enable %d) to %04X-%04X (enable %d)\n",
trap->base, trap->base + trap->size - 1, trap->enable, addr, addr + size - 1, enable);
/* Remove old I/O mapping. */
if (trap->enable && trap->size) {
io_removehandler(trap->base, trap->size,
io_trap_readb, io_trap_readw, io_trap_readl,
io_trap_writeb, io_trap_writew, io_trap_writel,
trap);
}
/* Set trap enable flag, base address and size. */
trap->enable = !!enable;
trap->base = addr;
trap->size = size;
/* Add new I/O mapping. */
if (trap->enable && trap->size) {
io_sethandler(trap->base, trap->size,
io_trap_readb, io_trap_readw, io_trap_readl,
io_trap_writeb, io_trap_writew, io_trap_writel,
trap);
}
}
void
io_trap_remove(void *handle)
{
io_trap_t *trap = (io_trap_t *) handle;
if (!trap)
return;
/* Unmap I/O trap before freeing it. */
io_trap_remap(trap, 0, 0, 0);
free(trap);
}
``` | /content/code_sandbox/src/io.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 7,260 |
```c
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <wchar.h>
#include <86box/io.h>
#include <86box/mca.h>
void (*mca_card_write[8])(int addr, uint8_t val, void *priv);
uint8_t (*mca_card_read[8])(int addr, void *priv);
uint8_t (*mca_card_feedb[8])(void *priv);
void (*mca_card_reset[8])(void *priv);
void *mca_priv[8];
static int mca_index;
static int mca_nr_cards;
void
mca_init(int nr_cards)
{
for (uint8_t c = 0; c < 8; c++) {
mca_card_read[c] = NULL;
mca_card_write[c] = NULL;
mca_card_reset[c] = NULL;
mca_priv[c] = NULL;
}
mca_index = 0;
mca_nr_cards = nr_cards;
}
void
mca_set_index(int index)
{
mca_index = index;
}
uint8_t
mca_read(uint16_t port)
{
if (mca_index >= mca_nr_cards)
return 0xff;
if (!mca_card_read[mca_index])
return 0xff;
return mca_card_read[mca_index](port, mca_priv[mca_index]);
}
uint8_t
mca_read_index(uint16_t port, int index)
{
if (mca_index >= mca_nr_cards)
return 0xff;
if (!mca_card_read[index])
return 0xff;
return mca_card_read[index](port, mca_priv[index]);
}
int
mca_get_nr_cards(void)
{
return mca_nr_cards;
}
void
mca_write(uint16_t port, uint8_t val)
{
if (mca_index >= mca_nr_cards)
return;
if (mca_card_write[mca_index])
mca_card_write[mca_index](port, val, mca_priv[mca_index]);
}
uint8_t
mca_feedb(void)
{
if (mca_card_feedb[mca_index])
return !!(mca_card_feedb[mca_index](mca_priv[mca_index]));
else
return 0;
}
void
mca_reset(void)
{
for (uint8_t c = 0; c < 8; c++) {
if (mca_card_reset[c])
mca_card_reset[c](mca_priv[c]);
}
}
void
mca_add(uint8_t (*read)(int addr, void *priv), void (*write)(int addr, uint8_t val, void *priv), uint8_t (*feedb)(void *priv), void (*reset)(void *priv), void *priv)
{
for (int c = 0; c < mca_nr_cards; c++) {
if (!mca_card_read[c] && !mca_card_write[c]) {
mca_card_read[c] = read;
mca_card_write[c] = write;
mca_card_feedb[c] = feedb;
mca_card_reset[c] = reset;
mca_priv[c] = priv;
return;
}
}
}
``` | /content/code_sandbox/src/mca.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 708 |
```c
#include <inttypes.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <86box/86box.h>
#include <86box/plat.h>
#include <86box/ui.h>
#include <86box/timer.h>
#include <86box/device.h>
#include <86box/fdd.h>
#include <86box/hdc.h>
#include <86box/scsi.h>
#include <86box/scsi_device.h>
#include <86box/cartridge.h>
#include <86box/cassette.h>
#include <86box/cdrom.h>
#include <86box/zip.h>
#include <86box/mo.h>
#include <86box/hdd.h>
#include <86box/thread.h>
#include <86box/network.h>
#include <86box/machine_status.h>
machine_status_t machine_status;
void
machine_status_init(void)
{
for (size_t i = 0; i < FDD_NUM; ++i) {
machine_status.fdd[i].empty = (strlen(floppyfns[i]) == 0);
machine_status.fdd[i].active = false;
}
for (size_t i = 0; i < CDROM_NUM; ++i) {
machine_status.cdrom[i].empty = (strlen(cdrom[i].image_path) == 0);
machine_status.cdrom[i].active = false;
}
for (size_t i = 0; i < ZIP_NUM; i++) {
machine_status.zip[i].empty = (strlen(zip_drives[i].image_path) == 0);
machine_status.zip[i].active = false;
}
for (size_t i = 0; i < MO_NUM; i++) {
machine_status.mo[i].empty = (strlen(mo_drives[i].image_path) == 0);
machine_status.mo[i].active = false;
}
machine_status.cassette.empty = (strlen(cassette_fname) == 0);
for (size_t i = 0; i < HDD_BUS_USB; i++) {
machine_status.hdd[i].active = false;
}
for (size_t i = 0; i < NET_CARD_MAX; i++) {
machine_status.net[i].active = false;
machine_status.net[i].empty = !network_is_connected(i);
}
}
``` | /content/code_sandbox/src/machine_status.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 503 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* GDB stub server for remote debugging.
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
#include <inttypes.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
# ifndef __clang__
# include <unistd.h>
# else
# include <io.h>
# define ssize_t long
# define strtok_r(a, b, c) strtok_s(a, b, c)
# endif
# include <winsock2.h>
# include <ws2tcpip.h>
#else
# include <unistd.h>
# include <arpa/inet.h>
# include <sys/socket.h>
# include <errno.h>
#endif
#define HAVE_STDARG_H
#include <86box/86box.h>
#include "cpu.h"
#include "x86seg.h"
#include "x87_sf.h"
#include "x87.h"
#include "x87_ops_conv.h"
#include <86box/io.h>
#include <86box/mem.h>
#include <86box/plat.h>
#include <86box/thread.h>
#include <86box/gdbstub.h>
#define FAST_RESPONSE(s) \
strcpy(client->response, s); \
client->response_pos = sizeof(s) - 1;
#define FAST_RESPONSE_HEX(s) gdbstub_client_respond_hex(client, (uint8_t *) s, sizeof(s));
enum {
GDB_SIGINT = 2,
GDB_SIGTRAP = 5
};
enum {
GDB_REG_EAX = 0,
GDB_REG_ECX,
GDB_REG_EDX,
GDB_REG_EBX,
GDB_REG_ESP,
GDB_REG_EBP,
GDB_REG_ESI,
GDB_REG_EDI,
GDB_REG_EIP,
GDB_REG_EFLAGS,
GDB_REG_CS,
GDB_REG_SS,
GDB_REG_DS,
GDB_REG_ES,
GDB_REG_FS,
GDB_REG_GS,
#if 0
GDB_REG_FS_BASE,
GDB_REG_GS_BASE,
#endif
GDB_REG_CR0,
GDB_REG_CR2,
GDB_REG_CR3,
GDB_REG_CR4,
GDB_REG_EFER,
GDB_REG_ST0,
GDB_REG_ST1,
GDB_REG_ST2,
GDB_REG_ST3,
GDB_REG_ST4,
GDB_REG_ST5,
GDB_REG_ST6,
GDB_REG_ST7,
GDB_REG_FCTRL,
GDB_REG_FSTAT,
GDB_REG_FTAG,
GDB_REG_FISEG,
GDB_REG_FIOFF,
GDB_REG_FOSEG,
GDB_REG_FOOFF,
GDB_REG_FOP,
GDB_REG_MM0,
GDB_REG_MM1,
GDB_REG_MM2,
GDB_REG_MM3,
GDB_REG_MM4,
GDB_REG_MM5,
GDB_REG_MM6,
GDB_REG_MM7,
GDB_REG_MAX
};
enum {
GDB_MODE_BASE10 = 0,
GDB_MODE_HEX,
GDB_MODE_OCT,
GDB_MODE_BIN
};
typedef struct _gdbstub_client_ {
int socket;
struct sockaddr_in addr;
char packet[16384], response[16384];
uint8_t has_packet : 1;
uint8_t first_packet_received : 1;
uint8_t ida_mode : 1;
uint8_t waiting_stop : 1;
int packet_pos;
int response_pos;
event_t *processed_event;
event_t *response_event;
uint16_t last_io_base;
uint16_t last_io_len;
uint16_t last_io_value;
struct _gdbstub_client_ *next;
} gdbstub_client_t;
typedef struct _gdbstub_breakpoint_ {
uint32_t addr;
union {
uint8_t orig_val;
uint32_t end;
};
struct _gdbstub_breakpoint_ *next;
} gdbstub_breakpoint_t;
#ifdef ENABLE_GDBSTUB_LOG
int gdbstub_do_log = ENABLE_GDBSTUB_LOG;
static void
gdbstub_log(const char *fmt, ...)
{
va_list ap;
if (gdbstub_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define gdbstub_log(fmt, ...)
#endif
static x86seg *segment_regs[] = { &cpu_state.seg_cs, &cpu_state.seg_ss, &cpu_state.seg_ds, &cpu_state.seg_es, &cpu_state.seg_fs, &cpu_state.seg_gs };
static uint32_t *cr_regs[] = { &cpu_state.CR0.l, &cr2, &cr3, &cr4 };
static void *fpu_regs[] = { &cpu_state.npxc, &cpu_state.npxs, NULL, &x87_pc_seg, &x87_pc_off, &x87_op_seg, &x87_op_off };
static char target_xml[] = /* QEMU gdb-xml/i386-32bit.xml with modifications (described in comments) */
// clang-format off
"<?xml version=\"1.0\"?>"
"<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
"<target>"
"<!-- architecture tag goes here -->" /* <architecture> patched in here (length must be kept) */
""
"<feature name=\"org.gnu.gdb.i386.core\">"
"<flags id=\"i386_eflags\" size=\"4\">"
"<field name=\"\" start=\"22\" end=\"31\"/>"
"<field name=\"ID\" start=\"21\" end=\"21\"/>"
"<field name=\"VIP\" start=\"20\" end=\"20\"/>"
"<field name=\"VIF\" start=\"19\" end=\"19\"/>"
"<field name=\"AC\" start=\"18\" end=\"18\"/>"
"<field name=\"VM\" start=\"17\" end=\"17\"/>"
"<field name=\"RF\" start=\"16\" end=\"16\"/>"
"<field name=\"\" start=\"15\" end=\"15\"/>"
"<field name=\"NT\" start=\"14\" end=\"14\"/>"
"<field name=\"IOPL\" start=\"12\" end=\"13\"/>"
"<field name=\"OF\" start=\"11\" end=\"11\"/>"
"<field name=\"DF\" start=\"10\" end=\"10\"/>"
"<field name=\"IF\" start=\"9\" end=\"9\"/>"
"<field name=\"TF\" start=\"8\" end=\"8\"/>"
"<field name=\"SF\" start=\"7\" end=\"7\"/>"
"<field name=\"ZF\" start=\"6\" end=\"6\"/>"
"<field name=\"\" start=\"5\" end=\"5\"/>"
"<field name=\"AF\" start=\"4\" end=\"4\"/>"
"<field name=\"PF\" start=\"2\" end=\"2\"/>"
"<field name=\"\" start=\"1\" end=\"1\"/>"
"<field name=\"CF\" start=\"0\" end=\"0\"/>"
"</flags>"
""
"<reg name=\"eax\" bitsize=\"32\" type=\"int32\" regnum=\"0\"/>"
"<reg name=\"ecx\" bitsize=\"32\" type=\"int32\"/>"
"<reg name=\"edx\" bitsize=\"32\" type=\"int32\"/>"
"<reg name=\"ebx\" bitsize=\"32\" type=\"int32\"/>"
"<reg name=\"esp\" bitsize=\"32\" type=\"data_ptr\"/>"
"<reg name=\"ebp\" bitsize=\"32\" type=\"data_ptr\"/>"
"<reg name=\"esi\" bitsize=\"32\" type=\"int32\"/>"
"<reg name=\"edi\" bitsize=\"32\" type=\"int32\"/>"
""
"<reg name=\"eip\" bitsize=\"32\" type=\"code_ptr\"/>"
"<reg name=\"eflags\" bitsize=\"32\" type=\"i386_eflags\"/>"
""
"<reg name=\"cs\" bitsize=\"16\" type=\"int32\"/>"
"<reg name=\"ss\" bitsize=\"16\" type=\"int32\"/>"
"<reg name=\"ds\" bitsize=\"16\" type=\"int32\"/>"
"<reg name=\"es\" bitsize=\"16\" type=\"int32\"/>"
"<reg name=\"fs\" bitsize=\"16\" type=\"int32\"/>"
"<reg name=\"gs\" bitsize=\"16\" type=\"int32\"/>"
""
#if 0
"<reg name=\"fs_base\" bitsize=\"32\" type=\"int32\"/>"
"<reg name=\"gs_base\" bitsize=\"32\" type=\"int32\"/>"
#endif
""
"<flags id=\"i386_cr0\" size=\"4\">"
"<field name=\"PG\" start=\"31\" end=\"31\"/>"
"<field name=\"CD\" start=\"30\" end=\"30\"/>"
"<field name=\"NW\" start=\"29\" end=\"29\"/>"
"<field name=\"AM\" start=\"18\" end=\"18\"/>"
"<field name=\"WP\" start=\"16\" end=\"16\"/>"
"<field name=\"NE\" start=\"5\" end=\"5\"/>"
"<field name=\"ET\" start=\"4\" end=\"4\"/>"
"<field name=\"TS\" start=\"3\" end=\"3\"/>"
"<field name=\"EM\" start=\"2\" end=\"2\"/>"
"<field name=\"MP\" start=\"1\" end=\"1\"/>"
"<field name=\"PE\" start=\"0\" end=\"0\"/>"
"</flags>"
""
"<flags id=\"i386_cr3\" size=\"4\">"
"<field name=\"PDBR\" start=\"12\" end=\"31\"/>"
"<field name=\"PCID\" start=\"0\" end=\"11\"/>"
"</flags>"
""
"<flags id=\"i386_cr4\" size=\"4\">"
"<field name=\"VME\" start=\"0\" end=\"0\"/>"
"<field name=\"PVI\" start=\"1\" end=\"1\"/>"
"<field name=\"TSD\" start=\"2\" end=\"2\"/>"
"<field name=\"DE\" start=\"3\" end=\"3\"/>"
"<field name=\"PSE\" start=\"4\" end=\"4\"/>"
"<field name=\"PAE\" start=\"5\" end=\"5\"/>"
"<field name=\"MCE\" start=\"6\" end=\"6\"/>"
"<field name=\"PGE\" start=\"7\" end=\"7\"/>"
"<field name=\"PCE\" start=\"8\" end=\"8\"/>"
"<field name=\"OSFXSR\" start=\"9\" end=\"9\"/>"
"<field name=\"OSXMMEXCPT\" start=\"10\" end=\"10\"/>"
"<field name=\"UMIP\" start=\"11\" end=\"11\"/>"
"<field name=\"LA57\" start=\"12\" end=\"12\"/>"
"<field name=\"VMXE\" start=\"13\" end=\"13\"/>"
"<field name=\"SMXE\" start=\"14\" end=\"14\"/>"
"<field name=\"FSGSBASE\" start=\"16\" end=\"16\"/>"
"<field name=\"PCIDE\" start=\"17\" end=\"17\"/>"
"<field name=\"OSXSAVE\" start=\"18\" end=\"18\"/>"
"<field name=\"SMEP\" start=\"20\" end=\"20\"/>"
"<field name=\"SMAP\" start=\"21\" end=\"21\"/>"
"<field name=\"PKE\" start=\"22\" end=\"22\"/>"
"</flags>"
""
"<flags id=\"i386_efer\" size=\"4\">"
"<field name=\"TCE\" start=\"15\" end=\"15\"/>"
"<field name=\"FFXSR\" start=\"14\" end=\"14\"/>"
"<field name=\"LMSLE\" start=\"13\" end=\"13\"/>"
"<field name=\"SVME\" start=\"12\" end=\"12\"/>"
"<field name=\"NXE\" start=\"11\" end=\"11\"/>"
"<field name=\"LMA\" start=\"10\" end=\"10\"/>"
"<field name=\"LME\" start=\"8\" end=\"8\"/>"
"<field name=\"SCE\" start=\"0\" end=\"0\"/>"
"</flags>"
""
"<reg name=\"cr0\" bitsize=\"32\" type=\"i386_cr0\"/>"
"<reg name=\"cr2\" bitsize=\"32\" type=\"int32\"/>"
"<reg name=\"cr3\" bitsize=\"32\" type=\"i386_cr3\"/>"
"<reg name=\"cr4\" bitsize=\"32\" type=\"i386_cr4\"/>"
"<reg name=\"efer\" bitsize=\"64\" type=\"i386_efer\"/>"
""
"<reg name=\"st0\" bitsize=\"80\" type=\"i387_ext\"/>"
"<reg name=\"st1\" bitsize=\"80\" type=\"i387_ext\"/>"
"<reg name=\"st2\" bitsize=\"80\" type=\"i387_ext\"/>"
"<reg name=\"st3\" bitsize=\"80\" type=\"i387_ext\"/>"
"<reg name=\"st4\" bitsize=\"80\" type=\"i387_ext\"/>"
"<reg name=\"st5\" bitsize=\"80\" type=\"i387_ext\"/>"
"<reg name=\"st6\" bitsize=\"80\" type=\"i387_ext\"/>"
"<reg name=\"st7\" bitsize=\"80\" type=\"i387_ext\"/>"
""
"<reg name=\"fctrl\" bitsize=\"16\" type=\"int\" group=\"float\"/>"
"<reg name=\"fstat\" bitsize=\"16\" type=\"int\" group=\"float\"/>"
"<reg name=\"ftag\" bitsize=\"16\" type=\"int\" group=\"float\"/>"
"<reg name=\"fiseg\" bitsize=\"16\" type=\"int\" group=\"float\"/>"
"<reg name=\"fioff\" bitsize=\"32\" type=\"int\" group=\"float\"/>"
"<reg name=\"foseg\" bitsize=\"16\" type=\"int\" group=\"float\"/>"
"<reg name=\"fooff\" bitsize=\"32\" type=\"int\" group=\"float\"/>"
"<reg name=\"fop\" bitsize=\"16\" type=\"int\" group=\"float\"/>"
""
"<vector id=\"v8i8\" type=\"int8\" count=\"8\"/>"
"<vector id=\"v8u8\" type=\"uint8\" count=\"8\"/>"
"<vector id=\"v4i16\" type=\"int16\" count=\"4\"/>"
"<vector id=\"v4u16\" type=\"uint16\" count=\"4\"/>"
"<vector id=\"v2i32\" type=\"int32\" count=\"2\"/>"
"<vector id=\"v2u32\" type=\"uint32\" count=\"2\"/>"
"<union id=\"mmx\">"
"<field name=\"uint64\" type=\"uint64\"/>"
"<field name=\"v2_int32\" type=\"v2i32\"/>"
"<field name=\"v4_int16\" type=\"v4i16\"/>"
"<field name=\"v8_int8\" type=\"v8i8\"/>"
"</union>"
""
"<reg name=\"mm0\" bitsize=\"64\" type=\"mmx\" group=\"mmx\"/>"
"<reg name=\"mm1\" bitsize=\"64\" type=\"mmx\" group=\"mmx\"/>"
"<reg name=\"mm2\" bitsize=\"64\" type=\"mmx\" group=\"mmx\"/>"
"<reg name=\"mm3\" bitsize=\"64\" type=\"mmx\" group=\"mmx\"/>"
"<reg name=\"mm4\" bitsize=\"64\" type=\"mmx\" group=\"mmx\"/>"
"<reg name=\"mm5\" bitsize=\"64\" type=\"mmx\" group=\"mmx\"/>"
"<reg name=\"mm6\" bitsize=\"64\" type=\"mmx\" group=\"mmx\"/>"
"<reg name=\"mm7\" bitsize=\"64\" type=\"mmx\" group=\"mmx\"/>"
"</feature>"
"</target>";
// clang-format on
#ifdef _WIN32
static WSADATA wsa;
#endif
static int gdbstub_socket = -1;
static int stop_reason_len = 0;
static int in_gdbstub = 0;
static uint32_t watch_addr;
static char stop_reason[2048];
static gdbstub_client_t *first_client = NULL;
static gdbstub_client_t *last_client = NULL;
static mutex_t *client_list_mutex;
static void (*cpu_exec_shadow)(int32_t cycs);
static gdbstub_breakpoint_t *first_swbreak = NULL;
static gdbstub_breakpoint_t *first_hwbreak = NULL;
static gdbstub_breakpoint_t *first_rwatch = NULL;
static gdbstub_breakpoint_t *first_wwatch = NULL;
static gdbstub_breakpoint_t *first_awatch = NULL;
int gdbstub_step = 0;
int gdbstub_next_asap = 0;
uint64_t gdbstub_watch_pages[(((uint32_t) -1) >> (MEM_GRANULARITY_BITS + 6)) + 1];
static void
gdbstub_break(void)
{
/* Pause CPU execution as soon as possible. */
if (gdbstub_step <= GDBSTUB_EXEC)
gdbstub_step = GDBSTUB_BREAK;
}
static void
gdbstub_jump(uint32_t new_pc)
{
cpu_state.pc = new_pc - cs;
flushmmucache();
}
static inline int
gdbstub_hex_decode(int c)
{
if ((c >= '0') && (c <= '9'))
return c - '0';
else if ((c >= 'A') && (c <= 'F'))
return c - 'A' + 10;
else if ((c >= 'a') && (c <= 'f'))
return c - 'a' + 10;
else
return 0;
}
static inline int
gdbstub_hex_encode(int c)
{
if (c < 10)
return c + '0';
else
return c - 10 + 'a';
}
static int
gdbstub_num_decode(char *p, int *dest, int mode)
{
/* Stop if the pointer is invalid. */
if (!p)
return 0;
/* Read sign. */
int sign = 1;
if ((p[0] == '+') || (p[0] == '-')) {
if (p[0] == '-')
sign = -1;
p++;
}
/* Read type identifer if present (0x/0o/0b/0n) */
if (p[0] == '0') {
switch (p[1]) {
case 'x':
mode = GDB_MODE_HEX;
break;
case '0' ... '7':
p -= 1;
/* fall-through */
case 'o':
mode = GDB_MODE_OCT;
break;
case 'b':
mode = GDB_MODE_BIN;
break;
case 'n':
mode = GDB_MODE_BASE10;
break;
default:
p -= 2;
break;
}
p += 2;
}
/* Parse each character. */
*dest = 0;
while (*p) {
switch (mode) {
case GDB_MODE_BASE10:
if ((*p >= '0') && (*p <= '9'))
*dest = ((*dest) * 10) + ((*p) - '0');
else
return 0;
break;
case GDB_MODE_HEX:
if (((*p >= '0') && (*p <= '9')) || ((*p >= 'A') && (*p <= 'F')) || ((*p >= 'a') && (*p <= 'f')))
*dest = ((*dest) << 4) | gdbstub_hex_decode(*p);
else
return 0;
break;
case GDB_MODE_OCT:
if ((*p >= '0') && (*p <= '7'))
*dest = ((*dest) << 3) | ((*p) - '0');
else
return 0;
break;
case GDB_MODE_BIN:
if ((*p == '0') || (*p == '1'))
*dest = ((*dest) << 1) | ((*p) - '0');
else
return 0;
break;
default:
break;
}
p++;
}
/* Apply sign. */
if (sign < 0)
*dest = -(*dest);
/* Return success. */
return 1;
}
static int
gdbstub_client_read_word(gdbstub_client_t *client, int *dest)
{
const char *p = &client->packet[client->packet_pos];
const char *q = p;
while (((*p >= '0') && (*p <= '9')) || ((*p >= 'A') && (*p <= 'F')) || ((*p >= 'a') && (*p <= 'f')))
*dest = ((*dest) << 4) | gdbstub_hex_decode(*p++);
return p - q;
}
static int
gdbstub_client_read_hex(gdbstub_client_t *client, uint8_t *buf, int size)
{
int pp = client->packet_pos;
while (size-- && (pp < (sizeof(client->packet) - 2))) {
*buf = gdbstub_hex_decode(client->packet[pp++]) << 4;
*buf++ |= gdbstub_hex_decode(client->packet[pp++]);
}
return pp - client->packet_pos;
}
static int
gdbstub_client_read_string(gdbstub_client_t *client, char *buf, int size, char terminator)
{
int pp = client->packet_pos;
char c;
while (size-- && (pp < (sizeof(client->packet) - 1))) {
c = client->packet[pp];
if ((c == terminator) || (c == '\0')) {
*buf = '\0';
break;
}
pp++;
*buf++ = c;
}
return pp - client->packet_pos;
}
static int
gdbstub_client_write_reg(int index, uint8_t *buf)
{
int width = 4;
switch (index) {
case GDB_REG_EAX ... GDB_REG_EDI:
cpu_state.regs[index - GDB_REG_EAX].l = *((uint32_t *) buf);
break;
case GDB_REG_EIP:
gdbstub_jump(*((uint32_t *) buf));
break;
case GDB_REG_EFLAGS:
cpu_state.flags = *((uint16_t *) &buf[0]);
cpu_state.eflags = *((uint16_t *) &buf[2]);
break;
case GDB_REG_CS ... GDB_REG_GS:
width = 2;
loadseg(*((uint16_t *) buf), segment_regs[index - GDB_REG_CS]);
flushmmucache();
break;
#if 0
case GDB_REG_FS_BASE ... GDB_REG_GS_BASE:
/* Do what qemu does and just load the base. */
segment_regs[(index - 16) + (GDB_REG_FS - GDB_REG_CS)]->base = *((uint32_t *) buf);
break;
#endif
case GDB_REG_CR0 ... GDB_REG_CR4:
*cr_regs[index - GDB_REG_CR0] = *((uint32_t *) buf);
flushmmucache();
break;
case GDB_REG_EFER:
msr.amd_efer = *((uint64_t *) buf);
break;
case GDB_REG_ST0 ... GDB_REG_ST7:
width = 10;
x87_conv_t conv = {
.eind = { .ll = *((uint64_t *) &buf[0]) },
.begin = *((uint16_t *) &buf[8])
};
cpu_state.ST[(cpu_state.TOP + (index - GDB_REG_ST0)) & 7] = x87_from80(&conv);
break;
case GDB_REG_FCTRL:
case GDB_REG_FISEG:
case GDB_REG_FOSEG:
width = 2;
*((uint16_t *) fpu_regs[index - GDB_REG_FCTRL]) = *((uint16_t *) buf);
if (index >= GDB_REG_FISEG)
flushmmucache();
break;
case GDB_REG_FSTAT:
case GDB_REG_FOP:
width = 2;
break;
case GDB_REG_FTAG:
width = 2;
x87_settag(*((uint16_t *) buf));
break;
case GDB_REG_FIOFF:
case GDB_REG_FOOFF:
*((uint32_t *) fpu_regs[index - GDB_REG_FCTRL]) = *((uint32_t *) buf);
break;
case GDB_REG_MM0 ... GDB_REG_MM7:
width = 8;
cpu_state.MM[index - GDB_REG_MM0].q = *((uint64_t *) buf);
break;
default:
width = 0;
}
#ifdef ENABLE_GDBSTUB_LOG
char logbuf[256], *p = logbuf + sprintf(logbuf, "GDB Stub: Setting register %d to ", index);
for (int i = width - 1; i >= 0; i--)
p += sprintf(p, "%02X", buf[i]);
sprintf(p, "\n");
gdbstub_log(logbuf);
#endif
return width;
}
static void
gdbstub_client_respond(gdbstub_client_t *client)
{
/* Calculate checksum. */
int checksum = 0;
int i;
for (i = 0; i < client->response_pos; i++)
checksum += client->response[i];
/* Send response packet. */
client->response[client->response_pos] = '\0';
#ifdef ENABLE_GDBSTUB_LOG
i = client->response[994]; /* pclog_ex buffer too small */
client->response[994] = '\0';
gdbstub_log("GDB Stub: Sending response: %s\n", client->response);
client->response[994] = i;
#endif
send(client->socket, "$", 1, 0);
send(client->socket, client->response, client->response_pos, 0);
char response_cksum[3] = { '#', gdbstub_hex_encode((checksum >> 4) & 0x0f), gdbstub_hex_encode(checksum & 0x0f) };
send(client->socket, response_cksum, sizeof(response_cksum), 0);
}
static void
gdbstub_client_respond_partial(gdbstub_client_t *client)
{
/* Send response. */
gdbstub_client_respond(client);
/* Wait for the response to be acknowledged. */
thread_wait_event(client->response_event, -1);
thread_reset_event(client->response_event);
}
static void
gdbstub_client_respond_hex(gdbstub_client_t *client, uint8_t *buf, int size)
{
while (size-- && (client->response_pos < (sizeof(client->response) - 2))) {
client->response[client->response_pos++] = gdbstub_hex_encode((*buf) >> 4);
client->response[client->response_pos++] = gdbstub_hex_encode((*buf++) & 0x0f);
}
}
static int
gdbstub_client_read_reg(int index, uint8_t *buf)
{
int width = 4;
switch (index) {
case GDB_REG_EAX ... GDB_REG_EDI:
*((uint32_t *) buf) = cpu_state.regs[index].l;
break;
case GDB_REG_EIP:
*((uint32_t *) buf) = cs + cpu_state.pc;
break;
case GDB_REG_EFLAGS:
*((uint16_t *) &buf[0]) = cpu_state.flags;
*((uint16_t *) &buf[2]) = cpu_state.eflags;
break;
case GDB_REG_CS ... GDB_REG_GS:
*((uint16_t *) buf) = segment_regs[index - GDB_REG_CS]->seg;
break;
#if 0
case GDB_REG_FS_BASE ... GDB_REG_GS_BASE:
*((uint32_t *) buf) = segment_regs[(index - 16) + (GDB_REG_FS - GDB_REG_CS)]->base;
break;
#endif
case GDB_REG_CR0 ... GDB_REG_CR4:
*((uint32_t *) buf) = *cr_regs[index - GDB_REG_CR0];
break;
case GDB_REG_EFER:
*((uint64_t *) buf) = msr.amd_efer;
break;
case GDB_REG_ST0 ... GDB_REG_ST7:
width = 10;
x87_conv_t conv;
x87_to80(cpu_state.ST[(cpu_state.TOP + (index - GDB_REG_ST0)) & 7], &conv);
*((uint64_t *) &buf[0]) = conv.eind.ll;
*((uint16_t *) &buf[8]) = conv.begin;
break;
case GDB_REG_FCTRL ... GDB_REG_FSTAT:
case GDB_REG_FISEG:
case GDB_REG_FOSEG:
width = 2;
*((uint16_t *) buf) = *((uint16_t *) fpu_regs[index - GDB_REG_FCTRL]);
break;
case GDB_REG_FTAG:
width = 2;
*((uint16_t *) buf) = x87_gettag();
break;
case GDB_REG_FIOFF:
case GDB_REG_FOOFF:
*((uint32_t *) buf) = *((uint32_t *) fpu_regs[index - GDB_REG_FCTRL]);
break;
case GDB_REG_FOP:
width = 2;
*((uint16_t *) buf) = 0; /* we don't store the FPU opcode */
break;
case GDB_REG_MM0 ... GDB_REG_MM7:
width = 8;
*((uint64_t *) buf) = cpu_state.MM[index - GDB_REG_MM0].q;
break;
default:
width = 0;
}
return width;
}
static void
gdbstub_client_packet(gdbstub_client_t *client)
{
gdbstub_breakpoint_t *breakpoint;
gdbstub_breakpoint_t *prev_breakpoint = NULL;
gdbstub_breakpoint_t **first_breakpoint = NULL;
#ifdef GDBSTUB_CHECK_CHECKSUM /* msys2 gdb 11.1 transmits qSupported and H with invalid checksum... */
uint8_t rcv_checksum = 0, checksum = 0;
#endif
int i;
int j = 0;
int k = 0;
int l;
uint8_t buf[10] = { 0 };
char *p;
/* Validate checksum. */
client->packet_pos -= 2;
#ifdef GDBSTUB_CHECK_CHECKSUM
gdbstub_client_read_hex(client, &rcv_checksum, 1);
#endif
*((uint16_t *) &client->packet[--client->packet_pos]) = 0;
#ifdef GDBSTUB_CHECK_CHECKSUM
for (i = 0; i < client->packet_pos; i++)
checksum += client->packet[i];
if (checksum != rcv_checksum) {
/* Send negative acknowledgement. */
# ifdef ENABLE_GDBSTUB_LOG
i = client->packet[953]; /* pclog_ex buffer too small */
client->packet[953] = '\0';
gdbstub_log("GDB Stub: Received packet with invalid checksum (expected %02X got %02X): %s\n", checksum, rcv_checksum, client->packet);
client->packet[953] = i;
# endif
send(client->socket, "-", 1, 0);
return;
}
#endif
/* Send positive acknowledgement. */
#ifdef ENABLE_GDBSTUB_LOG
i = client->packet[996]; /* pclog_ex buffer too small */
client->packet[996] = '\0';
gdbstub_log("GDB Stub: Received packet: %s\n", client->packet);
client->packet[996] = i;
#endif
send(client->socket, "+", 1, 0);
/* Block other responses from being written while this one (if any is produced) isn't acknowledged. */
if ((client->packet[0] != 'c') && (client->packet[0] != 's') && (client->packet[0] != 'v')) {
thread_wait_event(client->response_event, -1);
thread_reset_event(client->response_event);
}
client->response_pos = 0;
client->packet_pos = 1;
/* Handle IDA-specific hacks. */
if (!client->first_packet_received) {
client->first_packet_received = 1;
if (!strcmp(client->packet, "qSupported:xmlRegisters=i386,arm,mips")) {
gdbstub_log("GDB Stub: Enabling IDA mode\n");
client->ida_mode = 1;
}
}
/* Parse command. */
switch (client->packet[0]) {
case '?': /* stop reason */
/* Respond with a stop reply packet if one is present. */
if (stop_reason_len) {
strcpy(client->response, stop_reason);
client->response_pos = strlen(client->response);
}
break;
case 'c': /* continue */
case 's': /* step */
/* Flag that the client is waiting for a stop reason. */
client->waiting_stop = 1;
/* Jump to address if specified. */
if (client->packet[1] && gdbstub_client_read_word(client, &j))
gdbstub_jump(j);
/* Resume CPU. */
gdbstub_step = gdbstub_next_asap = (client->packet[0] == 's') ? GDBSTUB_SSTEP : GDBSTUB_EXEC;
return;
case 'D': /* detach */
/* Resume emulation. */
gdbstub_step = GDBSTUB_EXEC;
/* Respond positively. */
ok:
FAST_RESPONSE("OK");
break;
case 'g': /* read all registers */
/* Output the values of all registers. */
for (i = 0; i < GDB_REG_MAX; i++)
gdbstub_client_respond_hex(client, buf, gdbstub_client_read_reg(i, buf));
break;
case 'G': /* write all registers */
/* Write the values of all registers. */
for (i = 0; i < GDB_REG_MAX; i++) {
if (i == GDB_REG_MAX)
goto e22;
if (!gdbstub_client_read_hex(client, buf, sizeof(buf)))
break;
client->packet_pos += gdbstub_client_write_reg(i, buf) << 1;
}
/* Respond positively. */
goto ok;
case 'H': /* set thread */
/* Read operation type and thread ID. */
if ((client->packet[1] == '\0') || (client->packet[2] == '\0')) {
e22:
FAST_RESPONSE("E22");
break;
}
/* Respond positively only on thread 1. */
if ((client->packet[2] == '1') && !client->packet[3])
goto ok;
else
goto e22;
case 'm': /* read memory */
/* Read address and length. */
if (!(i = gdbstub_client_read_word(client, &j)))
goto e22;
client->packet_pos += i + 1;
gdbstub_client_read_word(client, &k);
if (!k)
goto e22;
/* Clamp length. */
if (k >= (sizeof(client->response) >> 1))
k = (sizeof(client->response) >> 1) - 1;
/* Read by qwords, then by dwords, then by words, then by bytes. */
i = 0;
if (is386) {
for (; i < (k & ~7); i += 8) {
*((uint64_t *) buf) = readmemql(j);
j += 8;
gdbstub_client_respond_hex(client, buf, 8);
}
for (; i < (k & ~3); i += 4) {
*((uint32_t *) buf) = readmemll(j);
j += 4;
gdbstub_client_respond_hex(client, buf, 4);
}
}
for (; i < (k & ~1); i += 2) {
*((uint16_t *) buf) = readmemwl(j);
j += 2;
gdbstub_client_respond_hex(client, buf, 2);
}
for (; i < k; i++) {
buf[0] = readmembl(j++);
gdbstub_client_respond_hex(client, buf, 1);
}
break;
case 'M': /* write memory */
case 'X': /* write memory binary */
/* Read address and length. */
if (!(i = gdbstub_client_read_word(client, &j)))
goto e22;
client->packet_pos += i + 1;
client->packet_pos += gdbstub_client_read_word(client, &k) + 1;
if (!k)
goto e22;
/* Clamp length. */
if (k >= ((sizeof(client->response) >> 1) - client->packet_pos))
k = (sizeof(client->response) >> 1) - client->packet_pos - 1;
/* Decode the data. */
if (client->packet[0] == 'M') { /* hex encoded */
gdbstub_client_read_hex(client, (uint8_t *) client->packet, k);
} else { /* binary encoded */
i = 0;
while (i < k) {
if (client->packet[client->packet_pos] == '}') {
client->packet_pos++;
client->packet[i++] = client->packet[client->packet_pos++] ^ 0x20;
} else {
client->packet[i++] = client->packet[client->packet_pos++];
}
}
}
/* Write by qwords, then by dwords, then by words, then by bytes. */
p = client->packet;
i = 0;
if (is386) {
for (; i < (k & ~7); i += 8) {
writememql(j, *((uint64_t *) p));
j += 8;
p += 8;
}
for (; i < (k & ~3); i += 4) {
writememll(j, *((uint32_t *) p));
j += 4;
p += 4;
}
}
for (; i < (k & ~1); i += 2) {
writememwl(j, *((uint16_t *) p));
j += 2;
p += 2;
}
for (; i < k; i++) {
writemembl(j++, p[0]);
p++;
}
/* Respond positively. */
goto ok;
case 'p': /* read register */
/* Read register index. */
if (!gdbstub_client_read_word(client, &j)) {
e14:
FAST_RESPONSE("E14");
break;
}
/* Read the register's value. */
if (!(i = gdbstub_client_read_reg(j, buf)))
goto e14;
/* Return value. */
gdbstub_client_respond_hex(client, buf, i);
break;
case 'P': /* write register */
/* Read register index and value. */
if (!(i = gdbstub_client_read_word(client, &j)))
goto e14;
client->packet_pos += i + 1;
if (!gdbstub_client_read_hex(client, buf, sizeof(buf)))
goto e14;
/* Write the value to the register. */
if (!gdbstub_client_write_reg(j, buf))
goto e14;
/* Respond positively. */
goto ok;
case 'q': /* query */
/* Erase response, as we'll use it as a scratch buffer. */
memset(client->response, 0, sizeof(client->response));
/* Read the query type. */
client->packet_pos += gdbstub_client_read_string(client, client->response, sizeof(client->response) - 1,
(client->packet[1] == 'R') ? ',' : ':')
+ 1;
/* Perform the query. */
if (!strcmp(client->response, "Supported")) {
/* Go through the feature list and negate ones we don't support. */
while ((client->response_pos < (sizeof(client->response) - 1)) && (i = gdbstub_client_read_string(client, &client->response[client->response_pos], sizeof(client->response) - client->response_pos - 1, ';'))) {
client->packet_pos += i + 1;
if (strncmp(&client->response[client->response_pos], "PacketSize", 10) && strcmp(&client->response[client->response_pos], "swbreak") && strcmp(&client->response[client->response_pos], "hwbreak") && strncmp(&client->response[client->response_pos], "xmlRegisters", 12) && strcmp(&client->response[client->response_pos], "qXfer:features:read")) {
gdbstub_log("GDB Stub: Feature \"%s\" is not supported\n", &client->response[client->response_pos]);
client->response_pos += i;
client->response[client->response_pos++] = '-';
client->response[client->response_pos++] = ';';
} else {
gdbstub_log("GDB Stub: Feature \"%s\" is supported\n", &client->response[client->response_pos]);
}
}
/* Add our supported features to the end. */
if (client->response_pos < (sizeof(client->response) - 1))
client->response_pos += snprintf(&client->response[client->response_pos], sizeof(client->response) - client->response_pos,
"PacketSize=%X;swbreak+;hwbreak+;qXfer:features:read+", (int) (sizeof(client->packet) - 1));
break;
} else if (!strcmp(client->response, "Xfer")) {
/* Read the transfer object. */
client->packet_pos += gdbstub_client_read_string(client, client->response, sizeof(client->response) - 1, ':') + 1;
if (!strcmp(client->response, "features")) {
/* Read the transfer operation. */
client->packet_pos += gdbstub_client_read_string(client, client->response, sizeof(client->response) - 1, ':') + 1;
if (!strcmp(client->response, "read")) {
/* Read the transfer annex. */
client->packet_pos += gdbstub_client_read_string(client, client->response, sizeof(client->response) - 1, ':') + 1;
if (!strcmp(client->response, "target.xml")) {
/* Patch architecture for IDA. */
p = strstr(target_xml, "<!-- architecture tag goes here -->");
if (p) {
if (client->ida_mode)
memcpy(p, "<architecture>i386</architecture> ", 35); /* make IDA not complain about i8086 being unknown */
else
memcpy(p, "<architecture>i8086</architecture> ", 35); /* start in 16-bit mode to work around known GDB bug preventing 32->16 switching */
}
/* Send target XML. */
p = target_xml;
} else {
p = NULL;
}
/* Stop if the file wasn't found. */
if (!p) {
e00:
FAST_RESPONSE("E00");
break;
}
/* Read offset and length. */
if (!(i = gdbstub_client_read_word(client, &j)))
goto e22;
client->packet_pos += i + 1;
client->packet_pos += gdbstub_client_read_word(client, &k) + 1;
if (!k)
goto e22;
/* Check if the offset is valid. */
l = strlen(p);
if (j > l)
goto e00;
p += j;
/* Return the more/less flag while also clamping the length. */
if (k >= ((sizeof(client->response) >> 1) - 2))
k = (sizeof(client->response) >> 1) - 3;
if (k < (l - j)) {
client->response[client->response_pos++] = 'm';
} else {
client->response[client->response_pos++] = 'l';
k = l - j;
}
/* Encode the data. */
while (k--) {
i = *p++;
if ((i == '\0') || (i == '#') || (i == '$') || (i == '*') || (i == '}')) {
client->response[client->response_pos++] = '}';
client->response[client->response_pos++] = i ^ 0x20;
} else {
client->response[client->response_pos++] = i;
}
}
break;
}
}
} else if (!strncmp(client->response, "Attached", 8)) {
FAST_RESPONSE("1");
} else if (!strcmp(client->response, "C")) {
FAST_RESPONSE("QC1");
} else if (!strcmp(client->response, "fThreadInfo")) {
FAST_RESPONSE("m1");
} else if (!strcmp(client->response, "sThreadInfo")) {
FAST_RESPONSE("l");
} else if (!strcmp(client->response, "Rcmd")) {
/* Read and decode command in-place. */
i = gdbstub_client_read_hex(client, (uint8_t *) client->packet, strlen(client->packet) - client->packet_pos);
client->packet[i] = 0;
gdbstub_log("GDB Stub: Monitor command: %s\n", client->packet);
/* Parse the command name. */
char *strtok_save;
p = strtok_r(client->packet, " ", &strtok_save);
if (!p)
goto ok;
i = strlen(p) - 1; /* get last character offset */
/* Interpret the command. */
if (p[0] == 'i') {
/* Read I/O operation width. */
l = (i < 1) ? '\0' : p[i];
/* Read optional I/O port. */
if (!(p = strtok_r(NULL, " ", &strtok_save)) || !gdbstub_num_decode(p, &j, GDB_MODE_HEX) || (j < 0) || (j >= 65536))
j = client->last_io_base;
else
client->last_io_base = j;
/* Read optional length. */
if (!(p = strtok_r(NULL, " ", &strtok_save)) || !gdbstub_num_decode(p, &k, GDB_MODE_BASE10))
k = client->last_io_len;
else
client->last_io_len = k;
/* Clamp length. */
if (k < 1)
k = 1;
if (k > (65536 - j))
k = 65536 - j;
/* Read ports. */
i = 0;
while (i < k) {
if ((i % 16) == 0) {
if (i) {
client->packet[client->packet_pos++] = '\n';
/* Provide partial response with the last line. */
client->response_pos = 0;
client->response[client->response_pos++] = 'O';
gdbstub_client_respond_hex(client, (uint8_t *) client->packet, client->packet_pos);
gdbstub_client_respond_partial(client);
}
client->packet_pos = sprintf(client->packet, "%04X:", j + i);
}
/* Act according to I/O operation width. */
switch (l) {
case 'd':
case 'l':
client->packet_pos += sprintf(&client->packet[client->packet_pos], " %08X", inl(j + i));
i += 4;
break;
case 'w':
client->packet_pos += sprintf(&client->packet[client->packet_pos], " %04X", inw(j + i));
i += 2;
break;
case 'b':
case '\0':
client->packet_pos += sprintf(&client->packet[client->packet_pos], " %02X", inb(j + i));
i++;
break;
default:
goto unknown;
}
}
client->packet[client->packet_pos++] = '\n';
/* Respond with the final line. */
client->response_pos = 0;
gdbstub_client_respond_hex(client, (uint8_t *) &client->packet, client->packet_pos);
break;
} else if (p[0] == 'o') {
/* Read I/O operation width. */
l = (i < 1) ? '\0' : p[i];
/* Read optional I/O port. */
if (!(p = strtok_r(NULL, " ", &strtok_save)) || !gdbstub_num_decode(p, &j, GDB_MODE_HEX) || (j < 0) || (j >= 65536))
j = -1;
/* Read optional value. */
if (!(p = strtok_r(NULL, " ", &strtok_save)) || !gdbstub_num_decode(p, &k, GDB_MODE_HEX)) {
if (j == -1)
k = client->last_io_value;
else
k = j; /* only one specified = treat as value on last port */
j = -1;
}
if (j == -1)
j = client->last_io_base;
else
client->last_io_base = j;
client->last_io_value = k;
/* Write port. */
switch (l) {
case 'd':
case 'l':
outl(j, k);
break;
case 'w':
outw(j, k);
break;
case 'b':
case 't':
case '\0':
outb(j, k);
break;
default:
goto unknown;
}
} else if (p[0] == 'r') {
pc_reset_hard();
} else if ((p[0] == '?') || !strcmp(p, "help")) {
FAST_RESPONSE_HEX(
"Commands:\n"
"- ib/iw/il [port [length]] - Read {length} (default 1) I/O ports starting from {port} (default last)\n"
"- ob/ow/ol [[port] value] - Write {value} to I/O {port} (both default last)\n"
"- r - Hard reset the emulated machine\n");
break;
} else {
unknown:
FAST_RESPONSE_HEX("Unknown command\n");
break;
}
goto ok;
}
break;
case 'z': /* remove break/watchpoint */
case 'Z': /* insert break/watchpoint */
/* Parse breakpoint type. */
switch (client->packet[1]) {
case '0': /* software breakpoint */
first_breakpoint = &first_swbreak;
break;
case '1': /* hardware breakpoint */
first_breakpoint = &first_hwbreak;
break;
case '2': /* write watchpoint */
first_breakpoint = &first_wwatch;
break;
case '3': /* read watchpoint */
first_breakpoint = &first_rwatch;
break;
case '4': /* access watchpoint */
first_breakpoint = &first_awatch;
break;
default: /* unknown type */
client->packet[2] = '\0'; /* force address check to fail */
break;
}
/* Read address. */
if (client->packet[2] != ',')
break;
client->packet_pos = 3;
if (!(i = gdbstub_client_read_word(client, &j)))
break;
client->packet_pos += i;
if (client->packet[client->packet_pos++] == ',')
gdbstub_client_read_word(client, &k);
else
k = 1;
/* Test writability of software breakpoint. */
if (client->packet[1] == '0') {
buf[0] = readmembl(j);
writemembl(j, 0xcc);
buf[1] = readmembl(j);
writemembl(j, buf[0]);
if (buf[1] != 0xcc)
goto end;
}
/* Find an existing breakpoint with this address. */
breakpoint = *first_breakpoint;
while (breakpoint) {
if (breakpoint->addr == j)
break;
prev_breakpoint = breakpoint;
breakpoint = breakpoint->next;
}
/* Check if the breakpoint is already present (when inserting) or not found (when removing). */
if ((!!breakpoint) ^ (client->packet[0] == 'z'))
goto e22;
/* Insert or remove the breakpoint. */
if (client->packet[0] != 'z') {
/* Allocate a new breakpoint. */
breakpoint = malloc(sizeof(gdbstub_breakpoint_t));
breakpoint->addr = j;
breakpoint->end = j + k;
breakpoint->next = NULL;
/* Add the new breakpoint to the list. */
if (!(*first_breakpoint))
*first_breakpoint = breakpoint;
else if (prev_breakpoint)
prev_breakpoint->next = breakpoint;
} else {
/* Remove breakpoint from the list. */
if (breakpoint == *first_breakpoint)
*first_breakpoint = breakpoint->next;
else if (prev_breakpoint)
prev_breakpoint->next = breakpoint->next;
/* De-allocate breakpoint. */
free(breakpoint);
}
/* Update the page watchpoint map if we're dealing with a watchpoint. */
if (client->packet[1] >= '2') {
/* Clear this watchpoint's corresponding page map groups,
as everything is going to be recomputed soon anyway. */
memset(&gdbstub_watch_pages[j >> (MEM_GRANULARITY_BITS + 6)], 0,
(((k - 1) >> (MEM_GRANULARITY_BITS + 6)) + 1) * sizeof(gdbstub_watch_pages[0]));
/* Go through all watchpoint lists. */
l = 0;
breakpoint = first_rwatch;
while (1) {
if (breakpoint) {
/* Flag this watchpoint's corresponding pages as having a watchpoint. */
k = (breakpoint->end - 1) >> MEM_GRANULARITY_BITS;
for (i = breakpoint->addr >> MEM_GRANULARITY_BITS; i <= k; i++)
gdbstub_watch_pages[i >> 6] |= (1ULL << (i & 63));
breakpoint = breakpoint->next;
} else {
/* Jump from list to list as a shortcut. */
if (l == 0)
breakpoint = first_wwatch;
else if (l == 1)
breakpoint = first_awatch;
else
break;
l++;
}
}
}
/* Respond positively. */
goto ok;
}
end:
/* Send response. */
gdbstub_client_respond(client);
}
static void
gdbstub_cpu_exec(int32_t cycs)
{
/* Flag that we're now in the debugger context to avoid triggering watchpoints. */
in_gdbstub = 1;
/* Handle CPU execution if it isn't paused. */
if (gdbstub_step <= GDBSTUB_SSTEP) {
/* Swap in any software breakpoints. */
gdbstub_breakpoint_t *swbreak = first_swbreak;
while (swbreak) {
/* Swap the INT 3 opcode into the address. */
swbreak->orig_val = readmembl(swbreak->addr);
writemembl(swbreak->addr, 0xcc);
swbreak = swbreak->next;
}
/* Call the original cpu_exec function outside the debugger context. */
if ((gdbstub_step == GDBSTUB_SSTEP) && ((cycles + cycs) <= 0))
cycs += -(cycles + cycs) + 1;
in_gdbstub = 0;
cpu_exec_shadow(cycs);
in_gdbstub = 1;
/* Swap out any software breakpoints. */
swbreak = first_swbreak;
while (swbreak) {
if (readmembl(swbreak->addr) == 0xcc)
writemembl(swbreak->addr, swbreak->orig_val);
swbreak = swbreak->next;
}
}
/* Populate stop reason if we have stopped. */
stop_reason_len = 0;
if (gdbstub_step > GDBSTUB_EXEC) {
/* Assemble stop reason manually, avoiding sprintf and friends for performance. */
stop_reason[stop_reason_len++] = 'T';
stop_reason[stop_reason_len++] = '0';
stop_reason[stop_reason_len++] = '0' + ((gdbstub_step == GDBSTUB_BREAK) ? GDB_SIGINT : GDB_SIGTRAP);
/* Add extended break reason. */
if (gdbstub_step >= GDBSTUB_BREAK_RWATCH) {
if (gdbstub_step != GDBSTUB_BREAK_WWATCH)
stop_reason[stop_reason_len++] = (gdbstub_step == GDBSTUB_BREAK_RWATCH) ? 'r' : 'a';
stop_reason[stop_reason_len++] = 'w';
stop_reason[stop_reason_len++] = 'a';
stop_reason[stop_reason_len++] = 't';
stop_reason[stop_reason_len++] = 'c';
stop_reason[stop_reason_len++] = 'h';
stop_reason[stop_reason_len++] = ':';
stop_reason_len += sprintf(&stop_reason[stop_reason_len], "%X;", watch_addr);
} else if (gdbstub_step >= GDBSTUB_BREAK_SW) {
stop_reason[stop_reason_len++] = (gdbstub_step == GDBSTUB_BREAK_SW) ? 's' : 'h';
stop_reason[stop_reason_len++] = 'w';
stop_reason[stop_reason_len++] = 'b';
stop_reason[stop_reason_len++] = 'r';
stop_reason[stop_reason_len++] = 'e';
stop_reason[stop_reason_len++] = 'a';
stop_reason[stop_reason_len++] = 'k';
stop_reason[stop_reason_len++] = ':';
stop_reason[stop_reason_len++] = ';';
}
/* Add register dump. */
uint8_t buf[10] = { 0 };
int j;
for (int i = 0; i < GDB_REG_MAX; i++) {
if (i >= 0x10)
stop_reason[stop_reason_len++] = gdbstub_hex_encode(i >> 4);
stop_reason[stop_reason_len++] = gdbstub_hex_encode(i & 0x0f);
stop_reason[stop_reason_len++] = ':';
j = gdbstub_client_read_reg(i, buf);
for (int k = 0; k < j; k++) {
stop_reason[stop_reason_len++] = gdbstub_hex_encode(buf[k] >> 4);
stop_reason[stop_reason_len++] = gdbstub_hex_encode(buf[k] & 0x0f);
}
stop_reason[stop_reason_len++] = ';';
}
/* Don't execute the CPU any further if single-stepping. */
gdbstub_step = GDBSTUB_BREAK;
}
/* Return the framerate to normal. */
gdbstub_next_asap = 0;
/* Process client packets. */
thread_wait_mutex(client_list_mutex);
gdbstub_client_t *client = first_client;
while (client) {
/* Report stop reason if the client is waiting for one. */
if (client->waiting_stop && stop_reason_len) {
client->waiting_stop = 0;
/* Wait for any pending responses to be acknowledged. */
if (!thread_wait_event(client->response_event, -1)) {
/* Block other responses from being written while this one isn't acknowledged. */
thread_reset_event(client->response_event);
/* Write stop reason response. */
strcpy(client->response, stop_reason);
client->response_pos = stop_reason_len;
gdbstub_client_respond(client);
} else {
gdbstub_log("GDB Stub: Timed out waiting for client %s:%d\n", inet_ntoa(client->addr.sin_addr), client->addr.sin_port);
}
}
if (client->has_packet) {
gdbstub_client_packet(client);
client->has_packet = client->packet_pos = 0;
thread_set_event(client->processed_event);
}
#ifdef GDBSTUB_ALLOW_MULTI_CLIENTS
client = client->next;
#else
break;
#endif
}
thread_release_mutex(client_list_mutex);
/* Flag that we're now out of the debugger context. */
in_gdbstub = 0;
}
static void
gdbstub_client_thread(void *priv)
{
gdbstub_client_t *client = (gdbstub_client_t *) priv;
uint8_t buf[256];
ssize_t bytes_read;
gdbstub_log("GDB Stub: New connection from %s:%d\n", inet_ntoa(client->addr.sin_addr), client->addr.sin_port);
/* Allow packets to be processed. */
thread_set_event(client->processed_event);
/* Read data from client. */
while ((bytes_read = recv(client->socket, (char *) buf, sizeof(buf), 0)) > 0) {
for (ssize_t i = 0; i < bytes_read; i++) {
switch (buf[i]) {
case '$': /* packet start */
/* Wait for any existing packets to be processed. */
thread_wait_event(client->processed_event, -1);
client->packet_pos = 0;
break;
case '-': /* negative acknowledgement */
/* Retransmit the current response. */
gdbstub_client_respond(client);
break;
case '+': /* positive acknowledgement */
/* Allow another response to be written. */
thread_set_event(client->response_event);
break;
case 0x03: /* break */
/* Wait for any existing packets to be processed. */
thread_wait_event(client->processed_event, -1);
/* Break immediately. */
gdbstub_log("GDB Stub: Break requested\n");
gdbstub_break();
break;
default:
/* Wait for any existing packets to be processed, just in case. */
thread_wait_event(client->processed_event, -1);
if (client->packet_pos < (sizeof(client->packet) - 1)) {
/* Append byte to the packet. */
client->packet[client->packet_pos++] = buf[i];
/* Check if we're at the end of a packet. */
if ((client->packet_pos >= 3) && (client->packet[client->packet_pos - 3] == '#')) { /* packet checksum start */
/* Small hack to speed up IDA instruction trace mode. */
if (*((uint32_t *) client->packet) == ('H' | ('c' << 8) | ('1' << 16) | ('#' << 24))) {
/* Send pre-computed response. */
send(client->socket, "+$OK#9A", 7, 0);
/* Skip processing. */
continue;
}
/* Flag that a packet should be processed. */
client->packet[client->packet_pos] = '\0';
thread_reset_event(client->processed_event);
gdbstub_next_asap = client->has_packet = 1;
}
}
break;
}
}
}
gdbstub_log("GDB Stub: Connection with %s:%d broken\n", inet_ntoa(client->addr.sin_addr), client->addr.sin_port);
/* Close socket. */
if (client->socket != -1) {
close(client->socket);
client->socket = -1;
}
/* Unblock anyone waiting on the response event. */
thread_set_event(client->response_event);
/* Remove this client from the list. */
thread_wait_mutex(client_list_mutex);
#ifdef GDBSTUB_ALLOW_MULTI_CLIENTS
if (client == first_client) {
#endif
first_client = client->next;
if (first_client == NULL) {
last_client = NULL;
gdbstub_step = GDBSTUB_EXEC; /* unpause CPU when all clients are disconnected */
}
#ifdef GDBSTUB_ALLOW_MULTI_CLIENTS
} else {
other_client = first_client;
while (other_client) {
if (other_client->next == client) {
if (last_client == client)
last_client = other_client;
other_client->next = client->next;
break;
}
other_client = other_client->next;
}
}
#endif
free(client);
thread_release_mutex(client_list_mutex);
}
static void
gdbstub_server_thread(void *priv)
{
/* Listen on GDB socket. */
listen(gdbstub_socket, 1);
/* Accept connections. */
gdbstub_client_t *client;
socklen_t sl = sizeof(struct sockaddr_in);
while (1) {
/* Allocate client structure. */
client = malloc(sizeof(gdbstub_client_t));
memset(client, 0, sizeof(gdbstub_client_t));
client->processed_event = thread_create_event();
client->response_event = thread_create_event();
/* Accept connection. */
client->socket = accept(gdbstub_socket, (struct sockaddr *) &client->addr, &sl);
if (client->socket < 0)
break;
/* Add to client list. */
thread_wait_mutex(client_list_mutex);
if (first_client) {
#ifdef GDBSTUB_ALLOW_MULTI_CLIENTS
last_client->next = client;
last_client = client;
#else
first_client->next = last_client = client;
close(first_client->socket);
#endif
} else {
first_client = last_client = client;
}
thread_release_mutex(client_list_mutex);
/* Pause CPU execution. */
gdbstub_break();
/* Start client thread. */
thread_create(gdbstub_client_thread, client);
}
/* Deallocate the redundant client structure. */
thread_destroy_event(client->processed_event);
thread_destroy_event(client->response_event);
free(client);
}
void
gdbstub_cpu_init(void)
{
/* Replace cpu_exec with our own function if the GDB stub is active. */
if ((gdbstub_socket != -1) && (cpu_exec != gdbstub_cpu_exec)) {
cpu_exec_shadow = cpu_exec;
cpu_exec = gdbstub_cpu_exec;
}
}
int
gdbstub_instruction(void)
{
/* Check hardware breakpoints if any are present. */
gdbstub_breakpoint_t *breakpoint = first_hwbreak;
if (breakpoint) {
/* Calculate the current instruction's address. */
uint32_t wanted_addr = cs + cpu_state.pc;
/* Go through the list of software breakpoints. */
do {
/* Check if the breakpoint coincides with this address. */
if (breakpoint->addr == wanted_addr) {
gdbstub_log("GDB Stub: Hardware breakpoint at %08X\n", wanted_addr);
/* Flag that we're in a hardware breakpoint. */
gdbstub_step = GDBSTUB_BREAK_HW;
/* Pause execution. */
return 1;
}
breakpoint = breakpoint->next;
} while (breakpoint);
}
/* No breakpoint found, continue execution or stop if execution is paused. */
return gdbstub_step - GDBSTUB_EXEC;
}
int
gdbstub_int3(void)
{
/* Check software breakpoints if any are present. */
gdbstub_breakpoint_t *breakpoint = first_swbreak;
if (breakpoint) {
/* Calculate the breakpoint instruction's address. */
uint32_t new_pc = cpu_state.pc - 1;
if (cpu_state.op32)
new_pc &= 0xffff;
uint32_t wanted_addr = cs + new_pc;
/* Go through the list of software breakpoints. */
do {
/* Check if the breakpoint coincides with this address. */
if (breakpoint->addr == wanted_addr) {
gdbstub_log("GDB Stub: Software breakpoint at %08X\n", wanted_addr);
/* Move EIP back to where the break instruction was. */
cpu_state.pc = new_pc;
/* Flag that we're in a software breakpoint. */
gdbstub_step = GDBSTUB_BREAK_SW;
/* Abort INT 3 execution. */
return 1;
}
breakpoint = breakpoint->next;
} while (breakpoint);
}
/* No breakpoint found, continue INT 3 execution as normal. */
return 0;
}
void
gdbstub_mem_access(uint32_t *addrs, int access)
{
/* Stop if we're in the debugger context. */
if (in_gdbstub)
return;
int width = access & (GDBSTUB_MEM_WRITE - 1);
int i;
/* Go through the lists of watchpoints for this type of access. */
gdbstub_breakpoint_t *watchpoint = (access & GDBSTUB_MEM_WRITE) ? first_wwatch : first_rwatch;
while (1) {
if (watchpoint) {
/* Check if any component of this address is within the breakpoint's range. */
for (i = 0; i < width; i++) {
if ((addrs[i] >= watchpoint->addr) && (addrs[i] < watchpoint->end)) {
watch_addr = addrs[i];
break;
}
}
if (i < width) {
gdbstub_log("GDB Stub: %s watchpoint at %08X\n", (access & GDBSTUB_MEM_AWATCH) ? "Access" : ((access & GDBSTUB_MEM_WRITE) ? "Write" : "Read"), watch_addr);
/* Flag that we're in a read/write watchpoint. */
gdbstub_step = (access & GDBSTUB_MEM_AWATCH) ? GDBSTUB_BREAK_AWATCH : ((access & GDBSTUB_MEM_WRITE) ? GDBSTUB_BREAK_WWATCH : GDBSTUB_BREAK_RWATCH);
/* Stop looking. */
return;
}
watchpoint = watchpoint->next;
} else {
/* Jump from list to list as a shortcut. */
if (access & GDBSTUB_MEM_AWATCH) {
break;
} else {
watchpoint = first_awatch;
access |= GDBSTUB_MEM_AWATCH;
}
}
}
}
void
gdbstub_init(void)
{
#ifdef _WIN32
WSAStartup(MAKEWORD(2, 2), &wsa);
#endif
/* Create GDB server socket. */
if ((gdbstub_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
pclog("GDB Stub: Failed to create socket\n");
return;
}
/* Bind GDB server socket. */
int port = 12345;
struct sockaddr_in bind_addr = {
.sin_family = AF_INET,
.sin_addr = { .s_addr = INADDR_ANY },
.sin_port = htons(port)
};
if (bind(gdbstub_socket, (struct sockaddr *) &bind_addr, sizeof(bind_addr)) == -1) {
pclog("GDB Stub: Failed to bind on port %d (%d)\n", port,
#ifdef _WIN32
WSAGetLastError()
#else
errno
#endif
);
gdbstub_socket = -1;
return;
}
/* Create client list mutex. */
client_list_mutex = thread_create_mutex();
/* Clear watchpoint page map. */
memset(gdbstub_watch_pages, 0, sizeof(gdbstub_watch_pages));
/* Start server thread. */
pclog("GDB Stub: Listening on port %d\n", port);
thread_create(gdbstub_server_thread, NULL);
/* Start the CPU paused. */
gdbstub_step = GDBSTUB_BREAK;
}
void
gdbstub_close(void)
{
/* Stop if the GDB server hasn't initialized. */
if (gdbstub_socket < 0)
return;
/* Close GDB server socket. */
close(gdbstub_socket);
/* Clear client list. */
thread_wait_mutex(client_list_mutex);
gdbstub_client_t *client = first_client;
int socket;
while (client) {
socket = client->socket;
client->socket = -1;
close(socket);
client = client->next;
}
thread_release_mutex(client_list_mutex);
thread_close_mutex(client_list_mutex);
}
``` | /content/code_sandbox/src/gdbstub.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 16,296 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation the PCI bus.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/machine.h>
#include "cpu.h"
#include "x86.h"
#include <86box/io.h>
#include <86box/pic.h>
#include <86box/mem.h>
#include <86box/device.h>
#include <86box/dma.h>
#include <86box/pci.h>
#include <86box/keyboard.h>
#include <86box/plat_unused.h>
#define PCI_ENABLED 0x80000000
typedef struct pci_card_t {
uint8_t bus;
uint8_t id;
uint8_t type;
uint8_t irq_routing[PCI_INT_PINS_NUM];
void * priv;
void (*write)(int func, int addr, uint8_t val, void *priv);
uint8_t (*read)(int func, int addr, void *priv);
} pci_card_t;
typedef struct pci_card_desc_t {
uint8_t type;
void * priv;
void (*write)(int func, int addr, uint8_t val, void *priv);
uint8_t (*read)(int func, int addr, void *priv);
uint8_t *slot;
} pci_card_desc_t;
typedef struct pci_mirq_t {
uint8_t enabled;
uint8_t irq_line;
uint8_t irq_level;
uint8_t pad;
} pci_mirq_t;
int pci_burst_time;
int agp_burst_time;
int pci_nonburst_time;
int agp_nonburst_time;
int pci_flags;
uint32_t pci_base = 0xc000;
uint32_t pci_size = 0x1000;
static pci_card_t pci_cards[PCI_CARDS_NUM];
static pci_card_desc_t pci_card_descs[PCI_CARDS_NUM];
static uint8_t pci_pmc = 0;
static uint8_t last_pci_card = 0;
static uint8_t last_normal_pci_card = 0;
static uint8_t last_normal_pci_card_id = 0;
static uint8_t last_pci_bus = 1;
static uint8_t next_pci_card = 0;
static uint8_t normal_pci_cards = 0;
static uint8_t next_normal_pci_card = 0;
static uint8_t pci_card_to_slot_mapping[256][PCI_CARDS_NUM];
static uint8_t pci_bus_number_to_index_mapping[256];
static uint8_t pci_irqs[PCI_IRQS_NUM];
static uint8_t pci_irq_level[PCI_IRQS_NUM];
static uint64_t pci_irq_hold[PCI_IRQS_NUM];
static pci_mirq_t pci_mirqs[PCI_MIRQS_NUM];
static int pci_index;
static int pci_func;
static int pci_card;
static int pci_bus;
static int pci_key;
static int pci_trc_reg = 0;
static uint32_t pci_enable = 0x00000000;
static void pci_reset_regs(void);
#ifdef ENABLE_PCI_LOG
int pci_do_log = ENABLE_PCI_LOG;
static void
pci_log(const char *fmt, ...)
{
va_list ap;
if (pci_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define pci_log(fmt, ...)
#endif
void
pci_set_irq_routing(int pci_int, int irq)
{
pci_irqs[pci_int - 1] = irq;
}
void
pci_set_irq_level(int pci_int, int level)
{
pci_irq_level[pci_int - 1] = !!level;
}
void
pci_enable_mirq(int mirq)
{
pci_mirqs[mirq].enabled = 1;
}
void
pci_set_mirq_routing(int mirq, uint8_t irq)
{
pci_mirqs[mirq].irq_line = irq;
}
uint8_t
pci_get_mirq_level(int mirq)
{
return pci_mirqs[mirq].irq_level;
}
void
pci_set_mirq_level(int mirq, uint8_t level)
{
pci_mirqs[mirq].irq_level = level;
}
/* PCI raise IRQ: the first parameter is slot if < PCI_MIRQ_BASE, MIRQ if >= PCI_MIRQ_BASE
and < PCI_DIRQ_BASE, and direct IRQ line if >= PCI_DIRQ_BASE (RichardG's
hack that may no longer be needed). */
void
pci_irq(uint8_t slot, uint8_t pci_int, int level, int set, uint8_t *irq_state)
{
uint8_t irq_routing = 0;
uint8_t pci_int_index = pci_int - PCI_INTA;
uint8_t irq_line = 0;
uint8_t is_vfio = 0;
/* The fast path out an invalid PCI card. */
if (slot == PCI_CARD_INVALID)
return;
switch (slot) {
default:
return;
case 0x00 ... PCI_CARD_MAX:
/* PCI card. */
if (!last_pci_card)
return;
if (pci_flags & FLAG_NO_IRQ_STEERING)
irq_line = pci_cards[slot].read(0, 0x3c, pci_cards[slot].priv);
else {
irq_routing = pci_cards[slot].irq_routing[pci_int_index];
switch (irq_routing) {
default:
case 0x00:
return;
case 0x01 ... PCI_IRQS_NUM:
is_vfio = pci_cards[slot].type & PCI_CARD_VFIO;
irq_routing = (irq_routing - PCI_INTA) & PCI_IRQ_MAX;
irq_line = pci_irqs[irq_routing];
/* Ignore what was provided to us as a parameter and override it with whatever
the chipset is set to. */
level = !!pci_irq_level[irq_routing];
if (level && is_vfio)
level--;
break;
/* Sometimes, PCI devices are mapped to direct IRQ's. */
case (PCI_DIRQ_BASE | 0x00) ... (PCI_DIRQ_BASE | PCI_DIRQ_MAX):
/* Direct IRQ line, always edge-triggered. */
irq_line = slot & PCI_IRQ_MAX;
break;
}
}
break;
case (PCI_IIRQ_BASE | 0x00) ... (PCI_IIRQ_BASE | PCI_IIRQS_NUM):
/* PCI internal routing. */
if (slot > 0x00) {
slot = (slot - 1) & PCI_INT_PINS_MAX;
irq_line = pci_irqs[slot];
/* Ignore what was provided to us as a parameter and override it with whatever
the chipset is set to. */
level = !!pci_irq_level[slot];
} else {
irq_line = 0xff;
level = 0;
}
break;
case (PCI_MIRQ_BASE | 0x00) ... (PCI_MIRQ_BASE | PCI_MIRQ_MAX):
/* MIRQ */
slot &= PCI_MIRQ_MAX;
if (!pci_mirqs[slot].enabled)
return;
irq_line = pci_mirqs[slot].irq_line;
break;
case (PCI_DIRQ_BASE | 0x00) ... (PCI_DIRQ_BASE | PCI_DIRQ_MAX):
/* Direct IRQ line (RichardG's ACPI workaround, may no longer be needed). */
irq_line = slot & PCI_IRQ_MAX;
break;
}
if (irq_line > PCI_IRQ_MAX)
return;
picint_common(1 << irq_line, level, set, irq_state);
}
uint8_t
pci_get_int(uint8_t slot, uint8_t pci_int)
{
return pci_cards[slot].irq_routing[pci_int - PCI_INTA];
}
static void
pci_clear_slot(int card)
{
pci_card_to_slot_mapping[pci_cards[card].bus][pci_cards[card].id] = PCI_CARD_INVALID;
pci_cards[card].id = 0xff;
pci_cards[card].type = 0xff;
for (uint8_t i = 0; i < 4; i++)
pci_cards[card].irq_routing[i] = 0;
pci_cards[card].read = NULL;
pci_cards[card].write = NULL;
pci_cards[card].priv = NULL;
}
/* Relocate a PCI device to a new slot, required for the configurable
IDSEL's of ALi M1543(c). */
void
pci_relocate_slot(int type, int new_slot)
{
int card = -1;
int old_slot;
if ((new_slot < 0) || (new_slot > 31))
return;
for (uint8_t i = 0; i < PCI_CARDS_NUM; i++) {
if ((pci_cards[i].bus == 0) && (pci_cards[i].type == type)) {
card = i;
break;
}
}
if (card == -1)
return;
old_slot = pci_cards[card].id;
pci_cards[card].id = new_slot;
if (pci_card_to_slot_mapping[0][old_slot] == card)
pci_card_to_slot_mapping[0][old_slot] = PCI_CARD_INVALID;
if (pci_card_to_slot_mapping[0][new_slot] == PCI_CARD_INVALID)
pci_card_to_slot_mapping[0][new_slot] = card;
}
/* Write PCI enable/disable key, split for the ALi M1435. */
void
pci_key_write(uint8_t val)
{
pci_key = val & 0xf0;
if (pci_key)
pci_flags |= FLAG_CONFIG_IO_ON;
else
pci_flags &= ~FLAG_CONFIG_IO_ON;
}
static void
pci_io_handlers(int set)
{
io_handler(set, 0x0cf8, 4, pci_read, pci_readw, pci_readl, pci_write, pci_writew, pci_writel, NULL);
if (pci_flags & FLAG_MECHANISM_1)
io_handler(set, 0x0cfc, 4, pci_read, pci_readw, pci_readl, pci_write, pci_writew, pci_writel, NULL);
if (pci_flags & FLAG_MECHANISM_2) {
if (set && pci_key)
pci_flags |= FLAG_CONFIG_IO_ON;
else
pci_flags &= ~FLAG_CONFIG_IO_ON;
}
}
/* Set PMC (ie. change PCI configuration mechanism), 0 = #2, 1 = #1. */
void
pci_set_pmc(uint8_t pmc)
{
pci_log("pci_set_pmc(%02X)\n", pmc);
pci_io_handlers(0);
pci_flags &= ~FLAG_MECHANISM_MASK;
pci_flags |= (FLAG_MECHANISM_1 + !(pmc & 0x01));
pci_io_handlers(1);
pci_pmc = (pmc & 0x01);
}
static void
pci_reg_write(uint16_t port, uint8_t val)
{
uint8_t slot = 0;
if (port >= 0xc000) {
pci_card = (port >> 8) & 0xf;
pci_index = port & 0xfc;
}
slot = pci_card_to_slot_mapping[pci_bus_number_to_index_mapping[pci_bus]][pci_card];
if (slot != PCI_CARD_INVALID) {
if (pci_cards[slot].write)
pci_cards[slot].write(pci_func, pci_index | (port & 0x03), val, pci_cards[slot].priv);
}
pci_log("PCI: [WB] Mechanism #%i, slot %02X, %s card %02X:%02X, function %02X, index %02X = %02X\n",
(port >= 0xc000) ? 2 : 1, slot,
(slot == PCI_CARD_INVALID) ? "non-existent" : (pci_cards[slot].write ? "used" : "unused"),
pci_card, pci_bus, pci_func, pci_index | (port & 0x03), val);
}
static void
pci_reset_regs(void)
{
pci_index = pci_card = pci_func = pci_bus = pci_key = 0;
pci_enable = 0x00000000;
pci_flags &= ~(FLAG_CONFIG_IO_ON | FLAG_CONFIG_M1_IO_ON);
}
void
pci_pic_reset(void)
{
pic_reset();
pic_set_pci_flag(last_pci_card > 0);
}
static void
pci_reset_hard(void)
{
pci_reset_regs();
for (uint8_t i = 0; i < PCI_IRQS_NUM; i++) {
if (pci_irq_hold[i]) {
pci_irq_hold[i] = 0;
picintc(1 << i);
}
}
pci_pic_reset();
}
void
pci_reset(void)
{
if (pci_flags & FLAG_MECHANISM_SWITCH) {
pci_log("pci_reset(): Switchable configuration mechanism\n");
pci_set_pmc(0x00);
}
pci_reset_hard();
}
static void
pci_trc_reset(uint8_t val)
{
if (val & 2) {
dma_reset();
dma_set_at(1);
device_reset_all(DEVICE_ALL);
cpu_alt_reset = 0;
pci_reset();
mem_a20_alt = 0;
mem_a20_recalc();
flushmmucache();
}
#ifdef USE_DYNAREC
if (cpu_use_dynarec)
cpu_init = 1;
else
resetx86();
#else
resetx86();
#endif
}
void
pci_write(uint16_t port, uint8_t val, UNUSED(void *priv))
{
pci_log("PCI: [WB] Mechanism #%i port %04X = %02X\n", ((port >= 0xcfc) && (port <= 0xcff)) ? 1 : 2, port, val);
switch (port) {
case 0xcf8:
if (pci_flags & FLAG_MECHANISM_2) {
pci_func = (val >> 1) & 7;
pci_key_write(val);
pci_log("PCI: Mechanism #2 CF8: %sllocating ports %04X-%04X...\n", (pci_flags & FLAG_CONFIG_IO_ON) ? "A" : "Dea",
pci_base, pci_base + pci_size - 1);
}
break;
case 0xcf9:
if (pci_flags & FLAG_TRC_CONTROLS_CPURST)
cpu_cpurst_on_sr = !(val & 0x10);
if (!(pci_trc_reg & 4) && (val & 4))
pci_trc_reset(val);
pci_trc_reg = val & 0xfd;
if (val & 2)
pci_trc_reg &= 0xfb;
break;
case 0xcfa:
if (pci_flags & FLAG_MECHANISM_2)
pci_bus = val;
break;
case 0xcfb:
if (pci_flags & FLAG_MECHANISM_SWITCH)
pci_set_pmc(val);
break;
case 0xcfc:
case 0xcfd:
case 0xcfe:
case 0xcff:
if ((pci_flags & FLAG_MECHANISM_1) && (pci_flags & FLAG_CONFIG_M1_IO_ON))
pci_reg_write(port, val);
break;
case 0xc000 ... 0xc0ff:
if ((pci_flags & FLAG_MECHANISM_2) && (pci_flags & (FLAG_CONFIG_IO_ON | FLAG_CONFIG_DEV0_IO_ON)))
pci_reg_write(port, val);
break;
case 0xc100 ... 0xcfff:
if ((pci_flags & FLAG_MECHANISM_2) && (pci_flags & FLAG_CONFIG_IO_ON))
pci_reg_write(port, val);
break;
default:
break;
}
}
void
pci_writew(uint16_t port, uint16_t val, UNUSED(void *priv))
{
if (port & 0x0001) {
/* Non-aligned access, split into two byte accesses. */
pci_write(port, val & 0xff, priv);
pci_write(port + 1, val >> 8, priv);
} else {
/* Aligned access, still split because we cheat. */
switch (port) {
case 0xcfc:
case 0xcfe:
case 0xc000 ... 0xcffe:
pci_write(port, val & 0xff, priv);
pci_write(port + 1, val >> 8, priv);
break;
default:
break;
}
}
}
void
pci_writel(uint16_t port, uint32_t val, UNUSED(void *priv))
{
if (port & 0x0003) {
/* Non-aligned access, split into two word accesses. */
pci_writew(port, val & 0xffff, priv);
pci_writew(port + 2, val >> 16, priv);
} else {
/* Aligned access. */
switch (port) {
case 0xcf8:
/* No split here, actual 32-bit access. */
if (pci_flags & FLAG_MECHANISM_1) {
pci_log("PCI: [WL] Mechanism #1 port 0CF8 = %08X\n", val);
pci_index = val & 0xff;
pci_func = (val >> 8) & 7;
pci_card = (val >> 11) & 31;
pci_bus = (val >> 16) & 0xff;
pci_enable = (val & PCI_ENABLED);
if (pci_enable)
pci_flags |= FLAG_CONFIG_M1_IO_ON;
else
pci_flags &= ~FLAG_CONFIG_M1_IO_ON;
break;
}
break;
case 0xcfc:
case 0xc000 ... 0xcffc:
/* Still split because we cheat. */
pci_writew(port, val & 0xffff, priv);
pci_writew(port + 2, val >> 16, priv);
break;
default:
break;
}
}
}
static uint8_t
pci_reg_read(uint16_t port)
{
uint8_t slot = 0;
uint8_t ret = 0xff;
if (port >= 0xc000) {
pci_card = (port >> 8) & 0xf;
pci_index = port & 0xfc;
}
slot = pci_card_to_slot_mapping[pci_bus_number_to_index_mapping[pci_bus]][pci_card];
if (slot != PCI_CARD_INVALID) {
if (pci_cards[slot].read)
ret = pci_cards[slot].read(pci_func, pci_index | (port & 0x03), pci_cards[slot].priv);
}
pci_log("PCI: [RB] Mechanism #%i, slot %02X, %s card %02X:%02X, function %02X, index %02X = %02X\n",
(port >= 0xc000) ? 2 : 1, slot,
(slot == PCI_CARD_INVALID) ? "non-existent" : (pci_cards[slot].read ? "used" : "unused"),
pci_card, pci_bus, pci_func, pci_index | (port & 0x03), ret);
return ret;
}
uint8_t
pci_read(uint16_t port, UNUSED(void *priv))
{
uint8_t ret = 0xff;
switch (port) {
case 0xcf8:
if (pci_flags & FLAG_MECHANISM_2)
ret = pci_key | (pci_func << 1);
break;
case 0xcf9:
ret = pci_trc_reg & 0xfb;
break;
case 0xcfa:
if (pci_flags & FLAG_MECHANISM_2)
ret = pci_bus;
break;
case 0xcfb:
if (pci_flags & FLAG_MECHANISM_SWITCH)
ret = pci_pmc;
break;
case 0xcfc:
case 0xcfd:
case 0xcfe:
case 0xcff:
if ((pci_flags & FLAG_MECHANISM_1) && (pci_flags & FLAG_CONFIG_M1_IO_ON))
ret = pci_reg_read(port);
break;
case 0xc000 ... 0xc0ff:
if ((pci_flags & FLAG_MECHANISM_2) && (pci_flags & (FLAG_CONFIG_IO_ON | FLAG_CONFIG_DEV0_IO_ON)))
ret = pci_reg_read(port);
break;
case 0xc100 ... 0xcfff:
if ((pci_flags & FLAG_MECHANISM_2) && (pci_flags & FLAG_CONFIG_IO_ON))
ret = pci_reg_read(port);
break;
default:
break;
}
pci_log("PCI: [RB] Mechanism #%i port %04X = %02X\n", ((port >= 0xcfc) && (port <= 0xcff)) ? 1 : 2, port, ret);
return ret;
}
uint16_t
pci_readw(uint16_t port, UNUSED(void *priv))
{
uint16_t ret = 0xffff;
if (port & 0x0001) {
/* Non-aligned access, split into two byte accesses. */
ret = pci_read(port, priv);
ret |= ((uint16_t) pci_read(port + 1, priv)) << 8;
} else {
/* Aligned access, still split because we cheat. */
switch (port) {
case 0xcfc:
case 0xcfe:
case 0xc000 ... 0xcffe:
ret = pci_read(port, priv);
ret |= ((uint16_t) pci_read(port + 1, priv)) << 8;
break;
default:
break;
}
}
return ret;
}
uint32_t
pci_readl(uint16_t port, UNUSED(void *priv))
{
uint32_t ret = 0xffffffff;
if (port & 0x0003) {
/* Non-aligned access, split into two word accesses. */
ret = pci_readw(port, priv);
ret |= ((uint32_t) pci_readw(port + 2, priv)) << 16;
} else {
/* Aligned access. */
switch (port) {
case 0xcf8:
/* No split here, actual 32-bit access. */
if (pci_flags & FLAG_MECHANISM_1) {
ret = pci_index | (pci_func << 8) | (pci_card << 11) | (pci_bus << 16);
if (pci_flags & FLAG_CONFIG_M1_IO_ON)
ret |= PCI_ENABLED;
pci_log("PCI: [RL] Mechanism #1 port 0CF8 = %08X\n", ret);
return ret;
}
break;
case 0xcfc:
case 0xc000 ... 0xcffc:
/* Still split because we cheat. */
ret = pci_readw(port, priv);
ret |= ((uint32_t) pci_readw(port + 2, priv)) << 16;
break;
}
}
return ret;
}
uint8_t
pci_register_bus(void)
{
return last_pci_bus++;
}
void
pci_remap_bus(uint8_t bus_index, uint8_t bus_number)
{
uint8_t i = 1;
do {
if (pci_bus_number_to_index_mapping[i] == bus_index)
pci_bus_number_to_index_mapping[i] = PCI_BUS_INVALID;
} while (i++ < 0xff);
if ((bus_number > 0) && (bus_number < 0xff))
pci_bus_number_to_index_mapping[bus_number] = bus_index;
}
void
pci_register_bus_slot(int bus, int card, int type, int inta, int intb, int intc, int intd)
{
pci_card_t *dev = &pci_cards[last_pci_card];
dev->bus = bus;
dev->id = card;
dev->type = type;
dev->irq_routing[0] = inta;
dev->irq_routing[1] = intb;
dev->irq_routing[2] = intc;
dev->irq_routing[3] = intd;
dev->read = NULL;
dev->write = NULL;
dev->priv = NULL;
pci_card_to_slot_mapping[bus][card] = last_pci_card;
pci_log("pci_register_slot(): pci_cards[%i].bus = %02X; .id = %02X\n", last_pci_card, bus, card);
if (type == PCI_CARD_NORMAL) {
last_normal_pci_card++;
/* This is needed to know at what position to add the bridge. */
last_normal_pci_card_id = last_pci_card;
}
last_pci_card++;
}
static uint8_t
pci_find_slot(uint8_t add_type, uint8_t ignore_slot)
{
const pci_card_t *dev;
/* Is the device being added with a strict slot type matching requirement? */
uint8_t strict = (add_type & PCI_ADD_STRICT);
/* The actual type of the device being added, with the strip flag, if any,
masked. */
uint8_t masked_add_type = (add_type & PCI_ADD_MASK);
/* Is the device being added normal, ie. without the possibility of ever
being used as an on-board device? */
uint8_t normal_add_type = (masked_add_type >= PCI_CARD_NORMAL);
uint8_t match;
uint8_t normal;
uint8_t empty;
uint8_t process;
uint8_t ret = PCI_CARD_INVALID;
/* Iterate i until we have either exhausted all the slot or the value of
ret has changed to something other than PCI_CARD_INVALID. */
for (uint8_t i = 0; (ret == PCI_CARD_INVALID) && (i < last_pci_card); i++) {
dev = &pci_cards[i];
/* Is the slot we are looking at of the exact same type as the device being
added? */
match = (dev->type == masked_add_type);
/* Is the slot we are looking at a normal slot (ie. not an on-board chip)? */
normal = (dev->type == PCI_CARD_NORMAL);
/* Is the slot we are looking at empty? */
empty = !dev->read && !dev->write;
/* Should we process this slot, ie. were we told to ignore it, if any at all? */
process = (ignore_slot == PCI_IGNORE_NO_SLOT) || (i != ignore_slot);
/* This condition is now refactored and made to be easily human-readable. */
if (empty && process && (match || (!strict && normal && normal_add_type)))
ret = i;
}
return ret;
}
/* Add a PCI card. */
void
pci_add_card(uint8_t add_type, uint8_t (*read)(int func, int addr, void *priv),
void (*write)(int func, int addr, uint8_t val, void *priv), void *priv, uint8_t *slot)
{
pci_card_desc_t *dev;
pci_log("pci_add_card(): PCI card #%02i: type = %i\n", next_pci_card, add_type);
if (next_pci_card < PCI_CARDS_NUM) {
dev = &pci_card_descs[next_pci_card];
dev->type = add_type | PCI_ADD_STRICT;
dev->read = read;
dev->write = write;
dev->priv = priv;
dev->slot = slot;
*(dev->slot) = PCI_CARD_INVALID;
next_pci_card++;
if (add_type == PCI_ADD_NORMAL)
normal_pci_cards++;
}
}
static void
pci_clear_card(UNUSED(int pci_card))
{
pci_card_desc_t *dev;
if (next_pci_card < PCI_CARDS_NUM) {
dev = &pci_card_descs[next_pci_card];
memset(dev, 0x00, sizeof(pci_card_desc_t));
}
}
static uint8_t
pci_register_card(int pci_card)
{
pci_card_desc_t *dev;
pci_card_t *card;
uint8_t i;
uint8_t ret = PCI_CARD_INVALID;
if (pci_card < PCI_CARDS_NUM) {
dev = &pci_card_descs[pci_card];
if (last_pci_card) {
/* First, find the next available slot. */
i = pci_find_slot(dev->type, 0xff);
if (i != PCI_CARD_INVALID) {
card = &pci_cards[i];
card->read = dev->read;
card->write = dev->write;
card->priv = dev->priv;
card->type |= (dev->type & PCI_CARD_VFIO);
*(dev->slot) = i;
ret = i;
}
}
pci_clear_card(pci_card);
}
return ret;
}
/* Add an instance of the PCI bridge. */
void
pci_add_bridge(uint8_t agp, uint8_t (*read)(int func, int addr, void *priv), void (*write)(int func, int addr, uint8_t val, void *priv), void *priv, uint8_t *slot)
{
pci_card_t *card;
uint8_t bridge_slot = agp ? pci_find_slot(PCI_ADD_AGPBRIDGE, 0xff) : last_normal_pci_card_id;
if (bridge_slot != PCI_CARD_INVALID) {
card = &pci_cards[bridge_slot];
card->read = read;
card->write = write;
card->priv = priv;
}
*slot = bridge_slot;
}
/* Register the cards that have been added into slots. */
void
pci_register_cards(void)
{
uint8_t normal;
#ifdef ENABLE_PCI_LOG
uint8_t type;
uint8_t *slot;
#endif
next_normal_pci_card = 0;
if (next_pci_card > 0) {
for (uint8_t i = 0; i < next_pci_card; i++) {
#ifdef ENABLE_PCI_LOG
type = pci_card_descs[i].type;
slot = pci_card_descs[i].slot;
#endif
normal = (pci_card_descs[i].type == PCI_CARD_NORMAL);
/* If this is a normal card, increase the next normal card index. */
if (normal)
next_normal_pci_card++;
/* If this is a normal card and the next one is going to be beyond the last slot,
add the bridge. */
if (normal && (next_normal_pci_card >= last_normal_pci_card) &&
(normal_pci_cards > last_normal_pci_card) && !(pci_flags & FLAG_NO_BRIDGES))
device_add_inst(&dec21150_device, last_pci_bus);
pci_register_card(i);
pci_log("pci_register_cards(): PCI card #%02i: type = %02X, pci device = %02X:%02X\n",
i, type, pci_cards[*slot].bus, pci_cards[*slot].id);
}
}
next_pci_card = 0;
normal_pci_cards = 0;
next_normal_pci_card = 0;
}
static void
pci_slots_clear(void)
{
uint8_t i;
last_pci_card = last_normal_pci_card = 0;
last_normal_pci_card = 0;
last_pci_bus = 1;
next_pci_card = 0;
normal_pci_cards = 0;
next_normal_pci_card = 0;
for (i = 0; i < PCI_CARDS_NUM; i++)
pci_clear_slot(i);
i = 0;
do {
for (uint8_t j = 0; j < PCI_CARDS_NUM; j++)
pci_card_to_slot_mapping[i][j] = PCI_CARD_INVALID;
pci_bus_number_to_index_mapping[i] = PCI_BUS_INVALID;
} while (i++ < 0xff);
pci_bus_number_to_index_mapping[0] = 0; /* always map bus 0 to index 0 */
}
void
pci_init(int flags)
{
int c;
pci_base = 0xc000;
pci_size = 0x1000;
pci_slots_clear();
pci_reset_hard();
pci_trc_reg = 0;
pci_flags = flags;
if (pci_flags & FLAG_NO_IRQ_STEERING) {
pic_elcr_io_handler(0);
pic_elcr_set_enabled(0);
} else {
pic_elcr_io_handler(1);
pic_elcr_set_enabled(1);
}
pci_pmc = (pci_flags & FLAG_MECHANISM_1) ? 0x01 : 0x00;
if ((pci_flags & FLAG_MECHANISM_2) && (pci_flags & FLAG_CONFIG_DEV0_IO_ON)) {
pci_log("PCI: Always expose device 0\n");
pci_base = 0xc100;
pci_size = 0x0f00;
}
if (pci_flags & FLAG_MECHANISM_SWITCH) {
pci_log("PCI: Switchable configuration mechanism\n");
pci_set_pmc(pci_pmc);
} else
pci_io_handlers(1);
for (c = 0; c < PCI_IRQS_NUM; c++) {
pci_irqs[c] = PCI_IRQ_DISABLED;
pci_irq_level[c] = (pci_flags & FLAG_NO_IRQ_STEERING) ? 0 : 1;
}
for (c = 0; c < PCI_MIRQS_NUM; c++) {
pci_mirqs[c].enabled = 0;
pci_mirqs[c].irq_line = PCI_IRQ_DISABLED;
}
pic_set_pci_flag(1);
}
``` | /content/code_sandbox/src/pci.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 7,520 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implement the VNC remote renderer with LibVNCServer.
*
*
*
* Authors: Fred N. van Kempen, <decwiz@yahoo.com>
* Based on raw code by RichardG, <richardg867@gmail.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <rfb/rfb.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/video.h>
#include <86box/keyboard.h>
#include <86box/mouse.h>
#include <86box/plat.h>
#include <86box/ui.h>
#include <86box/vnc.h>
#define VNC_MIN_X 320
#define VNC_MAX_X 2048
#define VNC_MIN_Y 200
#define VNC_MAX_Y 2048
static rfbScreenInfoPtr rfb = NULL;
static int clients;
static int updatingSize;
static int allowedX;
static int allowedY;
static int ptr_x;
static int ptr_y;
static int ptr_but;
#ifdef ENABLE_VNC_LOG
int vnc_do_log = ENABLE_VNC_LOG;
static void
vnc_log(const char *fmt, ...)
{
va_list ap;
if (vnc_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define vnc_log(fmt, ...)
#endif
static void
vnc_kbdevent(rfbBool down, rfbKeySym k, rfbClientPtr cl)
{
(void) cl;
/* Handle it through the lookup tables. */
vnc_kbinput(down ? 1 : 0, (int) k);
}
static void
vnc_ptrevent(int but, int x, int y, rfbClientPtr cl)
{
int dx;
int dy;
int b;
b = 0x00;
if (but & 0x01)
b |= 0x01;
if (but & 0x02)
b |= 0x04;
if (but & 0x04)
b |= 0x02;
mouse_set_buttons_ex(b);
ptr_but = but;
dx = (x - ptr_x) / 0.96; /* TODO: Figure out the correct scale factor for X and Y. */
dy = (y - ptr_y) / 0.96;
/* VNC uses absolute positions within the window, no deltas. */
mouse_scale(dx, dy);
ptr_x = x;
ptr_y = y;
mouse_x_abs = (double)ptr_x / (double)allowedX;
mouse_y_abs = (double)ptr_y / (double)allowedY;
if (mouse_x_abs > 1.0) mouse_x_abs = 1.0;
if (mouse_y_abs > 1.0) mouse_y_abs = 1.0;
if (mouse_x_abs < 0.0) mouse_x_abs = 0.0;
if (mouse_y_abs < 0.0) mouse_y_abs = 0.0;
rfbDefaultPtrAddEvent(but, x, y, cl);
}
static void
vnc_clientgone(UNUSED(rfbClientPtr cl))
{
vnc_log("VNC: client disconnected: %s\n", cl->host);
if (clients > 0)
clients--;
if (clients == 0) {
/* No more clients, pause the emulator. */
vnc_log("VNC: no clients, pausing..\n");
/* Disable the mouse. */
#if 0
plat_mouse_capture(0);
#endif
mouse_set_poll_ex(NULL);
plat_pause(1);
}
}
static enum rfbNewClientAction
vnc_newclient(rfbClientPtr cl)
{
/* Hook the ClientGone function so we know when they're gone. */
cl->clientGoneHook = vnc_clientgone;
vnc_log("VNC: new client: %s\n", cl->host);
if (++clients == 1) {
/* Reset the mouse. */
ptr_x = allowedX / 2;
ptr_y = allowedY / 2;
mouse_clear_coords();
mouse_clear_buttons();
/* We now have clients, un-pause the emulator if needed. */
vnc_log("VNC: unpausing..\n");
/* Enable the mouse. */
#if 0
plat_mouse_capture(1);
#endif
mouse_set_poll_ex(vnc_mouse_poll);
plat_pause(0);
}
/* For now, we always accept clients. */
return RFB_CLIENT_ACCEPT;
}
static void
vnc_display(rfbClientPtr cl)
{
/* Avoid race condition between resize and update. */
if (!updatingSize && cl->newFBSizePending) {
updatingSize = 1;
} else if (updatingSize && !cl->newFBSizePending) {
updatingSize = 0;
allowedX = rfb->width;
allowedY = rfb->height;
}
}
static void
vnc_blit(int x, int y, int w, int h, int monitor_index)
{
if (monitor_index || (x < 0) || (y < 0) || (w < VNC_MIN_X) || (h < VNC_MIN_Y) || (w > VNC_MAX_X) || (h > VNC_MAX_Y) || (buffer32 == NULL)) {
video_blit_complete_monitor(monitor_index);
return;
}
for (int row = 0; row < h; ++row)
video_copy(&(((uint8_t *) rfb->frameBuffer)[row * 2048 * sizeof(uint32_t)]), &(buffer32->line[y + row][x]), w * sizeof(uint32_t));
if (screenshots)
video_screenshot((uint32_t *) rfb->frameBuffer, 0, 0, VNC_MAX_X);
video_blit_complete_monitor(monitor_index);
if (!updatingSize)
rfbMarkRectAsModified(rfb, 0, 0, allowedX, allowedY);
}
/* Initialize VNC for operation. */
int
vnc_init(UNUSED(void *arg))
{
static char title[128];
rfbPixelFormat rpf = {
/*
* Screen format:
* 32bpp; 32 depth;
* little endian;
* true color;
* max 255 R/G/B;
* red shift 16; green shift 8; blue shift 0;
* padding
*/
32, 32, 0, 1, 255, 255, 255, 16, 8, 0, 0, 0
};
plat_pause(1);
cgapal_rebuild_monitor(0);
if (rfb == NULL) {
wcstombs(title, ui_window_title(NULL), sizeof(title));
updatingSize = 0;
allowedX = scrnsz_x;
allowedY = scrnsz_y;
rfb = rfbGetScreen(0, NULL, VNC_MAX_X, VNC_MAX_Y, 8, 3, 4);
rfb->desktopName = title;
rfb->frameBuffer = (char *) malloc(VNC_MAX_X * VNC_MAX_Y * 4);
rfb->serverFormat = rpf;
rfb->alwaysShared = TRUE;
rfb->displayHook = vnc_display;
rfb->ptrAddEvent = vnc_ptrevent;
rfb->kbdAddEvent = vnc_kbdevent;
rfb->newClientHook = vnc_newclient;
/* Set up our current resolution. */
rfb->width = allowedX;
rfb->height = allowedY;
rfbInitServer(rfb);
rfbRunEventLoop(rfb, -1, TRUE);
}
/* Set up our BLIT handlers. */
video_setblit(vnc_blit);
clients = 0;
vnc_log("VNC: init complete.\n");
return 1;
}
void
vnc_close(void)
{
video_setblit(NULL);
if (rfb != NULL) {
free(rfb->frameBuffer);
rfbScreenCleanup(rfb);
rfb = NULL;
}
}
void
vnc_resize(int x, int y)
{
rfbClientIteratorPtr iterator;
rfbClientPtr cl;
if (rfb == NULL)
return;
/* TightVNC doesn't like certain sizes.. */
if ((x < VNC_MIN_X) || (x > VNC_MAX_X) || (y < VNC_MIN_Y) || (y > VNC_MAX_Y)) {
vnc_log("VNC: invalid resoltion %dx%d requested!\n", x, y);
return;
}
if ((x != rfb->width || y != rfb->height) && x > 160 && y > 0) {
vnc_log("VNC: updating resolution: %dx%d\n", x, y);
allowedX = (rfb->width < x) ? rfb->width : x;
allowedY = (rfb->width < y) ? rfb->width : y;
rfb->width = x;
rfb->height = y;
iterator = rfbGetClientIterator(rfb);
while ((cl = rfbClientIteratorNext(iterator)) != NULL) {
LOCK(cl->updateMutex);
cl->newFBSizePending = 1;
UNLOCK(cl->updateMutex);
}
}
}
/* Tell them to pause if we have no clients. */
int
vnc_pause(void)
{
return ((clients > 0) ? 0 : 1);
}
void
vnc_take_screenshot(UNUSED(wchar_t *fn))
{
vnc_log("VNC: take_screenshot\n");
}
``` | /content/code_sandbox/src/vnc.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,269 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of Ports 61, 62, and 63 used by various
* machines.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <86box/86box.h>
#include <86box/device.h>
#include "cpu.h"
#include <86box/timer.h>
#include <86box/io.h>
#include <86box/keyboard.h>
#include <86box/mem.h>
#include <86box/m_xt_xi8088.h>
#include <86box/fdd.h>
#include <86box/fdc.h>
#include <86box/sound.h>
#include <86box/snd_speaker.h>
#include <86box/pit.h>
#include <86box/ppi.h>
#include <86box/video.h>
#include <86box/port_6x.h>
#include <86box/plat_unused.h>
#include <86box/random.h>
#define PS2_REFRESH_TIME (16 * TIMER_USEC)
#define PORT_6X_TURBO 1
#define PORT_6X_EXT_REF 2
#define PORT_6X_MIRROR 4
#define PORT_6X_SWA 8
static int cycles_sub = 0;
static void
port_6x_write(uint16_t port, uint8_t val, void *priv)
{
const port_6x_t *dev = (port_6x_t *) priv;
port &= 3;
cycles -= cycles_sub;
if ((port == 3) && (dev->flags & PORT_6X_MIRROR))
port = 1;
switch (port) {
case 1:
ppi.pb = (ppi.pb & 0x10) | (val & 0x0f);
speaker_update();
speaker_gated = val & 1;
speaker_enable = val & 2;
if (speaker_enable)
was_speaker_enable = 1;
pit_devs[0].set_gate(pit_devs[0].data, 2, val & 1);
if (dev->flags & PORT_6X_TURBO)
xi8088_turbo_set(!!(val & 0x04));
break;
default:
break;
}
}
static uint8_t
port_61_read_simple(UNUSED(uint16_t port), UNUSED(void *priv))
{
uint8_t ret = ppi.pb & 0x1f;
cycles -= cycles_sub;
if (ppispeakon)
ret |= 0x20;
return ret;
}
static uint8_t
port_61_read(UNUSED(uint16_t port), void *priv)
{
const port_6x_t *dev = (port_6x_t *) priv;
uint8_t ret = 0xff;
cycles -= cycles_sub;
if (dev->flags & PORT_6X_EXT_REF) {
ret = ppi.pb & 0x0f;
if (dev->refresh)
ret |= 0x10;
} else
ret = ppi.pb & 0x1f;
if (ppispeakon)
ret |= 0x20;
if (dev->flags & PORT_6X_TURBO)
ret = (ret & 0xfb) | (xi8088_turbo_get() ? 0x04 : 0x00);
return ret;
}
static uint8_t
port_62_read(UNUSED(uint16_t port), UNUSED(void *priv))
{
uint8_t ret = 0xff;
/* SWA on Olivetti M240 mainboard (off=1) */
ret = 0x00;
if (ppi.pb & 0x8) {
/* Switches 4, 5 - floppy drives (number) */
int fdd_count = 0;
for (uint8_t i = 0; i < FDD_NUM; i++) {
if (fdd_get_flags(i))
fdd_count++;
}
if (!fdd_count)
ret |= 0x00;
else
ret |= ((fdd_count - 1) << 2);
/* Switches 6, 7 - monitor type */
if (video_is_mda())
ret |= 0x3;
else if (video_is_cga())
ret |= 0x2; /* 0x10 would be 40x25 */
else
ret |= 0x0;
} else {
/* bit 2 always on */
ret |= 0x4;
/* Switch 8 - 8087 FPU. */
if (hasfpu)
ret |= 0x02;
}
return ret;
}
static void
port_6x_refresh(void *priv)
{
port_6x_t *dev = (port_6x_t *) priv;
dev->refresh = !dev->refresh;
timer_advance_u64(&dev->refresh_timer, PS2_REFRESH_TIME);
}
static void
port_6x_close(void *priv)
{
port_6x_t *dev = (port_6x_t *) priv;
timer_disable(&dev->refresh_timer);
free(dev);
}
void *
port_6x_init(const device_t *info)
{
port_6x_t *dev = (port_6x_t *) malloc(sizeof(port_6x_t));
memset(dev, 0, sizeof(port_6x_t));
dev->flags = info->local & 0xff;
if (dev->flags & (PORT_6X_TURBO | PORT_6X_EXT_REF)) {
io_sethandler(0x0061, 1, port_61_read, NULL, NULL, port_6x_write, NULL, NULL, dev);
if (dev->flags & PORT_6X_EXT_REF)
timer_add(&dev->refresh_timer, port_6x_refresh, dev, 1);
if (dev->flags & PORT_6X_MIRROR)
io_sethandler(0x0063, 1, port_61_read, NULL, NULL, port_6x_write, NULL, NULL, dev);
} else {
io_sethandler(0x0061, 1, port_61_read_simple, NULL, NULL, port_6x_write, NULL, NULL, dev);
if (dev->flags & PORT_6X_MIRROR)
io_sethandler(0x0063, 1, port_61_read_simple, NULL, NULL, port_6x_write, NULL, NULL, dev);
}
if (dev->flags & PORT_6X_SWA)
io_sethandler(0x0062, 1, port_62_read, NULL, NULL, NULL, NULL, NULL, dev);
cycles_sub = is486 ? ISA_CYCLES(8) : 0;
return dev;
}
const device_t port_6x_device = {
.name = "Port 6x Registers",
.internal_name = "port_6x",
.flags = 0,
.local = 0,
.init = port_6x_init,
.close = port_6x_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t port_6x_xi8088_device = {
.name = "Port 6x Registers (Xi8088)",
.internal_name = "port_6x_xi8088",
.flags = 0,
.local = PORT_6X_TURBO | PORT_6X_EXT_REF | PORT_6X_MIRROR,
.init = port_6x_init,
.close = port_6x_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t port_6x_ps2_device = {
.name = "Port 6x Registers (IBM PS/2)",
.internal_name = "port_6x_ps2",
.flags = 0,
.local = PORT_6X_EXT_REF,
.init = port_6x_init,
.close = port_6x_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t port_6x_olivetti_device = {
.name = "Port 6x Registers (Olivetti)",
.internal_name = "port_6x_olivetti",
.flags = 0,
.local = PORT_6X_SWA,
.init = port_6x_init,
.close = port_6x_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/port_6x.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,081 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* FIFO infrastructure.
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef FIFO_STANDALONE
#define fatal printf
#define pclog_ex printf
#define pclog printf
#include "include/86box/fifo.h"
#else
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/fifo.h>
#endif
#ifdef ENABLE_FIFO_LOG
int fifo_do_log = ENABLE_FIFO_LOG;
static void
fifo_log(const char *fmt, ...)
{
va_list ap;
if (fifo_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define fifo_log(fmt, ...)
#endif
int
fifo_get_count(void *priv)
{
const fifo_t *fifo = (fifo_t *) priv;
int ret = fifo->len;
if (fifo->end == fifo->start)
ret = fifo->full ? fifo->len : 0;
else
ret = abs(fifo->end - fifo->start);
return ret;
}
void
fifo_write(uint8_t val, void *priv)
{
fifo_t *fifo = (fifo_t *) priv;
fifo->d_full = fifo->d_empty = 0;
fifo->d_ready = fifo->d_overrun = 0;
if (fifo->full)
fifo->overrun = 1;
else {
fifo->buf[fifo->end] = val;
fifo->end = (fifo->end + 1) % fifo->len;
if (fifo->end == fifo->start)
fifo->full = 1;
fifo->empty = 0;
if (fifo_get_count(fifo) >= fifo->trigger_len)
fifo->ready = 1;
}
}
void
fifo_write_evt(uint8_t val, void *priv)
{
fifo_t *fifo = (fifo_t *) priv;
fifo->d_full = fifo->d_empty = 0;
fifo->d_ready = fifo->d_overrun = 0;
if (fifo->full) {
fifo->d_overrun = (fifo->overrun != 1);
fifo->overrun = 1;
if (fifo->d_overrun && (fifo->d_overrun_evt != NULL))
fifo->d_overrun_evt(fifo->priv);
} else {
fifo->buf[fifo->end] = val;
fifo->end = (fifo->end + 1) % fifo->len;
if (fifo->end == fifo->start) {
fifo->d_full = (fifo->full != 1);
fifo->full = 1;
if (fifo->d_full && (fifo->d_full_evt != NULL))
fifo->d_full_evt(fifo->priv);
}
fifo->d_empty = (fifo->empty != 0);
fifo->empty = 0;
if (fifo->d_empty && (fifo->d_empty_evt != NULL))
fifo->d_empty_evt(fifo->priv);
if (fifo_get_count(fifo) >= fifo->trigger_len) {
fifo->d_ready = (fifo->ready != 1);
fifo->ready = 1;
if (fifo->d_ready && (fifo->d_ready_evt != NULL))
fifo->d_ready_evt(fifo->priv);
}
}
}
uint8_t
fifo_read(void *priv)
{
fifo_t *fifo = (fifo_t *) priv;
uint8_t ret = 0x00;
int count;
if (!fifo->empty) {
ret = fifo->buf[fifo->start];
fifo->start = (fifo->start + 1) % fifo->len;
fifo->full = 0;
count = fifo_get_count(fifo);
if (count < fifo->trigger_len) {
fifo->ready = 0;
if (count == 0)
fifo->empty = 1;
}
}
return ret;
}
uint8_t
fifo_read_evt(void *priv)
{
fifo_t *fifo = (fifo_t *) priv;
uint8_t ret = 0x00;
int count;
fifo->d_full = fifo->d_empty = 0;
fifo->d_ready = 0;
if (!fifo->empty) {
ret = fifo->buf[fifo->start];
fifo->start = (fifo->start + 1) % fifo->len;
fifo->d_full = (fifo->full != 0);
fifo->full = 0;
if (fifo->d_full && (fifo->d_full_evt != NULL))
fifo->d_full_evt(fifo->priv);
count = fifo_get_count(fifo);
if (count < fifo->trigger_len) {
fifo->d_ready = (fifo->ready != 0);
fifo->ready = 0;
if (fifo->d_ready && (fifo->d_ready_evt != NULL))
fifo->d_ready_evt(fifo->priv);
if (count == 0) {
fifo->d_empty = (fifo->empty != 1);
fifo->empty = 1;
if (fifo->d_empty && (fifo->d_empty_evt != NULL))
fifo->d_empty_evt(fifo->priv);
}
}
}
return ret;
}
void
fifo_clear_overrun(void *priv)
{
fifo_t *fifo = (fifo_t *) priv;
fifo->d_overrun = (fifo->overrun != 0);
fifo->overrun = 0;
}
int
fifo_get_full(void *priv)
{
const fifo_t *fifo = (fifo_t *) priv;
return fifo->full;
}
int
fifo_get_d_full(void *priv)
{
fifo_t *fifo = (fifo_t *) priv;
int ret = fifo->d_full;
fifo->d_full = 0;
return ret;
}
int
fifo_get_empty(void *priv)
{
const fifo_t *fifo = (fifo_t *) priv;
return fifo->empty;
}
int
fifo_get_d_empty(void *priv)
{
fifo_t *fifo = (fifo_t *) priv;
int ret = fifo->d_empty;
fifo->d_empty = 0;
return ret;
}
int
fifo_get_overrun(void *priv)
{
const fifo_t *fifo = (fifo_t *) priv;
return fifo->overrun;
}
int
fifo_get_d_overrun(void *priv)
{
fifo_t *fifo = (fifo_t *) priv;
int ret = fifo->d_overrun;
fifo->d_overrun = 0;
return ret;
}
int
fifo_get_ready(void *priv)
{
const fifo_t *fifo = (fifo_t *) priv;
return fifo->ready;
}
int
fifo_get_d_ready(void *priv)
{
fifo_t *fifo = (fifo_t *) priv;
int ret = fifo->d_ready;
fifo->d_ready = 0;
return ret;
}
int
fifo_get_trigger_len(void *priv)
{
const fifo_t *fifo = (fifo_t *) priv;
return fifo->trigger_len;
}
void
fifo_set_trigger_len(void *priv, int trigger_len)
{
fifo_t *fifo = (fifo_t *) priv;
fifo->trigger_len = trigger_len;
}
void
fifo_set_len(void *priv, int len)
{
fifo_t *fifo = (fifo_t *) priv;
fifo->len = len;
}
void
fifo_set_d_full_evt(void *priv, void (*d_full_evt)(void *))
{
fifo_t *fifo = (fifo_t *) priv;
fifo->d_full_evt = d_full_evt;
}
void
fifo_set_d_empty_evt(void *priv, void (*d_empty_evt)(void *))
{
fifo_t *fifo = (fifo_t *) priv;
fifo->d_empty_evt = d_empty_evt;
}
void
fifo_set_d_overrun_evt(void *priv, void (*d_overrun_evt)(void *))
{
fifo_t *fifo = (fifo_t *) priv;
fifo->d_overrun_evt = d_overrun_evt;
}
void
fifo_set_d_ready_evt(void *priv, void (*d_ready_evt)(void *))
{
fifo_t *fifo = (fifo_t *) priv;
fifo->d_ready_evt = d_ready_evt;
}
void
fifo_set_priv(void *priv, void *sub_priv)
{
fifo_t *fifo = (fifo_t *) priv;
fifo->priv = sub_priv;
}
void
fifo_reset(void *priv)
{
fifo_t *fifo = (fifo_t *) priv;
fifo->start = fifo->end = 0;
fifo->full = fifo->overrun = 0;
fifo->empty = 1;
fifo->ready = 0;
}
void
fifo_reset_evt(void *priv)
{
fifo_t *fifo = (fifo_t *) priv;
fifo->start = fifo->end = 0;
fifo->full = fifo->overrun = 0;
fifo->empty = 1;
fifo->ready = 0;
fifo->d_full = fifo->d_overrun = 0;
fifo->d_empty = fifo->d_ready = 0;
if (fifo->d_full_evt != NULL)
fifo->d_full_evt(fifo->priv);
if (fifo->d_overrun_evt != NULL)
fifo->d_overrun_evt(fifo->priv);
if (fifo->d_empty_evt != NULL)
fifo->d_empty_evt(fifo->priv);
if (fifo->d_ready_evt != NULL)
fifo->d_ready_evt(fifo->priv);
}
void
fifo_close(void *priv)
{
free(priv);
}
void *
fifo_init(int len)
{
void *fifo = NULL;
if (len == 64)
fifo = calloc(1, sizeof(fifo64_t));
else if (len == 16)
fifo = calloc(1, sizeof(fifo16_t));
else {
fatal("FIFO : Invalid FIFO length: %i\n", len);
return NULL;
}
if (fifo == NULL)
fatal("FIFO%i: Failed to allocate memory for the FIFO\n", len);
else
((fifo_t *) fifo)->len = len;
return fifo;
}
#ifdef FIFO_STANDALONE
enum {
SERIAL_INT_LSR = 1,
SERIAL_INT_RECEIVE = 2,
SERIAL_INT_TRANSMIT = 4,
SERIAL_INT_MSR = 8,
SERIAL_INT_TIMEOUT = 16
};
typedef struct serial_t {
uint8_t lsr;
uint8_t int_status;
uint8_t tsr;
uint8_t tsr_empty;
fifo16_t *rcvr_fifo;
fifo16_t *xmit_fifo;
} serial_t;
static void
serial_receive_timer(fifo16_t *f16, uint8_t val)
{
fifo_write_evt(val, f16);
printf("Write %02X to FIFO [F: %i, E: %i, O: %i, R: %i]\n", val,
fifo_get_full(f16), fifo_get_empty(f16),
fifo_get_overrun(f16), fifo_get_ready(f16));
#if 0
if (fifo_get_d_overrun(f16))
dev->lsr = (dev->lsr & 0xfd) | (fifo_get_overrun(f16) << 1);
#endif
if (fifo_get_d_overrun(f16)) printf(" FIFO overrun state changed: %i -> %i\n",
!fifo_get_overrun(f16), fifo_get_overrun(f16));
#if 0
if (fifo_get_d_empty(f16)) {
dev->lsr = (dev->lsr & 0xfe) | !fifo_get_empty(f16);
timer_on_auto(&dev->timeout_timer, 4.0 * dev->bits * dev->transmit_period);
}
#endif
if (fifo_get_d_empty(f16))
printf(" FIFO empty state changed: %i -> %i\n",
!fifo_get_empty(f16), fifo_get_empty(f16));
#if 0
if (fifo_get_d_ready(f16)) {
dev->int_status = (dev->int_status & ~SERIAL_INT_RECEIVE) |
(fifo_get_ready(f16) ? SERIAL_INT_RECEIVE : 0);
serial_update_ints();
}
#endif
if (fifo_get_d_ready(f16)) printf(" FIFO ready state changed: %i -> %i\n",
!fifo_get_ready(f16), fifo_get_ready(f16));
}
static uint8_t
serial_read(fifo16_t *f16)
{
uint8_t ret;
ret = fifo_read_evt(f16);
printf("Read %02X from FIFO [F: %i, E: %i, O: %i, R: %i]\n", ret,
fifo_get_full(f16), fifo_get_empty(f16),
fifo_get_overrun(f16), fifo_get_ready(f16));
#if 0
if (fifo_get_d_ready(f16)) {
dev->int_status = (dev->int_status & ~SERIAL_INT_RECEIVE) |
(fifo_get_ready(f16) ? SERIAL_INT_RECEIVE : 0);
serial_update_ints();
}
#endif
if (fifo_get_d_ready(f16))
printf(" FIFO ready state changed: %i -> %i\n",
!fifo_get_ready(f16), fifo_get_ready(f16));
#if 0
if (fifo_get_d_empty(f16)) {
dev->lsr = (dev->lsr & 0xfe) | !fifo_get_empty(f16);
timer_on_auto(&dev->timeout_timer, 4.0 * dev->bits * dev->transmit_period);
}
#endif
if (fifo_get_d_empty(f16))
printf(" FIFO empty state changed: %i -> %i\n",
!fifo_get_empty(f16), fifo_get_empty(f16));
return ret;
}
static void
serial_xmit_d_empty_evt(void *priv)
{
serial_t *dev = (serial_t *) priv;
dev->lsr = (dev->lsr & 0x9f) | (fifo_get_empty(dev->xmit_fifo) << 5) |
((dev->tsr_empty && fifo_get_empty(dev->xmit_fifo)) << 6);
dev->int_status = (dev->int_status & ~SERIAL_INT_TRANSMIT) |
(fifo_get_empty(dev->xmit_fifo) ? SERIAL_INT_TRANSMIT : 0);
// serial_update_ints();
printf("NS16550: serial_xmit_d_empty_evt(%08X): dev->lsr = %02X\n", priv, dev->lsr);
printf("NS16550: serial_xmit_d_empty_evt(%08X): dev->int_status = %02X\n", priv, dev->int_status);
}
static void
serial_rcvr_d_empty_evt(void *priv)
{
serial_t *dev = (serial_t *) priv;
dev->lsr = (dev->lsr & 0xfe) | !fifo_get_empty(dev->rcvr_fifo);
// timer_on_auto(&dev->timeout_timer, 4.0 * dev->bits * dev->transmit_period);
printf("NS16550: serial_rcvr_d_empty_evt(%08X): dev->lsr = %02X\n", priv, dev->lsr);
}
static void
serial_rcvr_d_overrun_evt(void *priv)
{
serial_t *dev = (serial_t *) priv;
dev->lsr = (dev->lsr & 0xfd) | (fifo_get_overrun(dev->rcvr_fifo) << 1);
printf("NS16550: serial_rcvr_d_overrun_evt(%08X): dev->lsr = %02X\n", priv, dev->lsr);
}
static void
serial_rcvr_d_ready_evt(void *priv)
{
serial_t *dev = (serial_t *) priv;
dev->int_status = (dev->int_status & ~SERIAL_INT_RECEIVE) |
(fifo_get_ready(dev->rcvr_fifo) ? SERIAL_INT_RECEIVE : 0);
// serial_update_ints();
printf("NS16550: serial_rcvr_d_ready_evt(%08X): dev->int_status = %02X\n", priv, dev->int_status);
}
int
main(int argc, char *argv[])
{
uint8_t val;
uint8_t ret;
printf("Initializing serial...\n");
serial_t *dev = (serial_t *) calloc(1, sizeof(serial_t));
dev->tsr_empty = 1;
printf("Initializing dev->xmit_fifo...\n");
dev->xmit_fifo = fifo16_init();
fifo_set_trigger_len(dev->xmit_fifo, 255);
fifo_set_priv(dev->xmit_fifo, dev);
fifo_set_d_empty_evt(dev->xmit_fifo, serial_xmit_d_empty_evt);
printf("\nResetting dev->xmit_fifo...\n");
fifo_reset_evt(dev->xmit_fifo);
printf("\nInitializing dev->rcvr_fifo...\n");
dev->rcvr_fifo = fifo16_init();
fifo_set_trigger_len(dev->rcvr_fifo, 4);
fifo_set_priv(dev->rcvr_fifo, dev);
fifo_set_d_empty_evt(dev->rcvr_fifo, serial_rcvr_d_empty_evt);
fifo_set_d_overrun_evt(dev->rcvr_fifo, serial_rcvr_d_overrun_evt);
fifo_set_d_ready_evt(dev->rcvr_fifo, serial_rcvr_d_ready_evt);
printf("\nResetting dev->rcvr_fifo...\n");
fifo_reset_evt(dev->rcvr_fifo);
printf("\nSending/receiving data...\n");
serial_receive_timer(dev->rcvr_fifo, '8');
serial_receive_timer(dev->rcvr_fifo, '6');
ret = serial_read(dev->rcvr_fifo);
serial_receive_timer(dev->rcvr_fifo, 'B');
ret = serial_read(dev->rcvr_fifo);
serial_receive_timer(dev->rcvr_fifo, 'o');
ret = serial_read(dev->rcvr_fifo);
serial_receive_timer(dev->rcvr_fifo, 'x');
ret = serial_read(dev->rcvr_fifo);
ret = serial_read(dev->rcvr_fifo);
fifo_close(dev->rcvr_fifo);
fifo_close(dev->xmit_fifo);
free(dev);
return 0;
}
#endif
``` | /content/code_sandbox/src/fifo.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 4,136 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Configuration file handler.
*
*
*
* Authors: Sarah Walker, <path_to_url
* Miran Grca, <mgrca8@gmail.com>
* Fred N. van Kempen, <decwiz@yahoo.com>
* Overdoze,
* David Hrdlika, <hrdlickadavid@outlook.com>
*
*
* NOTE: Forcing config files to be in Unicode encoding breaks
* it on Windows XP, and possibly also Vista. Use the
* -DANSI_CFG for use on these systems.
*/
#include <inttypes.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/ini.h>
#include <86box/plat.h>
typedef struct _list_ {
struct _list_ *next;
} list_t;
typedef struct section_t {
list_t list;
char name[128];
list_t entry_head;
} section_t;
typedef struct entry_t {
list_t list;
char name[128];
char data[512];
wchar_t wdata[512];
} entry_t;
#define list_add(new, head) \
{ \
list_t *next = head; \
\
while (next->next != NULL) \
next = next->next; \
\
(next)->next = new; \
(new)->next = NULL; \
}
#define list_delete(old, head) \
{ \
list_t *next = head; \
\
while ((next)->next != old) { \
next = (next)->next; \
} \
\
(next)->next = (old)->next; \
if ((next) == (head)) \
(head)->next = (old)->next; \
}
#ifdef ENABLE_INI_LOG
int ini_do_log = ENABLE_INI_LOG;
static void
ini_log(const char *fmt, ...)
{
va_list ap;
if (ini_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define ini_log(fmt, ...)
#endif
static section_t *
find_section(list_t *head, const char *name)
{
section_t *sec = (section_t *) head->next;
const char blank[] = "";
if (name == NULL)
name = blank;
while (sec != NULL) {
if (!strncmp(sec->name, name, sizeof(sec->name)))
return sec;
sec = (section_t *) sec->list.next;
}
return NULL;
}
ini_section_t
ini_find_section(ini_t ini, const char *name)
{
if (ini == NULL)
return NULL;
return (ini_section_t) find_section((list_t *) ini, name);
}
void
ini_rename_section(ini_section_t section, const char *name)
{
section_t *sec = (section_t *) section;
if (sec == NULL)
return;
memset(sec->name, 0x00, sizeof(sec->name));
memcpy(sec->name, name, MIN(128, strlen(name) + 1));
}
static entry_t *
find_entry(section_t *section, const char *name)
{
entry_t *ent;
ent = (entry_t *) section->entry_head.next;
while (ent != NULL) {
if (!strncmp(ent->name, name, sizeof(ent->name)))
return ent;
ent = (entry_t *) ent->list.next;
}
return (NULL);
}
static int
entries_num(section_t *section)
{
entry_t *ent;
int i = 0;
ent = (entry_t *) section->entry_head.next;
while (ent != NULL) {
if (strlen(ent->name) > 0)
i++;
ent = (entry_t *) ent->list.next;
}
return i;
}
static void
delete_section_if_empty(list_t *head, section_t *section)
{
if (section == NULL)
return;
if (entries_num(section) == 0) {
list_delete(§ion->list, head);
free(section);
}
}
void
ini_delete_section_if_empty(ini_t ini, ini_section_t section)
{
if (ini == NULL || section == NULL)
return;
delete_section_if_empty((list_t *) ini, (section_t *) section);
}
static section_t *
create_section(list_t *head, const char *name)
{
section_t *ns = malloc(sizeof(section_t));
memset(ns, 0x00, sizeof(section_t));
memcpy(ns->name, name, strlen(name) + 1);
list_add(&ns->list, head);
return ns;
}
ini_section_t
ini_find_or_create_section(ini_t ini, const char *name)
{
if (ini == NULL)
return NULL;
section_t *section = find_section((list_t *) ini, name);
if (section == NULL)
section = create_section((list_t *) ini, name);
return (ini_section_t) section;
}
static entry_t *
create_entry(section_t *section, const char *name)
{
entry_t *ne = malloc(sizeof(entry_t));
memset(ne, 0x00, sizeof(entry_t));
memcpy(ne->name, name, strlen(name) + 1);
list_add(&ne->list, §ion->entry_head);
return ne;
}
void
ini_close(ini_t ini)
{
section_t *sec;
section_t *ns;
entry_t *ent;
list_t *list = (list_t *) ini;
if (list == NULL)
return;
sec = (section_t *) list->next;
while (sec != NULL) {
ns = (section_t *) sec->list.next;
ent = (entry_t *) sec->entry_head.next;
while (ent != NULL) {
entry_t *nent = (entry_t *) ent->list.next;
free(ent);
ent = nent;
}
free(sec);
sec = ns;
}
free(list);
}
static int
ini_detect_bom(const char *fn)
{
FILE *fp;
unsigned char bom[4] = { 0, 0, 0, 0 };
#if defined(ANSI_CFG) || !defined(_WIN32)
fp = plat_fopen(fn, "rt");
#else
fp = plat_fopen(fn, "rt, ccs=UTF-8");
#endif
if (fp == NULL)
return 0;
(void) !fread(bom, 1, 3, fp);
if (bom[0] == 0xEF && bom[1] == 0xBB && bom[2] == 0xBF) {
fclose(fp);
return 1;
}
fclose(fp);
return 0;
}
#ifdef __HAIKU__
/* Local version of fgetws to avoid a crash */
static wchar_t *
ini_fgetws(wchar_t *str, int count, FILE *stream)
{
int i = 0;
if (feof(stream))
return NULL;
for (i = 0; i < count; i++) {
wint_t curChar = fgetwc(stream);
if (curChar == WEOF) {
if (i + 1 < count)
str[i + 1] = 0;
return feof(stream) ? str : NULL;
}
str[i] = curChar;
if (curChar == '\n')
break;
}
if (i + 1 < count)
str[i + 1] = 0;
return str;
}
#endif
/* Read and parse the configuration file into memory. */
ini_t
ini_read(const char *fn)
{
char sname[128];
char ename[128];
wchar_t buff[1024];
section_t *sec;
section_t *ns;
entry_t *ne;
int c;
int d;
int bom;
FILE *fp;
list_t *head;
bom = ini_detect_bom(fn);
#if defined(ANSI_CFG) || !defined(_WIN32)
fp = plat_fopen(fn, "rt");
#else
fp = plat_fopen(fn, "rt, ccs=UTF-8");
#endif
if (fp == NULL)
return NULL;
head = malloc(sizeof(list_t));
memset(head, 0x00, sizeof(list_t));
sec = malloc(sizeof(section_t));
memset(sec, 0x00, sizeof(section_t));
list_add(&sec->list, head);
if (bom)
fseek(fp, 3, SEEK_SET);
while (1) {
memset(buff, 0x00, sizeof(buff));
#ifdef __HAIKU__
ini_fgetws(buff, sizeof_w(buff), fp);
#else
(void) !fgetws(buff, sizeof_w(buff), fp);
#endif
if (feof(fp))
break;
/* Make sure there are no stray newlines or hard-returns in there. */
if (wcslen(buff) > 0)
if (buff[wcslen(buff) - 1] == L'\n')
buff[wcslen(buff) - 1] = L'\0';
if (wcslen(buff) > 0)
if (buff[wcslen(buff) - 1] == L'\r')
buff[wcslen(buff) - 1] = L'\0';
/* Skip any leading whitespace. */
c = 0;
while ((buff[c] == L' ') || (buff[c] == L'\t'))
c++;
/* Skip empty lines. */
if (buff[c] == L'\0')
continue;
/* Skip lines that (only) have a comment. */
if ((buff[c] == L'#') || (buff[c] == L';'))
continue;
if (buff[c] == L'[') { /*Section*/
c++;
d = 0;
while (buff[c] != L']' && buff[c])
(void) !wctomb(&(sname[d++]), buff[c++]);
sname[d] = L'\0';
/* Is the section name properly terminated? */
if (buff[c] != L']')
continue;
/* Create a new section and insert it. */
ns = malloc(sizeof(section_t));
memset(ns, 0x00, sizeof(section_t));
memcpy(ns->name, sname, 128);
list_add(&ns->list, head);
/* New section is now the current one. */
sec = ns;
continue;
}
/* Get the variable name. */
d = 0;
while ((buff[c] != L'=') && (buff[c] != L' ') && buff[c])
(void) !wctomb(&(ename[d++]), buff[c++]);
ename[d] = L'\0';
/* Skip incomplete lines. */
if (buff[c] == L'\0')
continue;
/* Look for =, skip whitespace. */
while ((buff[c] == L'=' || buff[c] == L' ') && buff[c])
c++;
/* Skip incomplete lines. */
if (buff[c] == L'\0')
continue;
/* This is where the value part starts. */
d = c;
/* Allocate a new variable entry.. */
ne = malloc(sizeof(entry_t));
memset(ne, 0x00, sizeof(entry_t));
memcpy(ne->name, ename, 128);
wcsncpy(ne->wdata, &buff[d], sizeof_w(ne->wdata) - 1);
ne->wdata[sizeof_w(ne->wdata) - 1] = L'\0';
#ifdef _WIN32 /* Make sure the string is converted to UTF-8 rather than a legacy codepage */
c16stombs(ne->data, ne->wdata, sizeof(ne->data));
#else
wcstombs(ne->data, ne->wdata, sizeof(ne->data));
#endif
ne->data[sizeof(ne->data) - 1] = '\0';
/* .. and insert it. */
list_add(&ne->list, &sec->entry_head);
}
(void) fclose(fp);
return (ini_t) head;
}
/* Write the in-memory configuration to disk. */
void
ini_write(ini_t ini, const char *fn)
{
wchar_t wtemp[512];
list_t *list = (list_t *) ini;
section_t *sec;
FILE *fp;
int fl = 0;
if (list == NULL)
return;
sec = (section_t *) list->next;
#if defined(ANSI_CFG) || !defined(_WIN32)
fp = plat_fopen(fn, "wt");
#else
fp = plat_fopen(fn, "wt, ccs=UTF-8");
#endif
if (fp == NULL)
return;
while (sec != NULL) {
entry_t *ent;
if (sec->name[0]) {
mbstowcs(wtemp, sec->name, strlen(sec->name) + 1);
if (fl)
fwprintf(fp, L"\n[%ls]\n", wtemp);
else
fwprintf(fp, L"[%ls]\n", wtemp);
fl++;
}
ent = (entry_t *) sec->entry_head.next;
while (ent != NULL) {
if (ent->name[0] != '\0') {
mbstowcs(wtemp, ent->name, 128);
if (ent->wdata[0] == L'\0')
fwprintf(fp, L"%ls = \n", wtemp);
else
fwprintf(fp, L"%ls = %ls\n", wtemp, ent->wdata);
fl++;
}
ent = (entry_t *) ent->list.next;
}
sec = (section_t *) sec->list.next;
}
(void) fclose(fp);
}
ini_t
ini_new(void)
{
ini_t ini = malloc(sizeof(list_t));
memset(ini, 0, sizeof(list_t));
return ini;
}
void
ini_dump(ini_t ini)
{
section_t *sec = (section_t *) ini;
while (sec != NULL) {
entry_t *ent;
if (sec->name[0])
ini_log("[%s]\n", sec->name);
ent = (entry_t *) sec->entry_head.next;
while (ent != NULL) {
ini_log("%s = %s\n", ent->name, ent->data);
ent = (entry_t *) ent->list.next;
}
sec = (section_t *) sec->list.next;
}
}
void
ini_section_delete_var(ini_section_t self, const char *name)
{
section_t *section = (section_t *) self;
entry_t *entry;
if (section == NULL)
return;
entry = find_entry(section, name);
if (entry != NULL) {
list_delete(&entry->list, §ion->entry_head);
free(entry);
}
}
int
ini_section_get_int(ini_section_t self, const char *name, int def)
{
section_t *section = (section_t *) self;
const entry_t *entry;
int value = 0;
if (section == NULL)
return def;
entry = find_entry(section, name);
if (entry == NULL)
return def;
sscanf(entry->data, "%i", &value);
return value;
}
uint32_t
ini_section_get_uint(ini_section_t self, const char *name, uint32_t def)
{
section_t *section = (section_t *) self;
const entry_t *entry;
uint32_t value = 0;
if (section == NULL)
return def;
entry = find_entry(section, name);
if (entry == NULL)
return def;
sscanf(entry->data, "%u", &value);
return value;
}
#if 0
float
ini_section_get_float(ini_section_t self, const char *name, float def)
{
section_t *section = (section_t *) self;
const entry_t *entry;
float value = 0;
if (section == NULL)
return def;
entry = find_entry(section, name);
if (entry == NULL)
return def;
sscanf(entry->data, "%g", &value);
return value;
}
#endif
double
ini_section_get_double(ini_section_t self, const char *name, double def)
{
section_t *section = (section_t *) self;
const entry_t *entry;
double value = 0;
if (section == NULL)
return def;
entry = find_entry(section, name);
if (entry == NULL)
return def;
sscanf(entry->data, "%lg", &value);
return value;
}
int
ini_section_get_hex16(ini_section_t self, const char *name, int def)
{
section_t *section = (section_t *) self;
const entry_t *entry;
unsigned int value = 0;
if (section == NULL)
return def;
entry = find_entry(section, name);
if (entry == NULL)
return def;
sscanf(entry->data, "%04X", &value);
return value;
}
int
ini_section_get_hex20(ini_section_t self, const char *name, int def)
{
section_t *section = (section_t *) self;
const entry_t *entry;
unsigned int value = 0;
if (section == NULL)
return def;
entry = find_entry(section, name);
if (entry == NULL)
return def;
sscanf(entry->data, "%05X", &value);
return value;
}
int
ini_section_get_mac(ini_section_t self, const char *name, int def)
{
section_t *section = (section_t *) self;
const entry_t *entry;
unsigned int val0 = 0;
unsigned int val1 = 0;
unsigned int val2 = 0;
if (section == NULL)
return def;
entry = find_entry(section, name);
if (entry == NULL)
return def;
sscanf(entry->data, "%02x:%02x:%02x", &val0, &val1, &val2);
return ((val0 << 16) + (val1 << 8) + val2);
}
char *
ini_section_get_string(ini_section_t self, const char *name, char *def)
{
section_t *section = (section_t *) self;
entry_t *entry;
if (section == NULL)
return def;
entry = find_entry(section, name);
if (entry == NULL)
return def;
return (entry->data);
}
wchar_t *
ini_section_get_wstring(ini_section_t self, const char *name, wchar_t *def)
{
section_t *section = (section_t *) self;
entry_t *entry;
if (section == NULL)
return def;
entry = find_entry(section, name);
if (entry == NULL)
return def;
return (entry->wdata);
}
void
ini_section_set_int(ini_section_t self, const char *name, int val)
{
section_t *section = (section_t *) self;
entry_t *ent;
if (section == NULL)
return;
ent = find_entry(section, name);
if (ent == NULL)
ent = create_entry(section, name);
sprintf(ent->data, "%i", val);
mbstowcs(ent->wdata, ent->data, 512);
}
void
ini_section_set_uint(ini_section_t self, const char *name, uint32_t val)
{
section_t *section = (section_t *) self;
entry_t *ent;
if (section == NULL)
return;
ent = find_entry(section, name);
if (ent == NULL)
ent = create_entry(section, name);
sprintf(ent->data, "%i", val);
mbstowcs(ent->wdata, ent->data, 512);
}
#if 0
void
ini_section_set_float(ini_section_t self, const char *name, float val)
{
section_t *section = (section_t *) self;
entry_t *ent;
if (section == NULL)
return;
ent = find_entry(section, name);
if (ent == NULL)
ent = create_entry(section, name);
sprintf(ent->data, "%g", val);
mbstowcs(ent->wdata, ent->data, 512);
}
#endif
void
ini_section_set_double(ini_section_t self, const char *name, double val)
{
section_t *section = (section_t *) self;
entry_t *ent;
if (section == NULL)
return;
ent = find_entry(section, name);
if (ent == NULL)
ent = create_entry(section, name);
sprintf(ent->data, "%lg", val);
mbstowcs(ent->wdata, ent->data, 512);
}
void
ini_section_set_hex16(ini_section_t self, const char *name, int val)
{
section_t *section = (section_t *) self;
entry_t *ent;
if (section == NULL)
return;
ent = find_entry(section, name);
if (ent == NULL)
ent = create_entry(section, name);
sprintf(ent->data, "%04X", val);
mbstowcs(ent->wdata, ent->data, sizeof_w(ent->wdata));
}
void
ini_section_set_hex20(ini_section_t self, const char *name, int val)
{
section_t *section = (section_t *) self;
entry_t *ent;
if (section == NULL)
return;
ent = find_entry(section, name);
if (ent == NULL)
ent = create_entry(section, name);
sprintf(ent->data, "%05X", val);
mbstowcs(ent->wdata, ent->data, sizeof_w(ent->wdata));
}
void
ini_section_set_mac(ini_section_t self, const char *name, int val)
{
section_t *section = (section_t *) self;
entry_t *ent;
if (section == NULL)
return;
ent = find_entry(section, name);
if (ent == NULL)
ent = create_entry(section, name);
sprintf(ent->data, "%02x:%02x:%02x",
(val >> 16) & 0xff, (val >> 8) & 0xff, val & 0xff);
mbstowcs(ent->wdata, ent->data, 512);
}
void
ini_section_set_string(ini_section_t self, const char *name, const char *val)
{
section_t *section = (section_t *) self;
entry_t *ent;
if (section == NULL)
return;
ent = find_entry(section, name);
if (ent == NULL)
ent = create_entry(section, name);
if ((strlen(val) + 1) <= sizeof(ent->data))
memcpy(ent->data, val, strlen(val) + 1);
else
memcpy(ent->data, val, sizeof(ent->data));
#ifdef _WIN32 /* Make sure the string is converted from UTF-8 rather than a legacy codepage */
mbstoc16s(ent->wdata, ent->data, sizeof_w(ent->wdata));
#else
mbstowcs(ent->wdata, ent->data, sizeof_w(ent->wdata));
#endif
}
void
ini_section_set_wstring(ini_section_t self, const char *name, wchar_t *val)
{
section_t *section = (section_t *) self;
entry_t *ent;
if (section == NULL)
return;
ent = find_entry(section, name);
if (ent == NULL)
ent = create_entry(section, name);
memcpy(ent->wdata, val, sizeof_w(ent->wdata));
#ifdef _WIN32 /* Make sure the string is converted to UTF-8 rather than a legacy codepage */
c16stombs(ent->data, ent->wdata, sizeof(ent->data));
#else
wcstombs(ent->data, ent->wdata, sizeof(ent->data));
#endif
}
``` | /content/code_sandbox/src/ini.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 5,480 |
```c
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <wchar.h>
#include <86box/86box.h>
#include <86box/timer.h>
uint64_t TIMER_USEC;
uint32_t timer_target;
/*Enabled timers are stored in a linked list, with the first timer to expire at
the head.*/
pc_timer_t *timer_head = NULL;
/* Are we initialized? */
int timer_inited = 0;
static void timer_advance_ex(pc_timer_t *timer, int start);
void
timer_enable(pc_timer_t *timer)
{
pc_timer_t *timer_node = timer_head;
int ret = 0;
if (!timer_inited || (timer == NULL))
return;
if (timer->flags & TIMER_ENABLED)
timer_disable(timer);
if (timer->next || timer->prev)
fatal("timer_enable - timer->next\n");
/*List currently empty - add to head*/
if (!timer_head) {
timer_head = timer;
timer->next = timer->prev = NULL;
timer_target = timer_head->ts.ts32.integer;
ret = 1;
} else if (TIMER_LESS_THAN(timer, timer_head)) {
timer->next = timer_head;
timer->prev = NULL;
timer_head->prev = timer;
timer_head = timer;
timer_target = timer_head->ts.ts32.integer;
ret = 1;
} else if (!timer_head->next) {
timer_head->next = timer;
timer->prev = timer_head;
ret = 1;
}
if (ret == 0) {
pc_timer_t *prev = timer_head;
timer_node = timer_head->next;
while (1) {
/*Timer expires before timer_node. Add to list in front of timer_node*/
if (TIMER_LESS_THAN(timer, timer_node)) {
timer->next = timer_node;
timer->prev = prev;
timer_node->prev = timer;
prev->next = timer;
ret = 1;
break;
}
/*timer_node is last in the list. Add timer to end of list*/
if (!timer_node->next) {
timer_node->next = timer;
timer->prev = timer_node;
ret = 1;
break;
}
prev = timer_node;
timer_node = timer_node->next;
}
}
/* Do not mark it as enabled if it has failed every single condition. */
if (ret == 1)
timer->flags |= TIMER_ENABLED;
}
void
timer_disable(pc_timer_t *timer)
{
if (!timer_inited || (timer == NULL) || !(timer->flags & TIMER_ENABLED))
return;
if (!timer->next && !timer->prev && timer != timer_head)
fatal("timer_disable - !timer->next\n");
timer->flags &= ~TIMER_ENABLED;
timer->in_callback = 0;
if (timer->prev)
timer->prev->next = timer->next;
else
timer_head = timer->next;
if (timer->next)
timer->next->prev = timer->prev;
timer->prev = timer->next = NULL;
}
void
timer_process(void)
{
pc_timer_t *timer;
if (!timer_head)
return;
while (1) {
timer = timer_head;
if (!TIMER_LESS_THAN_VAL(timer, (uint32_t) tsc))
break;
timer_head = timer->next;
if (timer_head)
timer_head->prev = NULL;
timer->next = timer->prev = NULL;
timer->flags &= ~TIMER_ENABLED;
if (timer->flags & TIMER_SPLIT)
timer_advance_ex(timer, 0); /* We're splitting a > 1 s period into
multiple <= 1 s periods. */
else if (timer->callback != NULL) {
/* Make sure it's not NULL, so that we can
have a NULL callback when no operation
is needed. */
timer->in_callback = 1;
timer->callback(timer->priv);
timer->in_callback = 0;
}
}
timer_target = timer_head->ts.ts32.integer;
}
void
timer_close(void)
{
pc_timer_t *t = timer_head;
pc_timer_t *r;
/* Set all timers' prev and next to NULL so it is assured that
timers that are not in malloc'd structs don't keep pointing
to timers that may be in malloc'd structs. */
while (t != NULL) {
r = t;
r->prev = r->next = NULL;
t = r->next;
}
timer_head = NULL;
timer_inited = 0;
}
void
timer_init(void)
{
timer_target = 0ULL;
tsc = 0;
timer_inited = 1;
}
void
timer_add(pc_timer_t *timer, void (*callback)(void *priv), void *priv, int start_timer)
{
memset(timer, 0, sizeof(pc_timer_t));
timer->callback = callback;
timer->in_callback = 0;
timer->priv = priv;
timer->flags = 0;
timer->prev = timer->next = NULL;
if (start_timer)
timer_set_delay_u64(timer, 0);
}
/* The API for big timer periods starts here. */
void
timer_stop(pc_timer_t *timer)
{
if (!timer_inited || (timer == NULL))
return;
timer->period = 0.0;
timer_disable(timer);
timer->flags &= ~TIMER_SPLIT;
timer->in_callback = 0;
}
static void
timer_do_period(pc_timer_t *timer, uint64_t period, int start)
{
if (!timer_inited || (timer == NULL))
return;
if (start)
timer_set_delay_u64(timer, period);
else
timer_advance_u64(timer, period);
}
static void
timer_advance_ex(pc_timer_t *timer, int start)
{
if (!timer_inited || (timer == NULL))
return;
if (timer->period > MAX_USEC) {
timer_do_period(timer, MAX_USEC64 * TIMER_USEC, start);
timer->period -= MAX_USEC;
timer->flags |= TIMER_SPLIT;
} else {
if (timer->period > 0.0)
timer_do_period(timer, (uint64_t) (timer->period * ((double) TIMER_USEC)), start);
else
timer_disable(timer);
timer->period = 0.0;
timer->flags &= ~TIMER_SPLIT;
}
}
static void
timer_on(pc_timer_t *timer, double period, int start)
{
if (!timer_inited || (timer == NULL))
return;
timer->period = period;
timer_advance_ex(timer, start);
}
void
timer_on_auto(pc_timer_t *timer, double period)
{
if (!timer_inited || (timer == NULL))
return;
if (period > 0.0)
/* If the timer is in the callback, signal that, so that timer_advance_u64()
is used instead of timer_set_delay_u64(). */
timer_on(timer, period, (timer->period <= 0.0) && !timer->in_callback);
else
timer_stop(timer);
}
void
timer_set_new_tsc(uint64_t new_tsc)
{
pc_timer_t *timer = NULL;
/* Run timers already expired. */
#ifdef USE_DYNAREC
if (cpu_use_dynarec)
update_tsc();
#endif
if (!timer_head) {
tsc = new_tsc;
return;
}
timer = timer_head;
timer_target = new_tsc + (int32_t)(timer_get_ts_int(timer_head) - (uint32_t)tsc);
while (timer) {
int32_t offset_from_current_tsc = (int32_t)(timer_get_ts_int(timer) - (uint32_t)tsc);
timer->ts.ts32.integer = new_tsc + offset_from_current_tsc;
timer = timer->next;
}
tsc = new_tsc;
}
``` | /content/code_sandbox/src/timer.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,792 |
```c
/*
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
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.
*/
/* cJSON */
/* JSON parser in C. */
/* disable warnings about old C89 functions in MSVC */
#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
#define _CRT_SECURE_NO_DEPRECATE
#endif
#ifdef __GNUC__
#pragma GCC visibility push(default)
#endif
#if defined(_MSC_VER)
#pragma warning (push)
/* disable warning about single line comments in system headers */
#pragma warning (disable : 4001)
#endif
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>
#include <float.h>
#ifdef ENABLE_LOCALES
#include <locale.h>
#endif
#if defined(_MSC_VER)
#pragma warning (pop)
#endif
#ifdef __GNUC__
#pragma GCC visibility pop
#endif
#include "cJSON.h"
/* define our own boolean type */
#ifdef true
#undef true
#endif
#define true ((cJSON_bool)1)
#ifdef false
#undef false
#endif
#define false ((cJSON_bool)0)
/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */
#ifndef isinf
#define isinf(d) (isnan((d - d)) && !isnan(d))
#endif
#ifndef isnan
#define isnan(d) (d != d)
#endif
#ifndef NAN
#ifdef _WIN32
#define NAN sqrt(-1.0)
#else
#define NAN 0.0/0.0
#endif
#endif
typedef struct {
const unsigned char *json;
size_t position;
} error;
static error global_error = { NULL, 0 };
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)
{
return (const char*) (global_error.json + global_error.position);
}
CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item)
{
if (!cJSON_IsString(item))
{
return NULL;
}
return item->valuestring;
}
CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item)
{
if (!cJSON_IsNumber(item))
{
return (double) NAN;
}
return item->valuedouble;
}
/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */
#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 17)
#error cJSON.h and cJSON.c have different versions. Make sure that both have the same.
#endif
CJSON_PUBLIC(const char*) cJSON_Version(void)
{
static char version[15];
sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);
return version;
}
/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */
static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2)
{
if ((string1 == NULL) || (string2 == NULL))
{
return 1;
}
if (string1 == string2)
{
return 0;
}
for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
{
if (*string1 == '\0')
{
return 0;
}
}
return tolower(*string1) - tolower(*string2);
}
typedef struct internal_hooks
{
void *(CJSON_CDECL *allocate)(size_t size);
void (CJSON_CDECL *deallocate)(void *pointer);
void *(CJSON_CDECL *reallocate)(void *pointer, size_t size);
} internal_hooks;
#if defined(_MSC_VER)
/* work around MSVC error C2322: '...' address of dllimport '...' is not static */
static void * CJSON_CDECL internal_malloc(size_t size)
{
return malloc(size);
}
static void CJSON_CDECL internal_free(void *pointer)
{
free(pointer);
}
static void * CJSON_CDECL internal_realloc(void *pointer, size_t size)
{
return realloc(pointer, size);
}
#else
#define internal_malloc malloc
#define internal_free free
#define internal_realloc realloc
#endif
/* strlen of character literals resolved at compile time */
#define static_strlen(string_literal) (sizeof(string_literal) - sizeof(""))
static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc };
static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)
{
size_t length = 0;
unsigned char *copy = NULL;
if (string == NULL)
{
return NULL;
}
length = strlen((const char*)string) + sizeof("");
copy = (unsigned char*)hooks->allocate(length);
if (copy == NULL)
{
return NULL;
}
memcpy(copy, string, length);
return copy;
}
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
{
if (hooks == NULL)
{
/* Reset hooks */
global_hooks.allocate = malloc;
global_hooks.deallocate = free;
global_hooks.reallocate = realloc;
return;
}
global_hooks.allocate = malloc;
if (hooks->malloc_fn != NULL)
{
global_hooks.allocate = hooks->malloc_fn;
}
global_hooks.deallocate = free;
if (hooks->free_fn != NULL)
{
global_hooks.deallocate = hooks->free_fn;
}
/* use realloc only if both free and malloc are used */
global_hooks.reallocate = NULL;
if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
{
global_hooks.reallocate = realloc;
}
}
/* Internal constructor. */
static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
{
cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));
if (node)
{
memset(node, '\0', sizeof(cJSON));
}
return node;
}
/* Delete a cJSON structure. */
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
{
cJSON *next = NULL;
while (item != NULL)
{
next = item->next;
if (!(item->type & cJSON_IsReference) && (item->child != NULL))
{
cJSON_Delete(item->child);
}
if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL))
{
global_hooks.deallocate(item->valuestring);
}
if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
{
global_hooks.deallocate(item->string);
}
global_hooks.deallocate(item);
item = next;
}
}
/* get the decimal point character of the current locale */
static unsigned char get_decimal_point(void)
{
#ifdef ENABLE_LOCALES
struct lconv *lconv = localeconv();
return (unsigned char) lconv->decimal_point[0];
#else
return '.';
#endif
}
typedef struct
{
const unsigned char *content;
size_t length;
size_t offset;
size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */
internal_hooks hooks;
} parse_buffer;
/* check if the given size is left to read in a given parse buffer (starting with 1) */
#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length))
/* check if the buffer can be accessed at the given index (starting with 0) */
#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length))
#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index))
/* get a pointer to the buffer at the position */
#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset)
/* Parse the input text to generate a number, and populate the result into item. */
static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer)
{
double number = 0;
unsigned char *after_end = NULL;
unsigned char number_c_string[64];
unsigned char decimal_point = get_decimal_point();
size_t i = 0;
if ((input_buffer == NULL) || (input_buffer->content == NULL))
{
return false;
}
/* copy the number into a temporary buffer and replace '.' with the decimal point
* of the current locale (for strtod)
* This also takes care of '\0' not necessarily being available for marking the end of the input */
for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++)
{
switch (buffer_at_offset(input_buffer)[i])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '+':
case '-':
case 'e':
case 'E':
number_c_string[i] = buffer_at_offset(input_buffer)[i];
break;
case '.':
number_c_string[i] = decimal_point;
break;
default:
goto loop_end;
}
}
loop_end:
number_c_string[i] = '\0';
number = strtod((const char*)number_c_string, (char**)&after_end);
if (number_c_string == after_end)
{
return false; /* parse_error */
}
item->valuedouble = number;
/* use saturation in case of overflow */
if (number >= INT_MAX)
{
item->valueint = INT_MAX;
}
else if (number <= (double)INT_MIN)
{
item->valueint = INT_MIN;
}
else
{
item->valueint = (int)number;
}
item->type = cJSON_Number;
input_buffer->offset += (size_t)(after_end - number_c_string);
return true;
}
/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
{
if (number >= INT_MAX)
{
object->valueint = INT_MAX;
}
else if (number <= (double)INT_MIN)
{
object->valueint = INT_MIN;
}
else
{
object->valueint = (int)number;
}
return object->valuedouble = number;
}
CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring)
{
char *copy = NULL;
/* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */
if ((object == NULL) || !(object->type & cJSON_String) || (object->type & cJSON_IsReference))
{
return NULL;
}
/* return NULL if the object is corrupted */
if (object->valuestring == NULL)
{
return NULL;
}
if (strlen(valuestring) <= strlen(object->valuestring))
{
strcpy(object->valuestring, valuestring);
return object->valuestring;
}
copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks);
if (copy == NULL)
{
return NULL;
}
if (object->valuestring != NULL)
{
cJSON_free(object->valuestring);
}
object->valuestring = copy;
return copy;
}
typedef struct
{
unsigned char *buffer;
size_t length;
size_t offset;
size_t depth; /* current nesting depth (for formatted printing) */
cJSON_bool noalloc;
cJSON_bool format; /* is this print a formatted print */
internal_hooks hooks;
} printbuffer;
/* realloc printbuffer if necessary to have at least "needed" bytes more */
static unsigned char* ensure(printbuffer * const p, size_t needed)
{
unsigned char *newbuffer = NULL;
size_t newsize = 0;
if ((p == NULL) || (p->buffer == NULL))
{
return NULL;
}
if ((p->length > 0) && (p->offset >= p->length))
{
/* make sure that offset is valid */
return NULL;
}
if (needed > INT_MAX)
{
/* sizes bigger than INT_MAX are currently not supported */
return NULL;
}
needed += p->offset + 1;
if (needed <= p->length)
{
return p->buffer + p->offset;
}
if (p->noalloc) {
return NULL;
}
/* calculate new buffer size */
if (needed > (INT_MAX / 2))
{
/* overflow of int, use INT_MAX if possible */
if (needed <= INT_MAX)
{
newsize = INT_MAX;
}
else
{
return NULL;
}
}
else
{
newsize = needed * 2;
}
if (p->hooks.reallocate != NULL)
{
/* reallocate with realloc if available */
newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize);
if (newbuffer == NULL)
{
p->hooks.deallocate(p->buffer);
p->length = 0;
p->buffer = NULL;
return NULL;
}
}
else
{
/* otherwise reallocate manually */
newbuffer = (unsigned char*)p->hooks.allocate(newsize);
if (!newbuffer)
{
p->hooks.deallocate(p->buffer);
p->length = 0;
p->buffer = NULL;
return NULL;
}
memcpy(newbuffer, p->buffer, p->offset + 1);
p->hooks.deallocate(p->buffer);
}
p->length = newsize;
p->buffer = newbuffer;
return newbuffer + p->offset;
}
/* calculate the new length of the string in a printbuffer and update the offset */
static void update_offset(printbuffer * const buffer)
{
const unsigned char *buffer_pointer = NULL;
if ((buffer == NULL) || (buffer->buffer == NULL))
{
return;
}
buffer_pointer = buffer->buffer + buffer->offset;
buffer->offset += strlen((const char*)buffer_pointer);
}
/* securely comparison of floating-point variables */
static cJSON_bool compare_double(double a, double b)
{
double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b);
return (fabs(a - b) <= maxVal * DBL_EPSILON);
}
/* Render the number nicely from the given item into a string. */
static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)
{
unsigned char *output_pointer = NULL;
double d = item->valuedouble;
int length = 0;
size_t i = 0;
unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */
unsigned char decimal_point = get_decimal_point();
double test = 0.0;
if (output_buffer == NULL)
{
return false;
}
/* This checks for NaN and Infinity */
if (isnan(d) || isinf(d))
{
length = sprintf((char*)number_buffer, "null");
}
else if(d == (double)item->valueint)
{
length = sprintf((char*)number_buffer, "%d", item->valueint);
}
else
{
/* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
length = sprintf((char*)number_buffer, "%1.15g", d);
/* Check whether the original double can be recovered */
if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d))
{
/* If not, print with 17 decimal places of precision */
length = sprintf((char*)number_buffer, "%1.17g", d);
}
}
/* sprintf failed or buffer overrun occurred */
if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
{
return false;
}
/* reserve appropriate space in the output */
output_pointer = ensure(output_buffer, (size_t)length + sizeof(""));
if (output_pointer == NULL)
{
return false;
}
/* copy the printed number to the output and replace locale
* dependent decimal point with '.' */
for (i = 0; i < ((size_t)length); i++)
{
if (number_buffer[i] == decimal_point)
{
output_pointer[i] = '.';
continue;
}
output_pointer[i] = number_buffer[i];
}
output_pointer[i] = '\0';
output_buffer->offset += (size_t)length;
return true;
}
/* parse 4 digit hexadecimal number */
static unsigned parse_hex4(const unsigned char * const input)
{
unsigned int h = 0;
size_t i = 0;
for (i = 0; i < 4; i++)
{
/* parse digit */
if ((input[i] >= '0') && (input[i] <= '9'))
{
h += (unsigned int) input[i] - '0';
}
else if ((input[i] >= 'A') && (input[i] <= 'F'))
{
h += (unsigned int) 10 + input[i] - 'A';
}
else if ((input[i] >= 'a') && (input[i] <= 'f'))
{
h += (unsigned int) 10 + input[i] - 'a';
}
else /* invalid */
{
return 0;
}
if (i < 3)
{
/* shift left to make place for the next nibble */
h = h << 4;
}
}
return h;
}
/* converts a UTF-16 literal to UTF-8
* A literal can be one or two sequences of the form \uXXXX */
static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer)
{
long unsigned int codepoint = 0;
unsigned int first_code = 0;
const unsigned char *first_sequence = input_pointer;
unsigned char utf8_length = 0;
unsigned char utf8_position = 0;
unsigned char sequence_length = 0;
unsigned char first_byte_mark = 0;
if ((input_end - first_sequence) < 6)
{
/* input ends unexpectedly */
goto fail;
}
/* get the first utf16 sequence */
first_code = parse_hex4(first_sequence + 2);
/* check that the code is valid */
if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)))
{
goto fail;
}
/* UTF16 surrogate pair */
if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
{
const unsigned char *second_sequence = first_sequence + 6;
unsigned int second_code = 0;
sequence_length = 12; /* \uXXXX\uXXXX */
if ((input_end - second_sequence) < 6)
{
/* input ends unexpectedly */
goto fail;
}
if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u'))
{
/* missing second half of the surrogate pair */
goto fail;
}
/* get the second utf16 sequence */
second_code = parse_hex4(second_sequence + 2);
/* check that the code is valid */
if ((second_code < 0xDC00) || (second_code > 0xDFFF))
{
/* invalid second half of the surrogate pair */
goto fail;
}
/* calculate the unicode codepoint from the surrogate pair */
codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF));
}
else
{
sequence_length = 6; /* \uXXXX */
codepoint = first_code;
}
/* encode as UTF-8
* takes at maximum 4 bytes to encode:
* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
if (codepoint < 0x80)
{
/* normal ascii, encoding 0xxxxxxx */
utf8_length = 1;
}
else if (codepoint < 0x800)
{
/* two bytes, encoding 110xxxxx 10xxxxxx */
utf8_length = 2;
first_byte_mark = 0xC0; /* 11000000 */
}
else if (codepoint < 0x10000)
{
/* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
utf8_length = 3;
first_byte_mark = 0xE0; /* 11100000 */
}
else if (codepoint <= 0x10FFFF)
{
/* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
utf8_length = 4;
first_byte_mark = 0xF0; /* 11110000 */
}
else
{
/* invalid unicode codepoint */
goto fail;
}
/* encode as utf8 */
for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--)
{
/* 10xxxxxx */
(*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF);
codepoint >>= 6;
}
/* encode first byte */
if (utf8_length > 1)
{
(*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF);
}
else
{
(*output_pointer)[0] = (unsigned char)(codepoint & 0x7F);
}
*output_pointer += utf8_length;
return sequence_length;
fail:
return 0;
}
/* Parse the input text into an unescaped cinput, and populate item. */
static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer)
{
const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1;
const unsigned char *input_end = buffer_at_offset(input_buffer) + 1;
unsigned char *output_pointer = NULL;
unsigned char *output = NULL;
/* not a string */
if (buffer_at_offset(input_buffer)[0] != '\"')
{
goto fail;
}
{
/* calculate approximate size of the output (overestimate) */
size_t allocation_length = 0;
size_t skipped_bytes = 0;
while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"'))
{
/* is escape sequence */
if (input_end[0] == '\\')
{
if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length)
{
/* prevent buffer overflow when last input character is a backslash */
goto fail;
}
skipped_bytes++;
input_end++;
}
input_end++;
}
if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"'))
{
goto fail; /* string ended unexpectedly */
}
/* This is at most how much we need for the output */
allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes;
output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof(""));
if (output == NULL)
{
goto fail; /* allocation failure */
}
}
output_pointer = output;
/* loop through the string literal */
while (input_pointer < input_end)
{
if (*input_pointer != '\\')
{
*output_pointer++ = *input_pointer++;
}
/* escape sequence */
else
{
unsigned char sequence_length = 2;
if ((input_end - input_pointer) < 1)
{
goto fail;
}
switch (input_pointer[1])
{
case 'b':
*output_pointer++ = '\b';
break;
case 'f':
*output_pointer++ = '\f';
break;
case 'n':
*output_pointer++ = '\n';
break;
case 'r':
*output_pointer++ = '\r';
break;
case 't':
*output_pointer++ = '\t';
break;
case '\"':
case '\\':
case '/':
*output_pointer++ = input_pointer[1];
break;
/* UTF-16 literal */
case 'u':
sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer);
if (sequence_length == 0)
{
/* failed to convert UTF16-literal to UTF-8 */
goto fail;
}
break;
default:
goto fail;
}
input_pointer += sequence_length;
}
}
/* zero terminate the output */
*output_pointer = '\0';
item->type = cJSON_String;
item->valuestring = (char*)output;
input_buffer->offset = (size_t) (input_end - input_buffer->content);
input_buffer->offset++;
return true;
fail:
if (output != NULL)
{
input_buffer->hooks.deallocate(output);
}
if (input_pointer != NULL)
{
input_buffer->offset = (size_t)(input_pointer - input_buffer->content);
}
return false;
}
/* Render the cstring provided to an escaped version that can be printed. */
static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer)
{
const unsigned char *input_pointer = NULL;
unsigned char *output = NULL;
unsigned char *output_pointer = NULL;
size_t output_length = 0;
/* numbers of additional characters needed for escaping */
size_t escape_characters = 0;
if (output_buffer == NULL)
{
return false;
}
/* empty string */
if (input == NULL)
{
output = ensure(output_buffer, sizeof("\"\""));
if (output == NULL)
{
return false;
}
strcpy((char*)output, "\"\"");
return true;
}
/* set "flag" to 1 if something needs to be escaped */
for (input_pointer = input; *input_pointer; input_pointer++)
{
switch (*input_pointer)
{
case '\"':
case '\\':
case '\b':
case '\f':
case '\n':
case '\r':
case '\t':
/* one character escape sequence */
escape_characters++;
break;
default:
if (*input_pointer < 32)
{
/* UTF-16 escape sequence uXXXX */
escape_characters += 5;
}
break;
}
}
output_length = (size_t)(input_pointer - input) + escape_characters;
output = ensure(output_buffer, output_length + sizeof("\"\""));
if (output == NULL)
{
return false;
}
/* no characters have to be escaped */
if (escape_characters == 0)
{
output[0] = '\"';
memcpy(output + 1, input, output_length);
output[output_length + 1] = '\"';
output[output_length + 2] = '\0';
return true;
}
output[0] = '\"';
output_pointer = output + 1;
/* copy the string */
for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
{
if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
{
/* normal character, copy */
*output_pointer = *input_pointer;
}
else
{
/* character needs to be escaped */
*output_pointer++ = '\\';
switch (*input_pointer)
{
case '\\':
*output_pointer = '\\';
break;
case '\"':
*output_pointer = '\"';
break;
case '\b':
*output_pointer = 'b';
break;
case '\f':
*output_pointer = 'f';
break;
case '\n':
*output_pointer = 'n';
break;
case '\r':
*output_pointer = 'r';
break;
case '\t':
*output_pointer = 't';
break;
default:
/* escape and print as unicode codepoint */
sprintf((char*)output_pointer, "u%04x", *input_pointer);
output_pointer += 4;
break;
}
}
}
output[output_length + 1] = '\"';
output[output_length + 2] = '\0';
return true;
}
/* Invoke print_string_ptr (which is useful) on an item. */
static cJSON_bool print_string(const cJSON * const item, printbuffer * const p)
{
return print_string_ptr((unsigned char*)item->valuestring, p);
}
/* Predeclare these prototypes. */
static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer);
static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer);
static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer);
static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer);
static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer);
static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer);
/* Utility to jump whitespace and cr/lf */
static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)
{
if ((buffer == NULL) || (buffer->content == NULL))
{
return NULL;
}
if (cannot_access_at_index(buffer, 0))
{
return buffer;
}
while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32))
{
buffer->offset++;
}
if (buffer->offset == buffer->length)
{
buffer->offset--;
}
return buffer;
}
/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */
static parse_buffer *skip_utf8_bom(parse_buffer * const buffer)
{
if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0))
{
return NULL;
}
if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0))
{
buffer->offset += 3;
}
return buffer;
}
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
{
size_t buffer_length;
if (NULL == value)
{
return NULL;
}
/* Adding null character size due to require_null_terminated. */
buffer_length = strlen(value) + sizeof("");
return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated);
}
/* Parse an object - create a new root, and populate. */
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated)
{
parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };
cJSON *item = NULL;
/* reset error position */
global_error.json = NULL;
global_error.position = 0;
if (value == NULL || 0 == buffer_length)
{
goto fail;
}
buffer.content = (const unsigned char*)value;
buffer.length = buffer_length;
buffer.offset = 0;
buffer.hooks = global_hooks;
item = cJSON_New_Item(&global_hooks);
if (item == NULL) /* memory fail */
{
goto fail;
}
if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer))))
{
/* parse failure. ep is set. */
goto fail;
}
/* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
if (require_null_terminated)
{
buffer_skip_whitespace(&buffer);
if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0')
{
goto fail;
}
}
if (return_parse_end)
{
*return_parse_end = (const char*)buffer_at_offset(&buffer);
}
return item;
fail:
if (item != NULL)
{
cJSON_Delete(item);
}
if (value != NULL)
{
error local_error;
local_error.json = (const unsigned char*)value;
local_error.position = 0;
if (buffer.offset < buffer.length)
{
local_error.position = buffer.offset;
}
else if (buffer.length > 0)
{
local_error.position = buffer.length - 1;
}
if (return_parse_end != NULL)
{
*return_parse_end = (const char*)local_error.json + local_error.position;
}
global_error = local_error;
}
return NULL;
}
/* Default options for cJSON_Parse */
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
{
return cJSON_ParseWithOpts(value, 0, 0);
}
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length)
{
return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0);
}
#define cjson_min(a, b) (((a) < (b)) ? (a) : (b))
static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
{
static const size_t default_buffer_size = 256;
printbuffer buffer[1];
unsigned char *printed = NULL;
memset(buffer, 0, sizeof(buffer));
/* create buffer */
buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size);
buffer->length = default_buffer_size;
buffer->format = format;
buffer->hooks = *hooks;
if (buffer->buffer == NULL)
{
goto fail;
}
/* print the value */
if (!print_value(item, buffer))
{
goto fail;
}
update_offset(buffer);
/* check if reallocate is available */
if (hooks->reallocate != NULL)
{
printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1);
if (printed == NULL) {
goto fail;
}
buffer->buffer = NULL;
}
else /* otherwise copy the JSON over to a new buffer */
{
printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
if (printed == NULL)
{
goto fail;
}
memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1));
printed[buffer->offset] = '\0'; /* just to be sure */
/* free the buffer */
hooks->deallocate(buffer->buffer);
}
return printed;
fail:
if (buffer->buffer != NULL)
{
hooks->deallocate(buffer->buffer);
}
if (printed != NULL)
{
hooks->deallocate(printed);
}
return NULL;
}
/* Render a cJSON item/entity/structure to text. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
{
return (char*)print(item, true, &global_hooks);
}
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
{
return (char*)print(item, false, &global_hooks);
}
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
{
printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
if (prebuffer < 0)
{
return NULL;
}
p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
if (!p.buffer)
{
return NULL;
}
p.length = (size_t)prebuffer;
p.offset = 0;
p.noalloc = false;
p.format = fmt;
p.hooks = global_hooks;
if (!print_value(item, &p))
{
global_hooks.deallocate(p.buffer);
return NULL;
}
return (char*)p.buffer;
}
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format)
{
printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
if ((length < 0) || (buffer == NULL))
{
return false;
}
p.buffer = (unsigned char*)buffer;
p.length = (size_t)length;
p.offset = 0;
p.noalloc = true;
p.format = format;
p.hooks = global_hooks;
return print_value(item, &p);
}
/* Parser core - when encountering text, process appropriately. */
static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer)
{
if ((input_buffer == NULL) || (input_buffer->content == NULL))
{
return false; /* no input */
}
/* parse the different types of values */
/* null */
if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0))
{
item->type = cJSON_NULL;
input_buffer->offset += 4;
return true;
}
/* false */
if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0))
{
item->type = cJSON_False;
input_buffer->offset += 5;
return true;
}
/* true */
if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0))
{
item->type = cJSON_True;
item->valueint = 1;
input_buffer->offset += 4;
return true;
}
/* string */
if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"'))
{
return parse_string(item, input_buffer);
}
/* number */
if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9'))))
{
return parse_number(item, input_buffer);
}
/* array */
if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '['))
{
return parse_array(item, input_buffer);
}
/* object */
if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{'))
{
return parse_object(item, input_buffer);
}
return false;
}
/* Render a value to text. */
static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer)
{
unsigned char *output = NULL;
if ((item == NULL) || (output_buffer == NULL))
{
return false;
}
switch ((item->type) & 0xFF)
{
case cJSON_NULL:
output = ensure(output_buffer, 5);
if (output == NULL)
{
return false;
}
strcpy((char*)output, "null");
return true;
case cJSON_False:
output = ensure(output_buffer, 6);
if (output == NULL)
{
return false;
}
strcpy((char*)output, "false");
return true;
case cJSON_True:
output = ensure(output_buffer, 5);
if (output == NULL)
{
return false;
}
strcpy((char*)output, "true");
return true;
case cJSON_Number:
return print_number(item, output_buffer);
case cJSON_Raw:
{
size_t raw_length = 0;
if (item->valuestring == NULL)
{
return false;
}
raw_length = strlen(item->valuestring) + sizeof("");
output = ensure(output_buffer, raw_length);
if (output == NULL)
{
return false;
}
memcpy(output, item->valuestring, raw_length);
return true;
}
case cJSON_String:
return print_string(item, output_buffer);
case cJSON_Array:
return print_array(item, output_buffer);
case cJSON_Object:
return print_object(item, output_buffer);
default:
return false;
}
}
/* Build an array from input text. */
static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer)
{
cJSON *head = NULL; /* head of the linked list */
cJSON *current_item = NULL;
if (input_buffer->depth >= CJSON_NESTING_LIMIT)
{
return false; /* to deeply nested */
}
input_buffer->depth++;
if (buffer_at_offset(input_buffer)[0] != '[')
{
/* not an array */
goto fail;
}
input_buffer->offset++;
buffer_skip_whitespace(input_buffer);
if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']'))
{
/* empty array */
goto success;
}
/* check if we skipped to the end of the buffer */
if (cannot_access_at_index(input_buffer, 0))
{
input_buffer->offset--;
goto fail;
}
/* step back to character in front of the first element */
input_buffer->offset--;
/* loop through the comma separated array elements */
do
{
/* allocate next item */
cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
if (new_item == NULL)
{
goto fail; /* allocation failure */
}
/* attach next item to list */
if (head == NULL)
{
/* start the linked list */
current_item = head = new_item;
}
else
{
/* add to the end and advance */
current_item->next = new_item;
new_item->prev = current_item;
current_item = new_item;
}
/* parse next value */
input_buffer->offset++;
buffer_skip_whitespace(input_buffer);
if (!parse_value(current_item, input_buffer))
{
goto fail; /* failed to parse value */
}
buffer_skip_whitespace(input_buffer);
}
while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']')
{
goto fail; /* expected end of array */
}
success:
input_buffer->depth--;
if (head != NULL) {
head->prev = current_item;
}
item->type = cJSON_Array;
item->child = head;
input_buffer->offset++;
return true;
fail:
if (head != NULL)
{
cJSON_Delete(head);
}
return false;
}
/* Render an array to text */
static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer)
{
unsigned char *output_pointer = NULL;
size_t length = 0;
cJSON *current_element = item->child;
if (output_buffer == NULL)
{
return false;
}
/* Compose the output array. */
/* opening square bracket */
output_pointer = ensure(output_buffer, 1);
if (output_pointer == NULL)
{
return false;
}
*output_pointer = '[';
output_buffer->offset++;
output_buffer->depth++;
while (current_element != NULL)
{
if (!print_value(current_element, output_buffer))
{
return false;
}
update_offset(output_buffer);
if (current_element->next)
{
length = (size_t) (output_buffer->format ? 2 : 1);
output_pointer = ensure(output_buffer, length + 1);
if (output_pointer == NULL)
{
return false;
}
*output_pointer++ = ',';
if(output_buffer->format)
{
*output_pointer++ = ' ';
}
*output_pointer = '\0';
output_buffer->offset += length;
}
current_element = current_element->next;
}
output_pointer = ensure(output_buffer, 2);
if (output_pointer == NULL)
{
return false;
}
*output_pointer++ = ']';
*output_pointer = '\0';
output_buffer->depth--;
return true;
}
/* Build an object from the text. */
static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer)
{
cJSON *head = NULL; /* linked list head */
cJSON *current_item = NULL;
if (input_buffer->depth >= CJSON_NESTING_LIMIT)
{
return false; /* to deeply nested */
}
input_buffer->depth++;
if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{'))
{
goto fail; /* not an object */
}
input_buffer->offset++;
buffer_skip_whitespace(input_buffer);
if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}'))
{
goto success; /* empty object */
}
/* check if we skipped to the end of the buffer */
if (cannot_access_at_index(input_buffer, 0))
{
input_buffer->offset--;
goto fail;
}
/* step back to character in front of the first element */
input_buffer->offset--;
/* loop through the comma separated array elements */
do
{
/* allocate next item */
cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
if (new_item == NULL)
{
goto fail; /* allocation failure */
}
/* attach next item to list */
if (head == NULL)
{
/* start the linked list */
current_item = head = new_item;
}
else
{
/* add to the end and advance */
current_item->next = new_item;
new_item->prev = current_item;
current_item = new_item;
}
/* parse the name of the child */
input_buffer->offset++;
buffer_skip_whitespace(input_buffer);
if (!parse_string(current_item, input_buffer))
{
goto fail; /* failed to parse name */
}
buffer_skip_whitespace(input_buffer);
/* swap valuestring and string, because we parsed the name */
current_item->string = current_item->valuestring;
current_item->valuestring = NULL;
if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':'))
{
goto fail; /* invalid object */
}
/* parse the value */
input_buffer->offset++;
buffer_skip_whitespace(input_buffer);
if (!parse_value(current_item, input_buffer))
{
goto fail; /* failed to parse value */
}
buffer_skip_whitespace(input_buffer);
}
while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}'))
{
goto fail; /* expected end of object */
}
success:
input_buffer->depth--;
if (head != NULL) {
head->prev = current_item;
}
item->type = cJSON_Object;
item->child = head;
input_buffer->offset++;
return true;
fail:
if (head != NULL)
{
cJSON_Delete(head);
}
return false;
}
/* Render an object to text. */
static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer)
{
unsigned char *output_pointer = NULL;
size_t length = 0;
cJSON *current_item = item->child;
if (output_buffer == NULL)
{
return false;
}
/* Compose the output: */
length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */
output_pointer = ensure(output_buffer, length + 1);
if (output_pointer == NULL)
{
return false;
}
*output_pointer++ = '{';
output_buffer->depth++;
if (output_buffer->format)
{
*output_pointer++ = '\n';
}
output_buffer->offset += length;
while (current_item)
{
if (output_buffer->format)
{
size_t i;
output_pointer = ensure(output_buffer, output_buffer->depth);
if (output_pointer == NULL)
{
return false;
}
for (i = 0; i < output_buffer->depth; i++)
{
*output_pointer++ = '\t';
}
output_buffer->offset += output_buffer->depth;
}
/* print key */
if (!print_string_ptr((unsigned char*)current_item->string, output_buffer))
{
return false;
}
update_offset(output_buffer);
length = (size_t) (output_buffer->format ? 2 : 1);
output_pointer = ensure(output_buffer, length);
if (output_pointer == NULL)
{
return false;
}
*output_pointer++ = ':';
if (output_buffer->format)
{
*output_pointer++ = '\t';
}
output_buffer->offset += length;
/* print value */
if (!print_value(current_item, output_buffer))
{
return false;
}
update_offset(output_buffer);
/* print comma if not last */
length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0));
output_pointer = ensure(output_buffer, length + 1);
if (output_pointer == NULL)
{
return false;
}
if (current_item->next)
{
*output_pointer++ = ',';
}
if (output_buffer->format)
{
*output_pointer++ = '\n';
}
*output_pointer = '\0';
output_buffer->offset += length;
current_item = current_item->next;
}
output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2);
if (output_pointer == NULL)
{
return false;
}
if (output_buffer->format)
{
size_t i;
for (i = 0; i < (output_buffer->depth - 1); i++)
{
*output_pointer++ = '\t';
}
}
*output_pointer++ = '}';
*output_pointer = '\0';
output_buffer->depth--;
return true;
}
/* Get Array size/item / object item. */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
{
cJSON *child = NULL;
size_t size = 0;
if (array == NULL)
{
return 0;
}
child = array->child;
while(child != NULL)
{
size++;
child = child->next;
}
/* FIXME: Can overflow here. Cannot be fixed without breaking the API */
return (int)size;
}
static cJSON* get_array_item(const cJSON *array, size_t index)
{
cJSON *current_child = NULL;
if (array == NULL)
{
return NULL;
}
current_child = array->child;
while ((current_child != NULL) && (index > 0))
{
index--;
current_child = current_child->next;
}
return current_child;
}
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index)
{
if (index < 0)
{
return NULL;
}
return get_array_item(array, (size_t)index);
}
static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
{
cJSON *current_element = NULL;
if ((object == NULL) || (name == NULL))
{
return NULL;
}
current_element = object->child;
if (case_sensitive)
{
while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0))
{
current_element = current_element->next;
}
}
else
{
while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))
{
current_element = current_element->next;
}
}
if ((current_element == NULL) || (current_element->string == NULL)) {
return NULL;
}
return current_element;
}
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)
{
return get_object_item(object, string, false);
}
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
{
return get_object_item(object, string, true);
}
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
{
return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
/* Utility for array list handling. */
static void suffix_object(cJSON *prev, cJSON *item)
{
prev->next = item;
item->prev = prev;
}
/* Utility for handling references. */
static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
{
cJSON *reference = NULL;
if (item == NULL)
{
return NULL;
}
reference = cJSON_New_Item(hooks);
if (reference == NULL)
{
return NULL;
}
memcpy(reference, item, sizeof(cJSON));
reference->string = NULL;
reference->type |= cJSON_IsReference;
reference->next = reference->prev = NULL;
return reference;
}
static cJSON_bool add_item_to_array(cJSON *array, cJSON *item)
{
cJSON *child = NULL;
if ((item == NULL) || (array == NULL) || (array == item))
{
return false;
}
child = array->child;
/*
* To find the last item in array quickly, we use prev in array
*/
if (child == NULL)
{
/* list is empty, start new one */
array->child = item;
item->prev = item;
item->next = NULL;
}
else
{
/* append to the end */
if (child->prev)
{
suffix_object(child->prev, item);
array->child->prev = item;
}
}
return true;
}
/* Add item to array/object. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item)
{
return add_item_to_array(array, item);
}
#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
#pragma GCC diagnostic push
#endif
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wcast-qual"
#endif
/* helper function to cast away const */
static void* cast_away_const(const void* string)
{
return (void*)string;
}
#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
#pragma GCC diagnostic pop
#endif
static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key)
{
char *new_key = NULL;
int new_type = cJSON_Invalid;
if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item))
{
return false;
}
if (constant_key)
{
new_key = (char*)cast_away_const(string);
new_type = item->type | cJSON_StringIsConst;
}
else
{
new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks);
if (new_key == NULL)
{
return false;
}
new_type = item->type & ~cJSON_StringIsConst;
}
if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
{
hooks->deallocate(item->string);
}
item->string = new_key;
item->type = new_type;
return add_item_to_array(object, item);
}
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
{
return add_item_to_object(object, string, item, &global_hooks, false);
}
/* Add an item to an object with constant string as key */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
{
return add_item_to_object(object, string, item, &global_hooks, true);
}
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
{
if (array == NULL)
{
return false;
}
return add_item_to_array(array, create_reference(item, &global_hooks));
}
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
{
if ((object == NULL) || (string == NULL))
{
return false;
}
return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false);
}
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name)
{
cJSON *null = cJSON_CreateNull();
if (add_item_to_object(object, name, null, &global_hooks, false))
{
return null;
}
cJSON_Delete(null);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name)
{
cJSON *true_item = cJSON_CreateTrue();
if (add_item_to_object(object, name, true_item, &global_hooks, false))
{
return true_item;
}
cJSON_Delete(true_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name)
{
cJSON *false_item = cJSON_CreateFalse();
if (add_item_to_object(object, name, false_item, &global_hooks, false))
{
return false_item;
}
cJSON_Delete(false_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean)
{
cJSON *bool_item = cJSON_CreateBool(boolean);
if (add_item_to_object(object, name, bool_item, &global_hooks, false))
{
return bool_item;
}
cJSON_Delete(bool_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number)
{
cJSON *number_item = cJSON_CreateNumber(number);
if (add_item_to_object(object, name, number_item, &global_hooks, false))
{
return number_item;
}
cJSON_Delete(number_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string)
{
cJSON *string_item = cJSON_CreateString(string);
if (add_item_to_object(object, name, string_item, &global_hooks, false))
{
return string_item;
}
cJSON_Delete(string_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw)
{
cJSON *raw_item = cJSON_CreateRaw(raw);
if (add_item_to_object(object, name, raw_item, &global_hooks, false))
{
return raw_item;
}
cJSON_Delete(raw_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name)
{
cJSON *object_item = cJSON_CreateObject();
if (add_item_to_object(object, name, object_item, &global_hooks, false))
{
return object_item;
}
cJSON_Delete(object_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name)
{
cJSON *array = cJSON_CreateArray();
if (add_item_to_object(object, name, array, &global_hooks, false))
{
return array;
}
cJSON_Delete(array);
return NULL;
}
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item)
{
if ((parent == NULL) || (item == NULL))
{
return NULL;
}
if (item != parent->child)
{
/* not the first element */
item->prev->next = item->next;
}
if (item->next != NULL)
{
/* not the last element */
item->next->prev = item->prev;
}
if (item == parent->child)
{
/* first element */
parent->child = item->next;
}
else if (item->next == NULL)
{
/* last element */
parent->child->prev = item->prev;
}
/* make sure the detached item doesn't point anywhere anymore */
item->prev = NULL;
item->next = NULL;
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
{
if (which < 0)
{
return NULL;
}
return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which));
}
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
{
cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
{
cJSON *to_detach = cJSON_GetObjectItem(object, string);
return cJSON_DetachItemViaPointer(object, to_detach);
}
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string)
{
cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string);
return cJSON_DetachItemViaPointer(object, to_detach);
}
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
{
cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string)
{
cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string));
}
/* Replace array/object items with new ones. */
CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
{
cJSON *after_inserted = NULL;
if (which < 0 || newitem == NULL)
{
return false;
}
after_inserted = get_array_item(array, (size_t)which);
if (after_inserted == NULL)
{
return add_item_to_array(array, newitem);
}
if (after_inserted != array->child && after_inserted->prev == NULL) {
/* return false if after_inserted is a corrupted array item */
return false;
}
newitem->next = after_inserted;
newitem->prev = after_inserted->prev;
after_inserted->prev = newitem;
if (after_inserted == array->child)
{
array->child = newitem;
}
else
{
newitem->prev->next = newitem;
}
return true;
}
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement)
{
if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) || (item == NULL))
{
return false;
}
if (replacement == item)
{
return true;
}
replacement->next = item->next;
replacement->prev = item->prev;
if (replacement->next != NULL)
{
replacement->next->prev = replacement;
}
if (parent->child == item)
{
if (parent->child->prev == parent->child)
{
replacement->prev = replacement;
}
parent->child = replacement;
}
else
{ /*
* To find the last item in array quickly, we use prev in array.
* We can't modify the last item's next pointer where this item was the parent's child
*/
if (replacement->prev != NULL)
{
replacement->prev->next = replacement;
}
if (replacement->next == NULL)
{
parent->child->prev = replacement;
}
}
item->next = NULL;
item->prev = NULL;
cJSON_Delete(item);
return true;
}
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
{
if (which < 0)
{
return false;
}
return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem);
}
static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive)
{
if ((replacement == NULL) || (string == NULL))
{
return false;
}
/* replace the name in the replacement */
if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL))
{
cJSON_free(replacement->string);
}
replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
if (replacement->string == NULL)
{
return false;
}
replacement->type &= ~cJSON_StringIsConst;
return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement);
}
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
{
return replace_item_in_object(object, string, newitem, false);
}
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem)
{
return replace_item_in_object(object, string, newitem, true);
}
/* Create basic types: */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = cJSON_NULL;
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = cJSON_True;
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = cJSON_False;
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = boolean ? cJSON_True : cJSON_False;
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = cJSON_Number;
item->valuedouble = num;
/* use saturation in case of overflow */
if (num >= INT_MAX)
{
item->valueint = INT_MAX;
}
else if (num <= (double)INT_MIN)
{
item->valueint = INT_MIN;
}
else
{
item->valueint = (int)num;
}
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = cJSON_String;
item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
if(!item->valuestring)
{
cJSON_Delete(item);
return NULL;
}
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if (item != NULL)
{
item->type = cJSON_String | cJSON_IsReference;
item->valuestring = (char*)cast_away_const(string);
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if (item != NULL) {
item->type = cJSON_Object | cJSON_IsReference;
item->child = (cJSON*)cast_away_const(child);
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) {
cJSON *item = cJSON_New_Item(&global_hooks);
if (item != NULL) {
item->type = cJSON_Array | cJSON_IsReference;
item->child = (cJSON*)cast_away_const(child);
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = cJSON_Raw;
item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
if(!item->valuestring)
{
cJSON_Delete(item);
return NULL;
}
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type=cJSON_Array;
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if (item)
{
item->type = cJSON_Object;
}
return item;
}
/* Create Arrays: */
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
{
size_t i = 0;
cJSON *n = NULL;
cJSON *p = NULL;
cJSON *a = NULL;
if ((count < 0) || (numbers == NULL))
{
return NULL;
}
a = cJSON_CreateArray();
for(i = 0; a && (i < (size_t)count); i++)
{
n = cJSON_CreateNumber(numbers[i]);
if (!n)
{
cJSON_Delete(a);
return NULL;
}
if(!i)
{
a->child = n;
}
else
{
suffix_object(p, n);
}
p = n;
}
if (a && a->child) {
a->child->prev = n;
}
return a;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
{
size_t i = 0;
cJSON *n = NULL;
cJSON *p = NULL;
cJSON *a = NULL;
if ((count < 0) || (numbers == NULL))
{
return NULL;
}
a = cJSON_CreateArray();
for(i = 0; a && (i < (size_t)count); i++)
{
n = cJSON_CreateNumber((double)numbers[i]);
if(!n)
{
cJSON_Delete(a);
return NULL;
}
if(!i)
{
a->child = n;
}
else
{
suffix_object(p, n);
}
p = n;
}
if (a && a->child) {
a->child->prev = n;
}
return a;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
{
size_t i = 0;
cJSON *n = NULL;
cJSON *p = NULL;
cJSON *a = NULL;
if ((count < 0) || (numbers == NULL))
{
return NULL;
}
a = cJSON_CreateArray();
for(i = 0; a && (i < (size_t)count); i++)
{
n = cJSON_CreateNumber(numbers[i]);
if(!n)
{
cJSON_Delete(a);
return NULL;
}
if(!i)
{
a->child = n;
}
else
{
suffix_object(p, n);
}
p = n;
}
if (a && a->child) {
a->child->prev = n;
}
return a;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count)
{
size_t i = 0;
cJSON *n = NULL;
cJSON *p = NULL;
cJSON *a = NULL;
if ((count < 0) || (strings == NULL))
{
return NULL;
}
a = cJSON_CreateArray();
for (i = 0; a && (i < (size_t)count); i++)
{
n = cJSON_CreateString(strings[i]);
if(!n)
{
cJSON_Delete(a);
return NULL;
}
if(!i)
{
a->child = n;
}
else
{
suffix_object(p,n);
}
p = n;
}
if (a && a->child) {
a->child->prev = n;
}
return a;
}
/* Duplication */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
{
cJSON *newitem = NULL;
cJSON *child = NULL;
cJSON *next = NULL;
cJSON *newchild = NULL;
/* Bail on bad ptr */
if (!item)
{
goto fail;
}
/* Create new item */
newitem = cJSON_New_Item(&global_hooks);
if (!newitem)
{
goto fail;
}
/* Copy over all vars */
newitem->type = item->type & (~cJSON_IsReference);
newitem->valueint = item->valueint;
newitem->valuedouble = item->valuedouble;
if (item->valuestring)
{
newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
if (!newitem->valuestring)
{
goto fail;
}
}
if (item->string)
{
newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
if (!newitem->string)
{
goto fail;
}
}
/* If non-recursive, then we're done! */
if (!recurse)
{
return newitem;
}
/* Walk the ->next chain for the child. */
child = item->child;
while (child != NULL)
{
newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
if (!newchild)
{
goto fail;
}
if (next != NULL)
{
/* If newitem->child already set, then crosswire ->prev and ->next and move on */
next->next = newchild;
newchild->prev = next;
next = newchild;
}
else
{
/* Set newitem->child and move to it */
newitem->child = newchild;
next = newchild;
}
child = child->next;
}
if (newitem && newitem->child)
{
newitem->child->prev = newchild;
}
return newitem;
fail:
if (newitem != NULL)
{
cJSON_Delete(newitem);
}
return NULL;
}
static void skip_oneline_comment(char **input)
{
*input += static_strlen("//");
for (; (*input)[0] != '\0'; ++(*input))
{
if ((*input)[0] == '\n') {
*input += static_strlen("\n");
return;
}
}
}
static void skip_multiline_comment(char **input)
{
*input += static_strlen("/*");
for (; (*input)[0] != '\0'; ++(*input))
{
if (((*input)[0] == '*') && ((*input)[1] == '/'))
{
*input += static_strlen("*/");
return;
}
}
}
static void minify_string(char **input, char **output) {
(*output)[0] = (*input)[0];
*input += static_strlen("\"");
*output += static_strlen("\"");
for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) {
(*output)[0] = (*input)[0];
if ((*input)[0] == '\"') {
(*output)[0] = '\"';
*input += static_strlen("\"");
*output += static_strlen("\"");
return;
} else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) {
(*output)[1] = (*input)[1];
*input += static_strlen("\"");
*output += static_strlen("\"");
}
}
}
CJSON_PUBLIC(void) cJSON_Minify(char *json)
{
char *into = json;
if (json == NULL)
{
return;
}
while (json[0] != '\0')
{
switch (json[0])
{
case ' ':
case '\t':
case '\r':
case '\n':
json++;
break;
case '/':
if (json[1] == '/')
{
skip_oneline_comment(&json);
}
else if (json[1] == '*')
{
skip_multiline_comment(&json);
} else {
json++;
}
break;
case '\"':
minify_string(&json, (char**)&into);
break;
default:
into[0] = json[0];
json++;
into++;
}
}
/* and null-terminate. */
*into = '\0';
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_Invalid;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_False;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xff) == cJSON_True;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & (cJSON_True | cJSON_False)) != 0;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_NULL;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_Number;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_String;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_Array;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_Object;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_Raw;
}
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive)
{
if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)))
{
return false;
}
/* check if type is valid */
switch (a->type & 0xFF)
{
case cJSON_False:
case cJSON_True:
case cJSON_NULL:
case cJSON_Number:
case cJSON_String:
case cJSON_Raw:
case cJSON_Array:
case cJSON_Object:
break;
default:
return false;
}
/* identical objects are equal */
if (a == b)
{
return true;
}
switch (a->type & 0xFF)
{
/* in these cases and equal type is enough */
case cJSON_False:
case cJSON_True:
case cJSON_NULL:
return true;
case cJSON_Number:
if (compare_double(a->valuedouble, b->valuedouble))
{
return true;
}
return false;
case cJSON_String:
case cJSON_Raw:
if ((a->valuestring == NULL) || (b->valuestring == NULL))
{
return false;
}
if (strcmp(a->valuestring, b->valuestring) == 0)
{
return true;
}
return false;
case cJSON_Array:
{
cJSON *a_element = a->child;
cJSON *b_element = b->child;
for (; (a_element != NULL) && (b_element != NULL);)
{
if (!cJSON_Compare(a_element, b_element, case_sensitive))
{
return false;
}
a_element = a_element->next;
b_element = b_element->next;
}
/* one of the arrays is longer than the other */
if (a_element != b_element) {
return false;
}
return true;
}
case cJSON_Object:
{
cJSON *a_element = NULL;
cJSON *b_element = NULL;
cJSON_ArrayForEach(a_element, a)
{
/* TODO This has O(n^2) runtime, which is horrible! */
b_element = get_object_item(b, a_element->string, case_sensitive);
if (b_element == NULL)
{
return false;
}
if (!cJSON_Compare(a_element, b_element, case_sensitive))
{
return false;
}
}
/* doing this twice, once on a and b to prevent true comparison if a subset of b
* TODO: Do this the proper way, this is just a fix for now */
cJSON_ArrayForEach(b_element, b)
{
a_element = get_object_item(a, b_element->string, case_sensitive);
if (a_element == NULL)
{
return false;
}
if (!cJSON_Compare(b_element, a_element, case_sensitive))
{
return false;
}
}
return true;
}
default:
return false;
}
}
CJSON_PUBLIC(void *) cJSON_malloc(size_t size)
{
return global_hooks.allocate(size);
}
CJSON_PUBLIC(void) cJSON_free(void *object)
{
global_hooks.deallocate(object);
}
``` | /content/code_sandbox/src/cJSON.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 18,802 |
```c++
#include <mutex>
#include <thread>
#include <condition_variable>
#include <86box/plat.h>
#include <86box/thread.h>
struct event_cpp11_t {
std::condition_variable cond;
std::mutex mutex;
bool state = false;
};
extern "C" {
thread_t *
thread_create_named(void (*thread_rout)(void *param), void *param, const char *name)
{
auto thread = new std::thread([thread_rout, param, name] {
plat_set_thread_name(NULL, name);
thread_rout(param);
});
return thread;
}
int
thread_wait(thread_t *arg)
{
if (!arg)
return 0;
auto thread = reinterpret_cast<std::thread *>(arg);
thread->join();
return 0;
}
mutex_t *
thread_create_mutex(void)
{
auto mutex = new std::mutex;
return mutex;
}
int
thread_test_mutex(mutex_t *_mutex)
{
if (_mutex == nullptr)
return 0;
auto mutex = reinterpret_cast<std::mutex *>(_mutex);
return mutex->try_lock() ? 1 : 0;
}
int
thread_wait_mutex(mutex_t *_mutex)
{
if (_mutex == nullptr)
return 0;
auto mutex = reinterpret_cast<std::mutex *>(_mutex);
mutex->lock();
return 1;
}
int
thread_release_mutex(mutex_t *_mutex)
{
if (_mutex == nullptr)
return 0;
auto mutex = reinterpret_cast<std::mutex *>(_mutex);
mutex->unlock();
return 1;
}
void
thread_close_mutex(mutex_t *_mutex)
{
auto mutex = reinterpret_cast<std::mutex *>(_mutex);
delete mutex;
}
event_t *
thread_create_event()
{
auto ev = new event_cpp11_t;
return ev;
}
int
thread_wait_event(event_t *handle, int timeout)
{
auto event = reinterpret_cast<event_cpp11_t *>(handle);
auto lock = std::unique_lock<std::mutex>(event->mutex);
if (timeout < 0) {
event->cond.wait(lock, [event] { return event->state; });
} else {
auto to = std::chrono::system_clock::now() + std::chrono::milliseconds(timeout);
std::cv_status status;
do {
status = event->cond.wait_until(lock, to);
} while ((status != std::cv_status::timeout) && !event->state);
if (status == std::cv_status::timeout) {
return 1;
}
}
return 0;
}
void
thread_set_event(event_t *handle)
{
auto event = reinterpret_cast<event_cpp11_t *>(handle);
{
auto lock = std::unique_lock<std::mutex>(event->mutex);
event->state = true;
}
event->cond.notify_all();
}
void
thread_reset_event(event_t *handle)
{
auto event = reinterpret_cast<event_cpp11_t *>(handle);
auto lock = std::unique_lock<std::mutex>(event->mutex);
event->state = false;
}
void
thread_destroy_event(event_t *handle)
{
auto event = reinterpret_cast<event_cpp11_t *>(handle);
delete event;
}
}
``` | /content/code_sandbox/src/thread.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 700 |
```c
see COPYING for more details
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <wchar.h>
#include <86box/io.h>
#include <86box/nmi.h>
#include <86box/plat_unused.h>
int nmi_mask;
void
nmi_write(UNUSED(uint16_t port), uint8_t val, UNUSED(void *priv))
{
nmi_mask = val & 0x80;
}
void
nmi_init(void)
{
io_sethandler(0x00a0, 0x000f, NULL, NULL, NULL, nmi_write, NULL, NULL, NULL);
nmi_mask = 0;
}
``` | /content/code_sandbox/src/nmi.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 145 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Main emulator module where most things are controlled.
*
* Authors: Sarah Walker, <path_to_url
* Miran Grca, <mgrca8@gmail.com>
* Fred N. van Kempen, <decwiz@yahoo.com>
*
*/
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
#include <stdatomic.h>
#include <unistd.h>
#ifndef _WIN32
# include <pwd.h>
#endif
#ifdef __APPLE__
# include <string.h>
# include <dispatch/dispatch.h>
# ifdef __aarch64__
# include <pthread.h>
# endif
#endif
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/config.h>
#include <86box/mem.h>
#include "cpu.h"
#ifdef USE_DYNAREC
# include "codegen_public.h"
#endif
#include "x86_ops.h"
#include <86box/io.h>
#include <86box/rom.h>
#include <86box/dma.h>
#include <86box/pci.h>
#include <86box/pic.h>
#include <86box/timer.h>
#include <86box/device.h>
#include <86box/pit.h>
#include <86box/random.h>
#include <86box/nvr.h>
#include <86box/machine.h>
#include <86box/bugger.h>
#include <86box/postcard.h>
#include <86box/unittester.h>
#include <86box/novell_cardkey.h>
#include <86box/isamem.h>
#include <86box/isartc.h>
#include <86box/lpt.h>
#include <86box/serial.h>
#include <86box/serial_passthrough.h>
#include <86box/keyboard.h>
#include <86box/mouse.h>
#include <86box/gameport.h>
#include <86box/fdd.h>
#include <86box/fdc.h>
#include <86box/fdc_ext.h>
#include <86box/hdd.h>
#include <86box/hdc.h>
#include <86box/hdc_ide.h>
#include <86box/scsi.h>
#include <86box/scsi_device.h>
#include <86box/cdrom.h>
#include <86box/cdrom_interface.h>
#include <86box/zip.h>
#include <86box/mo.h>
#include <86box/scsi_disk.h>
#include <86box/cdrom_image.h>
#include <86box/thread.h>
#include <86box/network.h>
#include <86box/sound.h>
#include <86box/midi.h>
#include <86box/snd_speaker.h>
#include <86box/video.h>
#include <86box/ui.h>
#include <86box/path.h>
#include <86box/plat.h>
#include <86box/version.h>
#include <86box/gdbstub.h>
#include <86box/machine_status.h>
#include <86box/apm.h>
#include <86box/acpi.h>
// Disable c99-designator to avoid the warnings about int ng
#ifdef __clang__
# if __has_warning("-Wunused-but-set-variable")
# pragma clang diagnostic ignored "-Wunused-but-set-variable"
# endif
#endif
/* Stuff that used to be globally declared in plat.h but is now extern there
and declared here instead. */
int dopause = 1; /* system is paused */
atomic_flag doresize; /* screen resize requested */
volatile int is_quit; /* system exit requested */
uint64_t timer_freq;
char emu_version[200]; /* version ID string */
#ifdef MTR_ENABLED
int tracing_on = 0;
#endif
/* Commandline options. */
int dump_on_exit = 0; /* (O) dump regs on exit */
int start_in_fullscreen = 0; /* (O) start in fullscreen */
#ifdef _WIN32
int force_debug = 0; /* (O) force debug output */
#endif
#ifdef USE_WX
int video_fps = RENDER_FPS; /* (O) render speed in fps */
#endif
int settings_only = 0; /* (O) show only the settings dialog */
int confirm_exit_cmdl = 1; /* (O) do not ask for confirmation on quit if set to 0 */
#ifdef _WIN32
uint64_t unique_id = 0;
uint64_t source_hwnd = 0;
#endif
char rom_path[1024] = { '\0' }; /* (O) full path to ROMs */
rom_path_t rom_paths = { "", NULL }; /* (O) full paths to ROMs */
char log_path[1024] = { '\0' }; /* (O) full path of logfile */
char vm_name[1024] = { '\0' }; /* (O) display name of the VM */
int do_nothing = 0;
int dump_missing = 0;
int clear_cmos = 0;
#ifdef USE_INSTRUMENT
uint8_t instru_enabled = 0;
uint64_t instru_run_ms = 0;
#endif
int clear_flash = 0;
int auto_paused = 0;
/* Configuration values. */
int window_remember;
int vid_resize; /* (C) allow resizing */
int invert_display = 0; /* (C) invert the display */
int suppress_overscan = 0; /* (C) suppress overscans */
int scale = 0; /* (C) screen scale factor */
int dpi_scale = 0; /* (C) DPI scaling of the emulated
screen */
int vid_api = 0; /* (C) video renderer */
int vid_cga_contrast = 0; /* (C) video */
int video_fullscreen = 0; /* (C) video */
int video_fullscreen_scale = 0; /* (C) video */
int video_fullscreen_first = 0; /* (C) video */
int enable_overscan = 0; /* (C) video */
int force_43 = 0; /* (C) video */
int video_filter_method = 1; /* (C) video */
int video_vsync = 0; /* (C) video */
int video_framerate = -1; /* (C) video */
char video_shader[512] = { '\0' }; /* (C) video */
bool serial_passthrough_enabled[SERIAL_MAX] = { 0, 0, 0, 0, 0, 0, 0 }; /* (C) activation and kind of
pass-through for serial ports */
int bugger_enabled = 0; /* (C) enable ISAbugger */
int novell_keycard_enabled = 0; /* (C) enable Novell NetWare 2.x key card emulation. */
int postcard_enabled = 0; /* (C) enable POST card */
int unittester_enabled = 0; /* (C) enable unit tester device */
int isamem_type[ISAMEM_MAX] = { 0, 0, 0, 0 }; /* (C) enable ISA mem cards */
int isartc_type = 0; /* (C) enable ISA RTC card */
int gfxcard[GFXCARD_MAX] = { 0, 0 }; /* (C) graphics/video card */
int show_second_monitors = 1; /* (C) show non-primary monitors */
int sound_is_float = 1; /* (C) sound uses FP values */
int voodoo_enabled = 0; /* (C) video option */
int lba_enhancer_enabled = 0; /* (C) enable Vision Systems LBA Enhancer */
int ibm8514_standalone_enabled = 0; /* (C) video option */
int xga_standalone_enabled = 0; /* (C) video option */
uint32_t mem_size = 0; /* (C) memory size (Installed on
system board)*/
uint32_t isa_mem_size = 0; /* (C) memory size (ISA Memory Cards) */
int cpu_use_dynarec = 0; /* (C) cpu uses/needs Dyna */
int cpu = 0; /* (C) cpu type */
int fpu_type = 0; /* (C) fpu type */
int fpu_softfloat = 0; /* (C) fpu uses softfloat */
int time_sync = 0; /* (C) enable time sync */
int confirm_reset = 1; /* (C) enable reset confirmation */
int confirm_exit = 1; /* (C) enable exit confirmation */
int confirm_save = 1; /* (C) enable save confirmation */
int enable_discord = 0; /* (C) enable Discord integration */
int pit_mode = -1; /* (C) force setting PIT mode */
int fm_driver = 0; /* (C) select FM sound driver */
int open_dir_usr_path = 0; /* (C) default file open dialog directory
of usr_path */
int video_fullscreen_scale_maximized = 0; /* (C) Whether fullscreen scaling settings
also apply when maximized. */
int do_auto_pause = 0; /* (C) Auto-pause the emulator on focus
loss */
char uuid[MAX_UUID_LEN] = { '\0' }; /* (C) UUID or machine identifier */
int other_ide_present = 0; /* IDE controllers from non-IDE cards are
present */
int other_scsi_present = 0; /* SCSI controllers from non-SCSI cards are
present */
/* Statistics. */
extern int mmuflush;
extern int readlnum;
extern int writelnum;
/* emulator % */
int fps;
int framecount;
extern int CPUID;
extern int output;
int atfullspeed;
char exe_path[2048]; /* path (dir) of executable */
char usr_path[1024]; /* path (dir) of user data */
char cfg_path[1024]; /* full path of config file */
FILE *stdlog = NULL; /* file to log output to */
#if 0
int scrnsz_x = SCREEN_RES_X; /* current screen size, X */
int scrnsz_y = SCREEN_RES_Y; /* current screen size, Y */
#endif
int config_changed; /* config has changed */
int title_update;
int framecountx = 0;
int hard_reset_pending = 0;
#if 0
int unscaled_size_x = SCREEN_RES_X; /* current unscaled size X */
int unscaled_size_y = SCREEN_RES_Y; /* current unscaled size Y */
int efscrnsz_y = SCREEN_RES_Y;
#endif
static wchar_t mouse_msg[3][200];
static volatile atomic_int do_pause_ack = 0;
static volatile atomic_int pause_ack = 0;
#ifndef RELEASE_BUILD
static char buff[1024];
static int seen = 0;
static int suppr_seen = 1;
#endif
/*
* Log something to the logfile or stdout.
*
* To avoid excessively-large logfiles because some
* module repeatedly logs, we keep track of what is
* being logged, and catch repeating entries.
*/
void
pclog_ex(const char *fmt, va_list ap)
{
#ifndef RELEASE_BUILD
char temp[1024];
if (strcmp(fmt, "") == 0)
return;
if (stdlog == NULL) {
if (log_path[0] != '\0') {
stdlog = plat_fopen(log_path, "w");
if (stdlog == NULL)
stdlog = stdout;
} else
stdlog = stdout;
}
vsprintf(temp, fmt, ap);
if (suppr_seen && !strcmp(buff, temp))
seen++;
else {
if (suppr_seen && seen)
fprintf(stdlog, "*** %d repeats ***\n", seen);
seen = 0;
strcpy(buff, temp);
fprintf(stdlog, "%s", temp);
}
fflush(stdlog);
#endif
}
void
pclog_toggle_suppr(void)
{
#ifndef RELEASE_BUILD
suppr_seen ^= 1;
#endif
}
/* Log something. We only do this in non-release builds. */
void
pclog(const char *fmt, ...)
{
#ifndef RELEASE_BUILD
va_list ap;
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
#endif
}
/* Log a fatal error, and display a UI message before exiting. */
void
fatal(const char *fmt, ...)
{
char temp[1024];
va_list ap;
char *sp;
va_start(ap, fmt);
if (stdlog == NULL) {
if (log_path[0] != '\0') {
stdlog = plat_fopen(log_path, "w");
if (stdlog == NULL)
stdlog = stdout;
} else
stdlog = stdout;
}
vsprintf(temp, fmt, ap);
fprintf(stdlog, "%s", temp);
fflush(stdlog);
va_end(ap);
nvr_save();
config_save();
#ifdef ENABLE_808X_LOG
dumpregs(1);
#endif
/* Make sure the message does not have a trailing newline. */
if ((sp = strchr(temp, '\n')) != NULL)
*sp = '\0';
do_pause(2);
ui_msgbox(MBX_ERROR | MBX_FATAL | MBX_ANSI, temp);
/* Cleanly terminate all of the emulator's components so as
to avoid things like threads getting stuck. */
do_stop();
fflush(stdlog);
exit(-1);
}
void
fatal_ex(const char *fmt, va_list ap)
{
char temp[1024];
char *sp;
if (stdlog == NULL) {
if (log_path[0] != '\0') {
stdlog = plat_fopen(log_path, "w");
if (stdlog == NULL)
stdlog = stdout;
} else
stdlog = stdout;
}
vsprintf(temp, fmt, ap);
fprintf(stdlog, "%s", temp);
fflush(stdlog);
nvr_save();
config_save();
#ifdef ENABLE_808X_LOG
dumpregs(1);
#endif
/* Make sure the message does not have a trailing newline. */
if ((sp = strchr(temp, '\n')) != NULL)
*sp = '\0';
do_pause(2);
ui_msgbox(MBX_ERROR | MBX_FATAL | MBX_ANSI, temp);
/* Cleanly terminate all of the emulator's components so as
to avoid things like threads getting stuck. */
do_stop();
fflush(stdlog);
}
#ifdef ENABLE_PC_LOG
int pc_do_log = ENABLE_PC_LOG;
static void
pc_log(const char *fmt, ...)
{
va_list ap;
if (pc_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define pc_log(fmt, ...)
#endif
static void
delete_nvr_file(uint8_t flash)
{
char *fn = NULL;
int c;
/* Set up the NVR file's name. */
c = strlen(machine_get_internal_name()) + 5;
fn = (char *) malloc(c + 1);
if (fn == NULL)
fatal("Error allocating memory for the removal of the %s file\n",
flash ? "BIOS flash" : "CMOS");
if (flash)
sprintf(fn, "%s.bin", machine_get_internal_name());
else
sprintf(fn, "%s.nvr", machine_get_internal_name());
remove(nvr_path(fn));
free(fn);
fn = NULL;
}
/*
* Perform initial startup of the PC.
*
* This is the platform-indepenent part of the startup,
* where we check commandline arguments and load a
* configuration file.
*/
int
pc_init(int argc, char *argv[])
{
char *ppath = NULL;
char *rpath = NULL;
char *cfg = NULL;
char *p;
char temp[2048];
char *fn[FDD_NUM] = { NULL };
char drive = 0;
char *temp2 = NULL;
char *what;
const struct tm *info;
time_t now;
int c;
int lvmp = 0;
#ifdef ENABLE_NG
int ng = 0;
#endif
#ifdef _WIN32
uint32_t *uid;
uint32_t *shwnd;
#endif
uint32_t lang_init = 0;
/* Grab the executable's full path. */
plat_get_exe_name(exe_path, sizeof(exe_path) - 1);
p = path_get_filename(exe_path);
*p = '\0';
#if defined(__APPLE__)
c = strlen(exe_path);
if ((c >= 16) && !strcmp(&exe_path[c - 16], "/Contents/MacOS/")) {
exe_path[c - 16] = '\0';
p = path_get_filename(exe_path);
*p = '\0';
}
if (!strncmp(exe_path, "/private/var/folders/", 21)) {
ui_msgbox_header(MBX_FATAL, L"App Translocation", EMU_NAME_W L" cannot determine the emulated machine's location due to a macOS security feature. Please move the " EMU_NAME_W L" app to another folder (not /Applications), or make a copy of it and open that copy instead.");
return 0;
}
#elif !defined(_WIN32)
/* Grab the actual path if we are an AppImage. */
p = getenv("APPIMAGE");
if (p && (p[0] != '\0'))
path_get_dirname(exe_path, p);
#endif
path_slash(exe_path);
/*
* Get the current working directory.
*
* This is normally the directory from where the
* program was run. If we have been started via
* a shortcut (desktop icon), however, the CWD
* could have been set to something else.
*/
plat_getcwd(usr_path, sizeof(usr_path) - 1);
plat_getcwd(rom_path, sizeof(rom_path) - 1);
for (c = 1; c < argc; c++) {
if (argv[c][0] != '-')
break;
if (!strcasecmp(argv[c], "--help") || !strcasecmp(argv[c], "-?")) {
usage:
for (uint8_t i = 0; i < FDD_NUM; i++) {
if (fn[i] != NULL) {
free(fn[i]);
fn[i] = NULL;
}
}
printf("\nUsage: 86box [options] [cfg-file]\n\n");
printf("Valid options are:\n\n");
printf("-? or --help - show this information\n");
printf("-C or --config path - set 'path' to be config file\n");
#ifdef _WIN32
printf("-D or --debug - force debug output logging\n");
#endif
#if 0
printf("-E or --nographic - forces the old behavior\n");
#endif
printf("-F or --fullscreen - start in fullscreen mode\n");
printf("-G or --lang langid - start with specified language (e.g. en-US, or system)\n");
#ifdef _WIN32
printf("-H or --hwnd id,hwnd - sends back the main dialog's hwnd\n");
#endif
printf("-I or --image d:path - load 'path' as floppy image on drive d\n");
#ifdef USE_INSTRUMENT
printf("-J or --instrument name - set 'name' to be the profiling instrument\n");
#endif
printf("-K or --keycodes codes - set 'codes' to be the uncapture combination\n");
printf("-L or --logfile path - set 'path' to be the logfile\n");
printf("-M or --missing - dump missing machines and video cards\n");
printf("-N or --noconfirm - do not ask for confirmation on quit\n");
printf("-P or --vmpath path - set 'path' to be root for vm\n");
printf("-R or --rompath path - set 'path' to be ROM path\n");
#ifndef USE_SDL_UI
printf("-S or --settings - show only the settings dialog\n");
#endif
printf("-V or --vmname name - overrides the name of the running VM\n");
printf("-X or --clear what - clears the 'what' (cmos/flash/both)\n");
printf("-Y or --donothing - do not show any UI or run the emulation\n");
printf("-Z or --lastvmpath - the last parameter is VM path rather than config\n");
printf("\nA config file can be specified. If none is, the default file will be used.\n");
return 0;
} else if (!strcasecmp(argv[c], "--lastvmpath") || !strcasecmp(argv[c], "-Z")) {
lvmp = 1;
#ifdef _WIN32
} else if (!strcasecmp(argv[c], "--debug") || !strcasecmp(argv[c], "-D")) {
force_debug = 1;
#endif
#ifdef ENABLE_NG
} else if (!strcasecmp(argv[c], "--nographic") || !strcasecmp(argv[c], "-E")) {
/* Currently does nothing, but if/when we implement a built-in manager,
it's going to force the manager not to run, allowing the old usage
without parameter. */
ng = 1;
#endif
} else if (!strcasecmp(argv[c], "--fullscreen") || !strcasecmp(argv[c], "-F")) {
start_in_fullscreen = 1;
} else if (!strcasecmp(argv[c], "--logfile") || !strcasecmp(argv[c], "-L")) {
if ((c + 1) == argc)
goto usage;
strcpy(log_path, argv[++c]);
} else if (!strcasecmp(argv[c], "--vmpath") || !strcasecmp(argv[c], "-P")) {
if ((c + 1) == argc)
goto usage;
ppath = argv[++c];
} else if (!strcasecmp(argv[c], "--rompath") || !strcasecmp(argv[c], "-R")) {
if ((c + 1) == argc)
goto usage;
rpath = argv[++c];
rom_add_path(rpath);
} else if (!strcasecmp(argv[c], "--config") || !strcasecmp(argv[c], "-C")) {
if ((c + 1) == argc || plat_dir_check(argv[c + 1]))
goto usage;
cfg = argv[++c];
} else if (!strcasecmp(argv[c], "--image") || !strcasecmp(argv[c], "-I")) {
if ((c + 1) == argc)
goto usage;
temp2 = (char *) calloc(2048, 1);
sscanf(argv[++c], "%c:%s", &drive, temp2);
if (drive > 0x40)
drive = (drive & 0x1f) - 1;
else
drive = drive & 0x1f;
if (drive < 0)
drive = 0;
if (drive >= FDD_NUM)
drive = FDD_NUM - 1;
fn[(int) drive] = (char *) calloc(2048, 1);
strcpy(fn[(int) drive], temp2);
pclog("Drive %c: %s\n", drive + 0x41, fn[(int) drive]);
free(temp2);
temp2 = NULL;
} else if (!strcasecmp(argv[c], "--vmname") || !strcasecmp(argv[c], "-V")) {
if ((c + 1) == argc)
goto usage;
strcpy(vm_name, argv[++c]);
#ifndef USE_SDL_UI
} else if (!strcasecmp(argv[c], "--settings") || !strcasecmp(argv[c], "-S")) {
settings_only = 1;
#endif
} else if (!strcasecmp(argv[c], "--noconfirm") || !strcasecmp(argv[c], "-N")) {
confirm_exit_cmdl = 0;
} else if (!strcasecmp(argv[c], "--missing") || !strcasecmp(argv[c], "-M")) {
dump_missing = 1;
} else if (!strcasecmp(argv[c], "--donothing") || !strcasecmp(argv[c], "-Y")) {
do_nothing = 1;
} else if (!strcasecmp(argv[c], "--keycodes") || !strcasecmp(argv[c], "-K")) {
if ((c + 1) == argc)
goto usage;
sscanf(argv[++c], "%03hX,%03hX,%03hX,%03hX,%03hX,%03hX",
&key_prefix_1_1, &key_prefix_1_2, &key_prefix_2_1, &key_prefix_2_2,
&key_uncapture_1, &key_uncapture_2);
} else if (!strcasecmp(argv[c], "--clearboth") || !strcasecmp(argv[c], "-X")) {
if ((c + 1) == argc)
goto usage;
what = argv[++c];
if (!strcasecmp(what, "cmos"))
clear_cmos = 1;
else if (!strcasecmp(what, "flash"))
clear_flash = 1;
else if (!strcasecmp(what, "both")) {
clear_cmos = 1;
clear_flash = 1;
} else
goto usage;
#ifdef _WIN32
} else if (!strcasecmp(argv[c], "--hwnd") || !strcasecmp(argv[c], "-H")) {
if ((c + 1) == argc)
goto usage;
uid = (uint32_t *) &unique_id;
shwnd = (uint32_t *) &source_hwnd;
sscanf(argv[++c], "%08X%08X,%08X%08X", uid + 1, uid, shwnd + 1, shwnd);
#endif
} else if (!strcasecmp(argv[c], "--lang") || !strcasecmp(argv[c], "-G")) {
// This function is currently unimplemented for *nix but has placeholders.
lang_init = plat_language_code(argv[++c]);
if (!lang_init)
printf("\nWarning: Invalid language code, ignoring --lang parameter.\n\n");
// The return value of 0 only means that the code is invalid,
// not related to that translation is exists or not for the
// selected language.
} else if (!strcasecmp(argv[c], "--test") || !strcasecmp(argv[c], "-T")) {
/* some (undocumented) test function here.. */
/* .. and then exit. */
return 0;
#ifdef USE_INSTRUMENT
} else if (!strcasecmp(argv[c], "--instrument") || !strcasecmp(argv[c], "-J")) {
if ((c + 1) == argc)
goto usage;
instru_enabled = 1;
sscanf(argv[++c], "%llu", &instru_run_ms);
#endif
}
/* Uhm... out of options here.. */
else
goto usage;
}
/* One argument (config file) allowed. */
if (c < argc) {
if (lvmp)
ppath = argv[c++];
else
cfg = argv[c++];
}
if (c != argc)
goto usage;
path_slash(usr_path);
path_slash(rom_path);
/*
* If the user provided a path for files, use that
* instead of the current working directory. We do
* make sure that if that was a relative path, we
* make it absolute.
*/
if (ppath != NULL) {
if (!path_abs(ppath)) {
/*
* This looks like a relative path.
*
* Add it to the current working directory
* to convert it (back) to an absolute path.
*/
strcat(usr_path, ppath);
} else {
/*
* The user-provided path seems like an
* absolute path, so just use that.
*/
strcpy(usr_path, ppath);
}
/* If the specified path does not yet exist,
create it. */
if (!plat_dir_check(usr_path))
plat_dir_create(usr_path);
}
// Add the VM-local ROM path.
path_append_filename(temp, usr_path, "roms");
rom_add_path(temp);
// Add the standard ROM path in the same directory as the executable.
path_append_filename(temp, exe_path, "roms");
rom_add_path(temp);
plat_init_rom_paths();
/*
* If the user provided a path for ROMs, use that
* instead of the current working directory. We do
* make sure that if that was a relative path, we
* make it absolute.
*/
if (rpath != NULL) {
if (!path_abs(rpath)) {
/*
* This looks like a relative path.
*
* Add it to the current working directory
* to convert it (back) to an absolute path.
*/
strcat(rom_path, rpath);
} else {
/*
* The user-provided path seems like an
* absolute path, so just use that.
*/
strcpy(rom_path, rpath);
}
/* If the specified path does not yet exist,
create it. */
if (!plat_dir_check(rom_path))
plat_dir_create(rom_path);
} else
rom_path[0] = '\0';
/* Grab the name of the configuration file. */
if (cfg == NULL)
cfg = CONFIG_FILE;
/*
* If the configuration file name has (part of)
* a pathname, consider that to be part of the
* actual working directory.
*
* This can happen when people load a config
* file using the UI, for example.
*/
p = path_get_filename(cfg);
if (cfg != p) {
/*
* OK, the configuration file name has a
* path component. Separate the two, and
* add the path component to the cfg path.
*/
*(p - 1) = '\0';
/*
* If this is an absolute path, keep it, as
* there is probably have a reason to do so.
* Otherwise, assume the pathname given is
* relative to whatever the usr_path is.
*/
if (path_abs(cfg))
strcpy(usr_path, cfg);
else
strcat(usr_path, cfg);
}
/* Make sure we have a trailing backslash. */
path_slash(usr_path);
if (rom_path[0] != '\0')
path_slash(rom_path);
/* At this point, we can safely create the full path name. */
path_append_filename(cfg_path, usr_path, p);
/*
* Get the current directory's name
*
* At this point usr_path is perfectly initialized.
* If no --vmname parameter specified we'll use the
* working directory name as the VM's name.
*/
if (strlen(vm_name) == 0) {
char ltemp[1024] = { '\0' };
path_get_dirname(ltemp, usr_path);
strcpy(vm_name, path_get_filename(ltemp));
}
/*
* This is where we start outputting to the log file,
* if there is one. Create a little info header first.
*/
(void) time(&now);
info = localtime(&now);
strftime(temp, sizeof(temp), "%Y/%m/%d %H:%M:%S", info);
pclog("#\n# %ls v%ls logfile, created %s\n#\n",
EMU_NAME_W, EMU_VERSION_FULL_W, temp);
pclog("# VM: %s\n#\n", vm_name);
pclog("# Emulator path: %s\n", exe_path);
pclog("# Userfiles path: %s\n", usr_path);
for (rom_path_t *rom_path = &rom_paths; rom_path != NULL; rom_path = rom_path->next) {
pclog("# ROM path: %s\n", rom_path->path);
}
pclog("# Configuration file: %s\n#\n\n", cfg_path);
/*
* We are about to read the configuration file, which MAY
* put data into global variables (the hard- and floppy
* disks are an example) so we have to initialize those
* modules before we load the config..
*/
hdd_init();
network_init();
mouse_init();
cdrom_global_init();
zip_global_init();
mo_global_init();
/* Load the configuration file. */
config_load();
/* Clear the CMOS and/or BIOS flash file, if we were started with
the relevant parameter(s). */
if (clear_cmos) {
delete_nvr_file(0);
clear_cmos = 0;
}
if (clear_flash) {
delete_nvr_file(1);
clear_flash = 0;
}
for (uint8_t i = 0; i < FDD_NUM; i++) {
if (fn[i] != NULL) {
if (strlen(fn[i]) <= 511)
strncpy(floppyfns[i], fn[i], 511);
free(fn[i]);
fn[i] = NULL;
}
}
/* Load the desired language */
if (lang_init)
lang_id = lang_init;
gdbstub_init();
/* All good! */
return 1;
}
void
pc_speed_changed(void)
{
if (cpu_s->cpu_type >= CPU_286)
pit_set_clock(cpu_s->rspeed);
else
pit_set_clock((uint32_t) 14318184.0);
}
void
pc_full_speed(void)
{
if (!atfullspeed) {
pc_log("Set fullspeed - %i %i\n", is386, is486);
pc_speed_changed();
}
atfullspeed = 1;
}
/* Initialize modules, ran once, after pc_init. */
int
pc_init_modules(void)
{
int c;
int m;
wchar_t temp[512];
char tempc[512];
if (dump_missing) {
dump_missing = 0;
c = m = 0;
while (machine_get_internal_name_ex(c) != NULL) {
m = machine_available(c);
if (!m)
pclog("Missing machine: %s\n", machine_getname_ex(c));
c++;
}
c = m = 0;
while (video_get_internal_name(c) != NULL) {
memset(tempc, 0, sizeof(tempc));
device_get_name(video_card_getdevice(c), 0, tempc);
if ((c > 1) && !(tempc[0]))
break;
m = video_card_available(c);
if (!m)
pclog("Missing video card: %s\n", tempc);
c++;
}
}
pc_log("Scanning for ROM images:\n");
c = m = 0;
while (machine_get_internal_name_ex(m) != NULL) {
c += machine_available(m);
m++;
}
if (c == 0) {
/* No usable ROMs found, aborting. */
return 0;
}
pc_log("A total of %d ROM sets have been loaded.\n", c);
/* Load the ROMs for the selected machine. */
if (!machine_available(machine)) {
swprintf(temp, sizeof_w(temp), plat_get_string(STRING_HW_NOT_AVAILABLE_MACHINE), machine_getname());
c = 0;
machine = -1;
while (machine_get_internal_name_ex(c) != NULL) {
if (machine_available(c)) {
ui_msgbox_header(MBX_INFO, plat_get_string(STRING_HW_NOT_AVAILABLE_TITLE), temp);
machine = c;
config_save();
break;
}
c++;
}
if (machine == -1) {
fatal("No available machines\n");
exit(-1);
}
}
/* Make sure we have a usable video card. */
if (!video_card_available(gfxcard[0])) {
memset(tempc, 0, sizeof(tempc));
device_get_name(video_card_getdevice(gfxcard[0]), 0, tempc);
swprintf(temp, sizeof_w(temp), plat_get_string(STRING_HW_NOT_AVAILABLE_VIDEO), tempc);
c = 0;
while (video_get_internal_name(c) != NULL) {
gfxcard[0] = -1;
if (video_card_available(c)) {
ui_msgbox_header(MBX_INFO, plat_get_string(STRING_HW_NOT_AVAILABLE_TITLE), temp);
gfxcard[0] = c;
config_save();
break;
}
c++;
}
if (gfxcard[0] == -1) {
fatal("No available video cards\n");
exit(-1);
}
}
// TODO
for (uint8_t i = 1; i < GFXCARD_MAX; i ++) {
if (!video_card_available(gfxcard[i])) {
char tempc[512] = { 0 };
device_get_name(video_card_getdevice(gfxcard[i]), 0, tempc);
swprintf(temp, sizeof_w(temp), plat_get_string(STRING_HW_NOT_AVAILABLE_VIDEO2), tempc);
ui_msgbox_header(MBX_INFO, plat_get_string(STRING_HW_NOT_AVAILABLE_TITLE), temp);
gfxcard[i] = 0;
}
}
atfullspeed = 0;
random_init();
mem_init();
#ifdef USE_DYNAREC
# if defined(__APPLE__) && defined(__aarch64__)
if (__builtin_available(macOS 11.0, *)) {
pthread_jit_write_protect_np(0);
}
# endif
codegen_init();
# if defined(__APPLE__) && defined(__aarch64__)
if (__builtin_available(macOS 11.0, *)) {
pthread_jit_write_protect_np(1);
}
# endif
#endif
keyboard_init();
joystick_init();
video_init();
fdd_init();
sound_init();
hdc_init();
video_reset_close();
machine_status_init();
if (do_nothing) {
do_nothing = 0;
exit(-1);
}
return 1;
}
void
pc_send_ca(uint16_t sc)
{
keyboard_input(1, 0x1D); /* Ctrl key pressed */
keyboard_input(1, 0x38); /* Alt key pressed */
keyboard_input(1, sc);
usleep(50000);
keyboard_input(0, sc);
keyboard_input(0, 0x38); /* Alt key released */
keyboard_input(0, 0x1D); /* Ctrl key released */
}
/* Send the machine a Control-Alt-DEL sequence. */
void
pc_send_cad(void)
{
pc_send_ca(0x153);
}
/* Send the machine a Control-Alt-ESC sequence. */
void
pc_send_cae(void)
{
pc_send_ca(1);
}
void
pc_reset_hard_close(void)
{
ui_sb_set_ready(0);
/* Close all the memory mappings. */
mem_close();
suppress_overscan = 0;
/* Turn off timer processing to avoid potential segmentation faults. */
timer_close();
lpt_devices_close();
#ifdef UNCOMMENT_LATER
lpt_close();
#endif
nvr_save();
nvr_close();
mouse_close();
device_close_all();
scsi_device_close_all();
midi_out_close();
midi_in_close();
cdrom_close();
zip_close();
mo_close();
scsi_disk_close();
closeal();
video_reset_close();
cpu_close();
serial_set_next_inst(0);
}
/*
* This is basically the spot where we start up the actual machine,
* by issuing a 'hard reset' to the entire configuration. Order is
* somewhat important here. Functions here should be named _reset
* really, as that is what they do.
*/
void
pc_reset_hard_init(void)
{
/*
* First, we reset the modules that are not part of
* the actual machine, but which support some of the
* modules that are.
*/
/* Reset the IDE and SCSI presences */
other_ide_present = other_scsi_present = 0;
/* Mark ACPI as unavailable */
acpi_enabled = 0;
/* Reset the general machine support modules. */
io_init();
/* Turn on and (re)initialize timer processing. */
timer_init();
device_init();
sound_reset();
scsi_reset();
scsi_device_init();
/* Initialize the actual machine and its basic modules. */
machine_init();
/* Reset some basic devices. */
speaker_init();
shadowbios = 0;
/*
* Once the machine has been initialized, all that remains
* should be resetting all devices set up for it, to their
* current configurations !
*
* For now, we will call their reset functions here, but
* that will be a call to device_reset_all() later !
*/
/* Reset and reconfigure the Sound Card layer. */
sound_card_reset();
/* Initialize parallel devices. */
/* note: PLIP LPT side has to be initialized before the network side */
lpt_devices_init();
/* Reset and reconfigure the serial ports. */
/* note: SLIP COM side has to be initialized before the network side */
serial_standalone_init();
serial_passthrough_init();
/* Reset and reconfigure the Network Card layer. */
network_reset();
/*
* Reset the mouse, this will attach it to any port needed.
*/
mouse_reset();
/* Reset the Hard Disk Controller module. */
hdc_reset();
fdc_card_init();
fdd_reset();
/* Reset the CD-ROM Controller module. */
cdrom_interface_reset();
/* Reset and reconfigure the SCSI layer. */
scsi_card_init();
scsi_disk_hard_reset();
cdrom_hard_reset();
mo_hard_reset();
zip_hard_reset();
/* Reset any ISA RTC cards. */
isartc_reset();
/* Initialize the Voodoo cards here inorder to minimize
the chances of the SCSI controller ending up on the bridge. */
video_voodoo_init();
if (joystick_type)
gameport_update_joystick_type(); /* installs game port if no device provides one, must be late */
ui_sb_update_panes();
if (config_changed) {
config_save();
config_changed = 0;
} else
ui_sb_set_ready(1);
/* Needs the status bar... */
if (bugger_enabled)
device_add(&bugger_device);
if (postcard_enabled)
device_add(&postcard_device);
if (unittester_enabled)
device_add(&unittester_device);
if (lba_enhancer_enabled)
device_add(&lba_enhancer_device);
if (novell_keycard_enabled)
device_add(&novell_keycard_device);
if (IS_ARCH(machine, MACHINE_BUS_PCI)) {
pci_register_cards();
device_reset_all(DEVICE_PCI);
}
/* Mark IDE shadow drives (slaves with a present master) as such in case
the IDE controllers present are not some form of PCI. */
ide_drives_set_shadow();
/* Reset the CPU module. */
resetx86();
dma_reset();
pci_pic_reset();
cpu_cache_int_enabled = cpu_cache_ext_enabled = 0;
atfullspeed = 0;
pc_full_speed();
cycles = 0;
#ifdef FPU_CYCLES
fpu_cycles = 0;
#endif
#ifdef USE_DYNAREC
cycles_main = 0;
#endif
update_mouse_msg();
ui_hard_reset_completed();
}
void
update_mouse_msg(void)
{
wchar_t wcpufamily[2048];
wchar_t wcpu[2048];
wchar_t wmachine[2048];
wchar_t *wcp;
mbstowcs(wmachine, machine_getname(), strlen(machine_getname()) + 1);
if (!cpu_override)
mbstowcs(wcpufamily, cpu_f->name, strlen(cpu_f->name) + 1);
else
swprintf(wcpufamily, sizeof_w(wcpufamily), L"[U] %hs", cpu_f->name);
wcp = wcschr(wcpufamily, L'(');
if (wcp) /* remove parentheses */
*(wcp - 1) = L'\0';
mbstowcs(wcpu, cpu_s->name, strlen(cpu_s->name) + 1);
#ifdef _WIN32
swprintf(mouse_msg[0], sizeof_w(mouse_msg[0]), L"%%i%%%% - %ls",
plat_get_string(STRING_MOUSE_CAPTURE));
swprintf(mouse_msg[1], sizeof_w(mouse_msg[1]), L"%%i%%%% - %ls",
(mouse_get_buttons() > 2) ? plat_get_string(STRING_MOUSE_RELEASE) : plat_get_string(STRING_MOUSE_RELEASE_MMB));
wcsncpy(mouse_msg[2], L"%i%%", sizeof_w(mouse_msg[2]));
#else
swprintf(mouse_msg[0], sizeof_w(mouse_msg[0]), L"%ls v%ls - %%i%%%% - %ls - %ls/%ls - %ls",
EMU_NAME_W, EMU_VERSION_FULL_W, wmachine, wcpufamily, wcpu,
plat_get_string(STRING_MOUSE_CAPTURE));
swprintf(mouse_msg[1], sizeof_w(mouse_msg[1]), L"%ls v%ls - %%i%%%% - %ls - %ls/%ls - %ls",
EMU_NAME_W, EMU_VERSION_FULL_W, wmachine, wcpufamily, wcpu,
(mouse_get_buttons() > 2) ? plat_get_string(STRING_MOUSE_RELEASE) : plat_get_string(STRING_MOUSE_RELEASE_MMB));
swprintf(mouse_msg[2], sizeof_w(mouse_msg[2]), L"%ls v%ls - %%i%%%% - %ls - %ls/%ls",
EMU_NAME_W, EMU_VERSION_FULL_W, wmachine, wcpufamily, wcpu);
#endif
}
void
pc_reset_hard(void)
{
hard_reset_pending = 1;
}
void
pc_close(UNUSED(thread_t *ptr))
{
/* Wait a while so things can shut down. */
plat_delay_ms(200);
/* Claim the video blitter. */
startblit();
/* Terminate the UI thread. */
is_quit = 1;
nvr_save();
config_save();
plat_mouse_capture(0);
/* Close all the memory mappings. */
mem_close();
/* Turn off timer processing to avoid potential segmentation faults. */
timer_close();
lpt_devices_close();
for (uint8_t i = 0; i < FDD_NUM; i++)
fdd_close(i);
#ifdef ENABLE_808X_LOG
if (dump_on_exit)
dumpregs(0);
#endif
video_close();
device_close_all();
scsi_device_close_all();
midi_out_close();
midi_in_close();
network_close();
sound_cd_thread_end();
cdrom_close();
zip_close();
mo_close();
scsi_disk_close();
gdbstub_close();
}
#ifdef __APPLE__
static void
_ui_window_title(void *s)
{
ui_window_title((wchar_t *) s);
free(s);
}
#endif
void
ack_pause(void)
{
if (atomic_load(&do_pause_ack)) {
atomic_store(&do_pause_ack, 0);
atomic_store(&pause_ack, 1);
}
}
void
pc_run(void)
{
int mouse_msg_idx;
wchar_t temp[200];
/* Trigger a hard reset if one is pending. */
if (hard_reset_pending) {
hard_reset_pending = 0;
pc_reset_hard_close();
pc_reset_hard_init();
}
/* Run a block of code. */
startblit();
cpu_exec((int32_t) cpu_s->rspeed / 100);
ack_pause();
#ifdef USE_GDBSTUB /* avoid a KBC FIFO overflow when CPU emulation is stalled */
if (gdbstub_step == GDBSTUB_EXEC) {
#endif
if (!mouse_timed)
mouse_process();
#ifdef USE_GDBSTUB /* avoid a KBC FIFO overflow when CPU emulation is stalled */
}
#endif
joystick_process();
endblit();
/* Done with this frame, update statistics. */
framecount++;
if (++framecountx >= 100) {
framecountx = 0;
frames = 0;
}
if (title_update) {
mouse_msg_idx = ((mouse_type == MOUSE_TYPE_NONE) || (mouse_input_mode >= 1)) ? 2 : !!mouse_capture;
swprintf(temp, sizeof_w(temp), mouse_msg[mouse_msg_idx], fps);
#ifdef __APPLE__
/* Needed due to modifying the UI on the non-main thread is a big no-no. */
dispatch_async_f(dispatch_get_main_queue(), wcsdup((const wchar_t *) temp), _ui_window_title);
#else
ui_window_title(temp);
#endif
title_update = 0;
}
}
/* Handler for the 1-second timer to refresh the window title. */
void
pc_onesec(void)
{
fps = framecount;
framecount = 0;
title_update = 1;
}
void
set_screen_size_monitor(int x, int y, int monitor_index)
{
int temp_overscan_x = monitors[monitor_index].mon_overscan_x;
int temp_overscan_y = monitors[monitor_index].mon_overscan_y;
double dx;
double dy;
double dtx;
double dty;
/* Make sure we keep usable values. */
#if 0
pc_log("SetScreenSize(%d, %d) resize=%d\n", x, y, vid_resize);
#endif
if (x < 320)
x = 320;
if (y < 200)
y = 200;
if (x > 2048)
x = 2048;
if (y > 2048)
y = 2048;
/* Save the new values as "real" (unscaled) resolution. */
monitors[monitor_index].mon_unscaled_size_x = x;
monitors[monitor_index].mon_efscrnsz_y = y;
if (suppress_overscan)
temp_overscan_x = temp_overscan_y = 0;
if (force_43) {
dx = (double) x;
dtx = (double) temp_overscan_x;
dy = (double) y;
dty = (double) temp_overscan_y;
/* Account for possible overscan. */
if (video_get_type_monitor(monitor_index) != VIDEO_FLAG_TYPE_SPECIAL && (temp_overscan_y == 16)) {
/* CGA */
dy = (((dx - dtx) / 4.0) * 3.0) + dty;
} else if (video_get_type_monitor(monitor_index) != VIDEO_FLAG_TYPE_SPECIAL && (temp_overscan_y < 16)) {
/* MDA/Hercules */
dy = (x / 4.0) * 3.0;
} else {
if (enable_overscan) {
/* EGA/(S)VGA with overscan */
dy = (((dx - dtx) / 4.0) * 3.0) + dty;
} else {
/* EGA/(S)VGA without overscan */
dy = (x / 4.0) * 3.0;
}
}
monitors[monitor_index].mon_unscaled_size_y = (int) dy;
} else
monitors[monitor_index].mon_unscaled_size_y = monitors[monitor_index].mon_efscrnsz_y;
switch (scale) {
case 0: /* 50% */
monitors[monitor_index].mon_scrnsz_x = (monitors[monitor_index].mon_unscaled_size_x >> 1);
monitors[monitor_index].mon_scrnsz_y = (monitors[monitor_index].mon_unscaled_size_y >> 1);
break;
case 1: /* 100% */
monitors[monitor_index].mon_scrnsz_x = monitors[monitor_index].mon_unscaled_size_x;
monitors[monitor_index].mon_scrnsz_y = monitors[monitor_index].mon_unscaled_size_y;
break;
case 2: /* 150% */
monitors[monitor_index].mon_scrnsz_x = ((monitors[monitor_index].mon_unscaled_size_x * 3) >> 1);
monitors[monitor_index].mon_scrnsz_y = ((monitors[monitor_index].mon_unscaled_size_y * 3) >> 1);
break;
case 3: /* 200% */
monitors[monitor_index].mon_scrnsz_x = (monitors[monitor_index].mon_unscaled_size_x << 1);
monitors[monitor_index].mon_scrnsz_y = (monitors[monitor_index].mon_unscaled_size_y << 1);
break;
case 4: /* 300% */
monitors[monitor_index].mon_scrnsz_x = (monitors[monitor_index].mon_unscaled_size_x * 3);
monitors[monitor_index].mon_scrnsz_y = (monitors[monitor_index].mon_unscaled_size_y * 3);
break;
case 5: /* 400% */
monitors[monitor_index].mon_scrnsz_x = (monitors[monitor_index].mon_unscaled_size_x << 2);
monitors[monitor_index].mon_scrnsz_y = (monitors[monitor_index].mon_unscaled_size_y << 2);
break;
case 6: /* 500% */
monitors[monitor_index].mon_scrnsz_x = (monitors[monitor_index].mon_unscaled_size_x * 5);
monitors[monitor_index].mon_scrnsz_y = (monitors[monitor_index].mon_unscaled_size_y * 5);
break;
case 7: /* 600% */
monitors[monitor_index].mon_scrnsz_x = (monitors[monitor_index].mon_unscaled_size_x * 6);
monitors[monitor_index].mon_scrnsz_y = (monitors[monitor_index].mon_unscaled_size_y * 6);
break;
case 8: /* 700% */
monitors[monitor_index].mon_scrnsz_x = (monitors[monitor_index].mon_unscaled_size_x * 7);
monitors[monitor_index].mon_scrnsz_y = (monitors[monitor_index].mon_unscaled_size_y * 7);
break;
case 9: /* 800% */
monitors[monitor_index].mon_scrnsz_x = (monitors[monitor_index].mon_unscaled_size_x << 3);
monitors[monitor_index].mon_scrnsz_y = (monitors[monitor_index].mon_unscaled_size_y << 3);
break;
default:
break;
}
plat_resize_request(monitors[monitor_index].mon_scrnsz_x, monitors[monitor_index].mon_scrnsz_y, monitor_index);
}
void
set_screen_size(int x, int y)
{
set_screen_size_monitor(x, y, monitor_index_global);
}
void
reset_screen_size_monitor(int monitor_index)
{
set_screen_size(monitors[monitor_index].mon_unscaled_size_x, monitors[monitor_index].mon_efscrnsz_y);
}
void
reset_screen_size(void)
{
for (uint8_t i = 0; i < MONITORS_NUM; i++)
set_screen_size(monitors[i].mon_unscaled_size_x, monitors[i].mon_efscrnsz_y);
}
void
set_screen_size_natural(void)
{
for (uint8_t i = 0; i < MONITORS_NUM; i++)
set_screen_size(monitors[i].mon_unscaled_size_x, monitors[i].mon_unscaled_size_y);
}
int
get_actual_size_x(void)
{
return (unscaled_size_x);
}
int
get_actual_size_y(void)
{
return (efscrnsz_y);
}
void
do_pause(int p)
{
int old_p = dopause;
if ((p == 1) && !old_p)
do_pause_ack = p;
dopause = !!p;
if ((p == 1) && !old_p) {
while (!atomic_load(&pause_ack))
;
}
atomic_store(&pause_ack, 0);
}
``` | /content/code_sandbox/src/86box.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 12,554 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of a generic PIIX4-compatible SMBus host controller.
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/io.h>
#include <86box/device.h>
#include <86box/timer.h>
#include <86box/i2c.h>
#include <86box/smbus.h>
#include <86box/plat_fallthrough.h>
#ifdef ENABLE_SMBUS_PIIX4_LOG
int smbus_piix4_do_log = ENABLE_SMBUS_PIIX4_LOG;
static void
smbus_piix4_log(const char *fmt, ...)
{
va_list ap;
if (smbus_piix4_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define smbus_piix4_log(fmt, ...)
#endif
static uint8_t
smbus_piix4_read(uint16_t addr, void *priv)
{
smbus_piix4_t *dev = (smbus_piix4_t *) priv;
uint8_t ret = 0x00;
switch (addr - dev->io_base) {
case 0x00:
ret = dev->stat;
break;
case 0x02:
dev->index = 0; /* reading from this resets the block data index */
ret = dev->ctl;
break;
case 0x03:
ret = dev->cmd;
break;
case 0x04:
ret = dev->addr;
break;
case 0x05:
ret = dev->data0;
break;
case 0x06:
ret = dev->data1;
break;
case 0x07:
ret = dev->data[dev->index++];
if (dev->index >= SMBUS_PIIX4_BLOCK_DATA_SIZE)
dev->index = 0;
break;
default:
break;
}
smbus_piix4_log("SMBus PIIX4: read(%02X) = %02x\n", addr, ret);
return ret;
}
static void
smbus_piix4_write(uint16_t addr, uint8_t val, void *priv)
{
smbus_piix4_t *dev = (smbus_piix4_t *) priv;
uint8_t smbus_addr;
uint8_t cmd;
uint8_t read;
uint8_t block_len;
uint8_t prev_stat;
uint16_t timer_bytes = 0;
uint16_t i = 0;
smbus_piix4_log("SMBus PIIX4: write(%02X, %02X)\n", addr, val);
prev_stat = dev->next_stat;
dev->next_stat = 0x00;
switch (addr - dev->io_base) {
case 0x00:
for (smbus_addr = 0x02; smbus_addr <= 0x10; smbus_addr <<= 1) { /* handle clearable bits */
if (val & smbus_addr)
dev->stat &= ~smbus_addr;
}
break;
case 0x02:
dev->ctl = val & ((dev->local == SMBUS_VIA) ? 0x3f : 0x1f);
if (val & 0x02) { /* cancel an in-progress command if KILL is set */
if (prev_stat) { /* cancel only if a command is in progress */
timer_disable(&dev->response_timer);
dev->stat = 0x10; /* raise FAILED */
}
}
if (val & 0x40) { /* dispatch command if START is set */
timer_bytes++; /* address */
smbus_addr = dev->addr >> 1;
read = dev->addr & 0x01;
cmd = (dev->ctl >> 2) & 0xf;
smbus_piix4_log("SMBus PIIX4: addr=%02X read=%d protocol=%X cmd=%02X data0=%02X data1=%02X\n", smbus_addr, read, cmd, dev->cmd, dev->data0, dev->data1);
/* Raise DEV_ERR if no device is at this address, or if the device returned NAK. */
if (!i2c_start(i2c_smbus, smbus_addr, read)) {
dev->next_stat = 0x04;
break;
}
dev->next_stat = 0x02; /* raise INTER (command completed) by default */
/* Decode the command protocol.
VIA-specific modes (0x4 and [0x6:0xf]) are undocumented and required real hardware research. */
switch (cmd) {
case 0x0: /* quick R/W */
break;
case 0x1: /* byte R/W */
if (read) /* byte read */
dev->data0 = i2c_read(i2c_smbus, smbus_addr);
else /* byte write */
i2c_write(i2c_smbus, smbus_addr, dev->data0);
timer_bytes++;
break;
case 0x2: /* byte data R/W */
/* command write */
i2c_write(i2c_smbus, smbus_addr, dev->cmd);
timer_bytes++;
if (read) /* byte read */
dev->data0 = i2c_read(i2c_smbus, smbus_addr);
else /* byte write */
i2c_write(i2c_smbus, smbus_addr, dev->data0);
timer_bytes++;
break;
case 0x3: /* word data R/W */
/* command write */
i2c_write(i2c_smbus, smbus_addr, dev->cmd);
timer_bytes++;
if (read) { /* word read */
dev->data0 = i2c_read(i2c_smbus, smbus_addr);
dev->data1 = i2c_read(i2c_smbus, smbus_addr);
} else { /* word write */
i2c_write(i2c_smbus, smbus_addr, dev->data0);
i2c_write(i2c_smbus, smbus_addr, dev->data1);
}
timer_bytes += 2;
break;
case 0x4: /* process call */
if (dev->local != SMBUS_VIA) /* VIA only */
goto unknown_protocol;
if (!read) { /* command write (only when writing) */
i2c_write(i2c_smbus, smbus_addr, dev->cmd);
timer_bytes++;
}
fallthrough;
case 0xc: /* I2C process call */
if (!read) { /* word write (only when writing) */
i2c_write(i2c_smbus, smbus_addr, dev->data0);
i2c_write(i2c_smbus, smbus_addr, dev->data1);
timer_bytes += 2;
}
/* word read */
dev->data0 = i2c_read(i2c_smbus, smbus_addr);
dev->data1 = i2c_read(i2c_smbus, smbus_addr);
timer_bytes += 2;
break;
case 0x5: /* block R/W */
timer_bytes++; /* count the SMBus length byte now */
fallthrough;
case 0xd: /* I2C block R/W */
i2c_write(i2c_smbus, smbus_addr, dev->cmd);
timer_bytes++;
if (read) {
/* block read [data0] (I2C) or [first byte] (SMBus) bytes */
if (cmd == 0x5)
dev->data0 = i2c_read(i2c_smbus, smbus_addr);
for (i = 0; i < dev->data0; i++)
dev->data[i & SMBUS_PIIX4_BLOCK_DATA_MASK] = i2c_read(i2c_smbus, smbus_addr);
} else {
if (cmd == 0x5) /* send length [data0] as first byte on SMBus */
i2c_write(i2c_smbus, smbus_addr, dev->data0);
/* block write [data0] bytes */
for (i = 0; i < dev->data0; i++) {
if (!i2c_write(i2c_smbus, smbus_addr, dev->data[i & SMBUS_PIIX4_BLOCK_DATA_MASK]))
break;
}
}
timer_bytes += i;
break;
case 0x6: /* I2C with 10-bit address */
if (dev->local != SMBUS_VIA) /* VIA only */
goto unknown_protocol;
/* command write */
i2c_write(i2c_smbus, smbus_addr, dev->cmd);
timer_bytes++;
fallthrough;
case 0xe: /* I2C with 7-bit address */
if (!read) { /* word write (only when writing) */
i2c_write(i2c_smbus, smbus_addr, dev->data0);
i2c_write(i2c_smbus, smbus_addr, dev->data1);
timer_bytes += 2;
}
/* block read [first byte] bytes */
block_len = dev->data[0];
for (i = 0; i < block_len; i++)
dev->data[i & SMBUS_PIIX4_BLOCK_DATA_MASK] = i2c_read(i2c_smbus, smbus_addr);
timer_bytes += i;
break;
case 0xf: /* universal */
/* block write [data0] bytes */
for (i = 0; i < dev->data0; i++) {
if (!i2c_write(i2c_smbus, smbus_addr, dev->data[i & SMBUS_PIIX4_BLOCK_DATA_MASK]))
break; /* write NAK behavior is unknown */
}
timer_bytes += i;
/* block read [data1] bytes */
for (i = 0; i < dev->data1; i++)
dev->data[i & SMBUS_PIIX4_BLOCK_DATA_MASK] = i2c_read(i2c_smbus, smbus_addr);
timer_bytes += i;
break;
default: /* unknown */
unknown_protocol:
dev->next_stat = 0x04; /* raise DEV_ERR */
timer_bytes = 0;
break;
}
/* Finish transfer. */
i2c_stop(i2c_smbus, smbus_addr);
}
break;
case 0x03:
dev->cmd = val;
break;
case 0x04:
dev->addr = val;
break;
case 0x05:
dev->data0 = val;
break;
case 0x06:
dev->data1 = val;
break;
case 0x07:
dev->data[dev->index++] = val;
if (dev->index >= SMBUS_PIIX4_BLOCK_DATA_SIZE)
dev->index = 0;
break;
default:
break;
}
if (dev->next_stat) { /* schedule dispatch of any pending status register update */
dev->stat = 0x01; /* raise HOST_BUSY while waiting */
timer_disable(&dev->response_timer);
/* delay = ((half clock for start + half clock for stop) + (bytes * (8 bits + ack))) * bit period in usecs */
timer_set_delay_u64(&dev->response_timer, (1 + (timer_bytes * 9)) * dev->bit_period * TIMER_USEC);
}
}
static void
smbus_piix4_response(void *priv)
{
smbus_piix4_t *dev = (smbus_piix4_t *) priv;
/* Dispatch the status register update. */
dev->stat = dev->next_stat;
}
void
smbus_piix4_remap(smbus_piix4_t *dev, uint16_t new_io_base, uint8_t enable)
{
if (dev->io_base)
io_removehandler(dev->io_base, 0x10, smbus_piix4_read, NULL, NULL, smbus_piix4_write, NULL, NULL, dev);
dev->io_base = new_io_base;
smbus_piix4_log("SMBus PIIX4: remap to %04Xh (%sabled)\n", dev->io_base, enable ? "en" : "dis");
if (enable && dev->io_base)
io_sethandler(dev->io_base, 0x10, smbus_piix4_read, NULL, NULL, smbus_piix4_write, NULL, NULL, dev);
}
void
smbus_piix4_setclock(smbus_piix4_t *dev, int clock)
{
dev->clock = clock;
/* Set the bit period in usecs. */
dev->bit_period = 1000000.0 / dev->clock;
}
static void *
smbus_piix4_init(const device_t *info)
{
smbus_piix4_t *dev = (smbus_piix4_t *) malloc(sizeof(smbus_piix4_t));
memset(dev, 0, sizeof(smbus_piix4_t));
dev->local = info->local;
/* We save the I2C bus handle on dev but use i2c_smbus for all operations because
dev and therefore dev->i2c will be invalidated if a device triggers a hard reset. */
i2c_smbus = dev->i2c = i2c_addbus((dev->local == SMBUS_VIA) ? "smbus_vt82c686b" : "smbus_piix4");
timer_add(&dev->response_timer, smbus_piix4_response, dev, 0);
smbus_piix4_setclock(dev, 16384); /* default to 16.384 KHz */
return dev;
}
static void
smbus_piix4_close(void *priv)
{
smbus_piix4_t *dev = (smbus_piix4_t *) priv;
if (i2c_smbus == dev->i2c)
i2c_smbus = NULL;
i2c_removebus(dev->i2c);
free(dev);
}
const device_t piix4_smbus_device = {
.name = "PIIX4-compatible SMBus Host Controller",
.internal_name = "piix4_smbus",
.flags = DEVICE_AT,
.local = SMBUS_PIIX4,
.init = smbus_piix4_init,
.close = smbus_piix4_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t via_smbus_device = {
.name = "VIA VT82C686B SMBus Host Controller",
.internal_name = "via_smbus",
.flags = DEVICE_AT,
.local = SMBUS_VIA,
.init = smbus_piix4_init,
.close = smbus_piix4_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/device/smbus_piix4.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,562 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Emulation of the National Semiconductor LM78 hardware monitoring chip.
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#define HAVE_STDARG_H
#include <wchar.h>
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/io.h>
#include <86box/timer.h>
#include <86box/machine.h>
#include <86box/nvr.h>
#include <86box/plat_fallthrough.h>
#include <86box/plat_unused.h>
#include "cpu.h"
#include <86box/i2c.h>
#include <86box/hwm.h>
#define LM78_I2C 0x010000
#define LM78_W83781D 0x020000
#define LM78_AS99127F_REV1 0x040000
#define LM78_AS99127F_REV2 0x080000
#define LM78_W83782D 0x100000
#define LM78_P5A 0x200000
#define LM78_AS99127F (LM78_AS99127F_REV1 | LM78_AS99127F_REV2) /* mask covering both _REV1 and _REV2 */
#define LM78_WINBOND (LM78_W83781D | LM78_AS99127F | LM78_W83782D) /* mask covering all Winbond variants */
#define LM78_WINBOND_VENDOR_ID ((dev->local & LM78_AS99127F_REV1) ? 0x12c3 : 0x5ca3)
#define LM78_WINBOND_BANK (dev->regs[0x4e] & 0x07)
#define CLAMP(a, min, max) (((a) < (min)) ? (min) : (((a) > (max)) ? (max) : (a)))
#define LM78_RPM_TO_REG(r, d) ((r) ? CLAMP(1350000 / (r * d), 1, 255) : 0)
#define LM78_VOLTAGE_TO_REG(v) ((v) >> 4)
#define LM78_NEG_VOLTAGE(v, r) (v * (604.0 / ((double) r))) /* negative voltage formula from the W83781D datasheet */
#define LM78_NEG_VOLTAGE2(v, r) (((3600 + v) * (((double) r) / (((double) r) + 56.0))) - v) /* negative voltage formula from the W83782D datasheet */
typedef struct lm78_t {
uint32_t local;
hwm_values_t *values;
device_t *lm75[2];
pc_timer_t reset_timer;
uint8_t regs[256];
union {
struct w83782d {
uint8_t regs[2][16];
} w83782d;
struct as99127f {
uint8_t regs[3][128];
uint8_t nvram[1024], nvram_i2c_state : 2, nvram_updated : 1;
uint16_t nvram_addr_register : 10;
int8_t nvram_block_len : 6;
uint8_t security_i2c_state : 1, security_addr_register : 7;
} as99127f;
};
uint8_t addr_register;
uint8_t data_register;
uint8_t i2c_addr : 7;
uint8_t i2c_state : 1;
uint8_t i2c_enabled : 1;
} lm78_t;
static void lm78_remap(lm78_t *dev, uint8_t addr);
#ifdef ENABLE_LM78_LOG
int lm78_do_log = ENABLE_LM78_LOG;
static void
lm78_log(const char *fmt, ...)
{
va_list ap;
if (lm78_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define lm78_log(fmt, ...)
#endif
void
lm78_nvram(lm78_t *dev, uint8_t save)
{
size_t l = strlen(machine_get_internal_name_ex(machine)) + 14;
char *nvr_path = (char *) malloc(l);
sprintf(nvr_path, "%s_as99127f.nvr", machine_get_internal_name_ex(machine));
FILE *fp = nvr_fopen(nvr_path, save ? "wb" : "rb");
if (fp) {
if (save)
fwrite(&dev->as99127f.nvram, sizeof(dev->as99127f.nvram), 1, fp);
else
(void) !fread(&dev->as99127f.nvram, sizeof(dev->as99127f.nvram), 1, fp);
fclose(fp);
}
free(nvr_path);
}
static uint8_t
lm78_nvram_start(UNUSED(void *bus), UNUSED(uint8_t addr), UNUSED(uint8_t read), void *priv)
{
lm78_t *dev = (lm78_t *) priv;
dev->as99127f.nvram_i2c_state = 0;
return 1;
}
static uint8_t
lm78_nvram_read(UNUSED(void *bus), UNUSED(uint8_t addr), void *priv)
{
lm78_t *dev = (lm78_t *) priv;
uint8_t ret = 0xff;
switch (dev->as99127f.nvram_i2c_state) {
case 0:
dev->as99127f.nvram_i2c_state = 1;
fallthrough;
case 1:
ret = dev->as99127f.regs[0][0x0b] & 0x3f;
lm78_log("LM78: nvram_read(blocklen) = %02X\n", ret);
break;
case 2:
ret = dev->as99127f.nvram[dev->as99127f.nvram_addr_register];
lm78_log("LM78: nvram_read(%03X) = %02X\n", dev->as99127f.nvram_addr_register, ret);
dev->as99127f.nvram_addr_register++;
break;
default:
lm78_log("LM78: nvram_read(unknown) = %02X\n", ret);
break;
}
if (dev->as99127f.nvram_i2c_state < 2)
dev->as99127f.nvram_i2c_state++;
return ret;
}
static uint8_t
lm78_nvram_write(UNUSED(void *bus), uint8_t addr, uint8_t val, void *priv)
{
lm78_t *dev = (lm78_t *) priv;
switch (dev->as99127f.nvram_i2c_state) {
case 0:
lm78_log("LM78: nvram_write(address, %02X)\n", val);
dev->as99127f.nvram_addr_register = (addr << 8) | val;
break;
case 1:
lm78_log("LM78: nvram_write(blocklen, %02X)\n", val);
dev->as99127f.nvram_block_len = val & 0x3f;
if (dev->as99127f.nvram_block_len <= 0)
dev->as99127f.nvram_i2c_state = 3;
break;
case 2:
lm78_log("LM78: nvram_write(%03X, %02X)\n", dev->as99127f.nvram_addr_register, val);
dev->as99127f.nvram[dev->as99127f.nvram_addr_register++] = val;
dev->as99127f.nvram_updated = 1;
if (--dev->as99127f.nvram_block_len <= 0)
dev->as99127f.nvram_i2c_state = 3;
break;
default:
lm78_log("LM78: nvram_write(unknown, %02X)\n", val);
break;
}
if (dev->as99127f.nvram_i2c_state < 2)
dev->as99127f.nvram_i2c_state++;
return dev->as99127f.nvram_i2c_state < 3;
}
static uint8_t
lm78_security_start(UNUSED(void *bus), UNUSED(uint8_t addr), UNUSED(uint8_t read), void *priv)
{
lm78_t *dev = (lm78_t *) priv;
dev->as99127f.security_i2c_state = 0;
return 1;
}
static uint8_t
lm78_security_read(UNUSED(void *bus), UNUSED(uint8_t addr), void *priv)
{
lm78_t *dev = (lm78_t *) priv;
return dev->as99127f.regs[2][dev->as99127f.security_addr_register++];
}
static uint8_t
lm78_security_write(UNUSED(void *bus), UNUSED(uint8_t addr), uint8_t val, void *priv)
{
lm78_t *dev = (lm78_t *) priv;
if (dev->as99127f.security_i2c_state == 0) {
dev->as99127f.security_i2c_state = 1;
dev->as99127f.security_addr_register = val;
} else {
switch (dev->as99127f.security_addr_register) {
case 0xe0:
case 0xe4:
case 0xe5:
case 0xe6:
case 0xe7:
/* read-only registers */
return 1;
default:
break;
}
dev->as99127f.regs[2][dev->as99127f.security_addr_register++] = val;
}
return 1;
}
static void
lm78_reset(void *priv)
{
lm78_t *dev = (lm78_t *) priv;
uint8_t initialization = dev->regs[0x40] & 0x80;
memset(dev->regs, 0, 256);
memset(dev->regs + 0xc0, 0xff, 32); /* C0-DF are 0xFF on a real AS99127F */
dev->regs[0x40] = 0x08;
dev->regs[0x46] = 0x40;
dev->regs[0x47] = 0x50;
if (dev->local & LM78_I2C) {
if (!initialization) { /* don't reset main I2C address if the reset was triggered by the INITIALIZATION bit */
if (dev->local & LM78_P5A)
dev->i2c_addr = 0x77;
else
dev->i2c_addr = 0x2d;
dev->i2c_enabled = 1;
}
dev->regs[0x48] = dev->i2c_addr;
if (dev->local & LM78_WINBOND)
dev->regs[0x4a] = 0x01;
} else {
dev->regs[0x48] = 0x00;
if (dev->local & LM78_WINBOND)
dev->regs[0x4a] = 0x88;
}
if (dev->local & LM78_WINBOND) {
dev->regs[0x49] = 0x02;
dev->regs[0x4b] = 0x44;
dev->regs[0x4c] = 0x01;
dev->regs[0x4d] = 0x15;
dev->regs[0x4e] = 0x80;
dev->regs[0x4f] = LM78_WINBOND_VENDOR_ID >> 8;
dev->regs[0x57] = 0x80;
if (dev->local & LM78_AS99127F) {
dev->regs[0x49] = 0x20;
dev->regs[0x4c] = 0x00;
dev->regs[0x56] = 0xff;
dev->regs[0x57] = 0xff;
dev->regs[0x58] = 0x31;
dev->regs[0x59] = 0x8f;
dev->regs[0x5a] = 0x8f;
dev->regs[0x5b] = 0x2a;
dev->regs[0x5c] = 0xe0;
dev->regs[0x5d] = 0x48;
dev->regs[0x5e] = 0xe2;
dev->regs[0x5f] = 0x1f;
dev->as99127f.regs[0][0x02] = 0xff;
dev->as99127f.regs[0][0x03] = 0xff;
dev->as99127f.regs[0][0x08] = 0xff;
dev->as99127f.regs[0][0x09] = 0xff;
dev->as99127f.regs[0][0x0b] = 0x01;
/* regs[1] and regs[2] start at 0x80 */
dev->as99127f.regs[1][0x00] = 0x88;
dev->as99127f.regs[1][0x01] = 0x10;
dev->as99127f.regs[1][0x03] = 0x02; /* GPO, but things break if GPO16 isn't set */
dev->as99127f.regs[1][0x04] = 0x01;
dev->as99127f.regs[1][0x05] = 0x1f;
lm78_as99127f_write(dev, 0x06, 0x2f);
dev->as99127f.regs[2][0x60] = 0xf0;
} else if (dev->local & LM78_W83781D) {
dev->regs[0x58] = 0x10;
} else if (dev->local & LM78_W83782D) {
dev->regs[0x58] = 0x30;
}
} else {
dev->regs[0x49] = 0x40;
}
lm78_remap(dev, dev->i2c_addr | (dev->i2c_enabled ? 0x00 : 0x80));
}
static uint8_t
lm78_i2c_start(UNUSED(void *bus), UNUSED(uint8_t addr), UNUSED(uint8_t read), void *priv)
{
lm78_t *dev = (lm78_t *) priv;
dev->i2c_state = 0;
return 1;
}
static uint8_t
lm78_read(lm78_t *dev, uint8_t reg, uint8_t bank)
{
uint8_t ret = 0;
uint8_t masked_reg = reg;
uint8_t bankswitched = ((reg & 0xf8) == 0x50);
lm75_t *lm75;
if ((dev->local & LM78_AS99127F) && (bank == 3) && (reg != 0x4e)) {
/* AS99127F additional registers */
if (!((dev->local & LM78_AS99127F_REV2) && ((reg == 0x80) || (reg == 0x81))))
ret = dev->as99127f.regs[0][reg & 0x7f];
} else if (bankswitched && ((bank == 1) || (bank == 2))) {
/* LM75 registers */
lm75 = device_get_priv(dev->lm75[bank - 1]);
if (lm75)
ret = lm75_read(lm75, reg);
} else if (bankswitched && ((bank == 4) || (bank == 5) || (bank == 6))) {
/* W83782D additional registers */
if (dev->local & LM78_W83782D) {
if ((bank == 5) && ((reg == 0x50) || (reg == 0x51))) /* voltages */
ret = LM78_VOLTAGE_TO_REG(dev->values->voltages[7 + (reg & 1)]);
else if (bank < 6)
ret = dev->w83782d.regs[bank - 4][reg & 0x0f];
}
} else {
/* regular registers */
if ((reg >= 0x60) && (reg <= 0x94)) /* read auto-increment value RAM registers from their non-auto-increment locations */
masked_reg = reg & 0x3f;
if ((masked_reg >= 0x20) && (masked_reg <= 0x26)) /* voltages */
ret = LM78_VOLTAGE_TO_REG(dev->values->voltages[reg & 7]);
else if ((dev->local & LM78_AS99127F) && (masked_reg <= 0x05)) /* AS99127F additional voltages */
ret = LM78_VOLTAGE_TO_REG(dev->values->voltages[7 + masked_reg]);
else if (masked_reg == 0x27) /* temperature */
ret = dev->values->temperatures[0];
else if ((masked_reg >= 0x28) && (masked_reg <= 0x2a)) { /* fan speeds */
ret = (dev->regs[((reg & 3) == 2) ? 0x4b : 0x47] >> ((reg & 3) ? 6 : 4)) & 0x03; /* bits [1:0] */
if (dev->local & LM78_W83782D)
ret |= (dev->regs[0x5d] >> (3 + (reg & 3))) & 0x04; /* bit 2 */
ret = LM78_RPM_TO_REG(dev->values->fans[reg & 3], 1 << ret);
} else if ((reg == 0x4f) && (dev->local & LM78_WINBOND)) /* two-byte vendor ID register */
ret = (dev->regs[0x4e] & 0x80) ? (uint8_t) (LM78_WINBOND_VENDOR_ID >> 8) : (uint8_t) LM78_WINBOND_VENDOR_ID;
else
ret = dev->regs[masked_reg];
}
lm78_log("LM78: read(%02X, %d) = %02X\n", reg, bank, ret);
return ret;
}
static uint8_t
lm78_isa_read(uint16_t port, void *priv)
{
lm78_t *dev = (lm78_t *) priv;
uint8_t ret = 0xff;
switch (port & 0x7) {
case 0x5:
ret = dev->addr_register & 0x7f;
break;
case 0x6:
ret = lm78_read(dev, dev->addr_register, LM78_WINBOND_BANK);
if (((LM78_WINBOND_BANK == 0) && ((dev->addr_register == 0x41) || (dev->addr_register == 0x43) || (dev->addr_register == 0x45) || (dev->addr_register == 0x56) || ((dev->addr_register >= 0x60) && (dev->addr_register < 0x94)))) || ((dev->local & LM78_W83782D) && (LM78_WINBOND_BANK == 5) && (dev->addr_register >= 0x50) && (dev->addr_register < 0x58))) {
/* auto-increment registers */
dev->addr_register++;
}
break;
default:
lm78_log("LM78: Read from unknown ISA port %d\n", port & 0x7);
break;
}
return ret;
}
static uint8_t
lm78_i2c_read(UNUSED(void *bus), UNUSED(uint8_t addr), void *priv)
{
lm78_t *dev = (lm78_t *) priv;
return lm78_read(dev, dev->addr_register++, LM78_WINBOND_BANK);
}
uint8_t
lm78_as99127f_read(void *priv, uint8_t reg)
{
const lm78_t *dev = (lm78_t *) priv;
uint8_t ret = dev->as99127f.regs[1][reg & 0x7f];
lm78_log("LM78: read(%02X, AS99127F) = %02X\n", reg, ret);
return ret;
}
static uint8_t
lm78_write(lm78_t *dev, uint8_t reg, uint8_t val, uint8_t bank)
{
lm75_t *lm75;
lm78_log("LM78: write(%02X, %d, %02X)\n", reg, bank, val);
if ((dev->local & LM78_AS99127F) && (bank == 3) && (reg != 0x4e)) {
/* AS99127F additional registers */
reg &= 0x7f;
switch (reg) {
case 0x00:
case 0x01:
case 0x04:
case 0x05:
case 0x06:
case 0x07:
/* read-only registers */
return 0;
case 0x20:
val &= 0x7f;
break;
default:
break;
}
dev->as99127f.regs[0][reg] = val;
return 1;
} else if ((reg & 0xf8) == 0x50) {
if ((bank == 1) || (bank == 2)) {
/* LM75 registers */
lm75 = device_get_priv(dev->lm75[bank - 1]);
if (lm75)
return lm75_write(lm75, reg, val);
return 1;
} else if (dev->local & LM78_W83782D) {
/* W83782D additional registers */
if (bank == 4) {
switch (reg) {
case 0x50:
case 0x52:
case 0x53:
case 0x54:
case 0x55:
case 0x56:
case 0x57:
case 0x58:
case 0x59:
case 0x5a:
case 0x5b:
case 0x5d:
case 0x5e:
case 0x5f:
/* read-only registers */
return 0;
default:
break;
}
dev->w83782d.regs[0][reg & 0x0f] = val;
return 1;
} else if (bank == 5) {
switch (reg) {
case 0x50:
case 0x51:
case 0x52:
case 0x53:
case 0x58:
case 0x59:
case 0x5a:
case 0x5b:
case 0x5c:
case 0x5d:
case 0x5e:
case 0x5f:
/* read-only registers */
return 0;
default:
break;
}
dev->w83782d.regs[1][reg & 0x0f] = val;
return 1;
} else if (bank == 6) {
return 0;
}
}
}
/* regular registers */
switch (reg) {
case 0x41:
case 0x42:
case 0x4f:
case 0x58:
case 0x20:
case 0x21:
case 0x22:
case 0x23:
case 0x24:
case 0x25:
case 0x26:
case 0x27:
case 0x28:
case 0x29:
case 0x2a:
case 0x60:
case 0x61:
case 0x62:
case 0x63:
case 0x64:
case 0x65:
case 0x66:
case 0x67:
case 0x68:
case 0x69:
case 0x6a:
case 0x00:
case 0x01:
case 0x02:
case 0x03:
case 0x04:
case 0x05:
case 0x80:
case 0x81:
case 0x82:
case 0x83:
case 0x84:
case 0x85:
/* read-only registers */
return 0;
case 0x4a:
case 0x4b:
case 0x4c:
case 0x4d:
case 0x4e:
/* Winbond-only registers */
if (!(dev->local & LM78_WINBOND))
return 0;
break;
default:
break;
}
if ((reg >= 0x60) && (reg <= 0x94)) /* write auto-increment value RAM registers to their non-auto-increment locations */
reg &= 0x3f;
uint8_t prev = dev->regs[reg];
dev->regs[reg] = val;
switch (reg) {
case 0x40:
if (val & 0x80) /* INITIALIZATION bit resets all registers except main I2C address */
lm78_reset(dev);
break;
case 0x48:
/* set main I2C address */
if (dev->local & LM78_I2C)
lm78_remap(dev, dev->regs[0x48] & 0x7f);
break;
case 0x49:
if (!(dev->local & LM78_WINBOND)) {
if (val & 0x20) /* Chip Reset bit (LM78 only) resets all registers */
lm78_reset(dev);
else
dev->regs[0x49] = 0x40;
} else {
dev->regs[0x49] &= 0x01;
}
break;
case 0x4a:
/* set LM75 I2C addresses (Winbond only) */
if (dev->local & LM78_I2C) {
for (uint8_t i = 0; i <= 1; i++) {
lm75 = device_get_priv(dev->lm75[i]);
if (!lm75)
continue;
if (val & (0x08 * (0x10 * i))) /* DIS_T2 and DIS_T3 bit disable those interfaces */
lm75_remap(lm75, 0x80);
else
lm75_remap(lm75, 0x48 + ((val >> (i * 4)) & 0x7));
}
}
break;
case 0x5c:
/* enable/disable AS99127F NVRAM */
if (dev->local & LM78_AS99127F) {
if (prev & 0x01)
i2c_removehandler(i2c_smbus, (prev & 0xf8) >> 1, 4, lm78_nvram_start, lm78_nvram_read, lm78_nvram_write, NULL, dev);
if (val & 0x01)
i2c_sethandler(i2c_smbus, (val & 0xf8) >> 1, 4, lm78_nvram_start, lm78_nvram_read, lm78_nvram_write, NULL, dev);
}
break;
default:
break;
}
return 1;
}
static void
lm78_isa_write(uint16_t port, uint8_t val, void *priv)
{
lm78_t *dev = (lm78_t *) priv;
switch (port & 0x7) {
case 0x5:
dev->addr_register = val & 0x7f;
break;
case 0x6:
lm78_write(dev, dev->addr_register, val, LM78_WINBOND_BANK);
if (((LM78_WINBOND_BANK == 0) && ((dev->addr_register == 0x41) || (dev->addr_register == 0x43) || (dev->addr_register == 0x45) || (dev->addr_register == 0x56) || ((dev->addr_register >= 0x60) && (dev->addr_register < 0x94)))) || ((dev->local & LM78_W83782D) && (LM78_WINBOND_BANK == 5) && (dev->addr_register >= 0x50) && (dev->addr_register < 0x58))) {
/* auto-increment registers */
dev->addr_register++;
}
break;
default:
lm78_log("LM78: Write %02X to unknown ISA port %d\n", val, port & 0x7);
break;
}
}
static uint8_t
lm78_i2c_write(UNUSED(void *bus), UNUSED(uint8_t addr), uint8_t val, void *priv)
{
lm78_t *dev = (lm78_t *) priv;
if (dev->i2c_state == 0) {
dev->i2c_state = 1;
dev->addr_register = val;
} else
lm78_write(dev, dev->addr_register++, val, LM78_WINBOND_BANK);
return 1;
}
uint8_t
lm78_as99127f_write(void *priv, uint8_t reg, uint8_t val)
{
lm78_t *dev = (lm78_t *) priv;
lm78_log("LM78: write(%02X, AS99127F, %02X)\n", reg, val);
reg &= 0x7f;
uint8_t prev = dev->as99127f.regs[1][reg];
dev->as99127f.regs[1][reg] = val;
switch (reg) {
case 0x01:
if (val & 0x40) {
dev->as99127f.regs[1][0x00] = 0x88;
dev->as99127f.regs[1][0x01] &= 0xe0;
dev->as99127f.regs[1][0x03] &= 0xf7;
dev->as99127f.regs[1][0x07] &= 0xfe;
}
if (!(val & 0x10)) { /* CUV4X-LS */
lm78_log("LM78: Reset requested through AS99127F CLKRST\n");
timer_set_delay_u64(&dev->reset_timer, 300000 * TIMER_USEC);
}
break;
case 0x06:
/* security device I2C address */
i2c_removehandler(i2c_smbus, prev & 0x7f, 1, lm78_security_start, lm78_security_read, lm78_security_write, NULL, dev);
i2c_sethandler(i2c_smbus, val & 0x7f, 1, lm78_security_start, lm78_security_read, lm78_security_write, NULL, dev);
break;
case 0x07:
if (val & 0x01) { /* other AS99127F boards */
lm78_log("LM78: Reset requested through AS99127F GPO15\n");
resetx86();
}
break;
default:
break;
}
return 1;
}
static void
lm78_reset_timer(UNUSED(void *priv))
{
pc_reset_hard();
}
static void
lm78_remap(lm78_t *dev, uint8_t addr)
{
lm75_t *lm75;
if (!(dev->local & LM78_I2C))
return;
lm78_log("LM78: remapping to SMBus %02Xh\n", addr);
if (dev->i2c_enabled)
i2c_removehandler(i2c_smbus, dev->i2c_addr, 1, lm78_i2c_start, lm78_i2c_read, lm78_i2c_write, NULL, dev);
if (addr < 0x80)
i2c_sethandler(i2c_smbus, addr, 1, lm78_i2c_start, lm78_i2c_read, lm78_i2c_write, NULL, dev);
dev->i2c_addr = addr & 0x7f;
dev->i2c_enabled = !(addr & 0x80);
if (dev->local & LM78_AS99127F) {
/* Store our handle on the primary LM75 device to ensure reads/writes
to the AS99127F's proprietary registers are passed through to this side. */
if ((lm75 = device_get_priv(dev->lm75[0])))
lm75->as99127f = dev;
}
}
static void
lm78_close(void *priv)
{
lm78_t *dev = (lm78_t *) priv;
uint16_t isa_io = dev->local & 0xffff;
if (isa_io)
io_removehandler(isa_io, 8, lm78_isa_read, NULL, NULL, lm78_isa_write, NULL, NULL, dev);
if (dev->as99127f.nvram_updated)
lm78_nvram(dev, 1);
free(dev);
}
static void *
lm78_init(const device_t *info)
{
lm78_t *dev = (lm78_t *) malloc(sizeof(lm78_t));
memset(dev, 0, sizeof(lm78_t));
dev->local = info->local;
/* Set global default values. */
hwm_values_t defaults = {
{
/* fan speeds */
3000, /* usually Chassis, sometimes CPU */
3000, /* usually CPU, sometimes Chassis */
3000 /* usually PSU, sometimes Chassis */
},
{
/* temperatures */
30, /* usually Board, sometimes Chassis */
30, /* Winbond only: usually CPU, sometimes Probe */
30 /* Winbond only: usually CPU when not the one above */
},
{
/* voltages */
hwm_get_vcore(), /* Vcore */
0, /* sometimes Vtt, Vio or second CPU */
3300, /* +3.3V */
RESISTOR_DIVIDER(5000, 11, 16), /* +5V (divider values bruteforced) */
RESISTOR_DIVIDER(12000, 28, 10), /* +12V (28K/10K divider suggested in the W83781D datasheet) */
LM78_NEG_VOLTAGE(12000, 2100), /* -12V */
LM78_NEG_VOLTAGE(5000, 909), /* -5V */
RESISTOR_DIVIDER(5000, 51, 75), /* W83782D/AS99127F only: +5VSB (5.1K/7.5K divider suggested in the datasheet) */
3000, /* W83782D/AS99127F only: Vbat */
2500, /* AS99127F only: +2.5V */
1500, /* AS99127F only: +1.5V */
3000, /* AS99127F only: NVRAM */
3300 /* AS99127F only: +3.3VSB */
}
};
/* Set chip-specific default values. */
if (dev->local & LM78_AS99127F) {
/* AS99127F: different -12V Rin value (bruteforced) */
defaults.voltages[5] = LM78_NEG_VOLTAGE(12000, 2400);
timer_add(&dev->reset_timer, lm78_reset_timer, dev, 0);
lm78_nvram(dev, 0);
} else if (dev->local & LM78_W83782D) {
/* W83782D: different negative voltage formula */
defaults.voltages[5] = LM78_NEG_VOLTAGE2(12000, 232);
defaults.voltages[6] = LM78_NEG_VOLTAGE2(5000, 120);
}
hwm_values = defaults;
dev->values = &hwm_values;
/* Initialize secondary/tertiary LM75 sensors on Winbond. */
for (uint8_t i = 0; i <= 1; i++) {
if (dev->local & LM78_WINBOND) {
dev->lm75[i] = (device_t *) malloc(sizeof(device_t));
memcpy(dev->lm75[i], &lm75_w83781d_device, sizeof(device_t));
dev->lm75[i]->local = (i + 1) << 8;
if (dev->local & LM78_I2C)
dev->lm75[i]->local |= 0x48 + i;
device_add(dev->lm75[i]);
} else {
dev->lm75[i] = NULL;
}
}
lm78_reset(dev);
uint16_t isa_io = dev->local & 0xffff;
if (isa_io)
io_sethandler(isa_io, 8, lm78_isa_read, NULL, NULL, lm78_isa_write, NULL, NULL, dev);
return dev;
}
/* National Semiconductor LM78 on ISA and SMBus. */
const device_t lm78_device = {
.name = "National Semiconductor LM78 Hardware Monitor",
.internal_name = "lm78",
.flags = DEVICE_ISA,
.local = 0x290 | LM78_I2C,
.init = lm78_init,
.close = lm78_close,
.reset = lm78_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
/* Winbond W83781D on ISA and SMBus. */
const device_t w83781d_device = {
.name = "Winbond W83781D Hardware Monitor",
.internal_name = "w83781d",
.flags = DEVICE_ISA,
.local = 0x290 | LM78_I2C | LM78_W83781D,
.init = lm78_init,
.close = lm78_close,
.reset = lm78_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
/* Winbond W83781D on ISA and SMBus. */
const device_t w83781d_p5a_device = {
.name = "Winbond W83781D Hardware Monitor (ASUS P5A)",
.internal_name = "w83781d_p5a",
.flags = DEVICE_ISA,
.local = 0x290 | LM78_I2C | LM78_W83781D | LM78_P5A,
.init = lm78_init,
.close = lm78_close,
.reset = lm78_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
/* The AS99127F is an ASIC manufactured by Holtek for ASUS, containing an
I2C-only W83781D clone with additional voltages, GPIOs and fan control. */
const device_t as99127f_device = {
.name = "ASUS AS99127F Rev. 1 Hardware Monitor",
.internal_name = "as99137f",
.flags = DEVICE_ISA,
.local = LM78_I2C | LM78_AS99127F_REV1,
.init = lm78_init,
.close = lm78_close,
.reset = lm78_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
/* Rev. 2 is manufactured by Winbond and differs only in GPI registers. */
const device_t as99127f_rev2_device = {
.name = "ASUS AS99127F Rev. 2 Hardware Monitor",
.internal_name = "as99127f_rev2",
.flags = DEVICE_ISA,
.local = LM78_I2C | LM78_AS99127F_REV2,
.init = lm78_init,
.close = lm78_close,
.reset = lm78_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
/* Winbond W83782D on ISA and SMBus. */
const device_t w83782d_device = {
.name = "Winbond W83782D Hardware Monitor",
.internal_name = "w83783d",
.flags = DEVICE_ISA,
.local = 0x290 | LM78_I2C | LM78_W83782D,
.init = lm78_init,
.close = lm78_close,
.reset = lm78_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/device/hwm_lm78.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 9,409 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the PCjr cartridge emulation.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/timer.h>
#include <86box/plat.h>
#include <86box/ui.h>
#include <86box/mem.h>
#include <86box/machine.h>
#include <86box/cartridge.h>
typedef struct cart_t {
uint8_t *buf;
uint32_t base;
} cart_t;
char cart_fns[2][512];
static cart_t carts[2];
static mem_mapping_t cart_mappings[2];
#ifdef ENABLE_CARTRIDGE_LOG
int cartridge_do_log = ENABLE_CARTRIDGE_LOG;
static void
cartridge_log(const char *fmt, ...)
{
va_list ap;
if (cartridge_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define cartridge_log(fmt, ...)
#endif
static uint8_t
cart_read(uint32_t addr, void *priv)
{
const cart_t *dev = (cart_t *) priv;
return dev->buf[addr - dev->base];
}
static void
cart_load_error(int drive, UNUSED(char *fn))
{
cartridge_log("Cartridge: could not load '%s'\n", fn);
memset(cart_fns[drive], 0, sizeof(cart_fns[drive]));
ui_sb_update_icon_state(SB_CARTRIDGE | drive, 1);
}
static void
cart_image_close(int drive)
{
if (carts[drive].buf != NULL) {
free(carts[drive].buf);
carts[drive].buf = NULL;
}
carts[drive].base = 0x00000000;
mem_mapping_disable(&cart_mappings[drive]);
}
static void
cart_image_load(int drive, char *fn)
{
FILE *fp;
uint32_t size;
uint32_t base = 0x00000000;
cart_image_close(drive);
fp = fopen(fn, "rb");
if (fseek(fp, 0, SEEK_END) == -1)
fatal("cart_image_load(): Error seeking to the end of the file\n");
size = ftell(fp);
if (size < 0x1200) {
cartridge_log("cart_image_load(): File size %i is too small\n", size);
cart_load_error(drive, fn);
return;
}
if (size & 0x00000fff) {
size -= 0x00000200;
fseek(fp, 0x000001ce, SEEK_SET);
(void) !fread(&base, 1, 2, fp);
base <<= 4;
fseek(fp, 0x00000200, SEEK_SET);
carts[drive].buf = (uint8_t *) malloc(size);
memset(carts[drive].buf, 0x00, size);
(void) !fread(carts[drive].buf, 1, size, fp);
fclose(fp);
} else {
base = drive ? 0xe0000 : 0xd0000;
if (size == 32768)
base += 0x8000;
fseek(fp, 0x00000000, SEEK_SET);
carts[drive].buf = (uint8_t *) malloc(size);
memset(carts[drive].buf, 0x00, size);
(void) !fread(carts[drive].buf, 1, size, fp);
fclose(fp);
}
cartridge_log("cart_image_load(): %s at %08X-%08X\n", fn, base, base + size - 1);
carts[drive].base = base;
mem_mapping_set_addr(&cart_mappings[drive], base, size);
mem_mapping_set_exec(&cart_mappings[drive], carts[drive].buf);
mem_mapping_set_p(&cart_mappings[drive], &(carts[drive]));
}
static void
cart_load_common(int drive, char *fn, uint8_t hard_reset)
{
FILE *fp;
cartridge_log("Cartridge: loading drive %d with '%s'\n", drive, fn);
if (!fn)
return;
fp = plat_fopen(fn, "rb");
if (fp) {
fclose(fp);
strcpy(cart_fns[drive], fn);
cart_image_load(drive, cart_fns[drive]);
/* On the real PCjr, inserting a cartridge causes a reset
in order to boot from the cartridge. */
if (!hard_reset)
resetx86();
} else
cart_load_error(drive, fn);
}
void
cart_load(int drive, char *fn)
{
cart_load_common(drive, fn, 0);
}
void
cart_close(int drive)
{
cartridge_log("Cartridge: closing drive %d\n", drive);
cart_image_close(drive);
cart_fns[drive][0] = 0;
ui_sb_update_icon_state(SB_CARTRIDGE | drive, 1);
resetx86();
}
void
cart_reset(void)
{
cart_image_close(1);
cart_image_close(0);
if (!machine_has_cartridge(machine))
return;
for (uint8_t i = 0; i < 2; i++) {
mem_mapping_add(&cart_mappings[i], 0x000d0000, 0x00002000,
cart_read, NULL, NULL,
NULL, NULL, NULL,
NULL, MEM_MAPPING_EXTERNAL, NULL);
mem_mapping_disable(&cart_mappings[i]);
}
cart_load_common(0, cart_fns[0], 1);
cart_load_common(1, cart_fns[1], 1);
}
``` | /content/code_sandbox/src/device/cartridge.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,354 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* ACPI emulation.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <stdbool.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include "cpu.h"
#include <86box/device.h>
#include <86box/mem.h>
#include <86box/io.h>
#include <86box/pci.h>
#include <86box/pic.h>
#include <86box/plat.h>
#include <86box/timer.h>
#include <86box/keyboard.h>
#include <86box/nvr.h>
#include <86box/pit.h>
#include <86box/apm.h>
#include <86box/acpi.h>
#include <86box/machine.h>
#include <86box/i2c.h>
#include <86box/video.h>
#include <86box/smbus.h>
#include <86box/hdc_ide.h>
#include <86box/hdc_ide_sff8038i.h>
#include <86box/sis_55xx.h>
int acpi_rtc_status = 0;
atomic_int acpi_pwrbut_pressed = 0;
int acpi_enabled = 0;
static double cpu_to_acpi;
static int acpi_power_on = 0;
static uint64_t acpi_last_clock = 0ULL;
static int acpi_count = 0;
#ifdef ENABLE_ACPI_LOG
int acpi_do_log = ENABLE_ACPI_LOG;
static void
acpi_log(const char *fmt, ...)
{
va_list ap;
if (acpi_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define acpi_log(fmt, ...)
#endif
static uint64_t
acpi_clock_get(void)
{
return tsc * cpu_to_acpi;
}
static uint32_t
acpi_timer_get(acpi_t *dev)
{
uint64_t clock = acpi_clock_get();
if (dev->regs.timer32)
return clock & 0xffffffff;
else
return clock & 0xffffff;
}
static uint8_t
acpi_gp_timer_get(acpi_t *dev)
{
uint64_t clock = acpi_clock_get();
clock -= acpi_last_clock;
if (clock >= acpi_count)
clock = 0x00;
else
clock &= 0xff;
return clock;
}
static double
acpi_get_overflow_period(acpi_t *dev)
{
uint64_t timer = acpi_clock_get();
uint64_t overflow_time;
if (dev->regs.timer32)
overflow_time = (timer + 0x80000000LL) & ~0x7fffffffLL;
else
overflow_time = (timer + 0x800000LL) & ~0x7fffffLL;
uint64_t time_to_overflow = overflow_time - timer;
return ((double) time_to_overflow / (double) ACPI_TIMER_FREQ) * 1000000.0;
}
static void
acpi_timer_update(acpi_t *dev, bool enable)
{
if (enable)
timer_on_auto(&dev->timer, acpi_get_overflow_period(dev));
else
timer_stop(&dev->timer);
}
static void
acpi_timer_overflow(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
dev->regs.pmsts |= TMROF_STS;
acpi_update_irq(dev);
acpi_timer_update(dev, (dev->regs.pmen & TMROF_EN) && !(dev->regs.pmsts & TMROF_STS));
}
static void
acpi_gp_timer_update(acpi_t *dev, bool enable, int count)
{
if (enable) {
acpi_last_clock = acpi_clock_get();
acpi_count = count;
timer_on_auto(&dev->gp_timer, (1000000.0 / (double) ACPI_TIMER_FREQ) * ((double) count));
} else
timer_stop(&dev->timer);
}
void
acpi_sis5595_smi_raise(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
if (dev->regs.leg_en & 0x20) {
dev->regs.leg_sts |= 0x20;
smi_raise();
}
}
static void
acpi_gp_timer(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
if (dev->vendor == VEN_SIS_5595_1997) {
dev->regs.gpe_sts |= 0x20000000;
dev->regs.leg_sts |= 0x20;
acpi_gp_timer_update(dev, (dev->regs.gpe_en & 0x20000000), acpi_count);
acpi_sis5595_smi_raise(dev);
} else if (dev->vendor == VEN_SIS_5595) {
dev->regs.gpe_sts |= 0x00000400;
dev->regs.leg_sts |= 0x20;
acpi_gp_timer_update(dev, (dev->regs.gpe_en & 0x00000400), acpi_count);
acpi_sis5595_smi_raise(dev);
} else {
dev->regs.reg_14 |= 0x2000;
acpi_gp_timer_update(dev, (dev->regs.reg_16 & 0x2000), acpi_count);
smi_raise();
}
}
static void
acpi_per_timer(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
if (dev->vendor >= VEN_SIS_5595_1997) {
dev->regs.leg_sts |= 0x04;
acpi_sis5595_smi_raise(dev);
} else {
dev->regs.reg_25 |= 0x04;
smi_raise();
}
timer_on_auto(&dev->per_timer, 16000000.0);
}
void
acpi_update_irq(acpi_t *dev)
{
int sci_level = (dev->regs.pmsts & dev->regs.pmen) & (RTC_EN | PWRBTN_EN | GBL_EN | TMROF_EN);
sis_55xx_common_t *sis = (sis_55xx_common_t *) dev->priv;
switch (dev->vendor) {
case VEN_SMC:
sci_level |= (dev->regs.pmsts & BM_STS);
break;
case VEN_SIS_5595_1997:
case VEN_SIS_5595:
if ((sis != NULL) && (sis->pmu_regs != NULL)) {
sci_level |= (sis->pmu_regs[0x80] | sis->pmu_regs[0x81] |
sis->pmu_regs[0x82] | sis->pmu_regs[0x83]);
}
break;
}
if ((dev->regs.pmcntrl & 0x01) && sci_level) switch (dev->irq_mode) {
default:
picintlevel(1 << dev->irq_line, &dev->irq_state);
break;
case 1:
pci_set_irq(dev->slot, dev->irq_pin, &dev->irq_state);
break;
case 2:
pci_set_mirq(5, dev->mirq_is_level, &dev->irq_state);
break;
case -1:
break;
} else switch (dev->irq_mode) {
default:
picintclevel(1 << dev->irq_line, &dev->irq_state);
break;
case 1:
pci_clear_irq(dev->slot, dev->irq_pin, &dev->irq_state);
break;
case 2:
pci_clear_mirq(5, dev->mirq_is_level, &dev->irq_state);
break;
case -1:
break;
}
}
void
acpi_raise_smi(void *priv, int do_smi)
{
acpi_t *dev = (acpi_t *) priv;
if (dev->regs.glbctl & 0x01) {
if ((dev->vendor == VEN_VIA) || (dev->vendor == VEN_VIA_596B)) {
if (!dev->regs.smi_lock || !dev->regs.smi_active) {
if (do_smi)
smi_raise();
dev->regs.smi_active = 1;
}
} else if ((dev->vendor == VEN_INTEL) || (dev->vendor == VEN_ALI)) {
if (do_smi)
smi_raise();
/* Clear bit 16 of GLBCTL. */
if (dev->vendor == VEN_INTEL)
dev->regs.glbctl &= ~0x00010000;
else
dev->regs.ali_soft_smi = 1;
} else if (dev->vendor == VEN_SMC) {
if (do_smi)
smi_raise();
}
}
}
static uint32_t
acpi_reg_read_common_regs(UNUSED(int size), uint16_t addr, void *priv)
{
acpi_t *dev = (acpi_t *) priv;
uint32_t ret = 0x00000000;
int shift16;
int shift32;
addr &= 0x3f;
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x00:
case 0x01:
/* PMSTS - Power Management Status Register (IO) */
ret = (dev->regs.pmsts >> shift16) & 0xff;
if (addr == 0x01)
ret |= (acpi_rtc_status << 2);
break;
case 0x02:
case 0x03:
/* PMEN - Power Management Resume Enable Register (IO) */
ret = (dev->regs.pmen >> shift16) & 0xff;
break;
case 0x04:
case 0x05:
/* PMCNTRL - Power Management Control Register (IO) */
ret = (dev->regs.pmcntrl >> shift16) & 0xff;
if (addr == 0x05)
ret = (ret & 0xdf); /* Bit 5 is write-only. */
break;
case 0x08:
case 0x09:
case 0x0a:
case 0x0b:
/* PMTMR - Power Management Timer Register (IO) */
ret = (acpi_timer_get(dev) >> shift32) & 0xff;
#ifdef USE_DYNAREC
if (cpu_use_dynarec)
update_tsc();
#endif
break;
default:
break;
}
#ifdef ENABLE_ACPI_LOG
if (size != 1)
acpi_log("(%i) ACPI Read (%i) %02X: %02X\n", in_smm, size, addr, ret);
#endif
return ret;
}
static uint32_t
acpi_reg_read_ali(int size, uint16_t addr, void *priv)
{
const acpi_t *dev = (acpi_t *) priv;
uint32_t ret = 0x00000000;
int shift16;
int shift32;
addr &= 0x3f;
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x10:
case 0x11:
case 0x12:
case 0x13:
/* PCNTRL - Processor Control Register (IO) */
ret = (dev->regs.pcntrl >> shift16) & 0xff;
break;
case 0x14:
/* LVL2 - Processor Level 2 Register */
ret = dev->regs.plvl2;
break;
case 0x15:
/* LVL3 - Processor Level 3 Register */
ret = dev->regs.plvl3;
break;
case 0x18:
case 0x19:
/* GPE0_STS - General Purpose Event0 Status Register */
ret = (dev->regs.gpsts >> shift16) & 0xff;
break;
case 0x1a:
case 0x1b:
/* GPE0_EN - General Purpose Event0 Enable Register */
ret = (dev->regs.gpen >> shift16) & 0xff;
break;
case 0x1d:
case 0x1c:
/* GPE1_STS - General Purpose Event1 Status Register */
ret = (dev->regs.gpsts1 >> shift16) & 0xff;
break;
case 0x1f:
case 0x1e:
/* GPE1_EN - General Purpose Event1 Enable Register */
ret = (dev->regs.gpen1 >> shift16) & 0xff;
break;
case 0x20 ... 0x27:
/* GPE1_CTL - General Purpose Event1 Control Register */
ret = (dev->regs.gpcntrl >> shift32) & 0xff;
break;
case 0x30:
/* PM2_CNTRL - Power Management 2 Control Register( */
ret = dev->regs.pmcntrl;
break;
default:
ret = acpi_reg_read_common_regs(size, addr, priv);
break;
}
#ifdef ENABLE_ACPI_LOG
if (size != 1)
acpi_log("(%i) ACPI Read (%i) %02X: %02X\n", in_smm, size, addr, ret);
#endif
return ret;
}
static uint32_t
acpi_reg_read_intel(int size, uint16_t addr, void *priv)
{
const acpi_t *dev = (acpi_t *) priv;
uint32_t ret = 0x00000000;
int shift16;
int shift32;
addr &= 0x3f;
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x0c:
case 0x0d:
/* GPSTS - General Purpose Status Register (IO) */
ret = (dev->regs.gpsts >> shift16) & 0xff;
break;
case 0x0e:
case 0x0f:
/* GPEN - General Purpose Enable Register (IO) */
ret = (dev->regs.gpen >> shift16) & 0xff;
break;
case 0x10:
case 0x11:
case 0x12:
case 0x13:
/* PCNTRL - Processor Control Register (IO) */
ret = (dev->regs.pcntrl >> shift32) & 0xff;
break;
case 0x18:
case 0x19:
/* GLBSTS - Global Status Register (IO) */
ret = (dev->regs.glbsts >> shift16) & 0xff;
if (addr == 0x18) {
ret &= 0x27;
if (dev->regs.gpsts != 0x0000)
ret |= 0x80;
if (dev->regs.pmsts != 0x0000)
ret |= 0x40;
if (dev->regs.devsts != 0x00000000)
ret |= 0x10;
}
break;
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
/* DEVSTS - Device Status Register (IO) */
ret = (dev->regs.devsts >> shift32) & 0xff;
break;
case 0x20:
case 0x21:
/* GLBEN - Global Enable Register (IO) */
ret = (dev->regs.glben >> shift16) & 0xff;
break;
case 0x28:
case 0x29:
case 0x2a:
case 0x2b:
/* GLBCTL - Global Control Register (IO) */
ret = (dev->regs.glbctl >> shift32) & 0xff;
break;
case 0x2c:
case 0x2d:
case 0x2e:
case 0x2f:
/* DEVCTL - Device Control Register (IO) */
ret = (dev->regs.devctl >> shift32) & 0xff;
break;
case 0x30:
case 0x31:
case 0x32:
/* GPIREG - General Purpose Input Register (IO) */
if (size == 1)
ret = dev->regs.gpireg[addr & 3];
break;
case 0x34:
case 0x35:
case 0x36:
case 0x37:
/* GPOREG - General Purpose Output Register (IO) */
if (size == 1)
ret = dev->regs.gporeg[addr & 3];
break;
default:
ret = acpi_reg_read_common_regs(size, addr, priv);
break;
}
#ifdef ENABLE_ACPI_LOG
// if (size != 1)
// acpi_log("(%i) ACPI Read (%i) %02X: %02X\n", in_smm, size, addr, ret);
#endif
return ret;
}
static uint32_t
acpi_reg_read_via_common(int size, uint16_t addr, void *priv)
{
const acpi_t *dev = (acpi_t *) priv;
uint32_t ret = 0x00000000;
int shift16;
int shift32;
addr &= 0xff;
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x10:
case 0x11:
case 0x12:
case 0x13:
/* PCNTRL - Processor Control Register (IO) */
ret = (dev->regs.pcntrl >> shift32) & 0xff;
break;
case 0x20:
case 0x21:
/* GPSTS - General Purpose Status Register (IO) */
ret = (dev->regs.gpsts >> shift16) & 0xff;
break;
case 0x22:
case 0x23:
/* General Purpose SCI Enable */
ret = (dev->regs.gpscien >> shift16) & 0xff;
break;
case 0x24:
case 0x25:
/* General Purpose SMI Enable */
ret = (dev->regs.gpsmien >> shift16) & 0xff;
break;
case 0x26:
case 0x27:
/* Power Supply Control */
ret = (dev->regs.pscntrl >> shift16) & 0xff;
break;
case 0x28:
case 0x29:
/* GLBSTS - Global Status Register (IO) */
ret = (dev->regs.glbsts >> shift16) & 0xff;
break;
case 0x2a:
case 0x2b:
/* GLBEN - Global Enable Register (IO) */
ret = (dev->regs.glben >> shift16) & 0xff;
break;
case 0x2c:
case 0x2d:
/* GLBCTL - Global Control Register (IO) */
ret = (dev->regs.glbctl >> shift16) & 0xff;
ret &= ~0x0110;
ret |= (dev->regs.smi_lock ? 0x10 : 0x00);
ret |= (dev->regs.smi_active ? 0x01 : 0x00);
break;
case 0x2f:
/* SMI Command */
if (size == 1)
ret = dev->regs.smicmd & 0xff;
break;
case 0x30:
case 0x31:
case 0x32:
case 0x33:
/* Primary Activity Detect Status */
ret = (dev->regs.padsts >> shift32) & 0xff;
break;
case 0x34:
case 0x35:
case 0x36:
case 0x37:
/* Primary Activity Detect Enable */
ret = (dev->regs.paden >> shift32) & 0xff;
break;
case 0x38:
case 0x39:
case 0x3a:
case 0x3b:
/* GP Timer Reload Enable */
ret = (dev->regs.gptren >> shift32) & 0xff;
break;
default:
ret = acpi_reg_read_common_regs(size, addr, priv);
break;
}
#ifdef ENABLE_ACPI_LOG
if (size != 1)
acpi_log("(%i) ACPI Read (%i) %02X: %02X\n", in_smm, size, addr, ret);
#endif
return ret;
}
static uint32_t
acpi_reg_read_via(int size, uint16_t addr, void *priv)
{
acpi_t *dev = (acpi_t *) priv;
uint32_t ret = 0x00000000;
int shift16;
addr &= 0xff;
shift16 = (addr & 1) << 3;
switch (addr) {
case 0x40:
/* GPIO Direction Control */
if (size == 1)
ret = dev->regs.gpio_dir & 0xff;
break;
case 0x42:
/* GPIO port Output Value */
if (size == 1)
ret = dev->regs.gpio_val & 0x13;
break;
case 0x44:
/* GPIO port Input Value */
if (size == 1) {
ret = dev->regs.extsmi_val & 0xff;
if (dev->i2c) {
ret &= 0xf9;
if (!(dev->regs.gpio_dir & 0x02) && i2c_gpio_get_scl(dev->i2c))
ret |= 0x02;
if (!(dev->regs.gpio_dir & 0x04) && i2c_gpio_get_sda(dev->i2c))
ret |= 0x04;
}
}
break;
case 0x46:
case 0x47:
/* GPO Port Output Value */
ret = (dev->regs.gpo_val >> shift16) & 0xff;
break;
case 0x48:
case 0x49:
/* GPO Port Input Value */
ret = (dev->regs.gpi_val >> shift16) & 0xff;
break;
default:
ret = acpi_reg_read_via_common(size, addr, priv);
break;
}
#ifdef ENABLE_ACPI_LOG
if (size != 1)
acpi_log("(%i) ACPI Read (%i) %02X: %02X\n", in_smm, size, addr, ret);
#endif
return ret;
}
static uint32_t
acpi_reg_read_via_596b(int size, uint16_t addr, void *priv)
{
const acpi_t *dev = (acpi_t *) priv;
uint32_t ret = 0x00000000;
int shift16;
int shift32;
addr &= 0x7f;
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x40: /* Extended I/O Trap Status (686A/B) */
ret = dev->regs.extiotrapsts;
break;
case 0x42: /* Extended I/O Trap Enable (686A/B) */
ret = dev->regs.extiotrapen;
break;
case 0x44:
case 0x45:
/* External SMI Input Value */
ret = (dev->regs.extsmi_val >> shift16) & 0xff;
break;
case 0x48:
case 0x49:
case 0x4a:
case 0x4b:
/* GPI Port Input Value */
ret = (dev->regs.gpi_val >> shift32) & 0xff;
break;
case 0x4c:
case 0x4d:
case 0x4e:
case 0x4f:
/* GPO Port Output Value */
ret = (dev->regs.gpo_val >> shift32) & 0xff;
break;
default:
ret = acpi_reg_read_via_common(size, addr, priv);
break;
}
#ifdef ENABLE_ACPI_LOG
if (size != 1)
acpi_log("(%i) ACPI Read (%i) %02X: %02X\n", in_smm, size, addr, ret);
#endif
return ret;
}
static uint32_t
acpi_reg_read_smc(int size, uint16_t addr, void *priv)
{
uint32_t ret = 0x00000000;
addr &= 0x0f;
ret = acpi_reg_read_common_regs(size, addr, priv);
#ifdef ENABLE_ACPI_LOG
if (size != 1)
acpi_log("(%i) ACPI Read (%i) %02X: %02X\n", in_smm, size, addr, ret);
#endif
return ret;
}
static uint32_t
acpi_aux_reg_read_smc(UNUSED(int size), uint16_t addr, void *priv)
{
const acpi_t *dev = (acpi_t *) priv;
uint32_t ret = 0x00000000;
int shift16;
addr &= 0x07;
shift16 = (addr & 1) << 3;
switch (addr) {
case 0x00:
case 0x01:
/* SCI Status Register */
ret = (dev->regs.pcntrl >> shift16) & 0xff;
break;
case 0x02:
case 0x03:
/* SCI Enable Register */
ret = (dev->regs.gpscien >> shift16) & 0xff;
break;
case 0x04:
case 0x05:
/* Miscellaneous Status Register */
ret = (dev->regs.glbsts >> shift16) & 0xff;
break;
case 0x06:
/* Miscellaneous Enable Register */
ret = dev->regs.glben & 0xff;
break;
case 0x07:
/* Miscellaneous Control Register */
ret = dev->regs.glbctl & 0xff;
break;
default:
break;
}
acpi_log("(%i) ACPI Read (%i) %02X: %02X\n", in_smm, size, addr, ret);
return ret;
}
static uint32_t
acpi_reg_read_sis_5582(int size, uint16_t addr, void *priv)
{
const acpi_t *dev = (acpi_t *) priv;
uint32_t ret = 0x00000000;
int shift16;
int shift32;
addr &= 0x3f;
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x0c:
case 0x0d:
case 0x0e:
case 0x0f:
ret = (dev->regs.reg_0c >> shift32) & 0xff;
break;
case 0x10:
ret = dev->regs.enter_c2_ps;
break;
case 0x11:
ret = dev->regs.enter_c3_ps;
break;
case 0x12:
ret = dev->regs.reg_12;
break;
case 0x13:
ret = acpi_gp_timer_get((acpi_t *) dev) & 0xff;
#ifdef USE_DYNAREC
if (cpu_use_dynarec)
update_tsc();
#endif
break;
case 0x14:
case 0x15:
ret = (dev->regs.reg_14 >> shift16) & 0xff;
break;
case 0x16:
case 0x17:
ret = (dev->regs.reg_16 >> shift16) & 0xff;
break;
case 0x18:
case 0x19:
ret = (dev->regs.reg_18 >> shift16) & 0xff;
break;
case 0x1a:
case 0x1b:
ret = (dev->regs.reg_18 >> shift16) & 0xff;
break;
case 0x1c:
case 0x1d:
ret = (dev->regs.reg_1c >> shift16) & 0xff;
break;
case 0x20:
ret = dev->regs.smi_cmd;
break;
case 0x24:
ret = dev->regs.reg_24;
break;
case 0x25:
ret = dev->regs.reg_25;
break;
case 0x26:
ret = dev->regs.reg_26;
break;
case 0x28:
ret = dev->regs.smi_en_val;
break;
case 0x29:
ret = dev->regs.smi_dis_val;
break;
case 0x2a:
ret = dev->regs.mail_box;
break;
case 0x2b:
ret = dev->regs.reg_2b;
break;
default:
ret = acpi_reg_read_common_regs(size, addr, priv);
break;
}
#ifdef ENABLE_ACPI_LOG
// if (size != 1)
// acpi_log("(%i) ACPI Read (%i) %02X: %02X\n", in_smm, size, addr, ret);
#endif
return ret;
}
static uint32_t
acpi_reg_read_sis_5595(int size, uint16_t addr, void *priv)
{
const acpi_t *dev = (acpi_t *) priv;
uint32_t ret = 0x00000000;
int shift16;
int shift32;
addr &= 0x3f;
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x0c:
case 0x0d:
case 0x0e:
case 0x0f:
ret = (dev->regs.reg_0c >> shift32) & 0xff;
break;
case 0x10:
ret = dev->regs.enter_c2_ps;
break;
case 0x11:
ret = dev->regs.enter_c3_ps;
break;
case 0x12:
ret = dev->regs.reg_12;
break;
case 0x13:
ret = dev->regs.reg_13;
break;
case 0x14:
case 0x15:
case 0x16:
case 0x17:
ret = (dev->regs.gpe_sts >> shift32) & 0xff;
break;
case 0x18:
case 0x19:
case 0x1a:
case 0x1b:
ret = (dev->regs.gpe_en >> shift32) & 0xff;
break;
case 0x1c:
case 0x1d:
case 0x1e:
ret = (dev->regs.gpe_pin >> shift32) & 0xff;
break;
case 0x1f:
ret = acpi_gp_timer_get((acpi_t *) dev) & 0xff;
#ifdef USE_DYNAREC
if (cpu_use_dynarec)
update_tsc();
#endif
break;
case 0x20:
case 0x21:
case 0x22:
case 0x23:
ret = (dev->regs.gpe_io >> shift32) & 0xff;
break;
case 0x24:
case 0x25:
case 0x26:
case 0x27:
ret = (dev->regs.gpe_pol >> shift32) & 0xff;
break;
case 0x28:
case 0x29:
ret = (dev->regs.gpe_mul >> shift16) & 0xff;
break;
case 0x2a:
case 0x2b:
ret = (dev->regs.gpe_ctl >> shift16) & 0xff;
break;
case 0x2c:
case 0x2d:
ret = (dev->regs.gpe_smi >> shift16) & 0xff;
break;
case 0x2e:
case 0x2f:
ret = (dev->regs.gpe_rl >> shift16) & 0xff;
break;
case 0x30:
ret = dev->regs.leg_sts;
break;
case 0x31:
ret = dev->regs.leg_en;
break;
case 0x32:
if (dev->vendor == VEN_SIS_5595_1997)
ret = dev->regs.smi_cmd;
else
ret = 0x00;
break;
case 0x33:
ret = dev->regs.tst_ctl;
break;
case 0x34:
if (dev->vendor == VEN_SIS_5595_1997)
ret = dev->regs.smi_en_val;
else
ret = dev->regs.reg_34;
break;
case 0x35:
if (dev->vendor == VEN_SIS_5595_1997)
ret = dev->regs.smi_dis_val;
else
ret = dev->regs.smi_cmd;
break;
case 0x36:
ret = dev->regs.mail_box;
break;
case 0x38:
if (dev->vendor == VEN_SIS_5595)
ret = smbus_sis5595_read_index(dev->smbus);
break;
case 0x39:
if (dev->vendor == VEN_SIS_5595)
ret = smbus_sis5595_read_data(dev->smbus);
break;
default:
ret = acpi_reg_read_common_regs(size, addr, priv);
break;
}
#ifdef ENABLE_ACPI_LOG
// if (size != 1)
// acpi_log("(%i) ACPI Read (%i) %02X: %02X\n", in_smm, size, addr, ret);
#endif
return ret;
}
static void
acpi_reg_write_common_regs(UNUSED(int size), uint16_t addr, uint8_t val, void *priv)
{
acpi_t *dev = (acpi_t *) priv;
int shift16;
int sus_typ;
uint8_t old;
addr &= 0x3f;
#ifdef ENABLE_ACPI_LOG
if (size != 1)
acpi_log("(%i) ACPI Write (%i) %02X: %02X\n", in_smm, size, addr, val);
#endif
shift16 = (addr & 1) << 3;
switch (addr) {
case 0x00:
case 0x01:
/* PMSTS - Power Management Status Register (IO) */
dev->regs.pmsts &= ~((val << shift16) & 0x8d31);
if ((addr == 0x01) && (val & 0x04))
acpi_rtc_status = 0;
acpi_update_irq(dev);
break;
case 0x02:
case 0x03:
/* PMEN - Power Management Resume Enable Register (IO) */
dev->regs.pmen = ((dev->regs.pmen & ~(0xff << shift16)) | (val << shift16)) & 0x0521;
acpi_update_irq(dev);
break;
case 0x04:
case 0x05:
/* PMCNTRL - Power Management Control Register (IO) */
old = dev->regs.pmcntrl & 0xff;
if ((addr == 0x05) && (val & 0x20)) {
sus_typ = dev->suspend_types[(val >> 2) & 7];
acpi_log("ACPI suspend type %d flags %02X\n", (val >> 2) & 7, sus_typ);
if (sus_typ & SUS_POWER_OFF) {
/* Soft power off. */
plat_power_off();
return;
}
if (sus_typ & SUS_SUSPEND) {
if (sus_typ & SUS_NVR) {
/* Suspend to RAM. */
nvr_reg_write(0x000f, 0xff, dev->nvr);
}
if (sus_typ & SUS_RESET_PCI)
device_reset_all(DEVICE_PCI);
if (sus_typ & SUS_RESET_CPU)
cpu_alt_reset = 0;
if (sus_typ & SUS_RESET_PCI) {
pci_reset();
mem_a20_alt = 0;
mem_a20_recalc();
}
if (sus_typ & (SUS_RESET_CPU | SUS_RESET_CACHE))
flushmmucache();
if (sus_typ & SUS_RESET_CPU)
resetx86();
/* Since the UI doesn't have a power button at the moment, pause emulation,
then trigger a resume event so that the system resumes after unpausing. */
plat_pause(2); /* 2 means do not wait for pause as
we're already in the CPU thread. */
timer_set_delay_u64(&dev->resume_timer, 50 * TIMER_USEC);
}
}
dev->regs.pmcntrl = ((dev->regs.pmcntrl & ~(0xff << shift16)) | (val << shift16)) & 0x3f07 /* 0x3c07 */;
if ((addr == 0x04) && ((old ^ val) & 0x01))
acpi_update_irq(dev);
break;
default:
break;
}
}
static void
acpi_reg_write_ali(int size, uint16_t addr, uint8_t val, void *priv)
{
acpi_t *dev = (acpi_t *) priv;
int shift16;
int shift32;
addr &= 0x3f;
#ifdef ENABLE_ACPI_LOG
if (size != 1)
acpi_log("(%i) ACPI Write (%i) %02X: %02X\n", in_smm, size, addr, val);
#endif
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x10:
case 0x11:
case 0x12:
case 0x13:
/* PCNTRL - Processor Control Register (IO) */
dev->regs.pcntrl = ((dev->regs.pcntrl & ~(0xff << shift32)) | (val << shift32)) & 0x00023e1e;
break;
case 0x14:
/* LVL2 - Processor Level 2 Register */
dev->regs.plvl2 = val;
break;
case 0x15:
/* LVL3 - Processor Level 3 Register */
dev->regs.plvl3 = val;
break;
case 0x18:
case 0x19:
/* GPE0_STS - General Purpose Event0 Status Register */
dev->regs.gpsts &= ~((val << shift16) & 0x0d07);
break;
case 0x1a:
case 0x1b:
/* GPE0_EN - General Purpose Event0 Enable Register */
dev->regs.gpen = ((dev->regs.gpen & ~(0xff << shift16)) | (val << shift16)) & 0x0d07;
break;
case 0x1d:
case 0x1c:
/* GPE1_STS - General Purpose Event1 Status Register */
dev->regs.gpsts1 &= ~((val << shift16) & 0x0c01);
break;
case 0x1f:
case 0x1e:
/* GPE1_EN - General Purpose Event1 Enable Register */
dev->regs.gpen1 = ((dev->regs.gpen & ~(0xff << shift16)) | (val << shift16)) & 0x0c01;
break;
case 0x20 ... 0x27:
/* GPE1_CTL - General Purpose Event1 Control Register */
dev->regs.gpcntrl = ((dev->regs.gpcntrl & ~(0xff << shift32)) | (val << shift32)) & 0x00000001;
break;
case 0x30:
/* PM2_CNTRL - Power Management 2 Control Register */
dev->regs.pmcntrl = val & 1;
break;
default:
acpi_reg_write_common_regs(size, addr, val, priv);
/* Setting GBL_RLS also sets BIOS_STS and generates SMI. */
if ((addr == 0x00) && !(dev->regs.pmsts & 0x20))
dev->regs.gpcntrl &= ~0x0002;
else if ((addr == 0x04) && (dev->regs.pmcntrl & 0x0004)) {
dev->regs.gpsts1 |= 0x01;
if (dev->regs.gpen1 & 0x01)
acpi_raise_smi(dev, 1);
}
}
}
static void
acpi_reg_write_intel(int size, uint16_t addr, uint8_t val, void *priv)
{
acpi_t *dev = (acpi_t *) priv;
int shift16;
int shift32;
addr &= 0x3f;
#ifdef ENABLE_ACPI_LOG
if (size != 1)
acpi_log("(%i) ACPI Write (%i) %02X: %02X\n", in_smm, size, addr, val);
#endif
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x0c:
case 0x0d:
/* GPSTS - General Purpose Status Register (IO) */
dev->regs.gpsts &= ~((val << shift16) & 0x0f81);
break;
case 0x0e:
case 0x0f:
/* GPEN - General Purpose Enable Register (IO) */
dev->regs.gpen = ((dev->regs.gpen & ~(0xff << shift16)) | (val << shift16)) & 0x0f01;
break;
case 0x10:
case 0x11:
case 0x13:
/* PCNTRL - Processor Control Register (IO) */
dev->regs.pcntrl = ((dev->regs.pcntrl & ~(0xff << shift32)) | (val << shift32)) & 0x00023e1e;
break;
case 0x12:
/* PCNTRL - Processor Control Register (IO) */
dev->regs.pcntrl = ((dev->regs.pcntrl & ~(0xfd << shift32)) | (val << shift32)) & 0x00023e1e;
break;
case 0x18:
case 0x19:
/* GLBSTS - Global Status Register (IO) */
dev->regs.glbsts &= ~((val << shift16) & 0x0d27);
break;
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
/* DEVSTS - Device Status Register (IO) */
dev->regs.devsts &= ~((val << shift32) & 0x3fff0fff);
break;
case 0x20:
case 0x21:
/* GLBEN - Global Enable Register (IO) */
dev->regs.glben = ((dev->regs.glben & ~(0xff << shift16)) | (val << shift16)) & 0x8d1f;
break;
case 0x28:
case 0x29:
case 0x2a:
case 0x2b:
/* GLBCTL - Global Control Register (IO) */
dev->regs.glbctl = ((dev->regs.glbctl & ~(0xff << shift32)) | (val << shift32)) & 0x0701ff07;
/* Setting BIOS_RLS also sets GBL_STS and generates SMI. */
if (dev->regs.glbctl & 0x00000002) {
dev->regs.pmsts |= 0x20;
if (dev->regs.pmen & 0x20)
acpi_update_irq(dev);
}
break;
case 0x2c:
case 0x2d:
case 0x2e:
case 0x2f:
/* DEVCTL - Device Control Register (IO) */
dev->regs.devctl = ((dev->regs.devctl & ~(0xff << shift32)) | (val << shift32)) & 0x0fffffff;
if (dev->trap_update)
dev->trap_update(dev->trap_priv);
break;
case 0x34:
case 0x35:
case 0x36:
case 0x37:
/* GPOREG - General Purpose Output Register (IO) */
if (size == 1)
dev->regs.gporeg[addr & 3] = val;
break;
default:
acpi_reg_write_common_regs(size, addr, val, priv);
/* Setting GBL_RLS also sets BIOS_STS and generates SMI. */
if ((addr == 0x00) && !(dev->regs.pmsts & 0x20))
dev->regs.glbctl &= ~0x0002;
else if ((addr == 0x04) && (dev->regs.pmcntrl & 0x0004)) {
dev->regs.glbsts |= 0x01;
if (dev->regs.glben & 0x02)
acpi_raise_smi(dev, 1);
}
break;
}
}
static void
acpi_reg_write_via_common(int size, uint16_t addr, uint8_t val, void *priv)
{
acpi_t *dev = (acpi_t *) priv;
int shift16;
int shift32;
addr &= 0xff;
acpi_log("(%i) ACPI Write (%i) %02X: %02X\n", in_smm, size, addr, val);
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x10:
case 0x11:
case 0x12:
case 0x13:
/* PCNTRL - Processor Control Register (IO) */
dev->regs.pcntrl = ((dev->regs.pcntrl & ~(0xff << shift32)) | (val << shift32)) & 0x0000001e;
break;
case 0x20:
case 0x21:
/* GPSTS - General Purpose Status Register (IO) */
dev->regs.gpsts &= ~((val << shift16) & 0x03ff);
break;
case 0x22:
case 0x23:
/* General Purpose SCI Enable */
dev->regs.gpscien = ((dev->regs.gpscien & ~(0xff << shift16)) | (val << shift16)) & 0x03ff;
break;
case 0x24:
case 0x25:
/* General Purpose SMI Enable */
dev->regs.gpsmien = ((dev->regs.gpsmien & ~(0xff << shift16)) | (val << shift16)) & 0x03ff;
break;
case 0x26:
case 0x27:
/* Power Supply Control */
dev->regs.pscntrl = ((dev->regs.pscntrl & ~(0xff << shift16)) | (val << shift16)) & 0x0701;
break;
case 0x2c:
/* GLBCTL - Global Control Register (IO) */
dev->regs.glbctl = (dev->regs.glbctl & ~0xff) | (val & 0xff);
dev->regs.smi_lock = !!(dev->regs.glbctl & 0x0010);
/* Setting BIOS_RLS also sets GBL_STS and generates SMI. */
if (dev->regs.glbctl & 0x0002) {
dev->regs.pmsts |= 0x20;
if (dev->regs.pmen & 0x20)
acpi_update_irq(dev);
}
break;
case 0x2d:
/* GLBCTL - Global Control Register (IO) */
dev->regs.glbctl &= ~((val << 8) & 0x0100);
if (val & 0x01)
dev->regs.smi_active = 0;
break;
case 0x2f:
/* SMI Command */
if (size == 1) {
dev->regs.smicmd = val & 0xff;
dev->regs.glbsts |= 0x40;
if (dev->regs.glben & 0x40)
acpi_raise_smi(dev, 1);
}
break;
case 0x38:
case 0x39:
case 0x3a:
case 0x3b:
/* GP Timer Reload Enable */
dev->regs.gptren = ((dev->regs.gptren & ~(0xff << shift32)) | (val << shift32)) & 0x000000d9;
break;
default:
acpi_reg_write_common_regs(size, addr, val, priv);
/* Setting GBL_RLS also sets BIOS_STS and generates SMI. */
if ((addr == 0x00) && !(dev->regs.pmsts & 0x20))
dev->regs.glbctl &= ~0x0002;
else if ((addr == 0x04) && (dev->regs.pmcntrl & 0x0004)) {
dev->regs.glbsts |= 0x20;
if (dev->regs.glben & 0x20)
acpi_raise_smi(dev, 1);
}
break;
}
}
static void
acpi_i2c_set(acpi_t *dev)
{
if (dev->i2c)
i2c_gpio_set(dev->i2c, !(dev->regs.gpio_dir & 0x02) || (dev->regs.gpio_val & 0x02), !(dev->regs.gpio_dir & 0x04) || (dev->regs.gpio_val & 0x04));
}
static void
acpi_reg_write_via(int size, uint16_t addr, uint8_t val, void *priv)
{
acpi_t *dev = (acpi_t *) priv;
int shift16;
int shift32;
addr &= 0xff;
acpi_log("(%i) ACPI Write (%i) %02X: %02X\n", in_smm, size, addr, val);
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x28:
case 0x29:
/* GLBSTS - Global Status Register (IO) */
dev->regs.glbsts &= ~((val << shift16) & 0x007f);
break;
case 0x2a:
case 0x2b:
/* GLBEN - Global Enable Register (IO) */
dev->regs.glben = ((dev->regs.glben & ~(0xff << shift16)) | (val << shift16)) & 0x007f;
break;
case 0x30:
case 0x31:
case 0x32:
case 0x33:
/* Primary Activity Detect Status */
dev->regs.padsts &= ~((val << shift32) & 0x000000fd);
break;
case 0x34:
case 0x35:
case 0x36:
case 0x37:
/* Primary Activity Detect Enable */
dev->regs.paden = ((dev->regs.paden & ~(0xff << shift32)) | (val << shift32)) & 0x000000fd;
if (dev->trap_update)
dev->trap_update(dev->trap_priv);
break;
case 0x40:
/* GPIO Direction Control */
if (size == 1) {
dev->regs.gpio_dir = val & 0x7f;
acpi_i2c_set(dev);
}
break;
case 0x42:
/* GPIO port Output Value */
if (size == 1) {
dev->regs.gpio_val = val & 0x13;
acpi_i2c_set(dev);
}
break;
case 0x46:
case 0x47:
/* GPO Port Output Value */
dev->regs.gpo_val = ((dev->regs.gpo_val & ~(0xff << shift16)) | (val << shift16)) & 0xffff;
break;
default:
acpi_reg_write_via_common(size, addr, val, priv);
break;
}
}
static void
acpi_reg_write_via_596b(int size, uint16_t addr, uint8_t val, void *priv)
{
acpi_t *dev = (acpi_t *) priv;
int shift16;
int shift32;
addr &= 0x7f;
acpi_log("(%i) ACPI Write (%i) %02X: %02X\n", in_smm, size, addr, val);
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x28:
case 0x29:
/* GLBSTS - Global Status Register (IO) */
dev->regs.glbsts &= ~((val << shift16) & 0xfdff);
break;
case 0x2a:
case 0x2b:
/* GLBEN - Global Enable Register (IO) */
dev->regs.glben = ((dev->regs.glben & ~(0xff << shift16)) | (val << shift16)) & 0xfdff;
break;
case 0x30:
case 0x31:
case 0x32:
case 0x33:
/* Primary Activity Detect Status */
dev->regs.padsts &= ~((val << shift32) & 0x000007ff);
break;
case 0x34:
case 0x35:
case 0x36:
case 0x37:
/* Primary Activity Detect Enable */
dev->regs.paden = ((dev->regs.paden & ~(0xff << shift32)) | (val << shift32)) & 0x000007ff;
if (dev->trap_update)
dev->trap_update(dev->trap_priv);
break;
case 0x40: /* Extended I/O Trap Status (686A/B) */
dev->regs.extiotrapsts &= ~(val & 0x13);
break;
case 0x42: /* Extended I/O Trap Enable (686A/B) */
dev->regs.extiotrapen = val & 0x13;
break;
case 0x4c:
case 0x4d:
case 0x4e:
case 0x4f:
/* GPO Port Output Value */
dev->regs.gpo_val = ((dev->regs.gpo_val & ~(0xff << shift32)) | (val << shift32)) & 0x7fffffff;
break;
default:
acpi_reg_write_via_common(size, addr, val, priv);
break;
}
}
static void
acpi_reg_write_smc(int size, uint16_t addr, uint8_t val, void *priv)
{
acpi_t *dev = (acpi_t *) priv;
addr &= 0x0f;
acpi_log("(%i) ACPI Write (%i) %02X: %02X\n", in_smm, size, addr, val);
acpi_reg_write_common_regs(size, addr, val, priv);
/* Setting GBL_RLS also sets BIOS_STS and generates SMI. */
if ((addr == 0x00) && !(dev->regs.pmsts & 0x20))
dev->regs.glbctl &= ~0x0001;
else if ((addr == 0x04) && (dev->regs.pmcntrl & 0x0004)) {
dev->regs.glbsts |= 0x01;
if (dev->regs.glben & 0x01)
acpi_raise_smi(dev, 1);
}
}
static void
acpi_aux_reg_write_smc(UNUSED(int size), uint16_t addr, uint8_t val, void *priv)
{
acpi_t *dev = (acpi_t *) priv;
int shift16;
addr &= 0x07;
acpi_log("(%i) ACPI Write (%i) %02X: %02X\n", in_smm, size, addr, val);
shift16 = (addr & 1) << 3;
switch (addr) {
case 0x00:
case 0x01:
/* SCI Status Register */
dev->regs.gpscists &= ~((val << shift16) & 0x000c);
break;
case 0x02:
case 0x03:
/* SCI Enable Register */
dev->regs.gpscien = ((dev->regs.gpscien & ~(0xff << shift16)) | (val << shift16)) & 0x3fff;
break;
case 0x04:
case 0x05:
/* Miscellanous Status Register */
dev->regs.glbsts &= ~((val << shift16) & 0x001f);
break;
case 0x06:
/* Miscellaneous Enable Register */
dev->regs.glben = (uint16_t) (val & 0x03);
break;
case 0x07:
/* Miscellaneous Control Register */
dev->regs.glbctl = (uint16_t) (val & 0x03);
/* Setting BIOS_RLS also sets GBL_STS and generates SMI. */
if (dev->regs.glbctl & 0x0001) {
dev->regs.pmsts |= 0x20;
if (dev->regs.pmen & 0x20)
acpi_update_irq(dev);
}
if (dev->regs.glbctl & 0x0002) {
dev->regs.pmsts |= 0x10;
if (dev->regs.pmcntrl & 0x02)
acpi_update_irq(dev);
}
break;
default:
break;
}
}
void
acpi_sis5582_pmu_event(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
dev->regs.reg_25 |= 0x02;
if (dev->regs.reg_26 & 0x02)
smi_raise();
}
static void
acpi_reg_write_sis_5582(int size, uint16_t addr, uint8_t val, void *priv)
{
acpi_t *dev = (acpi_t *) priv;
int shift16;
int shift32;
uint8_t old;
addr &= 0x3f;
#ifdef ENABLE_ACPI_LOG
if (size != 1)
acpi_log("(%i) ACPI Write (%i) %02X: %02X\n", in_smm, size, addr, val);
#endif
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x0c:
case 0x0d:
case 0x0e:
case 0x0f:
dev->regs.reg_0c &= ~((val << shift32) & 0x007e);
break;
case 0x10:
dev->regs.enter_c2_ps = val;
break;
case 0x11:
dev->regs.enter_c3_ps = val;
break;
case 0x12:
dev->regs.reg_12 = val & 0x01;
break;
case 0x13:
dev->regs.reg_13 = val;
acpi_gp_timer_update(dev, (val != 0x00) && (dev->regs.reg_16 & 0x2000), val);
break;
case 0x14:
case 0x15:
dev->regs.reg_14 &= ~((val << shift32) & 0xff9f);
break;
case 0x16:
case 0x17:
dev->regs.reg_16 = ((dev->regs.reg_16 & ~(0xff << shift16)) | (val << shift16)) & 0xff1f;
break;
case 0x18:
case 0x19:
dev->regs.reg_18 = ((dev->regs.reg_18 & ~(0xff << shift16)) | (val << shift16)) & 0x07ff;
break;
case 0x1a:
case 0x1b:
dev->regs.reg_1a = ((dev->regs.reg_1a & ~(0xff << shift16)) | (val << shift16)) & 0x0387;
break;
case 0x1c:
case 0x1d:
dev->regs.reg_1c = ((dev->regs.reg_1c & ~(0xff << shift16)) | (val << shift16)) & 0x3f7f;
/* Setting BIOS_RLS also sets GBL_STS and generates SMI. */
if (dev->regs.reg_1c & 0x0400) {
dev->regs.pmsts |= 0x20;
if (dev->regs.pmen & 0x20)
acpi_update_irq(dev);
}
break;
case 0x20:
/* SMI Command Port */
dev->regs.smi_cmd = val;
if (val == dev->regs.smi_en_val) {
dev->regs.reg_25 |= 0x08;
if (dev->regs.reg_26 & 0x08)
smi_raise();
} else if (val == dev->regs.smi_dis_val) {
dev->regs.reg_25 |= 0x10;
if (dev->regs.reg_26 & 0x10)
smi_raise();
}
break;
case 0x24:
dev->regs.reg_24 = val & 0x43;
break;
case 0x25:
dev->regs.reg_25 &= ~(val & 0x1f);
break;
case 0x26:
old = dev->regs.reg_26;
dev->regs.reg_26 = val & 0x3f;
if (!(old & 0x04) && (val & 0x04))
timer_on_auto(&dev->per_timer, 16000000.0);
else if ((old & 0x04) && !(val & 0x04))
timer_stop(&dev->per_timer);
break;
case 0x28:
dev->regs.smi_en_val = val;
break;
case 0x29:
dev->regs.smi_dis_val = val;
break;
case 0x2a:
dev->regs.mail_box = val;
break;
case 0x2b:
dev->regs.reg_2b = val & 0x01;
break;
default:
acpi_reg_write_common_regs(size, addr, val, priv);
/* Setting GBL_RLS also sets BIOS_STS and generates SMI. */
if ((addr == 0x00) && !(dev->regs.pmsts & 0x20))
dev->regs.reg_1c &= ~0x0400;
else if ((addr == 0x04) && (dev->regs.pmcntrl & 0x0004)) {
dev->regs.reg_25 |= 0x01;
if (dev->regs.reg_26 & 0x01)
acpi_raise_smi(dev, 1);
}
break;
}
}
void
acpi_sis5595_pmu_event(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
if (dev->vendor == VEN_SIS_5595_1997)
acpi_sis5595_smi_raise(dev);
else if (dev->regs.gpe_en & 0x00001000) {
dev->regs.gpe_sts |= 0x00001000;
acpi_sis5595_smi_raise(dev);
}
}
void
acpi_sis5595_smbus_event(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
if (dev->regs.gpe_en & 0x00000800) {
dev->regs.gpe_sts |= 0x00000800;
acpi_sis5595_smi_raise(dev);
}
}
void
acpi_sis5595_software_smi(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
if (dev->regs.leg_en & 0x01) {
dev->regs.leg_sts |= 0x01;
acpi_sis5595_smi_raise(dev);
}
}
static void
acpi_reg_write_sis_5595(int size, uint16_t addr, uint8_t val, void *priv)
{
acpi_t *dev = (acpi_t *) priv;
int shift16;
int shift32;
uint8_t old;
uint8_t do_smi = 0;
addr &= 0x3f;
#ifdef ENABLE_ACPI_LOG
if (size != 1)
acpi_log("(%i) ACPI Write (%i) %02X: %02X\n", in_smm, size, addr, val);
#endif
shift16 = (addr & 1) << 3;
shift32 = (addr & 3) << 3;
switch (addr) {
case 0x0c:
case 0x0d:
case 0x0e:
case 0x0f:
dev->regs.reg_0c &= ~((val << shift32) & 0x001e);
break;
case 0x10:
dev->regs.enter_c2_ps = val;
break;
case 0x11:
dev->regs.enter_c3_ps = val;
break;
case 0x12:
dev->regs.reg_12 = val & 0x01;
break;
case 0x13:
dev->regs.reg_13 = val;
/* Setting BIOS_RLS also sets GBL_STS and generates SMI. */
if (dev->regs.reg_13 & 0x02) {
dev->regs.pmsts |= 0x20;
if (dev->regs.pmen & 0x20)
acpi_update_irq(dev);
}
break;
case 0x14:
case 0x15:
case 0x16:
case 0x17:
if (dev->vendor == VEN_SIS_5595_1997)
dev->regs.gpe_sts &= ~((val << shift32) & 0xff03ffbf);
else
dev->regs.gpe_sts &= ~((val << shift32) & 0xff83ffff);
break;
case 0x18:
case 0x19:
case 0x1a:
case 0x1b:
if (dev->vendor == VEN_SIS_5595_1997)
dev->regs.gpe_en = ((dev->regs.gpe_en & ~(0xff << shift32)) | (val << shift32));
else
dev->regs.gpe_en = ((dev->regs.gpe_en & ~(0xff << shift32)) |
(val << shift32)) & 0xff83ffff;
break;
case 0x1c:
dev->regs.gpe_pin = ((dev->regs.gpe_pin & ~(0xff << shift32)) | ((val & 0xff) << shift32));
if (!strcmp(machine_get_internal_name(), "m747") && (val & 0x10) &&
!(dev->regs.gpe_io & 0x00000010))
resetx86();
break;
case 0x1d:
dev->regs.gpe_pin = ((dev->regs.gpe_pin & ~(0x0f << shift32)) | ((val & 0x0f) << shift32));
break;
case 0x1e:
dev->regs.gpe_pin = ((dev->regs.gpe_pin & ~(0x03 << shift32)) | ((val & 0x03) << shift32));
break;
case 0x1f:
dev->regs.gp_tmr = val;
acpi_gp_timer_update(dev, (val != 0x00) && (dev->regs.gpe_en & 0x00000400), val);
break;
case 0x20:
dev->regs.gpe_io = ((dev->regs.gpe_io & ~(0x9f << shift32)) | ((val & 0x9f) << shift32));
break;
case 0x21:
dev->regs.gpe_io = ((dev->regs.gpe_io & ~(0x0f << shift32)) | ((val & 0x0f) << shift32));
break;
case 0x22:
dev->regs.gpe_io = ((dev->regs.gpe_io & ~(0x03 << shift32)) | ((val & 0x03) << shift32));
break;
case 0x24:
dev->regs.gpe_pol = ((dev->regs.gpe_pol & ~(0xbf << shift32)) | ((val & 0xbf) << shift32));
break;
case 0x25:
dev->regs.gpe_pol = ((dev->regs.gpe_pol & ~(0x0f << shift32)) | ((val & 0x0f) << shift32));
break;
case 0x26:
dev->regs.gpe_pol = ((dev->regs.gpe_pol & ~(0x03 << shift32)) | ((val & 0x03) << shift32));
break;
case 0x27:
dev->regs.gpe_pol = ((dev->regs.gpe_pol & ~(0x10 << shift32)) | ((val & 0x10) << shift32));
break;
case 0x28:
dev->regs.gpe_mul = ((dev->regs.gpe_mul & ~(0xf9 << shift16)) | ((val & 0xf9) << shift16));
break;
case 0x29:
dev->regs.gpe_mul = ((dev->regs.gpe_mul & ~(0x13 << shift16)) | ((val & 0x13) << shift16));
break;
case 0x2a:
case 0x2b:
dev->regs.gpe_ctl = ((dev->regs.gpe_ctl & ~(0xff << shift16)) | ((val & 0xff) << shift16));
break;
case 0x2c:
case 0x2d:
dev->regs.gpe_smi = ((dev->regs.gpe_smi & ~(0xff << shift16)) | ((val & 0xff) << shift16));
break;
case 0x2e:
case 0x2f:
dev->regs.gpe_rl = ((dev->regs.gpe_rl & ~(0xff << shift16)) | ((val & 0xff) << shift16));
break;
case 0x30:
dev->regs.leg_sts &= ~val;
break;
case 0x31:
old = dev->regs.leg_en;
dev->regs.leg_en = val;
if (!(old & 0x04) && (val & 0x04))
timer_on_auto(&dev->per_timer, 16000000.0);
else if ((old & 0x04) && !(val & 0x04))
timer_stop(&dev->per_timer);
break;
case 0x32:
if (dev->vendor == VEN_SIS_5595_1997) {
/* SMI Command Port */
dev->regs.smi_cmd = val;
if (val == dev->regs.smi_en_val) {
dev->regs.leg_sts |= 0x08;
if (dev->regs.leg_en & 0x08)
acpi_sis5595_smi_raise(dev);
} else if (val == dev->regs.smi_dis_val) {
dev->regs.leg_sts |= 0x10;
if (dev->regs.leg_en & 0x10)
acpi_sis5595_smi_raise(dev);
}
}
break;
case 0x33:
dev->regs.tst_ctl = val & 0x01;
break;
case 0x34:
if (dev->vendor == VEN_SIS_5595_1997)
dev->regs.smi_en_val = val;
else
dev->regs.reg_34 = val;
break;
case 0x35:
if (dev->vendor == VEN_SIS_5595_1997)
dev->regs.smi_dis_val = val;
else {
/* SMI Command Port */
dev->regs.smi_cmd = val;
dev->regs.leg_sts |= 0x10;
if (dev->regs.leg_en & 0x10)
acpi_sis5595_smi_raise(dev);
}
break;
case 0x36:
dev->regs.mail_box = val;
break;
case 0x38:
if (dev->vendor == VEN_SIS_5595) {
dev->regs.index = val;
smbus_sis5595_write_index(dev->smbus, val);
}
break;
case 0x39:
if (dev->vendor == VEN_SIS_5595) {
dev->regs.reg_ff = val & 0x3f;
smbus_sis5595_write_data(dev->smbus, val);
if (val & 0x20) { /* Set GPIO5_STS of GPE_STS */
dev->regs.gpe_sts |= 0x00000008;
do_smi |= (dev->regs.gpe_en & 0x00000004);
} else if (val & 0x10) { /* Set GPIO10_STS of GPE_STS */
dev->regs.gpe_sts |= 0x00000004;
do_smi |= (dev->regs.gpe_en & 0x00000008);
} else if (val & 0x08) { /* Set RI_STS in GPE_STS */
dev->regs.gpe_sts |= 0x00000002;
do_smi |= (dev->regs.gpe_en & 0x00000002);
} else if (val & 0x04) /* Set WAK_STS of PM1_STS */
dev->regs.pmsts |= 0x8000;
else if (val & 0x02) { /* Set RTC_STS of PM1_STS */
dev->regs.pmsts |= 0x0400;
do_smi |= (dev->regs.pmen & 0x0400);
} else if (val & 0x01) { /* Set PWRBTN_STS of PM1_STS */
dev->regs.pmsts |= 0x0100;
do_smi |= (dev->regs.pmen & 0x0100);
}
if (do_smi)
acpi_sis5595_smi_raise(dev);
}
break;
default:
acpi_reg_write_common_regs(size, addr, val, priv);
/* Setting GBL_RLS also sets BIOS_STS and generates SMI. */
if ((addr == 0x00) && !(dev->regs.pmsts & 0x20))
dev->regs.reg_13 &= ~0x02;
else if ((addr == 0x04) && (dev->regs.pmcntrl & 0x0004)) {
dev->regs.leg_sts |= 0x01;
if (dev->regs.leg_en & 0x01)
acpi_sis5595_smi_raise(dev);
}
break;
}
}
static uint32_t
acpi_reg_read_common(int size, uint16_t addr, void *priv)
{
const acpi_t *dev = (acpi_t *) priv;
uint8_t ret = 0xff;
switch (dev->vendor) {
case VEN_ALI:
ret = acpi_reg_read_ali(size, addr, priv);
break;
case VEN_VIA:
ret = acpi_reg_read_via(size, addr, priv);
break;
case VEN_VIA_596B:
ret = acpi_reg_read_via_596b(size, addr, priv);
break;
case VEN_INTEL:
ret = acpi_reg_read_intel(size, addr, priv);
break;
case VEN_SMC:
ret = acpi_reg_read_smc(size, addr, priv);
break;
case VEN_SIS_5582:
ret = acpi_reg_read_sis_5582(size, addr, priv);
break;
case VEN_SIS_5595_1997:
case VEN_SIS_5595:
ret = acpi_reg_read_sis_5595(size, addr, priv);
break;
}
return ret;
}
static void
acpi_reg_write_common(int size, uint16_t addr, uint8_t val, void *priv)
{
const acpi_t *dev = (acpi_t *) priv;
switch (dev->vendor) {
case VEN_ALI:
acpi_reg_write_ali(size, addr, val, priv);
break;
case VEN_VIA:
acpi_reg_write_via(size, addr, val, priv);
break;
case VEN_VIA_596B:
acpi_reg_write_via_596b(size, addr, val, priv);
break;
case VEN_INTEL:
acpi_reg_write_intel(size, addr, val, priv);
break;
case VEN_SMC:
acpi_reg_write_smc(size, addr, val, priv);
break;
case VEN_SIS_5582:
acpi_reg_write_sis_5582(size, addr, val, priv);
break;
case VEN_SIS_5595_1997:
case VEN_SIS_5595:
acpi_reg_write_sis_5595(size, addr, val, priv);
break;
}
}
static uint32_t
acpi_aux_reg_read_common(int size, uint16_t addr, void *priv)
{
const acpi_t *dev = (acpi_t *) priv;
uint8_t ret = 0xff;
if (dev->vendor == VEN_SMC)
ret = acpi_aux_reg_read_smc(size, addr, priv);
return ret;
}
static void
acpi_aux_reg_write_common(int size, uint16_t addr, uint8_t val, void *priv)
{
const acpi_t *dev = (acpi_t *) priv;
if (dev->vendor == VEN_SMC)
acpi_aux_reg_write_smc(size, addr, val, priv);
}
static uint32_t
acpi_reg_readl(uint16_t addr, void *priv)
{
uint32_t ret = 0x00000000;
ret = acpi_reg_read_common(4, addr, priv);
ret |= (acpi_reg_read_common(4, addr + 1, priv) << 8);
ret |= (acpi_reg_read_common(4, addr + 2, priv) << 16);
ret |= (acpi_reg_read_common(4, addr + 3, priv) << 24);
acpi_log("ACPI: Read L %08X from %04X\n", ret, addr);
return ret;
}
static uint16_t
acpi_reg_readw(uint16_t addr, void *priv)
{
uint16_t ret = 0x0000;
ret = acpi_reg_read_common(2, addr, priv);
ret |= (acpi_reg_read_common(2, addr + 1, priv) << 8);
acpi_log("ACPI: Read W %08X from %04X\n", ret, addr);
return ret;
}
static uint8_t
acpi_reg_read(uint16_t addr, void *priv)
{
uint8_t ret = 0x00;
ret = acpi_reg_read_common(1, addr, priv);
acpi_log("ACPI: Read B %02X from %04X\n", ret, addr);
return ret;
}
static uint32_t
acpi_aux_reg_readl(uint16_t addr, void *priv)
{
uint32_t ret = 0x00000000;
ret = acpi_aux_reg_read_common(4, addr, priv);
ret |= (acpi_aux_reg_read_common(4, addr + 1, priv) << 8);
ret |= (acpi_aux_reg_read_common(4, addr + 2, priv) << 16);
ret |= (acpi_aux_reg_read_common(4, addr + 3, priv) << 24);
acpi_log("ACPI: Read Aux L %08X from %04X\n", ret, addr);
return ret;
}
static uint16_t
acpi_aux_reg_readw(uint16_t addr, void *priv)
{
uint16_t ret = 0x0000;
ret = acpi_aux_reg_read_common(2, addr, priv);
ret |= (acpi_aux_reg_read_common(2, addr + 1, priv) << 8);
acpi_log("ACPI: Read Aux W %04X from %04X\n", ret, addr);
return ret;
}
static uint8_t
acpi_aux_reg_read(uint16_t addr, void *priv)
{
uint8_t ret = 0x00;
ret = acpi_aux_reg_read_common(1, addr, priv);
acpi_log("ACPI: Read Aux B %02X from %04X\n", ret, addr);
return ret;
}
static void
acpi_reg_writel(uint16_t addr, uint32_t val, void *priv)
{
acpi_log("ACPI: Write L %08X to %04X\n", val, addr);
acpi_reg_write_common(4, addr, val & 0xff, priv);
acpi_reg_write_common(4, addr + 1, (val >> 8) & 0xff, priv);
acpi_reg_write_common(4, addr + 2, (val >> 16) & 0xff, priv);
acpi_reg_write_common(4, addr + 3, (val >> 24) & 0xff, priv);
}
static void
acpi_reg_writew(uint16_t addr, uint16_t val, void *priv)
{
acpi_log("ACPI: Write W %04X to %04X\n", val, addr);
acpi_reg_write_common(2, addr, val & 0xff, priv);
acpi_reg_write_common(2, addr + 1, (val >> 8) & 0xff, priv);
}
static void
acpi_reg_write(uint16_t addr, uint8_t val, void *priv)
{
acpi_log("ACPI: Write B %02X to %04X\n", val, addr);
acpi_reg_write_common(1, addr, val, priv);
}
static void
acpi_aux_reg_writel(uint16_t addr, uint32_t val, void *priv)
{
acpi_log("ACPI: Write Aux L %08X to %04X\n", val, addr);
acpi_aux_reg_write_common(4, addr, val & 0xff, priv);
acpi_aux_reg_write_common(4, addr + 1, (val >> 8) & 0xff, priv);
acpi_aux_reg_write_common(4, addr + 2, (val >> 16) & 0xff, priv);
acpi_aux_reg_write_common(4, addr + 3, (val >> 24) & 0xff, priv);
}
static void
acpi_aux_reg_writew(uint16_t addr, uint16_t val, void *priv)
{
acpi_log("ACPI: Write Aux W %04X to %04X\n", val, addr);
acpi_aux_reg_write_common(2, addr, val & 0xff, priv);
acpi_aux_reg_write_common(2, addr + 1, (val >> 8) & 0xff, priv);
}
static void
acpi_aux_reg_write(uint16_t addr, uint8_t val, void *priv)
{
acpi_log("ACPI: Write Aux B %02X to %04X\n", val, addr);
acpi_aux_reg_write_common(1, addr, val, priv);
}
void
acpi_update_io_mapping(acpi_t *dev, uint32_t base, int chipset_en)
{
int size;
switch (dev->vendor) {
default:
case VEN_ALI:
case VEN_INTEL:
case VEN_SIS_5582:
case VEN_SIS_5595_1997:
case VEN_SIS_5595:
size = 0x040;
break;
case VEN_SMC:
size = 0x010;
break;
case VEN_VIA:
size = 0x100;
break;
case VEN_VIA_596B:
size = 0x080;
break;
}
acpi_log("ACPI: Update I/O %04X to %04X (%sabled)\n", dev->io_base, base, chipset_en ? "en" : "dis");
if (dev->io_base != 0x0000) {
io_removehandler(dev->io_base, size,
acpi_reg_read, acpi_reg_readw, acpi_reg_readl,
acpi_reg_write, acpi_reg_writew, acpi_reg_writel, dev);
}
dev->io_base = base;
if (chipset_en && (dev->io_base != 0x0000)) {
io_sethandler(dev->io_base, size,
acpi_reg_read, acpi_reg_readw, acpi_reg_readl,
acpi_reg_write, acpi_reg_writew, acpi_reg_writel, dev);
}
}
void
acpi_update_aux_io_mapping(acpi_t *dev, uint32_t base, int chipset_en)
{
int size;
switch (dev->vendor) {
case VEN_SMC:
size = 0x008;
break;
default:
size = 0x000;
break;
}
acpi_log("ACPI: Update Aux I/O %04X to %04X (%sabled)\n", dev->aux_io_base, base, chipset_en ? "en" : "dis");
if (dev->aux_io_base != 0x0000) {
io_removehandler(dev->aux_io_base, size,
acpi_aux_reg_read, acpi_aux_reg_readw, acpi_aux_reg_readl,
acpi_aux_reg_write, acpi_aux_reg_writew, acpi_aux_reg_writel, dev);
}
dev->aux_io_base = base;
if (chipset_en && (dev->aux_io_base != 0x0000)) {
io_sethandler(dev->aux_io_base, size,
acpi_aux_reg_read, acpi_aux_reg_readw, acpi_aux_reg_readl,
acpi_aux_reg_write, acpi_aux_reg_writew, acpi_aux_reg_writel, dev);
}
}
static void
acpi_timer_resume(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
dev->regs.pmsts |= 0x8000;
/* Nasty workaround for ASUS P2B-LS and potentially others, where the PMCNTRL
SMI trap handler clears the resume bit before returning control to the OS. */
if (in_smm)
timer_set_delay_u64(&dev->resume_timer, 50 * TIMER_USEC);
}
void
acpi_init_gporeg(acpi_t *dev, uint8_t val0, uint8_t val1, uint8_t val2, uint8_t val3)
{
dev->regs.gporeg[0] = dev->gporeg_default[0] = val0;
dev->regs.gporeg[1] = dev->gporeg_default[1] = val1;
dev->regs.gporeg[2] = dev->gporeg_default[2] = val2;
dev->regs.gporeg[3] = dev->gporeg_default[3] = val3;
acpi_log("acpi_init_gporeg(): %02X %02X %02X %02X\n", dev->regs.gporeg[0], dev->regs.gporeg[1], dev->regs.gporeg[2], dev->regs.gporeg[3]);
}
void
acpi_set_timer32(acpi_t *dev, uint8_t timer32)
{
dev->regs.timer32 = timer32;
}
void
acpi_set_slot(acpi_t *dev, int slot)
{
dev->slot = slot;
}
void
acpi_set_irq_mode(acpi_t *dev, int irq_mode)
{
dev->irq_mode = irq_mode;
}
void
acpi_set_irq_pin(acpi_t *dev, int irq_pin)
{
dev->irq_pin = irq_pin;
}
void
acpi_set_irq_line(acpi_t *dev, int irq_line)
{
dev->irq_line = irq_line;
}
void
acpi_set_mirq_is_level(acpi_t *dev, int mirq_is_level)
{
dev->mirq_is_level = mirq_is_level;
}
void
acpi_set_gpireg2_default(acpi_t *dev, uint8_t gpireg2_default)
{
dev->gpireg2_default = gpireg2_default;
dev->regs.gpireg[2] = dev->gpireg2_default;
}
void
acpi_set_nvr(acpi_t *dev, nvr_t *nvr)
{
dev->nvr = nvr;
}
void
acpi_set_trap_update(acpi_t *dev, void (*update)(void *priv), void *priv)
{
dev->trap_update = update;
dev->trap_priv = priv;
}
uint8_t
acpi_ali_soft_smi_status_read(acpi_t *dev)
{
return dev->regs.ali_soft_smi = 1;
}
void
acpi_ali_soft_smi_status_write(acpi_t *dev, uint8_t soft_smi)
{
dev->regs.ali_soft_smi = soft_smi;
}
void
acpi_pwrbtn_timer(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
timer_on_auto(&dev->pwrbtn_timer, 16. * 1000.);
if (acpi_pwrbut_pressed) {
acpi_pwrbut_pressed = 0;
if (dev->regs.pmen & PWRBTN_EN) {
dev->regs.pmsts |= PWRBTN_STS;
acpi_update_irq(dev);
}
}
}
static void
acpi_apm_out(uint16_t port, uint8_t val, void *priv)
{
acpi_t *dev = (acpi_t *) priv;
acpi_log("[%04X:%08X] APM write: %04X = %02X (AX = %04X, BX = %04X, CX = %04X)\n", CS, cpu_state.pc, port, val, AX, BX, CX);
port &= 0x0001;
if (dev->vendor == VEN_ALI) {
if (port == 0x0001) {
acpi_log("ALi SOFT SMI# status set (%i)\n", dev->apm->do_smi);
dev->apm->cmd = val;
#if 0
acpi_raise_smi(dev, dev->apm->do_smi);
#endif
if (dev->apm->do_smi)
smi_raise();
dev->regs.ali_soft_smi = 1;
} else if (port == 0x0003)
dev->apm->stat = val;
} else {
if (port == 0x0000) {
dev->apm->cmd = val;
if (dev->vendor == VEN_INTEL)
dev->regs.glbsts |= 0x20;
acpi_raise_smi(dev, dev->apm->do_smi);
} else
dev->apm->stat = val;
}
}
static uint8_t
acpi_apm_in(uint16_t port, void *priv)
{
const acpi_t *dev = (acpi_t *) priv;
uint8_t ret = 0xff;
port &= 0x0001;
if (dev->vendor == VEN_ALI) {
if (port == 0x0001)
ret = dev->apm->cmd;
else if (port == 0x0003)
ret = dev->apm->stat;
} else {
if (port == 0x0000)
ret = dev->apm->cmd;
else
ret = dev->apm->stat;
}
acpi_log("[%04X:%08X] APM read: %04X = %02X\n", CS, cpu_state.pc, port, ret);
return ret;
}
static void
acpi_reset(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
memset(&dev->regs, 0x00, sizeof(acpi_regs_t));
/* PC Chips M773:
- Bit 3: 80-conductor cable on unknown IDE channel (active low)
- Bit 1: 80-conductor cable on unknown IDE channel (active low) */
dev->regs.gpireg[0] = !strcmp(machine_get_internal_name(), "m773") ? 0xf5 : 0xff;
dev->regs.gpireg[1] = 0xff;
/* A-Trend ATC7020BXII:
- Bit 3: 80-conductor cable on secondary IDE channel (active low)
- Bit 2: 80-conductor cable on primary IDE channel (active low)
Gigabyte GA-686BX:
- Bit 1: CMOS battery low (active high) */
dev->regs.gpireg[2] = dev->gpireg2_default;
for (uint8_t i = 0; i < 4; i++)
dev->regs.gporeg[i] = dev->gporeg_default[i];
if (dev->vendor == VEN_VIA_596B) {
dev->regs.gpo_val = 0x7fffffff;
/* FIC VA-503A:
- Bit 11: ATX power (active high)
- Bit 4: 80-conductor cable on primary IDE channel (active low)
- Bit 3: 80-conductor cable on secondary IDE channel (active low)
- Bit 2: password cleared (active low)
ASUS P3V4X:
- Bit 15: 80-conductor cable on secondary IDE channel (active low)
- Bit 5: 80-conductor cable on primary IDE channel (active low)
BCM GT694VA:
- Bit 19: 80-conductor cable on secondary IDE channel (active low)
- Bit 17: 80-conductor cable on primary IDE channel (active low)
ASUS CUV4X-LS:
- Bit 2: 80-conductor cable on secondary IDE channel (active low)
- Bit 1: 80-conductor cable on primary IDE channel (active low)
Acorp 6VIA90AP:
- Bit 3: 80-conductor cable on secondary IDE channel (active low)
- Bit 1: 80-conductor cable on primary IDE channel (active low) */
dev->regs.gpi_val = 0xfff57fc1;
if (!strcmp(machine_get_internal_name(), "ficva503a") || !strcmp(machine_get_internal_name(), "6via90ap"))
dev->regs.gpi_val |= 0x00000004;
}
if (acpi_power_on) {
/* Power on always generates a resume event. */
dev->regs.pmsts |= 0x8100;
acpi_power_on = 0;
}
/* The Gateway Tomahawk requires the LID polarity bit to be set. */
if (!strcmp(machine_get_internal_name(), "tomahawk"))
dev->regs.glbctl |= 0x02000000;
acpi_rtc_status = 0;
acpi_update_irq(dev);
dev->irq_state = 0;
timer_disable(&dev->gp_timer);
acpi_last_clock = 0ULL;
acpi_count = 0;
timer_disable(&dev->per_timer);
if ((dev->vendor == VEN_SIS_5595_1997) || (dev->vendor == VEN_SIS_5595)) {
dev->regs.reg_13 = 0x20;
dev->regs.gp_tmr = 0xff;
dev->regs.gpe_io = 0x00030b9f;
dev->regs.gpe_mul = 0x1001;
}
}
static void
acpi_speed_changed(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
cpu_to_acpi = ACPI_TIMER_FREQ / cpuclock;
bool timer_enabled = timer_is_enabled(&dev->timer);
timer_stop(&dev->timer);
if (timer_enabled)
timer_on_auto(&dev->timer, acpi_get_overflow_period(dev));
if ((dev->vendor & 0xffff) == 0x1039) {
if (timer_is_on(&dev->gp_timer)) {
timer_stop(&dev->gp_timer);
if (dev->vendor == VEN_SIS_5595_1997)
acpi_gp_timer_update(dev, (dev->regs.gpe_en & 0x20000000), acpi_count);
else if (dev->vendor == VEN_SIS_5595)
acpi_gp_timer_update(dev, (dev->regs.gpe_en & 0x00000400), acpi_count);
else
acpi_gp_timer_update(dev, (dev->regs.reg_16 & 0x2000), acpi_count);
}
if (timer_is_on(&dev->per_timer)) {
timer_stop(&dev->per_timer);
timer_on_auto(&dev->per_timer, 16000000.0);
}
}
}
void *
acpi_get_smbus(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
return dev->smbus;
}
static void
acpi_close(void *priv)
{
acpi_t *dev = (acpi_t *) priv;
if (dev->i2c) {
if (i2c_smbus == i2c_gpio_get_bus(dev->i2c))
i2c_smbus = NULL;
i2c_gpio_close(dev->i2c);
}
timer_stop(&dev->timer);
free(dev);
}
static void *
acpi_init(const device_t *info)
{
acpi_t *dev;
dev = (acpi_t *) malloc(sizeof(acpi_t));
if (dev == NULL)
return NULL;
memset(dev, 0x00, sizeof(acpi_t));
cpu_to_acpi = ACPI_TIMER_FREQ / cpuclock;
dev->vendor = info->local;
dev->irq_line = 9;
if ((dev->vendor == VEN_INTEL) || (dev->vendor == VEN_ALI)) {
if (dev->vendor == VEN_ALI)
dev->irq_mode = 2;
dev->apm = device_add(&apm_pci_acpi_device);
if (dev->vendor == VEN_ALI) {
acpi_log("Setting I/O handler at port B1\n");
io_sethandler(0x00b1, 0x0003, acpi_apm_in, NULL, NULL, acpi_apm_out, NULL, NULL, dev);
} else
io_sethandler(0x00b2, 0x0002, acpi_apm_in, NULL, NULL, acpi_apm_out, NULL, NULL, dev);
} else if (dev->vendor == VEN_VIA) {
dev->i2c = i2c_gpio_init("smbus_vt82c586b");
i2c_smbus = i2c_gpio_get_bus(dev->i2c);
}
switch (dev->vendor) {
case VEN_ALI:
dev->suspend_types[0] = SUS_POWER_OFF;
dev->suspend_types[1] = SUS_POWER_OFF;
dev->suspend_types[2] = SUS_SUSPEND | SUS_NVR | SUS_RESET_CPU | SUS_RESET_PCI;
dev->suspend_types[3] = SUS_SUSPEND;
dev->suspend_types[5] = SUS_POWER_OFF; /* undocumented, used for S4/S5 by ASUS P5A ACPI table */
dev->suspend_types[7] = SUS_POWER_OFF; /* undocumented, used for S5 by Gigabyte GA-5AX ACPI table */
break;
case VEN_VIA:
dev->suspend_types[0] = SUS_POWER_OFF;
dev->suspend_types[2] = SUS_SUSPEND;
break;
case VEN_VIA_596B:
dev->suspend_types[1] = SUS_SUSPEND | SUS_NVR | SUS_RESET_CPU | SUS_RESET_PCI;
dev->suspend_types[2] = SUS_POWER_OFF;
dev->suspend_types[4] = SUS_SUSPEND;
dev->suspend_types[5] = SUS_SUSPEND | SUS_RESET_CPU;
dev->suspend_types[6] = SUS_SUSPEND | SUS_RESET_CPU | SUS_RESET_PCI;
break;
case VEN_INTEL:
dev->suspend_types[0] = SUS_POWER_OFF;
dev->suspend_types[1] = SUS_SUSPEND | SUS_NVR | SUS_RESET_CPU | SUS_RESET_PCI;
dev->suspend_types[2] = SUS_SUSPEND | SUS_RESET_CPU;
dev->suspend_types[3] = SUS_SUSPEND | SUS_RESET_CACHE;
dev->suspend_types[4] = SUS_SUSPEND;
break;
case VEN_SIS_5582:
dev->suspend_types[0] = SUS_SUSPEND; /* S1 */
dev->suspend_types[4] = SUS_POWER_OFF; /* S5 */
timer_add(&dev->gp_timer, acpi_gp_timer, dev, 0);
timer_add(&dev->per_timer, acpi_per_timer, dev, 0);
break;
case VEN_SIS_5595_1997:
case VEN_SIS_5595:
dev->suspend_types[1] = SUS_SUSPEND;
dev->suspend_types[2] = SUS_SUSPEND;
dev->suspend_types[3] = SUS_SUSPEND | SUS_NVR | SUS_RESET_CPU | SUS_RESET_PCI;
dev->suspend_types[4] = SUS_POWER_OFF;
dev->suspend_types[5] = SUS_POWER_OFF;
timer_add(&dev->gp_timer, acpi_gp_timer, dev, 0);
timer_add(&dev->per_timer, acpi_per_timer, dev, 0);
dev->smbus = device_add(&sis5595_smbus_device);
break;
default:
break;
}
timer_add(&dev->timer, acpi_timer_overflow, dev, 0);
timer_add(&dev->resume_timer, acpi_timer_resume, dev, 0);
timer_add(&dev->pwrbtn_timer, acpi_pwrbtn_timer, dev, 0);
timer_on_auto(&dev->pwrbtn_timer, 16. * 1000.);
acpi_reset(dev);
acpi_enabled = 1;
acpi_power_on = 1;
return dev;
}
const device_t acpi_ali_device = {
.name = "ALi M7101 ACPI",
.internal_name = "acpi_ali",
.flags = DEVICE_PCI,
.local = VEN_ALI,
.init = acpi_init,
.close = acpi_close,
.reset = acpi_reset,
{ .available = NULL },
.speed_changed = acpi_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t acpi_intel_device = {
.name = "Intel ACPI",
.internal_name = "acpi_intel",
.flags = DEVICE_PCI,
.local = VEN_INTEL,
.init = acpi_init,
.close = acpi_close,
.reset = acpi_reset,
{ .available = NULL },
.speed_changed = acpi_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t acpi_via_device = {
.name = "VIA ACPI",
.internal_name = "acpi_via",
.flags = DEVICE_PCI,
.local = VEN_VIA,
.init = acpi_init,
.close = acpi_close,
.reset = acpi_reset,
{ .available = NULL },
.speed_changed = acpi_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t acpi_via_596b_device = {
.name = "VIA VT82C596 ACPI",
.internal_name = "acpi_via_596b",
.flags = DEVICE_PCI,
.local = VEN_VIA_596B,
.init = acpi_init,
.close = acpi_close,
.reset = acpi_reset,
{ .available = NULL },
.speed_changed = acpi_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t acpi_smc_device = {
.name = "SMC FDC73C931APM ACPI",
.internal_name = "acpi_smc",
.flags = DEVICE_PCI,
.local = VEN_SMC,
.init = acpi_init,
.close = acpi_close,
.reset = acpi_reset,
{ .available = NULL },
.speed_changed = acpi_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t acpi_sis_5582_device = {
.name = "SiS 5582 ACPI",
.internal_name = "acpi_sis_5582",
.flags = DEVICE_PCI,
.local = VEN_SIS_5582,
.init = acpi_init,
.close = acpi_close,
.reset = acpi_reset,
{ .available = NULL },
.speed_changed = acpi_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t acpi_sis_5595_1997_device = {
.name = "SiS 5595 (1997) ACPI",
.internal_name = "acpi_sis_5595_1997",
.flags = DEVICE_PCI,
.local = VEN_SIS_5595_1997,
.init = acpi_init,
.close = acpi_close,
.reset = acpi_reset,
{ .available = NULL },
.speed_changed = acpi_speed_changed,
.force_redraw = NULL,
.config = NULL
};
const device_t acpi_sis_5595_device = {
.name = "SiS 5595 ACPI",
.internal_name = "acpi_sis_5595",
.flags = DEVICE_PCI,
.local = VEN_SIS_5595,
.init = acpi_init,
.close = acpi_close,
.reset = acpi_reset,
{ .available = NULL },
.speed_changed = acpi_speed_changed,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/acpi.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 24,688 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of PCI-PCI and host-AGP bridges.
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/machine.h>
#include "cpu.h"
#include <86box/io.h>
#include <86box/pic.h>
#include <86box/mem.h>
#include <86box/device.h>
#include <86box/pci.h>
#define PCI_BRIDGE_DEC_21150 0x10110022
#define AGP_BRIDGE_ALI_M5243 0x10b95243
#define AGP_BRIDGE_ALI_M5247 0x10b95247
#define AGP_BRIDGE_INTEL_440LX 0x80867181
#define AGP_BRIDGE_INTEL_440BX 0x80867191
#define AGP_BRIDGE_INTEL_440GX 0x808671a1
#define AGP_BRIDGE_VIA_597 0x11068597
#define AGP_BRIDGE_VIA_598 0x11068598
#define AGP_BRIDGE_VIA_691 0x11068691
#define AGP_BRIDGE_VIA_8601 0x11068601
#define AGP_BRIDGE_SIS_5XXX 0x10390001
#define AGP_BRIDGE_ALI(x) (((x) >> 16) == 0x10b9)
#define AGP_BRIDGE_INTEL(x) (((x) >> 16) == 0x8086)
#define AGP_BRIDGE_VIA(x) (((x) >> 16) == 0x1106)
#define AGP_BRIDGE_SIS(x) (((x) >> 16) == 0x1039)
#define AGP_BRIDGE(x) ((x) >= AGP_BRIDGE_SIS_5XXX)
typedef struct pci_bridge_t {
uint32_t local;
uint8_t type;
uint8_t ctl;
uint8_t regs[256];
uint8_t bus_index;
uint8_t slot;
} pci_bridge_t;
#ifdef ENABLE_PCI_BRIDGE_LOG
int pci_bridge_do_log = ENABLE_PCI_BRIDGE_LOG;
static void
pci_bridge_log(const char *fmt, ...)
{
va_list ap;
if (pci_bridge_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define pci_bridge_log(fmt, ...)
#endif
void
pci_bridge_set_ctl(void *priv, uint8_t ctl)
{
pci_bridge_t *dev = (pci_bridge_t *) priv;
dev->ctl = ctl;
}
static void
pci_bridge_write(int func, int addr, uint8_t val, void *priv)
{
pci_bridge_t *dev = (pci_bridge_t *) priv;
pci_bridge_log("PCI Bridge %d: write(%d, %02X, %02X)\n", dev->bus_index, func, addr, val);
if (func > 0)
return;
if ((dev->local == AGP_BRIDGE_ALI_M5247) && (addr >= 0x40))
return;
switch (addr) {
case 0x00:
case 0x01:
case 0x02:
case 0x03:
case 0x06:
case 0x08:
case 0x09:
case 0x0a:
case 0x0b:
case 0x0e:
case 0x0f:
case 0x10:
case 0x11:
case 0x12:
case 0x13:
case 0x14:
case 0x15:
case 0x16:
case 0x17:
case 0x1e:
case 0x34:
case 0x3d:
case 0x67:
case 0xdc:
case 0xdd:
case 0xde:
case 0xdf:
return;
case 0x04:
if (AGP_BRIDGE_INTEL(dev->local)) {
if (dev->local == AGP_BRIDGE_INTEL_440BX)
val &= 0x1f;
} else if (dev->local == AGP_BRIDGE_ALI_M5243)
val |= 0x02;
else if (dev->local == AGP_BRIDGE_ALI_M5247)
val &= 0xc3;
else if (AGP_BRIDGE_SIS(dev->local))
val &= 0x27;
else
val &= 0x67;
break;
case 0x05:
if (AGP_BRIDGE_INTEL(dev->local))
val &= 0x01;
else if (AGP_BRIDGE_ALI(dev->local))
val &= 0x01;
else
val &= 0x03;
break;
case 0x07:
if (dev->local == AGP_BRIDGE_INTEL_440LX)
dev->regs[addr] &= ~(val & 0x40);
else if (dev->local == AGP_BRIDGE_ALI_M5243)
dev->regs[addr] &= ~(val & 0xf8);
else if (dev->local == AGP_BRIDGE_ALI_M5247)
dev->regs[addr] &= ~(val & 0xc0);
return;
case 0x0c:
case 0x18:
/* Parent bus number (0x18) is always 0 on AGP bridges. */
if (AGP_BRIDGE(dev->local))
return;
break;
case 0x0d:
if (AGP_BRIDGE_VIA(dev->local))
return;
else if (AGP_BRIDGE_INTEL(dev->local))
val &= 0xf8;
else if (AGP_BRIDGE_ALI(dev->local))
val &= 0xf8;
break;
case 0x19:
/* Set our bus number. */
pci_bridge_log("PCI Bridge %d: remapping from bus %02X to %02X\n", dev->bus_index, dev->regs[addr], val);
pci_remap_bus(dev->bus_index, val);
break;
case 0x1f:
if (AGP_BRIDGE_INTEL(dev->local)) {
if (dev->local == AGP_BRIDGE_INTEL_440LX)
dev->regs[addr] &= ~(val & 0xf1);
else if ((dev->local == AGP_BRIDGE_INTEL_440BX) || (dev->local == AGP_BRIDGE_INTEL_440GX))
dev->regs[addr] &= ~(val & 0xf0);
} else if (AGP_BRIDGE_ALI(dev->local))
dev->regs[addr] &= ~(val & 0xf0);
return;
case 0x1c:
case 0x1d:
case 0x20:
case 0x22:
case 0x24:
case 0x26:
val &= 0xf0; /* SiS datasheets say 0Fh for 1Ch but that's clearly an erratum since the
definition of the bits is identical to the other vendors' AGP bridges. */
break;
case 0x3c:
if (!(dev->ctl & 0x80))
return;
break;
case 0x3e:
if (AGP_BRIDGE_VIA(dev->local))
val &= 0x0c;
else if (AGP_BRIDGE_SIS(dev->local))
val &= 0x0e;
else if (dev->local == AGP_BRIDGE_ALI_M5247)
val &= 0x0f;
else if (dev->local == AGP_BRIDGE_ALI_M5243)
return;
else if (AGP_BRIDGE(dev->local)) {
if ((dev->local == AGP_BRIDGE_INTEL_440BX) || (dev->local == AGP_BRIDGE_INTEL_440GX))
val &= 0xed;
else
val &= 0x0f;
} else if (dev->local == PCI_BRIDGE_DEC_21150)
val &= 0xef;
break;
case 0x3f:
if (dev->local == AGP_BRIDGE_INTEL_440LX) {
dev->regs[addr] = ((dev->regs[addr] & 0x04) | (val & 0x02)) & ~(val & 0x04);
return;
} else if (dev->local == AGP_BRIDGE_ALI_M5247)
return;
else if (dev->local == AGP_BRIDGE_ALI_M5243)
val &= 0x06;
else if (AGP_BRIDGE(dev->local))
return;
else if (dev->local == PCI_BRIDGE_DEC_21150)
val &= 0x0f;
break;
case 0x40:
if (dev->local == PCI_BRIDGE_DEC_21150)
val &= 0x32;
break;
case 0x41:
if (AGP_BRIDGE_VIA(dev->local))
val &= 0x7e;
else if (dev->local == PCI_BRIDGE_DEC_21150)
val &= 0x07;
break;
case 0x42:
if (AGP_BRIDGE_VIA(dev->local))
val &= 0xfe;
break;
case 0x43:
if (dev->local == PCI_BRIDGE_DEC_21150)
val &= 0x03;
break;
case 0x64:
if (dev->local == PCI_BRIDGE_DEC_21150)
val &= 0x7e;
break;
case 0x69:
if (dev->local == PCI_BRIDGE_DEC_21150)
val &= 0x3f;
break;
case 0x86:
if (AGP_BRIDGE_ALI(dev->local))
val &= 0x3f;
break;
case 0x87:
if (AGP_BRIDGE_ALI(dev->local))
val &= 0x60;
break;
case 0x88:
if (AGP_BRIDGE_ALI(dev->local))
val &= 0x8c;
break;
case 0x8b:
if (AGP_BRIDGE_ALI(dev->local))
val &= 0x0f;
break;
case 0x8c:
if (AGP_BRIDGE_ALI(dev->local))
val &= 0x83;
break;
case 0x8d:
if (AGP_BRIDGE_ALI(dev->local))
return;
break;
case 0xe0:
case 0xe1:
if (AGP_BRIDGE_ALI(dev->local)) {
if (!(dev->ctl & 0x20))
return;
} else
return;
break;
case 0xe2:
if (AGP_BRIDGE_ALI(dev->local)) {
if (dev->ctl & 0x20)
val &= 0x3f;
else
return;
} else
return;
break;
case 0xe3:
if (AGP_BRIDGE_ALI(dev->local)) {
if (dev->ctl & 0x20)
val &= 0xfe;
else
return;
} else
return;
break;
case 0xe4:
if (AGP_BRIDGE_ALI(dev->local)) {
if (dev->ctl & 0x20)
val &= 0x03;
else
return;
}
break;
case 0xe5:
if (AGP_BRIDGE_ALI(dev->local)) {
if (!(dev->ctl & 0x20))
return;
}
break;
case 0xe6:
if (AGP_BRIDGE_ALI(dev->local)) {
if (dev->ctl & 0x20)
val &= 0xc0;
else
return;
}
break;
case 0xe7:
if (AGP_BRIDGE_ALI(dev->local)) {
if (!(dev->ctl & 0x20))
return;
}
break;
default:
break;
}
dev->regs[addr] = val;
}
static uint8_t
pci_bridge_read(int func, int addr, void *priv)
{
const pci_bridge_t *dev = (pci_bridge_t *) priv;
uint8_t ret;
if (func > 0)
ret = 0xff;
else
ret = dev->regs[addr];
pci_bridge_log("PCI Bridge %d: read(%d, %02X) = %02X\n", dev->bus_index, func, addr, ret);
return ret;
}
static void
pci_bridge_reset(void *priv)
{
pci_bridge_t *dev = (pci_bridge_t *) priv;
pci_bridge_log("PCI Bridge %d: reset()\n", dev->bus_index);
memset(dev->regs, 0, sizeof(dev->regs));
/* IDs */
dev->regs[0x00] = dev->local >> 16;
dev->regs[0x01] = dev->local >> 24;
dev->regs[0x02] = dev->local;
dev->regs[0x03] = dev->local >> 8;
/* command and status */
switch (dev->local) {
case PCI_BRIDGE_DEC_21150:
dev->regs[0x06] = 0x80;
dev->regs[0x07] = 0x02;
break;
case AGP_BRIDGE_ALI_M5243:
dev->regs[0x04] = 0x06;
dev->regs[0x07] = 0x04;
dev->regs[0x0d] = 0x20;
dev->regs[0x19] = 0x01;
dev->regs[0x1b] = 0x20;
dev->regs[0x34] = 0xe0;
dev->regs[0x89] = 0x20;
dev->regs[0x8a] = 0xa0;
dev->regs[0x8e] = 0x20;
dev->regs[0x8f] = 0x20;
dev->regs[0xe0] = 0x01;
pci_remap_bus(dev->bus_index, 0x01);
break;
case AGP_BRIDGE_ALI_M5247:
dev->regs[0x04] = 0x03;
dev->regs[0x08] = 0x01;
break;
case AGP_BRIDGE_INTEL_440LX:
dev->regs[0x06] = 0xa0;
dev->regs[0x07] = 0x02;
dev->regs[0x08] = 0x03;
break;
case AGP_BRIDGE_INTEL_440BX:
case AGP_BRIDGE_INTEL_440GX:
dev->regs[0x06] = 0x20;
dev->regs[0x07] = dev->regs[0x08] = 0x02;
break;
case AGP_BRIDGE_VIA_597:
case AGP_BRIDGE_VIA_598:
case AGP_BRIDGE_VIA_691:
case AGP_BRIDGE_VIA_8601:
dev->regs[0x04] = 0x07;
dev->regs[0x06] = 0x20;
dev->regs[0x07] = 0x02;
break;
default:
break;
}
/* class */
dev->regs[0x0a] = 0x04; /* PCI-PCI bridge */
dev->regs[0x0b] = 0x06; /* bridge device */
dev->regs[0x0e] = 0x01; /* bridge header */
/* IO BARs */
if (AGP_BRIDGE(dev->local))
dev->regs[0x1c] = 0xf0;
else
dev->regs[0x1c] = dev->regs[0x1d] = 0x01;
if (dev->local == AGP_BRIDGE_ALI_M5247)
dev->regs[0x1e] = 0x20;
else if (!AGP_BRIDGE_VIA(dev->local)) {
dev->regs[0x1e] = AGP_BRIDGE(dev->local) ? 0xa0 : 0x80;
dev->regs[0x1f] = 0x02;
}
/* prefetchable memory limits */
if (AGP_BRIDGE(dev->local)) {
dev->regs[0x20] = dev->regs[0x24] = 0xf0;
dev->regs[0x21] = dev->regs[0x25] = 0xff;
} else {
dev->regs[0x24] = dev->regs[0x26] = 0x01;
}
/* power management */
if (dev->local == PCI_BRIDGE_DEC_21150) {
dev->regs[0x34] = 0xdc;
dev->regs[0x43] = 0x02;
dev->regs[0xdc] = dev->regs[0xde] = 0x01;
}
}
static void *
pci_bridge_init(const device_t *info)
{
uint8_t interrupts[4];
uint8_t interrupt_count;
uint8_t interrupt_mask;
uint8_t slot_count;
pci_bridge_t *dev = (pci_bridge_t *) malloc(sizeof(pci_bridge_t));
memset(dev, 0, sizeof(pci_bridge_t));
dev->local = info->local;
dev->bus_index = pci_register_bus();
pci_bridge_log("PCI Bridge %d: init()\n", dev->bus_index);
pci_bridge_reset(dev);
pci_add_bridge(AGP_BRIDGE(dev->local), pci_bridge_read, pci_bridge_write, dev, &dev->slot);
interrupt_count = sizeof(interrupts);
interrupt_mask = interrupt_count - 1;
if (dev->slot < 32) {
for (uint8_t i = 0; i < interrupt_count; i++)
interrupts[i] = pci_get_int(dev->slot, PCI_INTA + i);
}
pci_bridge_log("PCI Bridge %d: upstream bus %02X slot %02X interrupts %02X %02X %02X %02X\n",
dev->bus_index, (dev->slot >> 5) & 0xff, dev->slot & 31, interrupts[0],
interrupts[1], interrupts[2], interrupts[3]);
if (info->local == PCI_BRIDGE_DEC_21150)
slot_count = 9; /* 9 bus masters */
else
slot_count = 1; /* AGP bridges always have 1 slot */
for (uint8_t i = 0; i < slot_count; i++) {
/* Interrupts for bridge slots are assigned in round-robin: ABCD, BCDA, CDAB and so on. */
pci_bridge_log("PCI Bridge %d: downstream slot %02X interrupts %02X %02X %02X %02X\n",
dev->bus_index, i, interrupts[i & interrupt_mask],
interrupts[(i + 1) & interrupt_mask], interrupts[(i + 2) & interrupt_mask],
interrupts[(i + 3) & interrupt_mask]);
pci_register_bus_slot(dev->bus_index, i, AGP_BRIDGE(dev->local) ? PCI_CARD_AGP : PCI_CARD_NORMAL,
interrupts[i & interrupt_mask],
interrupts[(i + 1) & interrupt_mask],
interrupts[(i + 2) & interrupt_mask],
interrupts[(i + 3) & interrupt_mask]);
}
return dev;
}
/* PCI bridges */
const device_t dec21150_device = {
.name = "DEC 21150 PCI Bridge",
.internal_name = "dec21150",
.flags = DEVICE_PCI,
.local = PCI_BRIDGE_DEC_21150,
.init = pci_bridge_init,
.close = NULL,
.reset = pci_bridge_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
/* AGP bridges */
const device_t ali5243_agp_device = {
.name = "ALi M5243 AGP Bridge",
.internal_name = "ali5243_agp",
.flags = DEVICE_PCI,
.local = AGP_BRIDGE_ALI_M5243,
.init = pci_bridge_init,
.close = NULL,
.reset = pci_bridge_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
/* AGP bridges */
const device_t ali5247_agp_device = {
.name = "ALi M5247 AGP Bridge",
.internal_name = "ali5247_agp",
.flags = DEVICE_PCI,
.local = AGP_BRIDGE_ALI_M5247,
.init = pci_bridge_init,
.close = NULL,
.reset = pci_bridge_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t i440lx_agp_device = {
.name = "Intel 82443LX/EX AGP Bridge",
.internal_name = "i440lx_agp",
.flags = DEVICE_PCI,
.local = AGP_BRIDGE_INTEL_440LX,
.init = pci_bridge_init,
.close = NULL,
.reset = pci_bridge_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t i440bx_agp_device = {
.name = "Intel 82443BX/ZX AGP Bridge",
.internal_name = "i440bx_agp",
.flags = DEVICE_PCI,
.local = AGP_BRIDGE_INTEL_440BX,
.init = pci_bridge_init,
.close = NULL,
.reset = pci_bridge_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t i440gx_agp_device = {
.name = "Intel 82443GX AGP Bridge",
.internal_name = "i440gx_agp",
.flags = DEVICE_PCI,
.local = AGP_BRIDGE_INTEL_440GX,
.init = pci_bridge_init,
.close = NULL,
.reset = pci_bridge_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t via_vp3_agp_device = {
.name = "VIA Apollo VP3 AGP Bridge",
.internal_name = "via_vp3_agp",
.flags = DEVICE_PCI,
.local = AGP_BRIDGE_VIA_597,
.init = pci_bridge_init,
.close = NULL,
.reset = pci_bridge_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t via_mvp3_agp_device = {
.name = "VIA Apollo MVP3 AGP Bridge",
.internal_name = "via_mvp3_agp",
.flags = DEVICE_PCI,
.local = AGP_BRIDGE_VIA_598,
.init = pci_bridge_init,
.close = NULL,
.reset = pci_bridge_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t via_apro_agp_device = {
.name = "VIA Apollo Pro AGP Bridge",
.internal_name = "via_apro_agp",
.flags = DEVICE_PCI,
.local = AGP_BRIDGE_VIA_691,
.init = pci_bridge_init,
.close = NULL,
.reset = pci_bridge_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t via_vt8601_agp_device = {
.name = "VIA Apollo ProMedia AGP Bridge",
.internal_name = "via_vt8601_agp",
.flags = DEVICE_PCI,
.local = AGP_BRIDGE_VIA_8601,
.init = pci_bridge_init,
.close = NULL,
.reset = pci_bridge_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
const device_t sis_5xxx_agp_device = {
.name = "SiS 5591/(5)600 AGP Bridge",
.internal_name = "via_5xxx_agp",
.flags = DEVICE_PCI,
.local = AGP_BRIDGE_SIS_5XXX,
.init = pci_bridge_init,
.close = NULL,
.reset = pci_bridge_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/device/pci_bridge.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 5,905 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of a generic SiS 5595-compatible SMBus host
* controller.
*
* Authors: RichardG, <richardg867@gmail.com>
* Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/io.h>
#include <86box/device.h>
#include <86box/timer.h>
#include <86box/i2c.h>
#include <86box/pci.h>
#include <86box/smbus.h>
#include <86box/plat_fallthrough.h>
#ifdef ENABLE_SMBUS_SIS5595_LOG
int smbus_sis5595_do_log = ENABLE_SMBUS_SIS5595_LOG;
static void
smbus_sis5595_log(const char *fmt, ...)
{
va_list ap;
if (smbus_sis5595_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define smbus_sis5595_log(fmt, ...)
#endif
static void
smbus_sis5595_irq(smbus_sis5595_t *dev, int raise)
{
if (dev->irq_enable) {
if (raise)
pci_set_mirq(6, 1, &dev->irq_state);
else
pci_clear_mirq(6, 1, &dev->irq_state);
}
}
void
smbus_sis5595_irq_enable(void *priv, uint8_t enable)
{
smbus_sis5595_t *dev = (smbus_sis5595_t *) priv;
if (!enable && dev->irq_enable)
pci_clear_mirq(6, 1, &dev->irq_state);
dev->irq_enable = enable;
}
uint8_t
smbus_sis5595_read_index(void *priv)
{
smbus_sis5595_t *dev = (smbus_sis5595_t *) priv;
return dev->index;
}
uint8_t
smbus_sis5595_read_data(void *priv)
{
smbus_sis5595_t *dev = (smbus_sis5595_t *) priv;
uint8_t ret = 0x00;
switch (dev->index) {
case 0x00:
ret = dev->stat & 0xff;
break;
case 0x01:
ret = dev->stat >> 8;
break;
case 0x02:
ret = dev->ctl & 0xff;
break;
case 0x03:
ret = dev->ctl >> 8;
break;
case 0x04:
ret = dev->addr;
break;
case 0x05:
ret = dev->cmd;
break;
case 0x06:
ret = dev->block_ptr;
break;
case 0x07:
ret = dev->count;
break;
case 0x08 ... 0x0f:
ret = dev->data[(dev->index & 0x07) + (dev->block_ptr << 3)];
if (dev->index == 0x0f) {
dev->block_ptr = (dev->block_ptr + 1) & 3;
smbus_sis5595_irq(dev, dev->block_ptr != 0x00);
}
break;
case 0x10:
ret = dev->saved_addr;
break;
case 0x11:
ret = dev->data0;
break;
case 0x12:
ret = dev->data1;
break;
case 0x13:
ret = dev->alias;
break;
case 0xff:
ret = dev->reg_ff & 0xc0;
break;
default:
break;
}
smbus_sis5595_log("SMBus SIS5595: read(%02X) = %02x\n", dev->addr, ret);
return ret;
}
void
smbus_sis5595_write_index(void *priv, uint8_t val)
{
smbus_sis5595_t *dev = (smbus_sis5595_t *) priv;
dev->index = val;
}
void
smbus_sis5595_write_data(void *priv, uint8_t val)
{
smbus_sis5595_t *dev = (smbus_sis5595_t *) priv;
uint8_t smbus_addr;
uint8_t cmd;
uint8_t read;
uint16_t prev_stat;
uint16_t timer_bytes = 0;
smbus_sis5595_log("SMBus SIS5595: write(%02X, %02X)\n", dev->addr, val);
prev_stat = dev->next_stat;
dev->next_stat = 0x0000;
switch (dev->index) {
case 0x00:
dev->stat &= ~(val & 0xf0);
/* Make sure IDLE is set if we're not busy or errored. */
if (dev->stat == 0x04)
dev->stat = 0x00;
break;
case 0x01:
dev->stat &= ~(val & 0x07);
break;
case 0x02:
dev->ctl = (dev->ctl & 0xff00) | val;
if (val & 0x20) { /* cancel an in-progress command if KILL is set */
if (prev_stat) { /* cancel only if a command is in progress */
timer_disable(&dev->response_timer);
dev->stat = 0x80; /* raise FAILED */
}
} else if (val & 0x10) {
/* dispatch command if START is set */
timer_bytes++; /* address */
smbus_addr = (dev->addr >> 1);
read = dev->addr & 0x01;
cmd = (dev->ctl >> 1) & 0x7;
smbus_sis5595_log("SMBus SIS5595: addr=%02X read=%d protocol=%X cmd=%02X "
"data0=%02X data1=%02X\n", smbus_addr, read, cmd, dev->cmd,
dev->data0, dev->data1);
/* Raise DEV_ERR if no device is at this address, or if the device returned
NAK when starting the transfer. */
if (!i2c_start(i2c_smbus, smbus_addr, read)) {
dev->next_stat = 0x0020;
break;
}
dev->next_stat = 0x0040; /* raise INTER (command completed) by default */
/* Decode the command protocol. */
dev->block_ptr = 0x01;
switch (cmd) {
case 0x0: /* quick R/W */
break;
case 0x1: /* byte R/W */
if (read) /* byte read */
dev->data[0] = i2c_read(i2c_smbus, smbus_addr);
else /* byte write */
i2c_write(i2c_smbus, smbus_addr, dev->data[0]);
timer_bytes++;
break;
case 0x2: /* byte data R/W */
/* command write */
i2c_write(i2c_smbus, smbus_addr, dev->cmd);
timer_bytes++;
if (read) /* byte read */
dev->data[0] = i2c_read(i2c_smbus, smbus_addr);
else /* byte write */
i2c_write(i2c_smbus, smbus_addr, dev->data[0]);
timer_bytes++;
break;
case 0x3: /* word data R/W */
/* command write */
i2c_write(i2c_smbus, smbus_addr, dev->cmd);
timer_bytes++;
if (read) { /* word read */
dev->data[0] = i2c_read(i2c_smbus, smbus_addr);
dev->data[1] = i2c_read(i2c_smbus, smbus_addr);
} else { /* word write */
i2c_write(i2c_smbus, smbus_addr, dev->data[0]);
i2c_write(i2c_smbus, smbus_addr, dev->data[1]);
}
timer_bytes += 2;
break;
case 0x5: /* block R/W */
dev->block_ptr = 0x00;
timer_bytes++; /* count the SMBus length byte now */
fallthrough;
default: /* unknown */
dev->next_stat = 0x0010; /* raise DEV_ERR */
timer_bytes = 0;
break;
}
/* Finish transfer. */
i2c_stop(i2c_smbus, smbus_addr);
}
break;
case 0x03:
dev->ctl = (dev->ctl & 0x00ff) | (val << 8);
break;
case 0x04:
dev->addr = val;
break;
case 0x05:
dev->cmd = val;
break;
case 0x08 ... 0x0f:
dev->data[dev->index & 0x07] = val;
break;
case 0x10:
dev->saved_addr = val;
break;
case 0x11:
dev->data0 = val;
break;
case 0x12:
dev->data1 = val;
break;
case 0x13:
dev->alias = val & 0xfe;
break;
case 0xff:
dev->reg_ff = val & 0x3f;
break;
default:
break;
}
if (dev->next_stat != 0x04) { /* schedule dispatch of any pending status register update */
dev->stat = 0x08; /* raise HOST_BUSY while waiting */
timer_disable(&dev->response_timer);
/* delay = ((half clock for start + half clock for stop) + (bytes * (8 bits + ack))) * 60us period measured on real VIA 686B */
timer_set_delay_u64(&dev->response_timer, (1 + (timer_bytes * 9)) * 60 * TIMER_USEC);
}
}
static void
smbus_sis5595_response(void *priv)
{
smbus_sis5595_t *dev = (smbus_sis5595_t *) priv;
/* Dispatch the status register update. */
dev->stat = dev->next_stat;
}
static void
smbus_sis5595_reset(void *priv)
{
smbus_sis5595_t *dev = (smbus_sis5595_t *) priv;
timer_disable(&dev->response_timer);
dev->stat = 0x0000;
dev->block_ptr = 0x01;
}
static void *
smbus_sis5595_init(const device_t *info)
{
smbus_sis5595_t *dev = (smbus_sis5595_t *) malloc(sizeof(smbus_sis5595_t));
memset(dev, 0, sizeof(smbus_sis5595_t));
dev->local = info->local;
/* We save the I2C bus handle on dev but use i2c_smbus for all operations because
dev and therefore dev->i2c will be invalidated if a device triggers a hard reset. */
i2c_smbus = dev->i2c = i2c_addbus("smbus_sis5595");
timer_add(&dev->response_timer, smbus_sis5595_response, dev, 0);
smbus_sis5595_reset(dev);
return dev;
}
static void
smbus_sis5595_close(void *priv)
{
smbus_sis5595_t *dev = (smbus_sis5595_t *) priv;
if (i2c_smbus == dev->i2c)
i2c_smbus = NULL;
i2c_removebus(dev->i2c);
free(dev);
}
const device_t sis5595_smbus_device = {
.name = "SiS 5595-compatible SMBus Host Controller",
.internal_name = "sis5595_smbus",
.flags = DEVICE_AT,
.local = 0,
.init = smbus_sis5595_init,
.close = smbus_sis5595_close,
.reset = smbus_sis5595_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/device/smbus_sis5595.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,954 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Emulation of the VIA VT82C686A/B integrated hardware monitor.
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#define HAVE_STDARG_H
#include <wchar.h>
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/io.h>
#include <86box/hwm.h>
#include <86box/plat_unused.h>
#define CLAMP(a, min, max) (((a) < (min)) ? (min) : (((a) > (max)) ? (max) : (a)))
/* Formulas and factors derived from Linux's via686a.c driver. */
#define VT82C686_RPM_TO_REG(r, d) ((r) ? CLAMP(1350000 / (r * d), 1, 255) : 0)
#define VT82C686_TEMP_TO_REG(t) (-1.160370e-10 * (t * t * t * t * t * t) + 3.193693e-08 * (t * t * t * t * t) - 1.464447e-06 * (t * t * t * t) - 2.525453e-04 * (t * t * t) + 1.424593e-02 * (t * t) + 2.148941e+00 * t + 7.275808e+01)
#define VT82C686_VOLTAGE_TO_REG(v, f) CLAMP((((v) * (2.628 / (f))) - 120.5) / 25, 0, 255)
typedef struct vt82c686_t {
hwm_values_t *values;
uint8_t enable;
uint16_t io_base;
uint8_t regs[128];
} vt82c686_t;
static double voltage_factors[5] = { 1.25, 1.25, 1.67, 2.6, 6.3 };
static void vt82c686_reset(vt82c686_t *dev, uint8_t initialization);
static uint8_t
vt82c686_read(uint16_t addr, void *priv)
{
const vt82c686_t *dev = (vt82c686_t *) priv;
uint8_t ret;
addr -= dev->io_base;
switch (addr) {
case 0x00 ... 0x0f:
case 0x50 ... 0x7f: /* undefined registers */
/* Real 686B returns the contents of 0x40. */
ret = dev->regs[0x40];
break;
case 0x1f:
case 0x20:
case 0x21: /* temperatures */
ret = VT82C686_TEMP_TO_REG(dev->values->temperatures[(addr == 0x1f) ? 2 : (addr & 1)]);
break;
case 0x22:
case 0x23:
case 0x24:
case 0x25:
case 0x26: /* voltages */
ret = VT82C686_VOLTAGE_TO_REG(dev->values->voltages[addr - 0x22], voltage_factors[addr - 0x22]);
break;
case 0x29:
case 0x2a: /* fan speeds */
ret = VT82C686_RPM_TO_REG(dev->values->fans[addr - 0x29], 1 << ((dev->regs[0x47] >> ((addr == 0x29) ? 4 : 6)) & 0x3));
break;
default: /* other registers */
ret = dev->regs[addr];
break;
}
return ret;
}
static void
vt82c686_write(uint16_t port, uint8_t val, void *priv)
{
vt82c686_t *dev = (vt82c686_t *) priv;
uint8_t reg = port & 0x7f;
switch (reg) {
case 0x00 ... 0x0f:
case 0x3f:
case 0x41:
case 0x42:
case 0x4a:
case 0x4c ... 0x7f:
/* Read-only registers. */
return;
case 0x40:
/* Reset if requested. */
if (val & 0x80) {
vt82c686_reset(dev, 1);
return;
}
break;
case 0x48:
val &= 0x7f;
break;
default:
break;
}
dev->regs[reg] = val;
}
/* Writes to hardware monitor-related configuration space registers
of the VT82C686 power management function are sent here by via_pipc.c */
void
vt82c686_hwm_write(uint8_t addr, uint8_t val, void *priv)
{
vt82c686_t *dev = (vt82c686_t *) priv;
if (dev->io_base)
io_removehandler(dev->io_base, 128,
vt82c686_read, NULL, NULL, vt82c686_write, NULL, NULL, dev);
switch (addr) {
case 0x70:
dev->io_base &= 0xff00;
dev->io_base |= val & 0x80;
break;
case 0x71:
dev->io_base &= 0x00ff;
dev->io_base |= val << 8;
break;
case 0x74:
dev->enable = val & 0x01;
break;
default:
break;
}
if (dev->enable && dev->io_base)
io_sethandler(dev->io_base, 128,
vt82c686_read, NULL, NULL, vt82c686_write, NULL, NULL, dev);
}
static void
vt82c686_reset(vt82c686_t *dev, uint8_t initialization)
{
memset(dev->regs, 0, sizeof(dev->regs));
dev->regs[0x17] = 0x80;
dev->regs[0x3f] = 0xa2;
dev->regs[0x40] = 0x08;
dev->regs[0x47] = 0x50;
dev->regs[0x4b] = 0x15;
if (!initialization)
vt82c686_hwm_write(0x74, 0x00, dev);
}
static void
vt82c686_close(void *priv)
{
vt82c686_t *dev = (vt82c686_t *) priv;
free(dev);
}
static void *
vt82c686_init(UNUSED(const device_t *info))
{
vt82c686_t *dev = (vt82c686_t *) malloc(sizeof(vt82c686_t));
memset(dev, 0, sizeof(vt82c686_t));
/* Set default values. Since this hardware monitor has a complex voltage factor system,
the values struct contains voltage values *before* applying their respective factors. */
hwm_values_t defaults = {
// clang-format off
{ /* fan speeds */
3000, /* usually CPU */
3000 /* usually Chassis */
}, { /* temperatures */
30, /* usually CPU */
30, /* usually System */
30
}, { /* voltages */
hwm_get_vcore(), /* Vcore */
2500, /* +2.5V */
3300, /* +3.3V */
5000, /* +5V */
12000 /* +12V */
}
// clang-format on
};
hwm_values = defaults;
dev->values = &hwm_values;
vt82c686_reset(dev, 0);
return dev;
}
const device_t via_vt82c686_hwm_device = {
.name = "VIA VT82C686 Integrated Hardware Monitor",
.internal_name = "via_vt82c686_hwm",
.flags = DEVICE_ISA,
.local = 0,
.init = vt82c686_init,
.close = vt82c686_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/device/hwm_vt82c686.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,955 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of a generic ALi M7101-compatible SMBus host
* controller.
*
* Authors: RichardG, <richardg867@gmail.com>
* Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/io.h>
#include <86box/device.h>
#include <86box/timer.h>
#include <86box/i2c.h>
#include <86box/smbus.h>
#include <86box/plat_fallthrough.h>
#ifdef ENABLE_SMBUS_ALI7101_LOG
int smbus_ali7101_do_log = ENABLE_SMBUS_ALI7101_LOG;
static void
smbus_ali7101_log(const char *fmt, ...)
{
va_list ap;
if (smbus_ali7101_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define smbus_ali7101_log(fmt, ...)
#endif
static uint8_t
smbus_ali7101_read(uint16_t addr, void *priv)
{
smbus_ali7101_t *dev = (smbus_ali7101_t *) priv;
uint8_t ret = 0x00;
switch (addr - dev->io_base) {
case 0x00:
ret = dev->stat;
break;
case 0x03:
ret = dev->addr;
break;
case 0x04:
ret = dev->data0;
break;
case 0x05:
ret = dev->data1;
break;
case 0x06:
ret = dev->data[dev->index++];
if (dev->index >= SMBUS_ALI7101_BLOCK_DATA_SIZE)
dev->index = 0;
break;
case 0x07:
ret = dev->cmd;
break;
default:
break;
}
smbus_ali7101_log("SMBus ALI7101: read(%02X) = %02x\n", addr, ret);
return ret;
}
static void
smbus_ali7101_write(uint16_t addr, uint8_t val, void *priv)
{
smbus_ali7101_t *dev = (smbus_ali7101_t *) priv;
uint8_t smbus_addr;
uint8_t cmd;
uint8_t read;
uint8_t prev_stat;
uint16_t timer_bytes = 0;
smbus_ali7101_log("SMBus ALI7101: write(%02X, %02X)\n", addr, val);
prev_stat = dev->next_stat;
dev->next_stat = 0x04;
switch (addr - dev->io_base) {
case 0x00:
dev->stat &= ~(val & 0xf2);
/* Make sure IDLE is set if we're not busy or errored. */
if (dev->stat == 0x00)
dev->stat = 0x04;
break;
case 0x01:
dev->ctl = val & 0xfc;
if (val & 0x04) { /* cancel an in-progress command if KILL is set */
if (prev_stat) { /* cancel only if a command is in progress */
timer_disable(&dev->response_timer);
dev->stat = 0x80; /* raise FAILED */
}
} else if (val & 0x08) { /* T_OUT_CMD */
if (prev_stat) { /* cancel only if a command is in progress */
timer_disable(&dev->response_timer);
dev->stat = 0x20; /* raise DEVICE_ERR */
}
}
if (val & 0x80)
dev->index = 0;
break;
case 0x02:
/* dispatch command if START is set */
timer_bytes++; /* address */
smbus_addr = (dev->addr >> 1);
read = dev->addr & 0x01;
cmd = (dev->ctl >> 4) & 0x7;
smbus_ali7101_log("SMBus ALI7101: addr=%02X read=%d protocol=%X cmd=%02X data0=%02X data1=%02X\n", smbus_addr, read, cmd, dev->cmd, dev->data0, dev->data1);
/* Raise DEV_ERR if no device is at this address, or if the device returned NAK when starting the transfer. */
if (!i2c_start(i2c_smbus, smbus_addr, read)) {
dev->next_stat = 0x40;
break;
}
dev->next_stat = 0x10; /* raise INTER (command completed) by default */
/* Decode the command protocol. */
switch (cmd) {
case 0x0: /* quick R/W */
break;
case 0x1: /* byte R/W */
if (read) /* byte read */
dev->data0 = i2c_read(i2c_smbus, smbus_addr);
else /* byte write */
i2c_write(i2c_smbus, smbus_addr, dev->data0);
timer_bytes++;
break;
case 0x2: /* byte data R/W */
/* command write */
i2c_write(i2c_smbus, smbus_addr, dev->cmd);
timer_bytes++;
if (read) /* byte read */
dev->data0 = i2c_read(i2c_smbus, smbus_addr);
else /* byte write */
i2c_write(i2c_smbus, smbus_addr, dev->data0);
timer_bytes++;
break;
case 0x3: /* word data R/W */
/* command write */
i2c_write(i2c_smbus, smbus_addr, dev->cmd);
timer_bytes++;
if (read) { /* word read */
dev->data0 = i2c_read(i2c_smbus, smbus_addr);
dev->data1 = i2c_read(i2c_smbus, smbus_addr);
} else { /* word write */
i2c_write(i2c_smbus, smbus_addr, dev->data0);
i2c_write(i2c_smbus, smbus_addr, dev->data1);
}
timer_bytes += 2;
break;
case 0x4: /* block R/W */
timer_bytes++; /* count the SMBus length byte now */
fallthrough;
default: /* unknown */
dev->next_stat = 0x20; /* raise DEV_ERR */
timer_bytes = 0;
break;
}
/* Finish transfer. */
i2c_stop(i2c_smbus, smbus_addr);
break;
case 0x03:
dev->addr = val;
break;
case 0x04:
dev->data0 = val;
break;
case 0x05:
dev->data1 = val;
break;
case 0x06:
dev->data[dev->index++] = val;
if (dev->index >= SMBUS_ALI7101_BLOCK_DATA_SIZE)
dev->index = 0;
break;
case 0x07:
dev->cmd = val;
break;
default:
break;
}
if (dev->next_stat != 0x04) { /* schedule dispatch of any pending status register update */
dev->stat = 0x08; /* raise HOST_BUSY while waiting */
timer_disable(&dev->response_timer);
/* delay = ((half clock for start + half clock for stop) + (bytes * (8 bits + ack))) * 60us period measured on real VIA 686B */
timer_set_delay_u64(&dev->response_timer, (1 + (timer_bytes * 9)) * 60 * TIMER_USEC);
}
}
static void
smbus_ali7101_response(void *priv)
{
smbus_ali7101_t *dev = (smbus_ali7101_t *) priv;
/* Dispatch the status register update. */
dev->stat = dev->next_stat;
}
void
smbus_ali7101_remap(smbus_ali7101_t *dev, uint16_t new_io_base, uint8_t enable)
{
if (dev->io_base)
io_removehandler(dev->io_base, 0x10, smbus_ali7101_read, NULL, NULL, smbus_ali7101_write, NULL, NULL, dev);
dev->io_base = new_io_base;
smbus_ali7101_log("SMBus ALI7101: remap to %04Xh (%sabled)\n", dev->io_base, enable ? "en" : "dis");
if (enable && dev->io_base)
io_sethandler(dev->io_base, 0x10, smbus_ali7101_read, NULL, NULL, smbus_ali7101_write, NULL, NULL, dev);
}
static void
smbus_ali7101_reset(void *priv)
{
smbus_ali7101_t *dev = (smbus_ali7101_t *) priv;
timer_disable(&dev->response_timer);
dev->stat = 0x04;
}
static void *
smbus_ali7101_init(const device_t *info)
{
smbus_ali7101_t *dev = (smbus_ali7101_t *) malloc(sizeof(smbus_ali7101_t));
memset(dev, 0, sizeof(smbus_ali7101_t));
dev->local = info->local;
dev->stat = 0x04;
/* We save the I2C bus handle on dev but use i2c_smbus for all operations because
dev and therefore dev->i2c will be invalidated if a device triggers a hard reset. */
i2c_smbus = dev->i2c = i2c_addbus("smbus_ali7101");
timer_add(&dev->response_timer, smbus_ali7101_response, dev, 0);
return dev;
}
static void
smbus_ali7101_close(void *priv)
{
smbus_ali7101_t *dev = (smbus_ali7101_t *) priv;
if (i2c_smbus == dev->i2c)
i2c_smbus = NULL;
i2c_removebus(dev->i2c);
free(dev);
}
const device_t ali7101_smbus_device = {
.name = "ALi M7101-compatible SMBus Host Controller",
.internal_name = "ali7101_smbus",
.flags = DEVICE_AT,
.local = 0,
.init = smbus_ali7101_init,
.close = smbus_ali7101_close,
.reset = smbus_ali7101_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/device/smbus_ali7101.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,586 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of PS/2 series Mouse devices.
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdarg.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include "cpu.h"
#include <86box/device.h>
#include <86box/keyboard.h>
#include <86box/mouse.h>
#include <86box/plat.h>
#include <86box/plat_unused.h>
enum {
MODE_STREAM,
MODE_REMOTE,
MODE_ECHO
};
#define FLAG_EXPLORER 0x200 /* Has 5 buttons */
#define FLAG_5BTN 0x100 /* using Intellimouse Optical mode */
#define FLAG_INTELLI 0x80 /* device is IntelliMouse */
#define FLAG_INTMODE 0x40 /* using Intellimouse mode */
#define FLAG_SCALED 0x20 /* enable delta scaling */
#define FLAG_ENABLED 0x10 /* dev is enabled for use */
#define FLAG_CTRLDAT 0x08 /* ctrl or data mode */
#define FIFO_SIZE 16
int mouse_scan = 0;
#ifdef ENABLE_MOUSE_PS2_LOG
int mouse_ps2_do_log = ENABLE_MOUSE_PS2_LOG;
static void
mouse_ps2_log(const char *fmt, ...)
{
va_list ap;
if (mouse_ps2_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define mouse_ps2_log(fmt, ...)
#endif
void
mouse_clear_data(void *priv)
{
atkbc_dev_t *dev = (atkbc_dev_t *) priv;
dev->flags &= ~FLAG_CTRLDAT;
}
static void
ps2_report_coordinates(atkbc_dev_t *dev, int main)
{
uint8_t buff[3] = { 0x08, 0x00, 0x00 };
int delta_x;
int delta_y;
int overflow_x;
int overflow_y;
int b = mouse_get_buttons_ex();
int delta_z;
mouse_subtract_coords(&delta_x, &delta_y, &overflow_x, &overflow_y,
-256, 255, 1, 0);
mouse_subtract_z(&delta_z, -8, 7, 1);
buff[0] |= (overflow_y << 7) | (overflow_x << 6) |
((delta_y & 0x0100) >> 3) | ((delta_x & 0x0100) >> 4) |
(b & ((dev->flags & FLAG_INTELLI) ? 0x07 : 0x03));
buff[1] = (delta_x & 0x00ff);
buff[2] = (delta_y & 0x00ff);
kbc_at_dev_queue_add(dev, buff[0], main);
kbc_at_dev_queue_add(dev, buff[1], main);
kbc_at_dev_queue_add(dev, buff[2], main);
if (dev->flags & FLAG_INTMODE) {
delta_z &= 0x0f;
if (dev->flags & FLAG_5BTN) {
if (b & 8)
delta_z |= 0x10;
if (b & 16)
delta_z |= 0x20;
} else {
/* The wheel coordinate is sign-extended. */
if (delta_z & 0x08)
delta_z |= 0xf0;
}
kbc_at_dev_queue_add(dev, delta_z, main);
}
}
static void
ps2_set_defaults(atkbc_dev_t *dev)
{
dev->mode = MODE_STREAM;
dev->rate = 100;
mouse_set_sample_rate(100.0);
dev->resolution = 2;
dev->flags &= 0x188;
mouse_scan = 0;
}
static void
ps2_bat(void *priv)
{
atkbc_dev_t *dev = (atkbc_dev_t *) priv;
ps2_set_defaults(dev);
kbc_at_dev_queue_add(dev, 0xaa, 0);
kbc_at_dev_queue_add(dev, 0x00, 0);
}
static void
ps2_write(void *priv)
{
atkbc_dev_t *dev = (atkbc_dev_t *) priv;
int b;
uint8_t temp;
uint8_t val;
static uint8_t last_data[6] = { 0x00 };
if (dev->port == NULL)
return;
val = dev->port->dat;
dev->state = DEV_STATE_MAIN_OUT;
if (dev->flags & FLAG_CTRLDAT) {
dev->flags &= ~FLAG_CTRLDAT;
if (val == 0xff)
kbc_at_dev_reset(dev, 1);
else switch (dev->command) {
case 0xe8: /* set mouse resolution */
dev->resolution = val;
kbc_at_dev_queue_add(dev, 0xfa, 0);
mouse_ps2_log("%s: Set mouse resolution [%02X]\n", dev->name, val);
break;
case 0xf3: /* set sample rate */
dev->rate = val;
mouse_set_sample_rate((double) val);
kbc_at_dev_queue_add(dev, 0xfa, 0); /* Command response */
mouse_ps2_log("%s: Set sample rate [%02X]\n", dev->name, val);
break;
default:
kbc_at_dev_queue_add(dev, 0xfc, 0);
}
} else {
dev->command = val;
switch (dev->command) {
case 0xe6: /* set scaling to 1:1 */
mouse_ps2_log("%s: Set scaling to 1:1\n", dev->name);
dev->flags &= ~FLAG_SCALED;
kbc_at_dev_queue_add(dev, 0xfa, 0);
break;
case 0xe7: /* set scaling to 2:1 */
mouse_ps2_log("%s: Set scaling to 2:1\n", dev->name);
dev->flags |= FLAG_SCALED;
kbc_at_dev_queue_add(dev, 0xfa, 0);
break;
case 0xe8: /* set mouse resolution */
mouse_ps2_log("%s: Set mouse resolution\n", dev->name);
dev->flags |= FLAG_CTRLDAT;
kbc_at_dev_queue_add(dev, 0xfa, 0);
dev->state = DEV_STATE_MAIN_WANT_IN;
break;
case 0xe9: /* status request */
mouse_ps2_log("%s: Status request\n", dev->name);
b = mouse_get_buttons_ex();
kbc_at_dev_queue_add(dev, 0xfa, 0);
temp = (dev->flags & 0x20);
if (mouse_scan)
temp |= FLAG_ENABLED;
if (b & 1)
temp |= 4;
if (b & 2)
temp |= 1;
if ((b & 4) && (dev->flags & FLAG_INTELLI))
temp |= 2;
kbc_at_dev_queue_add(dev, temp, 0);
kbc_at_dev_queue_add(dev, dev->resolution, 0);
kbc_at_dev_queue_add(dev, dev->rate, 0);
break;
case 0xea: /* set stream */
mouse_ps2_log("%s: Set stream\n", dev->name);
dev->flags &= ~FLAG_CTRLDAT;
dev->mode = MODE_STREAM;
mouse_scan = 1;
kbc_at_dev_queue_add(dev, 0xfa, 0); /* ACK for command byte */
break;
case 0xeb: /* Get mouse data */
mouse_ps2_log("%s: Get mouse data\n", dev->name);
kbc_at_dev_queue_add(dev, 0xfa, 0);
ps2_report_coordinates(dev, 0);
break;
case 0xf0: /* set remote */
mouse_ps2_log("%s: Set remote\n", dev->name);
dev->flags &= ~FLAG_CTRLDAT;
dev->mode = MODE_REMOTE;
mouse_scan = 1;
kbc_at_dev_queue_add(dev, 0xfa, 0); /* ACK for command byte */
break;
case 0xf2: /* read ID */
mouse_ps2_log("%s: Read ID\n", dev->name);
kbc_at_dev_queue_add(dev, 0xfa, 0);
if (dev->flags & FLAG_INTMODE)
kbc_at_dev_queue_add(dev, (dev->flags & FLAG_5BTN) ? 0x04 : 0x03, 0);
else
kbc_at_dev_queue_add(dev, 0x00, 0);
break;
case 0xf3: /* set sample rate */
mouse_ps2_log("%s: Set sample rate\n", dev->name);
dev->flags |= FLAG_CTRLDAT;
kbc_at_dev_queue_add(dev, 0xfa, 0); /* ACK for command byte */
dev->state = DEV_STATE_MAIN_WANT_IN;
break;
case 0xf4: /* enable */
mouse_ps2_log("%s: Enable\n", dev->name);
mouse_scan = 1;
kbc_at_dev_queue_add(dev, 0xfa, 0);
break;
case 0xf5: /* disable */
mouse_ps2_log("%s: Disable\n", dev->name);
mouse_scan = 0;
kbc_at_dev_queue_add(dev, 0xfa, 0);
break;
case 0xf6: /* set defaults */
mouse_ps2_log("%s: Set defaults\n", dev->name);
ps2_set_defaults(dev);
kbc_at_dev_queue_add(dev, 0xfa, 0);
break;
case 0xff: /* reset */
mouse_ps2_log("%s: Reset\n", dev->name);
kbc_at_dev_reset(dev, 1);
break;
default:
mouse_ps2_log("%s: Bad command: %02X\n", dev->name, val);
kbc_at_dev_queue_add(dev, 0xfe, 0);
}
}
if (dev->flags & FLAG_INTELLI) {
for (temp = 0; temp < 5; temp++)
last_data[temp] = last_data[temp + 1];
last_data[5] = val;
if ((last_data[0] == 0xf3) && (last_data[1] == 0xc8) &&
(last_data[2] == 0xf3) && (last_data[3] == 0x64) &&
(last_data[4] == 0xf3) && (last_data[5] == 0x50))
dev->flags |= FLAG_INTMODE;
if ((dev->flags & FLAG_EXPLORER) && (dev->flags & FLAG_INTMODE) &&
(last_data[0] == 0xf3) && (last_data[1] == 0xc8) &&
(last_data[2] == 0xf3) && (last_data[3] == 0xc8) &&
(last_data[4] == 0xf3) && (last_data[5] == 0x50))
dev->flags |= FLAG_5BTN;
}
}
static int
ps2_poll(void *priv)
{
atkbc_dev_t *dev = (atkbc_dev_t *) priv;
int packet_size = (dev->flags & FLAG_INTMODE) ? 4 : 3;
int cond = (!mouse_capture && !video_fullscreen) || (!mouse_scan || !mouse_state_changed()) ||
((dev->mode == MODE_STREAM) && (kbc_at_dev_queue_pos(dev, 1) >= (FIFO_SIZE - packet_size)));
if (!cond && (dev->mode == MODE_STREAM))
ps2_report_coordinates(dev, 1);
return cond;
}
/*
* Initialize the device for use by the user.
*
* We also get called from the various machines.
*/
void *
mouse_ps2_init(const device_t *info)
{
atkbc_dev_t *dev = kbc_at_dev_init(DEV_AUX);
int i;
dev->name = info->name;
dev->type = info->local;
dev->mode = MODE_STREAM;
i = device_get_config_int("buttons");
if (i > 2)
dev->flags |= FLAG_INTELLI;
if (i > 4)
dev->flags |= FLAG_EXPLORER;
mouse_ps2_log("%s: buttons=%d\n", dev->name, i);
/* Tell them how many buttons we have. */
mouse_set_buttons(i);
dev->process_cmd = ps2_write;
dev->execute_bat = ps2_bat;
dev->scan = &mouse_scan;
dev->fifo_mask = FIFO_SIZE - 1;
if (dev->port != NULL)
kbc_at_dev_reset(dev, 0);
/* Return our private data to the I/O layer. */
return dev;
}
static void
ps2_close(void *priv)
{
atkbc_dev_t *dev = (atkbc_dev_t *) priv;
free(dev);
}
static const device_config_t ps2_config[] = {
// clang-format off
{
.name = "buttons",
.description = "Buttons",
.type = CONFIG_SELECTION,
.default_string = "",
.default_int = 2,
.file_filter = "",
.spinner = { 0 },
.selection = {
{ .description = "Two", .value = 2 },
{ .description = "Three", .value = 3 },
{ .description = "Wheel", .value = 4 },
{ .description = "Five + Wheel", .value = 5 },
{ .description = "" }
}
},
{
.name = "", .description = "", .type = CONFIG_END
}
// clang-format on
};
const device_t mouse_ps2_device = {
.name = "Standard PS/2 Mouse",
.internal_name = "ps2",
.flags = DEVICE_PS2,
.local = MOUSE_TYPE_PS2,
.init = mouse_ps2_init,
.close = ps2_close,
.reset = NULL,
{ .poll = ps2_poll },
.speed_changed = NULL,
.force_redraw = NULL,
.config = ps2_config
};
``` | /content/code_sandbox/src/device/mouse_ps2.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,328 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of ISA Plug and Play.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
* RichardG, <richardg867@gmail.com>
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/io.h>
#include <86box/isapnp.h>
#include <86box/plat_unused.h>
#define CHECK_CURRENT_LD() \
if (!ld) { \
isapnp_log("ISAPnP: No logical device selected\n"); \
goto vendor_defined; \
}
#define CHECK_CURRENT_CARD() \
if (!card) { \
isapnp_log("ISAPnP: No card in CONFIG state\n"); \
break; \
}
const uint8_t isapnp_init_key[32] = { 0x6A, 0xB5, 0xDA, 0xED, 0xF6, 0xFB, 0x7D, 0xBE,
0xDF, 0x6F, 0x37, 0x1B, 0x0D, 0x86, 0xC3, 0x61,
0xB0, 0x58, 0x2C, 0x16, 0x8B, 0x45, 0xA2, 0xD1,
0xE8, 0x74, 0x3A, 0x9D, 0xCE, 0xE7, 0x73, 0x39 };
static const device_t isapnp_device;
#ifdef ENABLE_ISAPNP_LOG
int isapnp_do_log = ENABLE_ISAPNP_LOG;
static void
isapnp_log(const char *fmt, ...)
{
va_list ap;
if (isapnp_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define isapnp_log(fmt, ...)
#endif
enum {
PNP_STATE_WAIT_FOR_KEY = 0,
PNP_STATE_CONFIG,
PNP_STATE_ISOLATION,
PNP_STATE_SLEEP
};
typedef struct _isapnp_device_ {
uint8_t number;
uint8_t regs[256];
uint8_t mem_upperlimit;
uint8_t irq_types;
uint8_t io_16bit;
uint8_t io_len[8];
const isapnp_device_config_t *defaults;
struct _isapnp_device_ *next;
} isapnp_device_t;
typedef struct _isapnp_card_ {
uint8_t enable;
uint8_t state;
uint8_t csn;
uint8_t ld;
uint8_t id_checksum;
uint8_t serial_read;
uint8_t serial_read_pair;
uint8_t serial_read_pos;
uint8_t *rom;
uint16_t rom_pos;
uint16_t rom_size;
void *priv;
/* ISAPnP memory and I/O addresses are awkwardly big endian, so we populate this
structure whenever something on some device changes, and pass it on instead. */
isapnp_device_config_t config;
void (*config_changed)(uint8_t ld, isapnp_device_config_t *config, void *priv);
void (*csn_changed)(uint8_t csn, void *priv);
uint8_t (*read_vendor_reg)(uint8_t ld, uint8_t reg, void *priv);
void (*write_vendor_reg)(uint8_t ld, uint8_t reg, uint8_t val, void *priv);
isapnp_device_t *first_ld;
struct _isapnp_card_ *next;
} isapnp_card_t;
typedef struct {
uint8_t reg;
uint8_t key_pos : 5;
uint16_t read_data_addr;
isapnp_card_t *first_card;
isapnp_card_t *isolated_card;
isapnp_card_t *current_ld_card;
isapnp_device_t *current_ld;
} isapnp_t;
static void
isapnp_device_config_changed(isapnp_card_t *card, isapnp_device_t *ld)
{
/* Ignore card if it hasn't signed up for configuration changes. */
if ((card == NULL) || !card->config_changed)
return;
/* Populate config structure, performing endianness conversion as needed. */
card->config.activate = ld->regs[0x30] & 0x01;
uint8_t reg_base;
for (uint8_t i = 0; i < 4; i++) {
reg_base = 0x40 + (8 * i);
card->config.mem[i].base = (ld->regs[reg_base] << 16) | (ld->regs[reg_base + 1] << 8);
card->config.mem[i].size = (ld->regs[reg_base + 3] << 16) | (ld->regs[reg_base + 4] << 8);
if (ld->regs[reg_base + 2] & 0x01) /* upper limit */
card->config.mem[i].size -= card->config.mem[i].base;
}
for (uint8_t i = 0; i < 4; i++) {
reg_base = (i == 0) ? 0x76 : (0x80 + (16 * i));
card->config.mem32[i].base = (ld->regs[reg_base] << 24) | (ld->regs[reg_base + 1] << 16) | (ld->regs[reg_base + 2] << 8) | ld->regs[reg_base + 3];
card->config.mem32[i].size = (ld->regs[reg_base + 5] << 24) | (ld->regs[reg_base + 6] << 16) | (ld->regs[reg_base + 7] << 8) | ld->regs[reg_base + 8];
if (ld->regs[reg_base + 4] & 0x01) /* upper limit */
card->config.mem32[i].size -= card->config.mem32[i].base;
}
for (uint8_t i = 0; i < 8; i++) {
reg_base = 0x60 + (2 * i);
if (ld->regs[0x31] & 0x02)
card->config.io[i].base = 0; /* let us handle I/O range check reads */
else
card->config.io[i].base = (ld->regs[reg_base] << 8) | ld->regs[reg_base + 1];
}
for (uint8_t i = 0; i < 2; i++) {
reg_base = 0x70 + (2 * i);
card->config.irq[i].irq = ld->regs[reg_base];
card->config.irq[i].level = ld->regs[reg_base + 1] & 0x02;
card->config.irq[i].type = ld->regs[reg_base + 1] & 0x01;
}
for (uint8_t i = 0; i < 2; i++) {
reg_base = 0x74 + i;
card->config.dma[i].dma = ld->regs[reg_base];
}
/* Signal the configuration change. */
card->config_changed(ld->number, &card->config, card->priv);
}
static void
isapnp_reset_ld_config(isapnp_device_t *ld)
{
/* Do nothing if there's no default configuration for this device. */
const isapnp_device_config_t *config = ld->defaults;
if (!config)
return;
/* Populate configuration registers. */
ld->regs[0x30] = !!config->activate;
uint8_t reg_base;
uint32_t size;
for (uint8_t i = 0; i < 4; i++) {
reg_base = 0x40 + (8 * i);
ld->regs[reg_base] = config->mem[i].base >> 16;
ld->regs[reg_base + 1] = config->mem[i].base >> 8;
size = config->mem[i].size;
if (ld->regs[reg_base + 2] & 0x01) /* upper limit */
size += config->mem[i].base;
ld->regs[reg_base + 3] = size >> 16;
ld->regs[reg_base + 4] = size >> 8;
}
for (uint8_t i = 0; i < 4; i++) {
reg_base = (i == 0) ? 0x76 : (0x80 + (16 * i));
ld->regs[reg_base] = config->mem32[i].base >> 24;
ld->regs[reg_base + 1] = config->mem32[i].base >> 16;
ld->regs[reg_base + 2] = config->mem32[i].base >> 8;
ld->regs[reg_base + 3] = config->mem32[i].base;
size = config->mem32[i].size;
if (ld->regs[reg_base + 4] & 0x01) /* upper limit */
size += config->mem32[i].base;
ld->regs[reg_base + 5] = size >> 24;
ld->regs[reg_base + 6] = size >> 16;
ld->regs[reg_base + 7] = size >> 8;
ld->regs[reg_base + 8] = size;
}
for (uint8_t i = 0; i < 8; i++) {
reg_base = 0x60 + (2 * i);
ld->regs[reg_base] = config->io[i].base >> 8;
ld->regs[reg_base + 1] = config->io[i].base;
}
for (uint8_t i = 0; i < 2; i++) {
reg_base = 0x70 + (2 * i);
ld->regs[reg_base] = config->irq[i].irq;
ld->regs[reg_base + 1] = (!!config->irq[i].level << 1) | !!config->irq[i].type;
}
for (uint8_t i = 0; i < 2; i++) {
reg_base = 0x74 + i;
ld->regs[reg_base] = config->dma[i].dma;
}
}
static void
isapnp_reset_ld_regs(isapnp_device_t *ld)
{
memset(ld->regs, 0, sizeof(ld->regs));
/* DMA disable uses a non-zero value. */
ld->regs[0x74] = ld->regs[0x75] = ISAPNP_DMA_DISABLED;
/* Set the upper limit bit on memory ranges which require it. */
for (uint8_t i = 0; i < 4; i++)
ld->regs[0x42 + (8 * i)] |= !!(ld->mem_upperlimit & (1 << i));
ld->regs[0x7a] |= !!(ld->mem_upperlimit & (1 << 4));
for (uint8_t i = 1; i < 4; i++)
ld->regs[0x84 + (16 * i)] |= !!(ld->mem_upperlimit & (1 << (4 + i)));
/* Set the default IRQ type bits. */
for (uint8_t i = 0; i < 2; i++) {
if (ld->irq_types & (0x1 << (4 * i)))
ld->regs[0x70 + (2 * i)] = 0x02;
else if (ld->irq_types & (0x2 << (4 * i)))
ld->regs[0x70 + (2 * i)] = 0x00;
else if (ld->irq_types & (0x4 << (4 * i)))
ld->regs[0x70 + (2 * i)] = 0x03;
else if (ld->irq_types & (0x8 << (4 * i)))
ld->regs[0x70 + (2 * i)] = 0x01;
}
/* Reset configuration registers to match the default configuration. */
isapnp_reset_ld_config(ld);
}
static uint8_t
isapnp_read_rangecheck(UNUSED(uint16_t addr), void *priv)
{
const isapnp_device_t *dev = (isapnp_device_t *) priv;
return (dev->regs[0x31] & 0x01) ? 0x55 : 0xaa;
}
static uint8_t
isapnp_read_common(isapnp_t *dev, isapnp_card_t *card, isapnp_device_t *ld, uint8_t reg)
{
uint8_t ret = 0xff;
uint8_t bit;
uint8_t next_shift;
switch (reg) {
case 0x01: /* Serial Isolation */
card = dev->first_card;
while (card) {
if (card->enable && card->rom && (card->state == PNP_STATE_ISOLATION))
break;
card = card->next;
}
dev->isolated_card = card;
if (card) {
if (card->serial_read_pair) { /* second byte (aa/00) */
card->serial_read <<= 1;
if (!card->serial_read_pos)
card->rom_pos = 0x09;
} else { /* first byte (55/00) */
if (card->serial_read_pos < 64) { /* reading 64-bit vendor/serial */
bit = (card->rom[card->serial_read_pos >> 3] >> (card->serial_read_pos & 0x7)) & 0x01;
next_shift = (!!(card->id_checksum & 0x02) ^ !!(card->id_checksum & 0x01) ^ bit) & 0x01;
card->id_checksum >>= 1;
card->id_checksum |= (next_shift << 7);
} else { /* reading 8-bit checksum */
if (card->serial_read_pos == 64) /* populate ID checksum in ROM */
card->rom[0x08] = card->id_checksum;
bit = (card->id_checksum >> (card->serial_read_pos & 0x7)) & 0x01;
}
isapnp_log("ISAPnP: Read bit %d of byte %02X (%02X) = %d\n", card->serial_read_pos & 0x7, card->serial_read_pos >> 3, card->rom[card->serial_read_pos >> 3], bit);
card->serial_read = bit ? 0x55 : 0x00;
card->serial_read_pos = (card->serial_read_pos + 1) % 72;
}
card->serial_read_pair ^= 1;
ret = card->serial_read;
}
break;
case 0x04: /* Resource Data */
CHECK_CURRENT_CARD();
isapnp_log("ISAPnP: Read resource data index %02X (%02X) from CSN %02X\n", card->rom_pos, card->rom[card->rom_pos], card->csn);
if (card->rom_pos >= card->rom_size)
ret = 0xff;
else
ret = card->rom[card->rom_pos++];
break;
case 0x05: /* Status */
ret = 0x00;
CHECK_CURRENT_CARD();
isapnp_log("ISAPnP: Query status for CSN %02X\n", card->csn);
ret = 0x01;
break;
case 0x06: /* Card Select Number */
ret = 0x00;
CHECK_CURRENT_CARD();
isapnp_log("ISAPnP: Query CSN %02X\n", card->csn);
ret = card->csn;
break;
case 0x07: /* Logical Device Number */
ret = 0x00;
CHECK_CURRENT_LD();
isapnp_log("ISAPnP: Query LDN for CSN %02X device %02X\n", card->csn, ld->number);
ret = ld->number;
break;
case 0x20 ... 0x2f:
case 0x38 ... 0x3f:
case 0xa9 ... 0xff:
vendor_defined:
CHECK_CURRENT_CARD();
isapnp_log("ISAPnP: Read vendor-defined register %02X from CSN %02X device %02X\n", reg, card->csn, ld ? ld->number : -1);
if (card->read_vendor_reg)
ret = card->read_vendor_reg(ld ? ld->number : -1, reg, card->priv);
break;
default:
if (reg >= 0x30) {
CHECK_CURRENT_LD();
isapnp_log("ISAPnP: Read register %02X from CSN %02X device %02X\n", reg, card->csn, ld->number);
ret = ld->regs[reg];
}
break;
}
isapnp_log("ISAPnP: read_common(%02X) = %02X\n", reg, ret);
return ret;
}
static uint8_t
isapnp_read_data(UNUSED(uint16_t addr), void *priv)
{
isapnp_t *dev = (isapnp_t *) priv;
isapnp_card_t *card = dev->first_card;
while (card) {
if (card->enable && (card->state == PNP_STATE_CONFIG))
break;
card = card->next;
}
isapnp_log("ISAPnP: read_data() => ");
return isapnp_read_common(dev, card, dev->current_ld, dev->reg);
}
static void
isapnp_set_read_data(uint16_t addr, isapnp_t *dev)
{
/* Remove existing READ_DATA port if set. */
if (dev->read_data_addr) {
io_removehandler(dev->read_data_addr, 1, isapnp_read_data, NULL, NULL, NULL, NULL, NULL, dev);
dev->read_data_addr = 0;
}
/* Set new READ_DATA port if within range. */
if ((addr >= 0x203) && (addr <= 0x3ff)) {
dev->read_data_addr = addr;
io_sethandler(dev->read_data_addr, 1, isapnp_read_data, NULL, NULL, NULL, NULL, NULL, dev);
}
}
static void
isapnp_write_addr(UNUSED(uint16_t addr), uint8_t val, void *priv)
{
isapnp_t *dev = (isapnp_t *) priv;
isapnp_card_t *card = dev->first_card;
isapnp_log("ISAPnP: write_addr(%02X)\n", val);
if (!card) /* don't do anything if we have no PnP cards */
return;
dev->reg = val;
if (card->state == PNP_STATE_WAIT_FOR_KEY) { /* checking only the first card should be fine */
/* Check written value against LFSR key. */
if (val == isapnp_init_key[dev->key_pos]) {
dev->key_pos++;
if (!dev->key_pos) {
isapnp_log("ISAPnP: Key unlocked, putting cards to SLEEP\n");
while (card) {
if (card->enable && (card->enable != ISAPNP_CARD_NO_KEY) && (card->state == PNP_STATE_WAIT_FOR_KEY))
card->state = PNP_STATE_SLEEP;
card = card->next;
}
}
} else {
dev->key_pos = 0;
}
}
}
static void
isapnp_write_common(isapnp_t *dev, isapnp_card_t *card, isapnp_device_t *ld, uint8_t reg, uint8_t val)
{
uint16_t io_addr;
uint16_t reset_cards = 0;
isapnp_log("ISAPnP: write_common(%02X, %02X)\n", reg, val);
switch (reg) {
case 0x00: /* Set RD_DATA Port */
isapnp_set_read_data((val << 2) | 3, dev);
isapnp_log("ISAPnP: Read data port set to %04X\n", dev->read_data_addr);
break;
case 0x02: /* Config Control */
if (val & 0x01) {
isapnp_log("ISAPnP: Reset\n");
card = dev->first_card;
while (card) {
ld = card->first_ld;
while (ld) {
if (card->state != PNP_STATE_WAIT_FOR_KEY) {
isapnp_reset_ld_regs(ld);
isapnp_device_config_changed(card, ld);
reset_cards++;
}
ld = ld->next;
}
card = card->next;
}
if (reset_cards != 0) {
dev->current_ld = NULL;
dev->current_ld_card = NULL;
dev->isolated_card = NULL;
}
}
if (val & 0x02) {
isapnp_log("ISAPnP: Return to WAIT_FOR_KEY\n");
card = dev->first_card;
while (card) {
card->state = PNP_STATE_WAIT_FOR_KEY;
card = card->next;
}
}
if (val & 0x04) {
isapnp_log("ISAPnP: Reset CSN\n");
card = dev->first_card;
while (card) {
isapnp_set_csn(card, 0);
card = card->next;
}
}
break;
case 0x03: /* Wake[CSN] */
isapnp_log("ISAPnP: Wake[%02X]\n", val);
card = dev->first_card;
while (card) {
if (card->csn == val) {
card->rom_pos = 0;
card->id_checksum = isapnp_init_key[0];
if (card->state == PNP_STATE_SLEEP)
card->state = (val == 0) ? PNP_STATE_ISOLATION : PNP_STATE_CONFIG;
} else {
card->state = PNP_STATE_SLEEP;
}
card = card->next;
}
break;
case 0x06: /* Card Select Number */
if (dev->isolated_card) {
isapnp_log("ISAPnP: Set CSN %02X\n", val);
isapnp_set_csn(dev->isolated_card, val);
dev->isolated_card->state = PNP_STATE_CONFIG;
dev->isolated_card = NULL;
} else {
isapnp_log("ISAPnP: Set CSN %02X but no card is isolated\n", val);
}
break;
case 0x07: /* Logical Device Number */
CHECK_CURRENT_CARD();
card->ld = val;
ld = card->first_ld;
while (ld) {
if (ld->number == val) {
isapnp_log("ISAPnP: Select CSN %02X device %02X\n", card->csn, val);
dev->current_ld_card = card;
dev->current_ld = ld;
break;
}
ld = ld->next;
}
if (!ld)
isapnp_log("ISAPnP: CSN %02X has no device %02X\n", card->csn, val);
break;
case 0x30: /* Activate */
CHECK_CURRENT_LD();
isapnp_log("ISAPnP: %sctivate CSN %02X device %02X\n", (val & 0x01) ? "A" : "Dea", card->csn, ld->number);
ld->regs[reg] = val & 0x01;
isapnp_device_config_changed(card, ld);
break;
case 0x31: /* I/O Range Check */
CHECK_CURRENT_LD();
for (uint8_t i = 0; i < 8; i++) {
if (!ld->io_len[i])
continue;
io_addr = (ld->regs[0x60 + (2 * i)] << 8) | ld->regs[0x61 + (2 * i)];
if (ld->regs[reg] & 0x02)
io_removehandler(io_addr, ld->io_len[i], isapnp_read_rangecheck, NULL, NULL, NULL, NULL, NULL, ld);
if (val & 0x02)
io_sethandler(io_addr, ld->io_len[i], isapnp_read_rangecheck, NULL, NULL, NULL, NULL, NULL, ld);
}
ld->regs[reg] = val & 0x03;
isapnp_device_config_changed(card, ld);
break;
case 0x20 ... 0x2f:
case 0x38 ... 0x3f:
case 0xa9 ... 0xff:
vendor_defined:
CHECK_CURRENT_CARD();
isapnp_log("ISAPnP: Write %02X to vendor-defined register %02X on CSN %02X device %02X\n", val, reg, card->csn, ld ? ld->number : -1);
if (card->write_vendor_reg)
card->write_vendor_reg(ld ? ld->number : -1, reg, val, card->priv);
break;
default:
if (reg >= 0x40) {
CHECK_CURRENT_LD();
isapnp_log("ISAPnP: Write %02X to register %02X on CSN %02X device %02X\n", val, reg, card->csn, ld->number);
switch (reg) {
case 0x42:
case 0x4a:
case 0x52:
case 0x5a:
case 0x7a:
case 0x84:
case 0x94:
case 0xa4:
/* Read-only memory range length / upper limit bit. */
val = (val & 0xfe) | (ld->regs[reg] & 0x01);
break;
case 0x60:
case 0x62:
case 0x64:
case 0x66:
case 0x68:
case 0x6a:
case 0x6c:
case 0x6e:
/* Discard upper address bits if this I/O range can only decode 10-bit. */
if (!(ld->io_16bit & (1 << ((reg >> 1) & 0x07))))
val &= 0x03;
break;
case 0x71:
case 0x73:
/* Limit IRQ types to supported ones. */
if ((val & 0x01) && !(ld->irq_types & ((reg == 0x71) ? 0x0c : 0xc0))) /* level, not supported = force edge */
val &= ~0x01;
else if (!(val & 0x01) && !(ld->irq_types & ((reg == 0x71) ? 0x03 : 0x30))) /* edge, not supported = force level */
val |= 0x01;
if ((val & 0x02) && !(ld->irq_types & ((reg == 0x71) ? 0x05 : 0x50))) /* high, not supported = force low */
val &= ~0x02;
else if (!(val & 0x02) && !(ld->irq_types & ((reg == 0x71) ? 0x0a : 0xa0))) /* low, not supported = force high */
val |= 0x02;
break;
default:
break;
}
ld->regs[reg] = val;
isapnp_device_config_changed(card, ld);
}
break;
}
}
static void
isapnp_write_data(UNUSED(uint16_t addr), uint8_t val, void *priv)
{
isapnp_t *dev = (isapnp_t *) priv;
isapnp_card_t *card = NULL;
if (!card) {
card = dev->first_card;
while (card) {
if (card->enable && (card->state == PNP_STATE_CONFIG))
break;
card = card->next;
}
}
isapnp_log("ISAPnP: write_data(%02X) => ", val);
isapnp_write_common(dev, card, dev->current_ld, dev->reg, val);
}
static void *
isapnp_init(UNUSED(const device_t *info))
{
isapnp_t *dev = (isapnp_t *) malloc(sizeof(isapnp_t));
memset(dev, 0, sizeof(isapnp_t));
io_sethandler(0x279, 1, NULL, NULL, NULL, isapnp_write_addr, NULL, NULL, dev);
io_sethandler(0xa79, 1, NULL, NULL, NULL, isapnp_write_data, NULL, NULL, dev);
return dev;
}
static void
isapnp_close(void *priv)
{
isapnp_t *dev = (isapnp_t *) priv;
isapnp_card_t *card = dev->first_card;
isapnp_card_t *next_card;
isapnp_device_t *ld;
isapnp_device_t *next_ld;
while (card) {
ld = card->first_ld;
while (ld) {
next_ld = ld->next;
free(ld);
ld = next_ld;
}
next_card = card->next;
free(card);
card = next_card;
}
io_removehandler(0x279, 1, NULL, NULL, NULL, isapnp_write_addr, NULL, NULL, dev);
io_removehandler(0xa79, 1, NULL, NULL, NULL, isapnp_write_data, NULL, NULL, dev);
free(dev);
}
void *
isapnp_add_card(uint8_t *rom, uint16_t rom_size,
void (*config_changed)(uint8_t ld, isapnp_device_config_t *config, void *priv),
void (*csn_changed)(uint8_t csn, void *priv),
uint8_t (*read_vendor_reg)(uint8_t ld, uint8_t reg, void *priv),
void (*write_vendor_reg)(uint8_t ld, uint8_t reg, uint8_t val, void *priv),
void *priv)
{
isapnp_t *dev = (isapnp_t *) device_get_priv(&isapnp_device);
if (!dev)
dev = (isapnp_t *) device_add(&isapnp_device);
isapnp_card_t *card = (isapnp_card_t *) malloc(sizeof(isapnp_card_t));
memset(card, 0, sizeof(isapnp_card_t));
card->enable = 1;
card->priv = priv;
card->config_changed = config_changed;
card->csn_changed = csn_changed;
card->read_vendor_reg = read_vendor_reg;
card->write_vendor_reg = write_vendor_reg;
if (!dev->first_card) {
dev->first_card = card;
} else {
isapnp_card_t *prev_card = dev->first_card;
while (prev_card->next)
prev_card = prev_card->next;
prev_card->next = card;
}
if (rom && rom_size)
isapnp_update_card_rom(card, rom, rom_size);
return card;
}
void
isapnp_update_card_rom(void *priv, uint8_t *rom, uint16_t rom_size)
{
isapnp_card_t *card = (isapnp_card_t *) priv;
card->rom = rom;
card->rom_size = rom_size;
/* Parse resources in ROM to allocate logical devices,
and determine the state of read-only register bits. */
#ifdef ENABLE_ISAPNP_LOG
uint16_t vendor = (card->rom[0] << 8) | card->rom[1];
isapnp_log("ISAPnP: Parsing ROM resources for card %c%c%c%02X%02X (serial %08X)\n", '@' + ((vendor >> 10) & 0x1f), '@' + ((vendor >> 5) & 0x1f), '@' + (vendor & 0x1f), card->rom[2], card->rom[3], (card->rom[7] << 24) | (card->rom[6] << 16) | (card->rom[5] << 8) | card->rom[4]);
const char *df_priority[] = { "good", "acceptable", "sub-optimal", "unknown priority" };
const char *mem_control[] = { "8-bit", "16-bit", "8/16-bit", "32-bit" };
const char *dma_transfer[] = { "8-bit", "8/16-bit", "16-bit", "Reserved" };
const char *dma_speed[] = { "compatibility", "Type A", "Type B", "Type F" };
#endif
uint16_t i = 9;
uint8_t existing = 0;
uint8_t ldn = 0;
uint8_t res;
uint8_t in_df = 0;
uint8_t irq = 0;
uint8_t dma = 0;
uint8_t io = 0;
uint8_t mem_range = 0;
uint8_t mem_range_32 = 0;
uint8_t irq_df = 0;
uint8_t dma_df = 0;
uint8_t io_df = 0;
uint8_t mem_range_df = 0;
uint8_t mem_range_32_df = 0;
uint32_t len;
isapnp_device_t *ld = NULL;
isapnp_device_t *prev_ld = NULL;
/* Check if this is an existing card which already has logical devices.
Any new logical devices will be added to the list after existing ones.
Removed LDs are not flushed as we may end up with an invalid ROM. */
existing = !!card->first_ld;
/* Iterate through ROM resources. */
while (i < card->rom_size) {
if (card->rom[i] & 0x80) { /* large resource */
res = card->rom[i] & 0x7f;
len = (card->rom[i + 2] << 8) | card->rom[i + 1];
switch (res) {
case 0x01: /* memory range */
case 0x05: /* 32-bit memory range */
if (res == 0x01) {
if (!ld) {
isapnp_log("ISAPnP: >>%s Memory descriptor with no logical device\n", in_df ? ">" : "");
break;
}
if (mem_range > 3) {
isapnp_log("ISAPnP: >>%s Memory descriptor overflow (%d)\n", in_df ? ">" : "", mem_range++);
break;
}
isapnp_log("ISAPnP: >>%s Memory range %d with %d bytes at %06X-%06X, align %d",
in_df ? ">" : "", mem_range,
*((uint16_t *) &card->rom[i + 10]) << 8, *((uint16_t *) &card->rom[i + 4]) << 8, ((card->rom[i + 3] & 0x4) ? 0 : (*((uint16_t *) &card->rom[i + 4]) << 8)) + (*((uint16_t *) &card->rom[i + 6]) << 8),
(*((uint16_t *) &card->rom[i + 8]) + 1) << 16);
res = 1 << mem_range;
mem_range++;
} else {
if (!ld) {
isapnp_log("ISAPnP: >>%s 32-bit memory descriptor with no logical device\n", in_df ? ">" : "");
break;
}
if (mem_range_32 > 3) {
isapnp_log("ISAPnP: >>%s 32-bit memory descriptor overflow (%d)\n", in_df ? ">" : "", mem_range_32++);
break;
}
isapnp_log("ISAPnP: >>%s 32-bit memory range %d with %d bytes at %08X-%08X, align %d", in_df ? ">" : "", mem_range_32,
*((uint32_t *) &card->rom[i + 16]) << 8, *((uint32_t *) &card->rom[i + 4]) << 8, ((card->rom[i + 3] & 0x4) ? 0 : (*((uint32_t *) &card->rom[i + 4]) << 8)) + (*((uint32_t *) &card->rom[i + 8]) << 8),
*((uint32_t *) &card->rom[i + 12]));
res = 1 << (4 + mem_range_32);
mem_range_32++;
}
#ifdef ENABLE_ISAPNP_LOG
isapnp_log(" bytes, %swritable, %sread cacheable, %s, %s, %sshadowable, %sexpansion ROM\n",
(card->rom[i + 3] & 0x01) ? "not " : "",
(card->rom[i + 3] & 0x02) ? "not " : "",
(card->rom[i + 3] & 0x04) ? "upper limit" : "range length",
mem_control[(card->rom[i + 3] >> 3) & 0x03],
(card->rom[i + 3] & 0x20) ? "not " : "",
(card->rom[i + 3] & 0x40) ? "not " : "");
#endif
if (card->rom[i + 3] & 0x4)
ld->mem_upperlimit |= res;
else
ld->mem_upperlimit &= ~res;
break;
#ifdef ENABLE_ISAPNP_LOG
case 0x02: /* ANSI identifier */
res = card->rom[i + 3 + len];
card->rom[i + 3 + len] = '\0';
isapnp_log("ISAPnP: >%s ANSI identifier: \"%s\"\n", ldn ? ">" : "", &card->rom[i + 3]);
card->rom[i + 3 + len] = res;
break;
#endif
default:
isapnp_log("ISAPnP: >%s%s Large resource %02X (length %d)\n", ldn ? ">" : "", in_df ? ">" : "", res, (card->rom[i + 2] << 8) | card->rom[i + 1]);
break;
}
i += 3; /* header */
} else { /* small resource */
res = (card->rom[i] >> 3) & 0x0f;
len = card->rom[i] & 0x07;
switch (res) {
#ifdef ENABLE_ISAPNP_LOG
case 0x01: /* PnP version */
isapnp_log("ISAPnP: > PnP version %d.%d, vendor-specific version %02X\n", card->rom[i + 1] >> 4, card->rom[i + 1] & 0x0f, card->rom[i + 2]);
break;
#endif
case 0x02: /* logical device */
#ifdef ENABLE_ISAPNP_LOG
vendor = (card->rom[i + 1] << 8) | card->rom[i + 2];
isapnp_log("ISAPnP: > Logical device %02X: %c%c%c%02X%02X\n", ldn, '@' + ((vendor >> 10) & 0x1f), '@' + ((vendor >> 5) & 0x1f), '@' + (vendor & 0x1f), card->rom[i + 3], card->rom[i + 4]);
#endif
/* We're done with the previous logical device. */
if (ld && !existing)
isapnp_reset_ld_regs(ld);
/* Look for an existing logical device with this number,
and create one if none exist. */
if (existing) {
ld = card->first_ld;
while (ld && (ld->number != ldn))
ld = ld->next;
}
if (ld && (ld->number == ldn)) {
/* Reset some logical device state. */
ld->mem_upperlimit = ld->io_16bit = ld->irq_types = 0;
memset(ld->io_len, 0, sizeof(ld->io_len));
} else {
/* Create logical device. */
ld = (isapnp_device_t *) malloc(sizeof(isapnp_device_t));
memset(ld, 0, sizeof(isapnp_device_t));
/* Add to end of list. */
prev_ld = card->first_ld;
if (prev_ld) {
while (prev_ld->next)
prev_ld = prev_ld->next;
prev_ld->next = ld;
} else {
card->first_ld = ld;
}
}
/* Set and increment logical device number. */
ld->number = ldn++;
/* Start the position counts over. */
irq = dma = io = mem_range = mem_range_32 = irq_df = dma_df = io_df = mem_range_df = mem_range_32_df = 0;
break;
#ifdef ENABLE_ISAPNP_LOG
case 0x03: /* compatible device ID */
if (!ld) {
isapnp_log("ISAPnP: >> Compatible device ID with no logical device\n");
break;
}
vendor = (card->rom[i + 1] << 8) | card->rom[i + 2];
isapnp_log("ISAPnP: >> Compatible device ID: %c%c%c%02X%02X\n", '@' + ((vendor >> 10) & 0x1f), '@' + ((vendor >> 5) & 0x1f), '@' + (vendor & 0x1f), card->rom[i + 3], card->rom[i + 4]);
break;
#endif
case 0x04: /* IRQ */
if (!ld) {
isapnp_log("ISAPnP: >>%s IRQ descriptor with no logical device\n", in_df ? ">" : "");
break;
}
if (irq > 1) {
isapnp_log("ISAPnP: >>%s IRQ descriptor overflow (%d)\n", in_df ? ">" : "", irq++);
break;
}
if (len == 2) /* default */
res = 0x01; /* high true edge sensitive */
else /* specific */
res = card->rom[i + 3] & 0x0f;
isapnp_log("ISAPnP: >>%s IRQ index %d with mask %04X, types %01X\n", in_df ? ">" : "", irq, *((uint16_t *) &card->rom[i + 1]), res);
ld->irq_types &= ~(0x0f << (4 * irq));
ld->irq_types |= res << (4 * irq);
irq++;
break;
#ifdef ENABLE_ISAPNP_LOG
case 0x05: /* DMA */
isapnp_log("ISAPnP: >>%s DMA index %d with mask %02X, %s, %sbus master, %scount by byte, %scount by word, %s speed\n", in_df ? ">" : "", dma++, card->rom[i + 1],
dma_transfer[card->rom[i + 2] & 3],
(card->rom[i + 2] & 0x04) ? "" : "not ",
(card->rom[i + 2] & 0x08) ? "" : "not ",
(card->rom[i + 2] & 0x10) ? "" : "not ",
dma_speed[(card->rom[i + 2] >> 5) & 3]);
break;
#endif
case 0x06: /* start dependent function */
if (!ld) {
isapnp_log("ISAPnP: >> Start dependent function with no logical device\n");
break;
}
#ifdef ENABLE_ISAPNP_LOG
isapnp_log("ISAPnP: >> Start dependent function: %s\n", df_priority[(len < 1) ? 1 : (card->rom[i + 1] & 3)]);
#endif
if (in_df) {
/* We're in a dependent function and this is the next one starting.
Walk positions back to the saved values. */
irq = irq_df;
dma = dma_df;
io = io_df;
mem_range = mem_range_df;
mem_range_32 = mem_range_32_df;
} else {
/* Save current positions to restore at the next DF. */
irq_df = irq;
dma_df = dma;
io_df = io;
mem_range_df = mem_range;
mem_range_32_df = mem_range_32;
in_df = 1;
}
break;
case 0x07: /* end dependent function */
isapnp_log("ISAPnP: >> End dependent function\n");
in_df = 0;
break;
case 0x08: /* I/O port */
if (!ld) {
isapnp_log("ISAPnP: >>%s I/O descriptor with no logical device\n", in_df ? ">" : "");
break;
}
if (io > 7) {
isapnp_log("ISAPnP: >>%s I/O descriptor overflow (%d)\n", in_df ? ">" : "", io++);
break;
}
isapnp_log("ISAPnP: >>%s I/O range %d with %d ports at %04X-%04X, align %d, %d-bit decode\n", in_df ? ">" : "", io, card->rom[i + 7], *((uint16_t *) &card->rom[i + 2]), *((uint16_t *) &card->rom[i + 4]), card->rom[i + 6], (card->rom[i + 1] & 0x01) ? 16 : 10);
if (card->rom[i + 1] & 0x01)
ld->io_16bit |= 1 << io;
else
ld->io_16bit &= ~(1 << io);
if (card->rom[i + 7] > ld->io_len[io])
ld->io_len[io] = card->rom[i + 7];
io++;
break;
case 0x09: /* Fixed I/O port */
if (!ld) {
isapnp_log("ISAPnP: >>%s Fixed I/O descriptor with no logical device\n", in_df ? ">" : "");
break;
}
if (io > 7) {
isapnp_log("ISAPnP: >>%s Fixed I/O descriptor overflow (%d)\n", in_df ? ">" : "", io++);
break;
}
isapnp_log("ISAPnP: >>%s Fixed I/O range %d with %d ports at %04X\n", in_df ? ">" : "", io, card->rom[i + 3], *((uint16_t *) &card->rom[i + 1]));
/* Fixed I/O port ranges of this kind are always 10-bit. */
ld->io_16bit &= ~(1 << io);
if (card->rom[i + 3] > ld->io_len[io])
ld->io_len[io] = card->rom[i + 3];
io++;
break;
case 0x0f: /* end tag */
/* Calculate checksum. */
res = 0x00;
for (uint16_t j = 9; j <= i; j++)
res += card->rom[j];
card->rom[i + 1] = -res;
isapnp_log("ISAPnP: End card resources (checksum %02X)\n", card->rom[i + 1]);
/* Stop parsing here. */
card->rom_size = i + 2;
break;
default:
isapnp_log("ISAPnP: >%s%s Small resource %02X (length %d)\n", ldn ? ">" : "", in_df ? ">" : "", res, card->rom[i] & 0x07);
break;
}
i++; /* header */
}
i += len; /* specified length */
}
/* We're done with the last logical device. */
if (ld && !existing)
isapnp_reset_ld_regs(ld);
}
void
isapnp_enable_card(void *priv, uint8_t enable)
{
isapnp_t *dev = (isapnp_t *) device_get_priv(&isapnp_device);
if (!dev)
return;
/* Look for a matching card. */
isapnp_card_t *card = dev->first_card;
while (card) {
if (card == priv) {
/* Enable or disable the card. */
if (!!enable ^ !!card->enable)
card->state = (enable == ISAPNP_CARD_FORCE_CONFIG) ? PNP_STATE_CONFIG : PNP_STATE_WAIT_FOR_KEY;
card->enable = enable;
/* Invalidate other references if we're disabling this card. */
if (!card->enable) {
if (dev->isolated_card == card)
dev->isolated_card = NULL;
if (dev->current_ld_card == card) {
dev->current_ld = NULL;
dev->current_ld_card = NULL;
}
}
break;
}
card = card->next;
}
}
void
isapnp_set_csn(void *priv, uint8_t csn)
{
isapnp_card_t *card = (isapnp_card_t *) priv;
card->csn = csn;
if (card->csn_changed)
card->csn_changed(card->csn, card->priv);
}
uint8_t
isapnp_read_reg(void *priv, uint8_t ldn, uint8_t reg)
{
isapnp_card_t *card = (isapnp_card_t *) priv;
isapnp_device_t *ld = card->first_ld;
while (ld) {
if (ld->number == ldn)
break;
ld = ld->next;
}
return isapnp_read_common(device_get_priv(&isapnp_device), card, ld, reg);
}
void
isapnp_write_reg(void *priv, uint8_t ldn, uint8_t reg, uint8_t val)
{
isapnp_card_t *card = (isapnp_card_t *) priv;
isapnp_device_t *ld = card->first_ld;
while (ld) {
if (ld->number == ldn)
break;
ld = ld->next;
}
isapnp_write_common(device_get_priv(&isapnp_device), card, ld, reg, val);
}
void
isapnp_set_device_defaults(void *priv, uint8_t ldn, const isapnp_device_config_t *config)
{
isapnp_card_t *card = (isapnp_card_t *) priv;
isapnp_device_t *ld = card->first_ld;
/* Look for a logical device with this number. */
while (ld && (ld->number != ldn))
ld = ld->next;
if (!ld) /* none found */
return;
ld->defaults = config;
}
void
isapnp_reset_card(void *priv)
{
isapnp_card_t *card = (isapnp_card_t *) priv;
isapnp_device_t *ld = card->first_ld;
/* Reset all logical devices. */
while (ld) {
/* Reset the logical device's configuration. */
isapnp_reset_ld_config(ld);
isapnp_device_config_changed(card, ld);
ld = ld->next;
}
}
void
isapnp_reset_device(void *priv, uint8_t ldn)
{
isapnp_card_t *card = (isapnp_card_t *) priv;
isapnp_device_t *ld = card->first_ld;
/* Look for a logical device with this number. */
while (ld && (ld->number != ldn))
ld = ld->next;
if (!ld) /* none found */
return;
/* Reset the logical device's configuration. */
isapnp_reset_ld_config(ld);
isapnp_device_config_changed(card, ld);
}
static const device_t isapnp_device = {
.name = "ISA Plug and Play",
.internal_name = "isapnp",
.flags = 0,
.local = 0,
.init = isapnp_init,
.close = isapnp_close,
.reset = NULL,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/device/isapnp.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 12,091 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of Serial Mouse devices.
*
* TODO: Add the Genius Serial Mouse.
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/timer.h>
#include <86box/serial.h>
#include <86box/mouse.h>
#include <86box/plat.h>
#include <86box/version.h>
#define SERMOUSE_PORT 0 /* attach to Serial0 */
enum {
STATE_RESET,
STATE_BAUD_RATE,
STATE_DORMANT,
STATE_IDLE,
STATE_COMMAND,
STATE_DATA,
STATE_TRANSMIT,
STATE_TRANSMIT_REPORT,
STATE_SKIP_REPORT
};
enum {
FORMAT_BP1_ABS = 0x01,
FORMAT_BP1_REL,
FORMAT_MM_SERIES = 0x13,
FORMAT_PB_3BYTE,
FORMAT_PB_5BYTE,
FORMAT_MSYSTEMS = 0x15, /* Alias for FORMAT_PB_5BYTE. */
FORMAT_MS,
FORMAT_HEX,
FORMAT_MS_4BYTE,
FORMAT_MS_WHEEL,
FORMATS_NUM
};
typedef struct mouse_t {
const char *name; /* name of this device */
uint8_t id[252];
uint8_t buf[256];
uint8_t flags; /* device flags */
uint8_t but;
uint8_t rts_toggle;
uint8_t status;
uint8_t format;
uint8_t prompt;
uint8_t continuous;
uint8_t ib;
uint8_t command;
uint8_t buf_len;
uint8_t report_mode;
uint8_t id_len;
uint8_t buf_pos;
uint8_t rev;
int8_t type; /* type of this device */
int8_t port;
int state;
int bps;
int rps;
double transmit_period;
double report_period;
double cur_period;
double min_bit_period;
double acc_time;
double host_transmit_period;
pc_timer_t timer;
serial_t * serial;
} mouse_t;
#define FLAG_INPORT 0x80 /* device is MS InPort */
#define FLAG_3BTN 0x20 /* enable 3-button mode */
#define FLAG_SCALED 0x10 /* enable delta scaling */
#define FLAG_INTR 0x04 /* dev can send interrupts */
#define FLAG_FROZEN 0x02 /* do not update counters */
#define FLAG_ENABLED 0x01 /* dev is enabled for use */
#ifdef ENABLE_MOUSE_SERIAL_LOG
int mouse_serial_do_log = ENABLE_MOUSE_SERIAL_LOG;
static void
mouse_serial_log(const char *fmt, ...)
{
va_list ap;
if (mouse_serial_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define mouse_serial_log(fmt, ...)
#endif
static void
sermouse_set_period(mouse_t *dev, double period)
{
dev->cur_period = period; /* Needed for the recalculation of the timings. */
timer_stop(&dev->timer);
if (period > 0.0)
timer_on_auto(&dev->timer, 10000.0);
}
static void
sermouse_transmit_byte(mouse_t *dev, int do_next)
{
if (dev->buf_pos == 0)
dev->acc_time = 0.0;
serial_write_fifo(dev->serial, dev->buf[dev->buf_pos]);
if (do_next) {
dev->buf_pos = (dev->buf_pos + 1) % dev->buf_len;
if (dev->buf_pos != 0)
sermouse_set_period(dev, dev->transmit_period);
}
}
static void
sermouse_transmit(mouse_t *dev, int len, int from_report, int to_report)
{
dev->state = to_report ? STATE_TRANSMIT_REPORT : STATE_TRANSMIT;
dev->buf_pos = 0;
dev->buf_len = len;
if (from_report) {
if (dev->acc_time > dev->report_period)
dev->acc_time -= dev->report_period;
/* We have too little time left, pretend it's zero and handle
schedule the next report at byte period. */
if (dev->acc_time < dev->min_bit_period)
sermouse_set_period(dev, dev->transmit_period);
/* We have enough time, schedule the next report at report period,
subtract the accumulated time from the total period, and add
one byte period (the first byte delay). */
else
sermouse_set_period(dev, dev->report_period - dev->acc_time + dev->transmit_period);
} else
sermouse_set_period(dev, dev->transmit_period);
}
static uint8_t
sermouse_report_msystems(mouse_t *dev)
{
int delta_x = 0;
int delta_y = 0;
int b = mouse_get_buttons_ex();
mouse_subtract_coords(&delta_x, &delta_y, NULL, NULL, -128, 127, 1, 0);
dev->buf[0] = 0x80;
dev->buf[0] |= (b & 0x01) ? 0x00 : 0x04; /* left button */
if (dev->but >= 3)
dev->buf[0] |= (b & 0x04) ? 0x00 : 0x02; /* middle button */
else
dev->buf[0] |= 0x02; /* middle button */
dev->buf[0] |= (b & 0x02) ? 0x00 : 0x01; /* right button */
dev->buf[1] = delta_x;
dev->buf[2] = delta_y;
dev->buf[3] = delta_x; /* same as byte 1 */
dev->buf[4] = delta_y; /* same as byte 2 */
return 5;
}
static uint8_t
sermouse_report_3bp(mouse_t *dev)
{
int delta_x = 0;
int delta_y = 0;
int b = mouse_get_buttons_ex();
mouse_subtract_coords(&delta_x, &delta_y, NULL, NULL, -128, 127, 1, 0);
dev->buf[0] = 0x80;
dev->buf[0] |= (b & 0x01) ? 0x04 : 0x00; /* left button */
if (dev->but >= 3)
dev->buf[0] |= (b & 0x04) ? 0x02 : 0x00; /* middle button */
dev->buf[0] |= (b & 0x02) ? 0x01 : 0x00; /* right button */
dev->buf[1] = delta_x;
dev->buf[2] = delta_y;
return 3;
}
static uint8_t
sermouse_report_mmseries(mouse_t *dev)
{
int delta_x = 0;
int delta_y = 0;
int b = mouse_get_buttons_ex();
mouse_subtract_coords(&delta_x, &delta_y, NULL, NULL, -127, 127, 1, 0);
dev->buf[0] = 0x80;
if (delta_x >= 0)
dev->buf[0] |= 0x10;
if (delta_y >= 0)
dev->buf[0] |= 0x08;
dev->buf[0] |= (b & 0x01) ? 0x04 : 0x00; /* left button */
if (dev->but >= 3)
dev->buf[0] |= (b & 0x04) ? 0x02 : 0x00; /* middle button */
dev->buf[0] |= (b & 0x02) ? 0x01 : 0x00; /* right button */
dev->buf[1] = ABS(delta_x) & 0x7f;
dev->buf[2] = ABS(delta_y) & 0x7f;
mouse_serial_log("MM series mouse report: %02X %02X %02X\n", dev->buf[0], dev->buf[1], dev->buf[2]);
return 3;
}
static uint8_t
sermouse_report_bp1(mouse_t *dev, int abs)
{
int delta_x = 0;
int delta_y = 0;
int b = mouse_get_buttons_ex();
mouse_subtract_coords(&delta_x, &delta_y, NULL, NULL, -2048, 2047, 1, abs);
dev->buf[0] = 0x80;
dev->buf[0] |= (b & 0x01) ? 0x10 : 0x00; /* left button */
if (dev->but >= 3)
dev->buf[0] |= (b & 0x04) ? 0x08 : 0x00; /* middle button */
dev->buf[0] |= (b & 0x02) ? 0x04 : 0x00; /* right button */
dev->buf[1] = (delta_x & 0x3f);
dev->buf[2] = ((delta_x >> 6) & 0x3f);
dev->buf[3] = (delta_y & 0x3f);
dev->buf[4] = ((delta_y >> 6) & 0x3f);
return 5;
}
static uint8_t
sermouse_report_ms(mouse_t *dev)
{
uint8_t len;
int delta_x = 0;
int delta_y = 0;
int delta_z = 0;
int b = mouse_get_buttons_ex();
mouse_subtract_coords(&delta_x, &delta_y, NULL, NULL, -128, 127, 0, 0);
mouse_subtract_z(&delta_z, -8, 7, 1);
dev->buf[0] = 0x40;
dev->buf[0] |= (((delta_y >> 6) & 0x03) << 2);
dev->buf[0] |= ((delta_x >> 6) & 0x03);
if (b & 0x01)
dev->buf[0] |= 0x20;
if (b & 0x02)
dev->buf[0] |= 0x10;
dev->buf[1] = delta_x & 0x3f;
dev->buf[2] = delta_y & 0x3f;
mouse_serial_log("Microsoft serial mouse report: %02X %02X %02X\n", dev->buf[0], dev->buf[1], dev->buf[2]);
if (dev->but == 3) {
len = 3;
if (dev->format == FORMAT_MS) {
if (b & 0x04) {
dev->buf[3] = 0x20;
len++;
}
} else {
if (mouse_mbut_changed()) {
/* Microsoft 3-button mice send a fourth byte of 0x00 when the middle button
has changed. */
dev->buf[3] = 0x00;
len++;
}
}
} else if (dev->but == 4) {
len = 4;
dev->buf[3] = delta_z & 0x0f;
if (b & 0x04)
dev->buf[3] |= 0x10;
} else
len = 3;
return len;
}
static uint8_t
sermouse_report_hex(mouse_t *dev)
{
char ret[6] = { 0, 0, 0, 0, 0, 0 };
uint8_t but = 0x00;
int delta_x = 0;
int delta_y = 0;
int b = mouse_get_buttons_ex();
mouse_subtract_coords(&delta_x, &delta_y, NULL, NULL, -128, 127, 1, 0);
but |= (b & 0x01) ? 0x04 : 0x00; /* left button */
if (dev->but >= 3)
but |= (b & 0x04) ? 0x02 : 0x00; /* middle button */
but |= (b & 0x02) ? 0x01 : 0x00; /* right button */
sprintf(ret, "%01X%02X%02X", but & 0x0f, (int8_t) delta_x, (int8_t) delta_y);
memcpy(dev->buf, ret, 5);
return 5;
}
static int
sermouse_report(mouse_t *dev)
{
int len = 0;
memset(dev->buf, 0, 5);
switch (dev->format) {
case FORMAT_PB_5BYTE:
len = sermouse_report_msystems(dev);
break;
case FORMAT_PB_3BYTE:
len = sermouse_report_3bp(dev);
break;
case FORMAT_HEX:
len = sermouse_report_hex(dev);
break;
case FORMAT_BP1_REL:
len = sermouse_report_bp1(dev, 0);
break;
case FORMAT_MM_SERIES:
len = sermouse_report_mmseries(dev);
break;
case FORMAT_BP1_ABS:
len = sermouse_report_bp1(dev, 1);
break;
case FORMAT_MS:
case FORMAT_MS_4BYTE:
case FORMAT_MS_WHEEL:
len = sermouse_report_ms(dev);
break;
default:
break;
}
return len;
}
static void
sermouse_transmit_report(mouse_t *dev, int from_report)
{
if (mouse_capture && mouse_state_changed())
sermouse_transmit(dev, sermouse_report(dev), from_report, 1);
else {
if (dev->prompt || dev->continuous)
sermouse_set_period(dev, 0.0);
else {
dev->state = STATE_SKIP_REPORT;
/* Not in prompt or continuous mode and there have been no changes,
skip the next report entirely. */
if (from_report) {
if (dev->acc_time > dev->report_period)
dev->acc_time -= dev->report_period;
if (dev->acc_time < dev->min_bit_period)
sermouse_set_period(dev, dev->report_period);
else
sermouse_set_period(dev, (dev->report_period * 2.0) - dev->acc_time);
} else
sermouse_set_period(dev, dev->report_period);
}
}
}
static int
sermouse_poll(void *priv)
{
mouse_t *dev = (mouse_t *) priv;
if (!mouse_capture || dev->prompt || !dev->continuous || (dev->state != STATE_IDLE))
return 1;
sermouse_transmit_report(dev, 0);
return (dev->cur_period == 0.0) ? 1 : 0;
}
static void
ltsermouse_set_prompt_mode(mouse_t *dev, int prompt)
{
dev->prompt = prompt;
if (prompt || dev->continuous)
sermouse_set_period(dev, 0.0);
else
sermouse_set_period(dev, dev->transmit_period);
}
static void
ltsermouse_set_report_period(mouse_t *dev, int rps)
{
/* Limit the reports rate according to the baud rate. */
if (rps == 0) {
sermouse_set_period(dev, 0.0);
dev->report_period = 0.0;
dev->continuous = 1;
} else {
#if 0
if (rps > dev->max_rps)
rps = dev->max_rps;
#endif
dev->continuous = 0;
dev->report_period = 1000000.0 / ((double) rps);
/* Actual spacing between reports. */
}
}
static void
ltsermouse_update_report_period(mouse_t *dev)
{
ltsermouse_set_report_period(dev, dev->rps);
ltsermouse_set_prompt_mode(dev, 0);
mouse_serial_log("ltsermouse_update_report_period(): %i, %i\n", dev->continuous, dev->prompt);
if (dev->continuous)
dev->state = STATE_IDLE;
else {
sermouse_transmit_report(dev, 0);
dev->state = STATE_TRANSMIT_REPORT;
}
}
static void
ltsermouse_switch_baud_rate(mouse_t *dev, int next_state)
{
double word_lens[FORMATS_NUM] = {
[FORMAT_BP1_ABS] = 7.0 + 1.0, /* 7 data bits + even parity */
[FORMAT_BP1_REL] = 7.0 + 1.0, /* 7 data bits + even parity */
[FORMAT_MM_SERIES] = 8.0 + 1.0, /* 8 data bits + odd parity */
[FORMAT_PB_3BYTE] = 8.0, /* 8 data bits + no parity */
[FORMAT_PB_5BYTE] = 8.0, /* 8 data bits + no parity */
[FORMAT_MS] = 7.0, /* 7 datas bits + no parity */
[FORMAT_HEX] = 8.0, /* 8 data bits + no parity */
[FORMAT_MS_4BYTE] = 7.0, /* 7 datas bits + no parity */
[FORMAT_MS_WHEEL] = 7.0 }; /* 7 datas bits + no parity */
double word_len = word_lens[dev->format];
word_len += 1.0 + 2.0; /* 1 start bit + 2 stop bits */
#if 0
dev->max_rps = (int) floor(((double) dev->bps) / (word_len * num_words));
#endif
if (next_state == STATE_BAUD_RATE)
dev->transmit_period = dev->host_transmit_period;
else
dev->transmit_period = 1000000.0 / ((double) dev->bps);
dev->min_bit_period = dev->transmit_period;
dev->transmit_period *= word_len;
/* The transmit period for the entire report, we're going to need this in ltsermouse_set_report_period(). */
#if 0
dev->report_transmit_period = dev->transmit_period * num_words;
#endif
ltsermouse_set_report_period(dev, dev->rps);
if (!dev->continuous && (next_state != STATE_BAUD_RATE)) {
if (dev->prompt)
ltsermouse_set_prompt_mode(dev, 0);
sermouse_transmit_report(dev, 0);
}
dev->state = next_state;
}
static int
sermouse_next_state(mouse_t *dev)
{
int ret = STATE_IDLE;
if (dev->prompt || (dev->rps == 0))
ret = STATE_IDLE;
else
ret = STATE_TRANSMIT;
return ret;
}
static void
ltsermouse_process_command(mouse_t *dev)
{
int cmd_to_rps[9] = { 10, 20, 35, 70, 150, 0, -1, 100, 50 };
int b;
uint8_t format_codes[FORMATS_NUM] = {
[FORMAT_BP1_ABS] = 0x0c,
[FORMAT_BP1_REL] = 0x06,
[FORMAT_MM_SERIES] = 0x0a,
[FORMAT_PB_3BYTE] = 0x00,
[FORMAT_PB_5BYTE] = 0x02,
[FORMAT_MS] = 0x0e,
[FORMAT_HEX] = 0x04,
[FORMAT_MS_4BYTE] = 0x08, /* Guess */
[FORMAT_MS_WHEEL] = 0x08 }; /* Guess */
const char *copr = "\r\n(C) " COPYRIGHT_YEAR " 86Box, Revision 3.0";
mouse_serial_log("ltsermouse_process_command(): %02X\n", dev->ib);
dev->command = dev->ib;
switch (dev->command) {
case 0x20:
/* Auto Baud Selection */
dev->bps = (int) floor(1000000.0 / dev->host_transmit_period);
dev->transmit_period = dev->host_transmit_period;
dev->buf[0] = 0x06;
sermouse_transmit(dev, 1, 0, 0);
ltsermouse_switch_baud_rate(dev, STATE_BAUD_RATE);
break;
case 0x4a: /* Report Rate Selection commands */
case 0x4b:
case 0x4c:
case 0x52:
case 0x4d:
case 0x51:
case 0x4e:
case 0x4f:
dev->report_mode = dev->command;
dev->rps = cmd_to_rps[dev->command - 0x4a];
ltsermouse_update_report_period(dev);
break;
case 0x44:
/* Select Prompt Mode */
dev->report_mode = dev->command;
ltsermouse_set_prompt_mode(dev, 1);
dev->state = STATE_IDLE;
break;
case 0x50:
/* Promopt to send a report (also enters Prompt Mode). */
if (!dev->prompt) {
dev->report_mode = 0x44;
ltsermouse_set_prompt_mode(dev, 1);
}
sermouse_transmit_report(dev, 0);
dev->state = STATE_TRANSMIT_REPORT;
break;
case 0x41:
/* Absolute Bit Pad One Packed Binary Format */
mouse_clear_coords();
fallthrough;
case 0x42: /* Relative Bit Pad One Packed Binary Format */
case 0x53: /* MM Series Data Format */
case 0x54: /* Three Byte Packed Binary Format */
case 0x55: /* Five Byte Packed Binary Format (Mouse Systems-compatible) */
case 0x56: /* Microsoft Compatible Format */
case 0x57: /* Hexadecimal Format */
case 0x58: /* Microsoft Compatible Format (3+1 byte 3-button, from the FreeBSD source code) */
if ((dev->rev >= 0x02) && ((dev->command != 0x58) || (dev->rev > 0x04))) {
dev->format = dev->command & 0x1f;
ltsermouse_switch_baud_rate(dev, sermouse_next_state(dev));
}
break;
case 0x2a:
if (dev->rev >= 0x03) {
/* Programmable Baud Rate Selection */
dev->state = STATE_DATA;
}
break;
case 0x73:
/* Status */
dev->buf[0] = dev->prompt ? 0x4f : 0x0f;
sermouse_transmit(dev, 1, 0, 0);
break;
case 0x05:
/* Diagnostic */
b = mouse_get_buttons_ex();
dev->buf[0] = ((b & 0x01) << 2) | ((b & 0x06) >> 1);
dev->buf[1] = dev->buf[2] = 0x00;
sermouse_transmit(dev, 3, 0, 0);
break;
case 0x66:
if (dev->rev >= 0x20) {
/* Format and Revision Number */
dev->buf[0] = format_codes[dev->format];
dev->buf[0] |= 0x10; /* Revision 3.0, 0x00 would be Revision 2.0 */
sermouse_transmit(dev, 1, 0, 0);
}
break;
case 0x74:
/* Format and Mode in ASCII */
if (dev->rev >= 0x03) {
dev->buf[0] = dev->format | 0x40;
dev->buf[1] = dev->report_mode;
sermouse_transmit(dev, 2, 0, 0);
}
break;
case 0x63:
if (dev->rev >= 0x03) {
memcpy(&(dev->buf[0]), copr, strlen(copr) + 1);
sermouse_transmit(dev, strlen(copr) + 1, 0, 0);
} else {
memcpy(&(dev->buf[0]), copr, strlen(copr));
sermouse_transmit(dev, strlen(copr), 0, 0);
}
dev->buf[29] = dev->rev | 0x30;
break;
case 0x64:
/* Dormant State */
dev->state = STATE_DORMANT;
break;
case 0x6b:
/* Buttons - 86Box-specific command. */
dev->state = dev->but;
break;
default:
break;
}
}
static void
ltsermouse_process_data(mouse_t *dev)
{
mouse_serial_log("ltsermouse_process_data(): %02X (command = %02X)\n", dev->ib, dev->command);
switch(dev->command) {
case 0x2a:
switch (dev->ib) {
default:
fallthrough;
case 0x6e:
dev->bps = 1200;
break;
case 0x6f:
dev->bps = 2400;
break;
case 0x70:
dev->bps = 4800;
break;
case 0x71:
dev->bps = 9600;
break;
}
ltsermouse_switch_baud_rate(dev, (dev->prompt || dev->continuous) ? STATE_IDLE : STATE_TRANSMIT_REPORT);
break;
default:
dev->state = STATE_IDLE;
break;
}
}
static void
sermouse_reset(mouse_t *dev, int callback)
{
sermouse_set_period(dev, 0.0);
dev->bps = 1200;
dev->rps = 0;
dev->prompt = 0;
if (dev->id[0] == 'H')
dev->format = FORMAT_MSYSTEMS;
else switch (dev->but) {
default:
case 2:
dev->format = FORMAT_MS;
break;
case 3:
dev->format = (dev->type == MOUSE_TYPE_LT3BUTTON) ? FORMAT_MS : FORMAT_MS_4BYTE;
break;
case 4:
dev->format = FORMAT_MS_WHEEL;
break;
}
ltsermouse_switch_baud_rate(dev, callback ? STATE_TRANSMIT : STATE_IDLE);
}
static void
sermouse_timer(void *priv)
{
mouse_t *dev = (mouse_t *) priv;
#ifdef ENABLE_MOUSE_SERIAL_LOG
int old_state = dev->state;
#endif
switch (dev->state) {
case STATE_RESET:
/* All three mice default to continuous reporting. */
sermouse_reset(dev, 0);
break;
case STATE_DATA:
ltsermouse_process_data(dev);
break;
case STATE_COMMAND:
ltsermouse_process_command(dev);
break;
case STATE_SKIP_REPORT:
if (!dev->prompt && !dev->continuous)
sermouse_transmit_report(dev, (dev->state == STATE_TRANSMIT_REPORT));
else
dev->state = STATE_IDLE;
break;
case STATE_TRANSMIT_REPORT:
case STATE_TRANSMIT:
case STATE_BAUD_RATE:
sermouse_transmit_byte(dev, 1);
if (dev->buf_pos == 0) {
if (!dev->prompt && !dev->continuous)
sermouse_transmit_report(dev, (dev->state == STATE_TRANSMIT_REPORT));
else
dev->state = STATE_IDLE;
}
break;
default:
break;
}
mouse_serial_log("sermouse_timer(): %02i -> %02i\n", old_state, dev->state);
}
static void
ltsermouse_write(UNUSED(struct serial_s *serial), void *priv, uint8_t data)
{
mouse_t *dev = (mouse_t *) priv;
mouse_serial_log("ltsermouse_write(): %02X\n", data);
dev->ib = data;
switch (dev->state) {
case STATE_RESET:
case STATE_BAUD_RATE:
break;
case STATE_TRANSMIT_REPORT:
case STATE_TRANSMIT:
case STATE_SKIP_REPORT:
sermouse_set_period(dev, 0.0);
fallthrough;
default:
dev->state = STATE_COMMAND;
fallthrough;
case STATE_DATA:
sermouse_timer(dev);
break;
}
}
/* Callback from serial driver: RTS was toggled. */
static void
sermouse_callback(UNUSED(struct serial_s *serial), void *priv)
{
mouse_t *dev = (mouse_t *) priv;
sermouse_reset(dev, 1);
memcpy(dev->buf, dev->id, dev->id_len);
sermouse_transmit(dev, dev->id_len, 0, 0);
}
static void
ltsermouse_transmit_period(UNUSED(serial_t *serial), void *priv, double transmit_period)
{
mouse_t *dev = (mouse_t *) priv;
dev->host_transmit_period = transmit_period;
}
static void
sermouse_speed_changed(void *priv)
{
mouse_t *dev = (mouse_t *) priv;
if (dev->cur_period != 0.0)
sermouse_set_period(dev, dev->cur_period);
}
static void
sermouse_close(void *priv)
{
mouse_t *dev = (mouse_t *) priv;
/* Detach serial port from the mouse. */
if (dev && dev->serial && dev->serial->sd)
memset(dev->serial->sd, 0, sizeof(serial_device_t));
free(dev);
}
/* Initialize the device for use by the user. */
static void *
sermouse_init(const device_t *info)
{
mouse_t *dev;
void (*rcr_callback)(struct serial_s *serial, void *priv);
void (*dev_write)(struct serial_s *serial, void *priv, uint8_t data);
void (*transmit_period_callback)(struct serial_s *serial, void *priv, double transmit_period);
dev = (mouse_t *) malloc(sizeof(mouse_t));
memset(dev, 0x00, sizeof(mouse_t));
dev->name = info->name;
dev->but = device_get_config_int("buttons");
dev->rev = device_get_config_int("revision");
if (info->local == 0)
dev->rts_toggle = 1;
else
dev->rts_toggle = device_get_config_int("rts_toggle");
if (dev->but > 2)
dev->flags |= FLAG_3BTN;
if (info->local == MOUSE_TYPE_MSYSTEMS) {
dev->format = 0;
dev->type = info->local;
dev->id_len = 1;
dev->id[0] = 'H';
} else {
dev->format = 7;
dev->status = 0x0f;
dev->id_len = 1;
dev->id[0] = 'M';
if (info->local)
dev->rev = device_get_config_int("revision");
switch (dev->but) {
default:
case 2:
dev->type = info->local ? MOUSE_TYPE_LOGITECH : MOUSE_TYPE_MICROSOFT;
break;
case 3:
dev->type = info->local ? MOUSE_TYPE_LT3BUTTON : MOUSE_TYPE_MS3BUTTON;
dev->id_len = 2;
dev->id[1] = '3';
break;
case 4:
dev->type = MOUSE_TYPE_MSWHEEL;
dev->id_len = 6;
dev->id[1] = 'Z';
dev->id[2] = '@';
break;
}
}
dev->port = device_get_config_int("port");
/* Attach a serial port to the mouse. */
rcr_callback = dev->rts_toggle ? sermouse_callback : NULL;
dev_write = (info->local == 1) ? ltsermouse_write : NULL;
transmit_period_callback = (info->local == 1) ? ltsermouse_transmit_period : NULL;
dev->serial = serial_attach_ex(dev->port, rcr_callback, dev_write,
transmit_period_callback, NULL, dev);
mouse_serial_log("%s: port=COM%d\n", dev->name, dev->port + 1);
timer_add(&dev->timer, sermouse_timer, dev, 0);
/* The five second delay allows the mouse to execute internal initializations. */
sermouse_set_period(dev, 5000000.0);
/* Tell them how many buttons we have. */
mouse_set_buttons(dev->but);
/* Return our private data to the I/O layer. */
return dev;
}
static const device_config_t msssermouse_config[] = {
// clang-format off
{
.name = "port",
.description = "Serial Port",
.type = CONFIG_SELECTION,
.default_string = "",
.default_int = 0,
.file_filter = "",
.spinner = { 0 },
.selection = {
{ .description = "COM1", .value = 0 },
{ .description = "COM2", .value = 1 },
{ .description = "COM3", .value = 2 },
{ .description = "COM4", .value = 3 },
{ .description = "" }
}
},
{
.name = "buttons",
.description = "Buttons",
.type = CONFIG_SELECTION,
.default_string = "",
.default_int = 2,
.file_filter = "",
.spinner = { 0 },
.selection = {
{ .description = "Two", .value = 2 },
{ .description = "Three", .value = 3 },
{ .description = "" }
}
},
{
.name = "rts_toggle",
.description = "RTS toggle",
.type = CONFIG_BINARY,
.default_string = "",
.default_int = 0
},
{ .name = "", .description = "", .type = CONFIG_END }
// clang-format on
};
static const device_config_t mssermouse_config[] = {
// clang-format off
{
.name = "port",
.description = "Serial Port",
.type = CONFIG_SELECTION,
.default_string = "",
.default_int = 0,
.file_filter = "",
.spinner = { 0 },
.selection = {
{ .description = "COM1", .value = 0 },
{ .description = "COM2", .value = 1 },
{ .description = "COM3", .value = 2 },
{ .description = "COM4", .value = 3 },
{ .description = "" }
}
},
{
.name = "buttons",
.description = "Buttons",
.type = CONFIG_SELECTION,
.default_string = "",
.default_int = 2,
.file_filter = "",
.spinner = { 0 },
.selection = {
{ .description = "Two", .value = 2 },
{ .description = "Three", .value = 3 },
{ .description = "Wheel", .value = 4 },
{ .description = "" }
}
},
{ .name = "", .description = "", .type = CONFIG_END }
// clang-format on
};
static const device_config_t ltsermouse_config[] = {
// clang-format off
{
.name = "port",
.description = "Serial Port",
.type = CONFIG_SELECTION,
.default_string = "",
.default_int = 0,
.file_filter = "",
.spinner = { 0 },
.selection = {
{ .description = "COM1", .value = 0 },
{ .description = "COM2", .value = 1 },
{ .description = "COM3", .value = 2 },
{ .description = "COM4", .value = 3 },
{ .description = "" }
}
},
{
.name = "buttons",
.description = "Buttons",
.type = CONFIG_SELECTION,
.default_string = "",
.default_int = 2,
.file_filter = "",
.spinner = { 0 },
.selection = {
{ .description = "Two", .value = 2 },
{ .description = "Three", .value = 3 },
{ .description = "" }
}
},
{
.name = "revision",
.description = "Revision",
.type = CONFIG_SELECTION,
.default_string = "",
.default_int = 3,
.file_filter = "",
.spinner = { 0 },
.selection = {
{ .description = "LOGIMOUSE R7 1.0", .value = 1 },
{ .description = "LOGIMOUSE R7 2.0", .value = 2 },
{ .description = "LOGIMOUSE C7 3.0", .value = 3 },
{ .description = "Logitech MouseMan", .value = 4 },
{ .description = "" }
}
},
{
.name = "rts_toggle",
.description = "Microsoft-compatible RTS toggle",
.type = CONFIG_BINARY,
.default_string = "",
.default_int = 0
},
{ .name = "", .description = "", .type = CONFIG_END }
// clang-format on
};
const device_t mouse_mssystems_device = {
.name = "Mouse Systems Serial Mouse",
.internal_name = "mssystems",
.flags = DEVICE_COM,
.local = MOUSE_TYPE_MSYSTEMS,
.init = sermouse_init,
.close = sermouse_close,
.reset = NULL,
{ .poll = sermouse_poll },
.speed_changed = sermouse_speed_changed,
.force_redraw = NULL,
.config = msssermouse_config
};
const device_t mouse_msserial_device = {
.name = "Microsoft Serial Mouse",
.internal_name = "msserial",
.flags = DEVICE_COM,
.local = 0,
.init = sermouse_init,
.close = sermouse_close,
.reset = NULL,
{ .poll = sermouse_poll },
.speed_changed = sermouse_speed_changed,
.force_redraw = NULL,
.config = mssermouse_config
};
const device_t mouse_ltserial_device = {
.name = "Logitech Serial Mouse",
.internal_name = "ltserial",
.flags = DEVICE_COM,
.local = 1,
.init = sermouse_init,
.close = sermouse_close,
.reset = NULL,
{ .poll = sermouse_poll },
.speed_changed = sermouse_speed_changed,
.force_redraw = NULL,
.config = ltsermouse_config
};
``` | /content/code_sandbox/src/device/mouse_serial.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 8,916 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.