aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.clang-format428
-rw-r--r--.gitignore10
-rw-r--r--.vscode/extensions.json9
-rw-r--r--.vscode/settings.json8
-rw-r--r--.vscode/tasks.json63
-rw-r--r--Kconfig21
-rw-r--r--LICENSE280
-rw-r--r--Makefile38
-rw-r--r--README.md12
-rw-r--r--configfs.c235
-rw-r--r--core.c519
-rw-r--r--core.h70
-rw-r--r--docs/1.Introduction.md38
-rw-r--r--docs/2.Building.md62
-rw-r--r--docs/3.Usage.md140
-rw-r--r--docs/4.4A-Integration.md22
-rw-r--r--docs/images/arch-4a.pngbin0 -> 282311 bytes
-rw-r--r--dummy/Kconfig12
-rw-r--r--dummy/Makefile6
-rw-r--r--dummy/dummy.c307
-rw-r--r--loopback/Kconfig12
-rw-r--r--loopback/Makefile7
-rw-r--r--loopback/loopback.c1111
-rw-r--r--pcm.c332
-rwxr-xr-xscripts/load.sh13
-rwxr-xr-xscripts/make-agl.sh14
-rwxr-xr-xscripts/test_configfs.sh21
-rwxr-xr-xscripts/unload.sh13
-rw-r--r--sound/avirt.h122
-rw-r--r--utils.h42
-rw-r--r--xds-project.conf4
31 files changed, 3967 insertions, 4 deletions
diff --git a/.clang-format b/.clang-format
new file mode 100644
index 0000000..1d5da22
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,428 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# clang-format configuration file. Intended for clang-format >= 4.
+#
+# For more information, see:
+#
+# Documentation/process/clang-format.rst
+# https://clang.llvm.org/docs/ClangFormat.html
+# https://clang.llvm.org/docs/ClangFormatStyleOptions.html
+#
+---
+AccessModifierOffset: -4
+AlignAfterOpenBracket: Align
+AlignConsecutiveAssignments: false
+AlignConsecutiveDeclarations: false
+#AlignEscapedNewlines: Left # Unknown to clang-format-4.0
+AlignOperands: true
+AlignTrailingComments: false
+AllowAllParametersOfDeclarationOnNextLine: false
+AllowShortBlocksOnASingleLine: false
+AllowShortCaseLabelsOnASingleLine: false
+AllowShortFunctionsOnASingleLine: None
+AllowShortIfStatementsOnASingleLine: false
+AllowShortLoopsOnASingleLine: false
+AlwaysBreakAfterDefinitionReturnType: None
+AlwaysBreakAfterReturnType: None
+AlwaysBreakBeforeMultilineStrings: false
+AlwaysBreakTemplateDeclarations: false
+BinPackArguments: true
+BinPackParameters: true
+BraceWrapping:
+ AfterClass: false
+ AfterControlStatement: false
+ AfterEnum: false
+ AfterFunction: true
+ AfterNamespace: true
+ AfterObjCDeclaration: false
+ AfterStruct: false
+ AfterUnion: false
+ #AfterExternBlock: false # Unknown to clang-format-5.0
+ BeforeCatch: false
+ BeforeElse: false
+ IndentBraces: false
+ #SplitEmptyFunction: true # Unknown to clang-format-4.0
+ #SplitEmptyRecord: true # Unknown to clang-format-4.0
+ #SplitEmptyNamespace: true # Unknown to clang-format-4.0
+BreakBeforeBinaryOperators: None
+BreakBeforeBraces: Custom
+#BreakBeforeInheritanceComma: false # Unknown to clang-format-4.0
+BreakBeforeTernaryOperators: false
+BreakConstructorInitializersBeforeComma: false
+#BreakConstructorInitializers: BeforeComma # Unknown to clang-format-4.0
+BreakAfterJavaFieldAnnotations: false
+BreakStringLiterals: false
+ColumnLimit: 80
+CommentPragmas: '^ IWYU pragma:'
+#CompactNamespaces: false # Unknown to clang-format-4.0
+ConstructorInitializerAllOnOneLineOrOnePerLine: false
+ConstructorInitializerIndentWidth: 8
+ContinuationIndentWidth: 8
+Cpp11BracedListStyle: false
+DerivePointerAlignment: false
+DisableFormat: false
+ExperimentalAutoDetectBinPacking: false
+#FixNamespaceComments: false # Unknown to clang-format-4.0
+
+# Taken from:
+# git grep -h '^#define [^[:space:]]*for_each[^[:space:]]*(' include/ \
+# | sed "s,^#define \([^[:space:]]*for_each[^[:space:]]*\)(.*$, - '\1'," \
+# | sort | uniq
+ForEachMacros:
+ - 'apei_estatus_for_each_section'
+ - 'ata_for_each_dev'
+ - 'ata_for_each_link'
+ - 'ax25_for_each'
+ - 'ax25_uid_for_each'
+ - 'bio_for_each_integrity_vec'
+ - '__bio_for_each_segment'
+ - 'bio_for_each_segment'
+ - 'bio_for_each_segment_all'
+ - 'bio_list_for_each'
+ - 'bip_for_each_vec'
+ - 'blkg_for_each_descendant_post'
+ - 'blkg_for_each_descendant_pre'
+ - 'blk_queue_for_each_rl'
+ - 'bond_for_each_slave'
+ - 'bond_for_each_slave_rcu'
+ - 'btree_for_each_safe128'
+ - 'btree_for_each_safe32'
+ - 'btree_for_each_safe64'
+ - 'btree_for_each_safel'
+ - 'card_for_each_dev'
+ - 'cgroup_taskset_for_each'
+ - 'cgroup_taskset_for_each_leader'
+ - 'cpufreq_for_each_entry'
+ - 'cpufreq_for_each_entry_idx'
+ - 'cpufreq_for_each_valid_entry'
+ - 'cpufreq_for_each_valid_entry_idx'
+ - 'css_for_each_child'
+ - 'css_for_each_descendant_post'
+ - 'css_for_each_descendant_pre'
+ - 'device_for_each_child_node'
+ - 'drm_atomic_crtc_for_each_plane'
+ - 'drm_atomic_crtc_state_for_each_plane'
+ - 'drm_atomic_crtc_state_for_each_plane_state'
+ - 'drm_for_each_connector_iter'
+ - 'drm_for_each_crtc'
+ - 'drm_for_each_encoder'
+ - 'drm_for_each_encoder_mask'
+ - 'drm_for_each_fb'
+ - 'drm_for_each_legacy_plane'
+ - 'drm_for_each_plane'
+ - 'drm_for_each_plane_mask'
+ - 'drm_mm_for_each_hole'
+ - 'drm_mm_for_each_node'
+ - 'drm_mm_for_each_node_in_range'
+ - 'drm_mm_for_each_node_safe'
+ - 'for_each_active_drhd_unit'
+ - 'for_each_active_iommu'
+ - 'for_each_available_child_of_node'
+ - 'for_each_bio'
+ - 'for_each_board_func_rsrc'
+ - 'for_each_bvec'
+ - 'for_each_child_of_node'
+ - 'for_each_clear_bit'
+ - 'for_each_clear_bit_from'
+ - 'for_each_cmsghdr'
+ - 'for_each_compatible_node'
+ - 'for_each_console'
+ - 'for_each_cpu'
+ - 'for_each_cpu_and'
+ - 'for_each_cpu_not'
+ - 'for_each_cpu_wrap'
+ - 'for_each_dev_addr'
+ - 'for_each_dma_cap_mask'
+ - 'for_each_drhd_unit'
+ - 'for_each_dss_dev'
+ - 'for_each_efi_memory_desc'
+ - 'for_each_efi_memory_desc_in_map'
+ - 'for_each_endpoint_of_node'
+ - 'for_each_evictable_lru'
+ - 'for_each_fib6_node_rt_rcu'
+ - 'for_each_fib6_walker_rt'
+ - 'for_each_free_mem_range'
+ - 'for_each_free_mem_range_reverse'
+ - 'for_each_func_rsrc'
+ - 'for_each_hstate'
+ - 'for_each_if'
+ - 'for_each_iommu'
+ - 'for_each_ip_tunnel_rcu'
+ - 'for_each_irq_nr'
+ - 'for_each_lru'
+ - 'for_each_matching_node'
+ - 'for_each_matching_node_and_match'
+ - 'for_each_memblock'
+ - 'for_each_memblock_type'
+ - 'for_each_memcg_cache_index'
+ - 'for_each_mem_pfn_range'
+ - 'for_each_mem_range'
+ - 'for_each_mem_range_rev'
+ - 'for_each_migratetype_order'
+ - 'for_each_msi_entry'
+ - 'for_each_net'
+ - 'for_each_netdev'
+ - 'for_each_netdev_continue'
+ - 'for_each_netdev_continue_rcu'
+ - 'for_each_netdev_feature'
+ - 'for_each_netdev_in_bond_rcu'
+ - 'for_each_netdev_rcu'
+ - 'for_each_netdev_reverse'
+ - 'for_each_netdev_safe'
+ - 'for_each_net_rcu'
+ - 'for_each_new_connector_in_state'
+ - 'for_each_new_crtc_in_state'
+ - 'for_each_new_plane_in_state'
+ - 'for_each_new_private_obj_in_state'
+ - 'for_each_node'
+ - 'for_each_node_by_name'
+ - 'for_each_node_by_type'
+ - 'for_each_node_mask'
+ - 'for_each_node_state'
+ - 'for_each_node_with_cpus'
+ - 'for_each_node_with_property'
+ - 'for_each_of_allnodes'
+ - 'for_each_of_allnodes_from'
+ - 'for_each_of_pci_range'
+ - 'for_each_old_connector_in_state'
+ - 'for_each_old_crtc_in_state'
+ - 'for_each_oldnew_connector_in_state'
+ - 'for_each_oldnew_crtc_in_state'
+ - 'for_each_oldnew_plane_in_state'
+ - 'for_each_oldnew_private_obj_in_state'
+ - 'for_each_old_plane_in_state'
+ - 'for_each_old_private_obj_in_state'
+ - 'for_each_online_cpu'
+ - 'for_each_online_node'
+ - 'for_each_online_pgdat'
+ - 'for_each_pci_bridge'
+ - 'for_each_pci_dev'
+ - 'for_each_pci_msi_entry'
+ - 'for_each_populated_zone'
+ - 'for_each_possible_cpu'
+ - 'for_each_present_cpu'
+ - 'for_each_prime_number'
+ - 'for_each_prime_number_from'
+ - 'for_each_process'
+ - 'for_each_process_thread'
+ - 'for_each_property_of_node'
+ - 'for_each_reserved_mem_region'
+ - 'for_each_resv_unavail_range'
+ - 'for_each_rtdcom'
+ - 'for_each_rtdcom_safe'
+ - 'for_each_set_bit'
+ - 'for_each_set_bit_from'
+ - 'for_each_sg'
+ - 'for_each_sg_page'
+ - '__for_each_thread'
+ - 'for_each_thread'
+ - 'for_each_zone'
+ - 'for_each_zone_zonelist'
+ - 'for_each_zone_zonelist_nodemask'
+ - 'fwnode_for_each_available_child_node'
+ - 'fwnode_for_each_child_node'
+ - 'fwnode_graph_for_each_endpoint'
+ - 'gadget_for_each_ep'
+ - 'hash_for_each'
+ - 'hash_for_each_possible'
+ - 'hash_for_each_possible_rcu'
+ - 'hash_for_each_possible_rcu_notrace'
+ - 'hash_for_each_possible_safe'
+ - 'hash_for_each_rcu'
+ - 'hash_for_each_safe'
+ - 'hctx_for_each_ctx'
+ - 'hlist_bl_for_each_entry'
+ - 'hlist_bl_for_each_entry_rcu'
+ - 'hlist_bl_for_each_entry_safe'
+ - 'hlist_for_each'
+ - 'hlist_for_each_entry'
+ - 'hlist_for_each_entry_continue'
+ - 'hlist_for_each_entry_continue_rcu'
+ - 'hlist_for_each_entry_continue_rcu_bh'
+ - 'hlist_for_each_entry_from'
+ - 'hlist_for_each_entry_from_rcu'
+ - 'hlist_for_each_entry_rcu'
+ - 'hlist_for_each_entry_rcu_bh'
+ - 'hlist_for_each_entry_rcu_notrace'
+ - 'hlist_for_each_entry_safe'
+ - '__hlist_for_each_rcu'
+ - 'hlist_for_each_safe'
+ - 'hlist_nulls_for_each_entry'
+ - 'hlist_nulls_for_each_entry_from'
+ - 'hlist_nulls_for_each_entry_rcu'
+ - 'hlist_nulls_for_each_entry_safe'
+ - 'ide_host_for_each_port'
+ - 'ide_port_for_each_dev'
+ - 'ide_port_for_each_present_dev'
+ - 'idr_for_each_entry'
+ - 'idr_for_each_entry_continue'
+ - 'idr_for_each_entry_ul'
+ - 'inet_bind_bucket_for_each'
+ - 'inet_lhash2_for_each_icsk_rcu'
+ - 'iov_for_each'
+ - 'key_for_each'
+ - 'key_for_each_safe'
+ - 'klp_for_each_func'
+ - 'klp_for_each_object'
+ - 'kvm_for_each_memslot'
+ - 'kvm_for_each_vcpu'
+ - 'list_for_each'
+ - 'list_for_each_entry'
+ - 'list_for_each_entry_continue'
+ - 'list_for_each_entry_continue_rcu'
+ - 'list_for_each_entry_continue_reverse'
+ - 'list_for_each_entry_from'
+ - 'list_for_each_entry_from_reverse'
+ - 'list_for_each_entry_lockless'
+ - 'list_for_each_entry_rcu'
+ - 'list_for_each_entry_reverse'
+ - 'list_for_each_entry_safe'
+ - 'list_for_each_entry_safe_continue'
+ - 'list_for_each_entry_safe_from'
+ - 'list_for_each_entry_safe_reverse'
+ - 'list_for_each_prev'
+ - 'list_for_each_prev_safe'
+ - 'list_for_each_safe'
+ - 'llist_for_each'
+ - 'llist_for_each_entry'
+ - 'llist_for_each_entry_safe'
+ - 'llist_for_each_safe'
+ - 'media_device_for_each_entity'
+ - 'media_device_for_each_intf'
+ - 'media_device_for_each_link'
+ - 'media_device_for_each_pad'
+ - 'netdev_for_each_lower_dev'
+ - 'netdev_for_each_lower_private'
+ - 'netdev_for_each_lower_private_rcu'
+ - 'netdev_for_each_mc_addr'
+ - 'netdev_for_each_uc_addr'
+ - 'netdev_for_each_upper_dev_rcu'
+ - 'netdev_hw_addr_list_for_each'
+ - 'nft_rule_for_each_expr'
+ - 'nla_for_each_attr'
+ - 'nla_for_each_nested'
+ - 'nlmsg_for_each_attr'
+ - 'nlmsg_for_each_msg'
+ - 'nr_neigh_for_each'
+ - 'nr_neigh_for_each_safe'
+ - 'nr_node_for_each'
+ - 'nr_node_for_each_safe'
+ - 'of_for_each_phandle'
+ - 'of_property_for_each_string'
+ - 'of_property_for_each_u32'
+ - 'pci_bus_for_each_resource'
+ - 'ping_portaddr_for_each_entry'
+ - 'plist_for_each'
+ - 'plist_for_each_continue'
+ - 'plist_for_each_entry'
+ - 'plist_for_each_entry_continue'
+ - 'plist_for_each_entry_safe'
+ - 'plist_for_each_safe'
+ - 'pnp_for_each_card'
+ - 'pnp_for_each_dev'
+ - 'protocol_for_each_card'
+ - 'protocol_for_each_dev'
+ - 'queue_for_each_hw_ctx'
+ - 'radix_tree_for_each_contig'
+ - 'radix_tree_for_each_slot'
+ - 'radix_tree_for_each_tagged'
+ - 'rbtree_postorder_for_each_entry_safe'
+ - 'resource_list_for_each_entry'
+ - 'resource_list_for_each_entry_safe'
+ - 'rhl_for_each_entry_rcu'
+ - 'rhl_for_each_rcu'
+ - 'rht_for_each'
+ - 'rht_for_each_continue'
+ - 'rht_for_each_entry'
+ - 'rht_for_each_entry_continue'
+ - 'rht_for_each_entry_rcu'
+ - 'rht_for_each_entry_rcu_continue'
+ - 'rht_for_each_entry_safe'
+ - 'rht_for_each_rcu'
+ - 'rht_for_each_rcu_continue'
+ - '__rq_for_each_bio'
+ - 'rq_for_each_segment'
+ - 'scsi_for_each_prot_sg'
+ - 'scsi_for_each_sg'
+ - 'sctp_for_each_hentry'
+ - 'sctp_skb_for_each'
+ - 'shdma_for_each_chan'
+ - '__shost_for_each_device'
+ - 'shost_for_each_device'
+ - 'sk_for_each'
+ - 'sk_for_each_bound'
+ - 'sk_for_each_entry_offset_rcu'
+ - 'sk_for_each_from'
+ - 'sk_for_each_rcu'
+ - 'sk_for_each_safe'
+ - 'sk_nulls_for_each'
+ - 'sk_nulls_for_each_from'
+ - 'sk_nulls_for_each_rcu'
+ - 'snd_pcm_group_for_each_entry'
+ - 'snd_soc_dapm_widget_for_each_path'
+ - 'snd_soc_dapm_widget_for_each_path_safe'
+ - 'snd_soc_dapm_widget_for_each_sink_path'
+ - 'snd_soc_dapm_widget_for_each_source_path'
+ - 'tb_property_for_each'
+ - 'udp_portaddr_for_each_entry'
+ - 'udp_portaddr_for_each_entry_rcu'
+ - 'usb_hub_for_each_child'
+ - 'v4l2_device_for_each_subdev'
+ - 'v4l2_m2m_for_each_dst_buf'
+ - 'v4l2_m2m_for_each_dst_buf_safe'
+ - 'v4l2_m2m_for_each_src_buf'
+ - 'v4l2_m2m_for_each_src_buf_safe'
+ - 'zorro_for_each_dev'
+
+#IncludeBlocks: Preserve # Unknown to clang-format-5.0
+IncludeCategories:
+ - Regex: '.*'
+ Priority: 1
+IncludeIsMainRegex: '(Test)?$'
+IndentCaseLabels: false
+#IndentPPDirectives: None # Unknown to clang-format-5.0
+IndentWidth: 8
+IndentWrappedFunctionNames: false
+JavaScriptQuotes: Leave
+JavaScriptWrapImports: true
+KeepEmptyLinesAtTheStartOfBlocks: false
+MacroBlockBegin: ''
+MacroBlockEnd: ''
+MaxEmptyLinesToKeep: 1
+NamespaceIndentation: Inner
+#ObjCBinPackProtocolList: Auto # Unknown to clang-format-5.0
+ObjCBlockIndentWidth: 8
+ObjCSpaceAfterProperty: true
+ObjCSpaceBeforeProtocolList: true
+
+# Taken from git's rules
+#PenaltyBreakAssignment: 10 # Unknown to clang-format-4.0
+PenaltyBreakBeforeFirstCallParameter: 30
+PenaltyBreakComment: 10
+PenaltyBreakFirstLessLess: 0
+PenaltyBreakString: 10
+PenaltyExcessCharacter: 100
+PenaltyReturnTypeOnItsOwnLine: 60
+
+PointerAlignment: Right
+ReflowComments: false
+SortIncludes: false
+#SortUsingDeclarations: false # Unknown to clang-format-4.0
+SpaceAfterCStyleCast: false
+SpaceAfterTemplateKeyword: true
+SpaceBeforeAssignmentOperators: true
+#SpaceBeforeCtorInitializerColon: true # Unknown to clang-format-5.0
+#SpaceBeforeInheritanceColon: true # Unknown to clang-format-5.0
+SpaceBeforeParens: ControlStatements
+#SpaceBeforeRangeBasedForLoopColon: true # Unknown to clang-format-5.0
+SpaceInEmptyParentheses: false
+SpacesBeforeTrailingComments: 1
+SpacesInAngles: false
+SpacesInContainerLiterals: false
+SpacesInCStyleCastParentheses: false
+SpacesInParentheses: false
+SpacesInSquareBrackets: false
+Standard: Cpp03
+TabWidth: 8
+UseTab: Always
+...
diff --git a/.gitignore b/.gitignore
index fcd6a60..7032bb1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,6 @@
-build/
-CMakeCache.txt
-Makefile
-*.so
+*.o*
+*.ko*
+*.symvers
+*.mod*
+*.mk*
+build*/** \ No newline at end of file
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
new file mode 100644
index 0000000..1e19bad
--- /dev/null
+++ b/.vscode/extensions.json
@@ -0,0 +1,9 @@
+{
+ // See https://go.microsoft.com/fwlink/?LinkId=827846
+ // for the documentation about the extensions.json format
+ "recommendations": [
+ "ms-vscode.cpptools",
+ "xaver.clang-format",
+ "bierner.markdown-preview-github-styles",
+ ]
+} \ No newline at end of file
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000..4dc08b0
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,8 @@
+{
+ "editor.tabSize": 8,
+ "editor.insertSpaces": false,
+ "editor.rulers": [
+ 80
+ ],
+ "editor.formatOnSave": true,
+} \ No newline at end of file
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
new file mode 100644
index 0000000..8a0a070
--- /dev/null
+++ b/.vscode/tasks.json
@@ -0,0 +1,63 @@
+{
+ // See https://go.microsoft.com/fwlink/?LinkId=733558
+ // for the documentation about the tasks.json format
+ "version": "2.0.0",
+ "type": "shell",
+ "presentation": {
+ "reveal": "always"
+ },
+ "tasks": [
+ {
+ "label": "Make Driver",
+ "command": "make all",
+ "group": "build",
+ "problemMatcher": ["$gcc"]
+ },
+ {
+ "label": "Clean Driver",
+ "command": "make clean",
+ "group": "build",
+ "problemMatcher": ["$gcc"]
+ },
+ {
+ "label": "Deploy Drivers",
+ "command": "sudo sh -c './scripts/unload.sh && ./scripts/load.sh'",
+ "problemMatcher": []
+ },
+ {
+ "label": "Make and Deploy Drivers",
+ "command": "make all && sudo sh -c './scripts/unload.sh && ./scripts/load.sh'",
+ "problemMatcher": []
+ },
+ {
+ "label": "Unload new drivers",
+ "command": "sudo sh ./scripts/unload.sh",
+ "problemMatcher": []
+ },
+ {
+ "label": "Load new drivers",
+ "command": "sudo sh ./scripts/load.sh",
+ "problemMatcher": []
+ },
+ {
+ "label": "Make Driver AGL",
+ "type": "shell",
+ "command": "./scripts/make-agl.sh 6864c558",
+ "group": "build",
+ "problemMatcher": ["$gcc"]
+ },
+ {
+ "label": "Clean Driver AGL",
+ "type": "shell",
+ "command": "./scripts/make-agl.sh 6864c558 clean",
+ "group": "build",
+ "problemMatcher": ["$gcc"]
+ },
+ {
+ "label": "Deploy Driver AGL",
+ "type": "shell",
+ "command": "rsync -av avirt_core.ko dummy/avirt_dummyap.ko loopback/avirt_loopbackap.ko root@192.168.1.193:/lib/modules/4.14.0-yocto-standard/extra",
+ "problemMatcher": ["$gcc"]
+ }
+ ]
+}
diff --git a/Kconfig b/Kconfig
new file mode 100644
index 0000000..b15bcbe
--- /dev/null
+++ b/Kconfig
@@ -0,0 +1,21 @@
+menuconfig AVIRT
+ tristate "AVIRT support"
+ default n
+ ---help---
+ Say Y here if you want to enable AVIRT support.
+ This driver needs at least one additional audio path in
+ order to establish audio routing.
+
+ To compile this driver as a module, choose M here: the
+ module will be called avirt_core.
+
+ If in doubt, say N here.
+
+
+
+if AVIRT
+
+source "drivers/staging/avirt/dummy/Kconfig"
+source "drivers/staging/avirt/loopback/Kconfig"
+
+endif
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d8cf7d4
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,280 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..e2a154e
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,38 @@
+# SPDX-License-Identifier: GPL-2.0
+obj-$(CONFIG_AVIRT) += snd-avirt-core.o
+snd-avirt-core-y := core.o
+snd-avirt-core-y += pcm.o
+snd-avirt-core-y += configfs.o
+
+ifeq ($(CONFIG_AVIRT_BUILDLOCAL),)
+ CCFLAGS_AVIRT := "drivers/staging/"
+else
+ CCFLAGS_AVIRT := "$(PWD)"
+endif
+
+ccflags-y += -I${CCFLAGS_AVIRT}
+
+$(info $(KERNELRELEASE))
+obj-$(CONFIG_AVIRT_AP_DUMMY) += dummy/
+obj-$(CONFIG_AVIRT_AP_LOOPBACK) += loopback/
+
+###
+# For out-of-tree building
+###
+ifdef PKG_CONFIG_SYSROOT_DIR
+ # AGL SDK kernel src path
+ KERNEL_SRC=$(PKG_CONFIG_SYSROOT_DIR)/usr/src/kernel
+else
+ # General Linux distro kernel src path
+ KERNEL_SRC=/lib/modules/$(shell uname -r)/build
+endif
+
+all:
+ CONFIG_AVIRT=m CONFIG_AVIRT_BUILDLOCAL=y \
+ CONFIG_AVIRT_AP_DUMMY=m \
+ CONFIG_AVIRT_AP_LOOPBACK=m \
+ make -C $(KERNEL_SRC) M=$(PWD)
+
+clean:
+ make -C $(KERNEL_SRC) M=$(PWD) clean
+
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..a653f0e
--- /dev/null
+++ b/README.md
@@ -0,0 +1,12 @@
+# Alsa Virtual Sound Driver
+
+1. [Introduction](docs/1.Introduction.md)
+2. [Building](docs/2.Building.md)
+3. [Usage](docs/3.Usage.md)
+4. [4A Integration](docs/4.4A-Integration.md)
+
+
+## TODO
+
+- Currently, playback only - implementing capture is WIP.
+
diff --git a/configfs.c b/configfs.c
new file mode 100644
index 0000000..12e95a5
--- /dev/null
+++ b/configfs.c
@@ -0,0 +1,235 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * AVIRT - ALSA Virtual Soundcard
+ *
+ * Copyright (c) 2010-2018 Fiberdyne Systems Pty Ltd
+ *
+ * configfs.c - AVIRT configfs support
+ */
+
+#include <linux/slab.h>
+
+#include "core.h"
+
+#define D_LOGNAME "configfs"
+
+#define D_INFOK(fmt, args...) DINFO(D_LOGNAME, fmt, ##args)
+#define D_PRINTK(fmt, args...) DDEBUG(D_LOGNAME, fmt, ##args)
+#define D_ERRORK(fmt, args...) DERROR(D_LOGNAME, fmt, ##args)
+
+static ssize_t cfg_snd_avirt_stream_direction_show(struct config_item *item,
+ char *page)
+{
+ ssize_t count;
+ struct snd_avirt_stream *stream =
+ snd_avirt_stream_from_config_item(item);
+
+ count = sprintf(page, "%d\n", stream->direction);
+
+ return count;
+}
+CONFIGFS_ATTR_RO(cfg_snd_avirt_stream_, direction);
+
+static ssize_t cfg_snd_avirt_stream_map_show(struct config_item *item,
+ char *page)
+{
+ struct snd_avirt_stream *stream =
+ snd_avirt_stream_from_config_item(item);
+
+ return sprintf(page, "%s\n", stream->map);
+}
+
+static ssize_t cfg_snd_avirt_stream_map_store(struct config_item *item,
+ const char *page, size_t count)
+{
+ char *split;
+ struct snd_avirt_stream *stream =
+ snd_avirt_stream_from_config_item(item);
+
+ split = strsep((char **)&page, "\n");
+ memcpy(stream->map, (char *)split, count);
+
+ return count;
+}
+CONFIGFS_ATTR(cfg_snd_avirt_stream_, map);
+
+static ssize_t cfg_snd_avirt_stream_channels_show(struct config_item *item,
+ char *page)
+{
+ ssize_t count;
+ struct snd_avirt_stream *stream =
+ snd_avirt_stream_from_config_item(item);
+
+ count = sprintf(page, "%d\n", stream->channels);
+
+ return count;
+}
+
+static ssize_t cfg_snd_avirt_stream_channels_store(struct config_item *item,
+ const char *page,
+ size_t count)
+{
+ int err;
+ struct snd_avirt_stream *stream =
+ snd_avirt_stream_from_config_item(item);
+ unsigned long tmp;
+ char *p = (char *)page;
+
+ err = kstrtoul(p, 10, &tmp);
+ if (err < 0)
+ return err;
+
+ if (tmp > INT_MAX)
+ return -ERANGE;
+
+ stream->channels = tmp;
+
+ return count;
+}
+CONFIGFS_ATTR(cfg_snd_avirt_stream_, channels);
+
+static struct configfs_attribute *cfg_snd_avirt_stream_attrs[] = {
+ &cfg_snd_avirt_stream_attr_channels,
+ &cfg_snd_avirt_stream_attr_map,
+ &cfg_snd_avirt_stream_attr_direction,
+ NULL,
+};
+
+static void cfg_snd_avirt_stream_release(struct config_item *item)
+{
+ D_INFOK("item->name:%s", item->ci_namebuf);
+ kfree(snd_avirt_stream_from_config_item(item));
+}
+
+static struct configfs_item_operations cfg_snd_avirt_stream_ops = {
+ .release = cfg_snd_avirt_stream_release,
+};
+
+static struct config_item_type cfg_snd_avirt_stream_type = {
+ .ct_item_ops = &cfg_snd_avirt_stream_ops,
+ .ct_attrs = cfg_snd_avirt_stream_attrs,
+ .ct_owner = THIS_MODULE,
+};
+
+static struct config_item *
+cfg_snd_avirt_stream_make_item(struct config_group *group, const char *name)
+{
+ char *split;
+ int direction;
+ struct snd_avirt_stream *stream;
+
+ // Get prefix (playback_ or capture_)
+ split = strsep((char **)&name, "_");
+ if (!split) {
+ D_ERRORK("Stream name: '%s' invalid!", split);
+ D_ERRORK("Must begin with playback_ * or capture_ *");
+ return ERR_PTR(-EINVAL);
+ }
+ if (!strcmp(split, "playback")) {
+ direction = SNDRV_PCM_STREAM_PLAYBACK;
+ } else if (!strcmp(split, "capture")) {
+ direction = SNDRV_PCM_STREAM_CAPTURE;
+ } else {
+ D_ERRORK("Stream name: '%s' invalid!", split);
+ D_ERRORK("Must begin with playback_ * or capture_ ");
+ return ERR_PTR(-EINVAL);
+ }
+
+ // Get stream name, and create PCM for stream
+ split = strsep((char **)&name, "\n");
+ stream = snd_avirt_stream_create(split, direction);
+ if (IS_ERR(stream))
+ return ERR_PTR(PTR_ERR(stream));
+
+ config_item_init_type_name(&stream->item, name,
+ &cfg_snd_avirt_stream_type);
+
+ return &stream->item;
+}
+
+static ssize_t cfg_snd_avirt_stream_group_sealed_show(struct config_item *item,
+ char *page)
+{
+ return snprintf(page, PAGE_SIZE, "%d\n", snd_avirt_streams_sealed());
+}
+
+static ssize_t cfg_snd_avirt_stream_group_sealed_store(struct config_item *item,
+ const char *page,
+ size_t count)
+{
+ unsigned long tmp;
+ char *p = (char *)page;
+
+ CHK_ERR(kstrtoul(p, 10, &tmp));
+
+ if (tmp != 1) {
+ D_ERRORK("streams can only be sealed, not unsealed!");
+ return -ERANGE;
+ }
+
+ snd_avirt_streams_seal();
+
+ return count;
+}
+CONFIGFS_ATTR(cfg_snd_avirt_stream_group_, sealed);
+
+static struct configfs_attribute *cfg_snd_avirt_stream_group_attrs[] = {
+ &cfg_snd_avirt_stream_group_attr_sealed,
+ NULL,
+};
+
+static struct configfs_group_operations cfg_snd_avirt_stream_group_ops = {
+ .make_item = cfg_snd_avirt_stream_make_item
+};
+
+static struct config_item_type cfg_stream_group_type = {
+ .ct_group_ops = &cfg_snd_avirt_stream_group_ops,
+ .ct_attrs = cfg_snd_avirt_stream_group_attrs,
+ .ct_owner = THIS_MODULE
+};
+
+static struct config_item_type cfg_avirt_group_type = {
+ .ct_owner = THIS_MODULE,
+};
+
+static struct configfs_subsystem cfg_subsys = {
+ .su_group = {
+ .cg_item = {
+ .ci_namebuf = "snd-avirt",
+ .ci_type = &cfg_avirt_group_type,
+ },
+ },
+};
+
+int __init snd_avirt_configfs_init(struct snd_avirt_core *core)
+{
+ int err;
+
+ config_group_init(&cfg_subsys.su_group);
+ mutex_init(&cfg_subsys.su_mutex);
+ err = configfs_register_subsystem(&cfg_subsys);
+ if (err) {
+ D_ERRORK("Cannot register configfs subsys!");
+ return err;
+ }
+ core->stream_group = configfs_register_default_group(
+ &cfg_subsys.su_group, "streams", &cfg_stream_group_type);
+ if (IS_ERR(core->stream_group)) {
+ err = PTR_ERR(core->stream_group);
+ D_ERRORK("Cannot register configfs default group 'streams'!");
+ goto exit_configfs;
+ }
+
+ return 0;
+
+exit_configfs:
+ configfs_unregister_subsystem(&cfg_subsys);
+
+ return err;
+}
+
+void __exit snd_avirt_configfs_exit(struct snd_avirt_core *core)
+{
+ configfs_unregister_default_group(core->stream_group);
+ configfs_unregister_subsystem(&cfg_subsys);
+}
diff --git a/core.c b/core.c
new file mode 100644
index 0000000..aacc0a1
--- /dev/null
+++ b/core.c
@@ -0,0 +1,519 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * AVIRT - ALSA Virtual Soundcard
+ *
+ * Copyright (c) 2010-2018 Fiberdyne Systems Pty Ltd
+ *
+ * core.c - AVIRT core internals
+ */
+
+#include <linux/module.h>
+#include <linux/string.h>
+#include <linux/slab.h>
+#include <sound/initval.h>
+
+#include "core.h"
+
+MODULE_AUTHOR("James O'Shannessy <james.oshannessy@fiberdyne.com.au>");
+MODULE_AUTHOR("Mark Farrugia <mark.farrugia@fiberdyne.com.au>");
+MODULE_DESCRIPTION("ALSA virtual, dynamic soundcard");
+MODULE_LICENSE("GPL v2");
+
+#define D_LOGNAME "core"
+
+#define D_INFOK(fmt, args...) DINFO(D_LOGNAME, fmt, ##args)
+#define D_PRINTK(fmt, args...) DDEBUG(D_LOGNAME, fmt, ##args)
+#define D_ERRORK(fmt, args...) DERROR(D_LOGNAME, fmt, ##args)
+
+#define SND_AVIRTUAL_DRIVER "snd_avirt"
+
+static struct snd_avirt_core core = {
+ .stream_count = 0,
+ .streams_sealed = false,
+};
+
+struct snd_avirt_coreinfo coreinfo = {
+ .version = { 0, 0, 1 },
+};
+
+static LIST_HEAD(audiopath_list);
+
+struct snd_avirt_audiopath_obj {
+ struct kobject kobj;
+ struct list_head list;
+ struct snd_avirt_audiopath *path;
+};
+
+static struct kset *snd_avirt_audiopath_kset;
+static struct kobject *kobj;
+
+#define to_audiopath_obj(d) \
+ container_of(d, struct snd_avirt_audiopath_obj, kobj)
+#define to_audiopath_attr(a) \
+ container_of(a, struct snd_avirt_audiopath_attribute, attr)
+
+/**
+ * struct snd_avirt_audiopath_attribute - access the attributes of Audio Path
+ * @attr: attributes of an Audio Path
+ * @show: pointer to the show function
+ * @store: pointer to the store function
+ */
+struct snd_avirt_audiopath_attribute {
+ struct attribute attr;
+ ssize_t (*show)(struct snd_avirt_audiopath_obj *d,
+ struct snd_avirt_audiopath_attribute *attr, char *buf);
+ ssize_t (*store)(struct snd_avirt_audiopath_obj *d,
+ struct snd_avirt_audiopath_attribute *attr,
+ const char *buf, size_t count);
+};
+
+/**
+ * audiopath_attr_show - show function of an Audio Path
+ * @kobj: pointer to kobject
+ * @attr: pointer to attribute struct
+ * @buf: buffer
+ */
+static ssize_t audiopath_attr_show(struct kobject *kobj, struct attribute *attr,
+ char *buf)
+{
+ struct snd_avirt_audiopath_attribute *audiopath_attr;
+ struct snd_avirt_audiopath_obj *audiopath_obj;
+
+ audiopath_attr = to_audiopath_attr(attr);
+ audiopath_obj = to_audiopath_obj(kobj);
+
+ if (!audiopath_attr->show)
+ return -EIO;
+
+ return audiopath_attr->show(audiopath_obj, audiopath_attr, buf);
+}
+
+/**
+ * audiopath_attr_store - attribute store function of Audio Path object
+ * @kobj: pointer to kobject
+ * @attr: pointer to attribute struct
+ * @buf: buffer
+ * @len: length of buffer
+ */
+static ssize_t audiopath_attr_store(struct kobject *kobj,
+ struct attribute *attr, const char *buf,
+ size_t len)
+{
+ struct snd_avirt_audiopath_attribute *audiopath_attr;
+ struct snd_avirt_audiopath_obj *audiopath_obj;
+
+ audiopath_attr = to_audiopath_attr(attr);
+ audiopath_obj = to_audiopath_obj(kobj);
+
+ if (!audiopath_attr->store)
+ return -EIO;
+ return audiopath_attr->store(audiopath_obj, audiopath_attr, buf, len);
+}
+
+static const struct sysfs_ops snd_avirt_audiopath_sysfs_ops = {
+ .show = audiopath_attr_show,
+ .store = audiopath_attr_store,
+};
+
+/**
+ * snd_avirt_audiopath_release - Audio Path release function
+ * @kobj: pointer to Audio Paths's kobject
+ */
+static void snd_avirt_audiopath_release(struct kobject *kobj)
+{
+ struct snd_avirt_audiopath_obj *audiopath_obj = to_audiopath_obj(kobj);
+
+ kfree(audiopath_obj);
+}
+
+static ssize_t
+ audiopath_name_show(struct snd_avirt_audiopath_obj *audiopath_obj,
+ struct snd_avirt_audiopath_attribute *attr,
+ char *buf)
+{
+ return sprintf(buf, "%s\n", audiopath_obj->path->name);
+}
+
+static ssize_t
+ audiopath_version_show(struct snd_avirt_audiopath_obj *audiopath_obj,
+ struct snd_avirt_audiopath_attribute *attr,
+ char *buf)
+{
+ struct snd_avirt_audiopath *audiopath = audiopath_obj->path;
+
+ return sprintf(buf, "%d.%d.%d\n", audiopath->version[0],
+ audiopath->version[1], audiopath->version[2]);
+}
+
+static struct snd_avirt_audiopath_attribute snd_avirt_audiopath_attrs[] = {
+ __ATTR_RO(audiopath_name),
+ __ATTR_RO(audiopath_version),
+};
+
+static struct attribute *snd_avirt_audiopath_def_attrs[] = {
+ &snd_avirt_audiopath_attrs[0].attr,
+ &snd_avirt_audiopath_attrs[1].attr,
+ NULL,
+};
+
+static struct kobj_type snd_avirt_audiopath_ktype = {
+ .sysfs_ops = &snd_avirt_audiopath_sysfs_ops,
+ .release = snd_avirt_audiopath_release,
+ .default_attrs = snd_avirt_audiopath_def_attrs,
+};
+
+/**
+ * create_snd_avirt_audiopath_obj - creates an Audio Path object
+ * @uid: Unique ID of the Audio Path
+ *
+ * This creates an Audio Path object and assigns the kset and registers
+ * it with sysfs.
+ * @return: Pointer to the Audio Path object or NULL if it failed.
+ */
+static struct snd_avirt_audiopath_obj *
+ create_snd_avirt_audiopath_obj(const char *uid)
+{
+ struct snd_avirt_audiopath_obj *snd_avirt_audiopath;
+ int retval;
+
+ snd_avirt_audiopath = kzalloc(sizeof(*snd_avirt_audiopath), GFP_KERNEL);
+ if (!snd_avirt_audiopath)
+ return NULL;
+ snd_avirt_audiopath->kobj.kset = snd_avirt_audiopath_kset;
+ retval = kobject_init_and_add(&snd_avirt_audiopath->kobj,
+ &snd_avirt_audiopath_ktype, kobj, "%s",
+ uid);
+ if (retval) {
+ kobject_put(&snd_avirt_audiopath->kobj);
+ return NULL;
+ }
+ kobject_uevent(&snd_avirt_audiopath->kobj, KOBJ_ADD);
+ return snd_avirt_audiopath;
+}
+
+static struct snd_pcm *pcm_create(struct snd_avirt_stream *stream)
+{
+ bool playback = false, capture = false;
+ struct snd_pcm *pcm;
+ int err;
+
+ /** Special case: loopback */
+ if (!strcmp(stream->map, "ap_loopback")) {
+ playback = true;
+ capture = true;
+ (&pcm_ops)->copy_user = NULL;
+ } else if (!stream->direction) {
+ playback = true;
+ } else {
+ capture = true;
+ }
+
+ err = snd_pcm_new(core.card, stream->name, stream->device, playback,
+ capture, &pcm);
+
+ if (err < 0)
+ return ERR_PTR(err);
+
+ /** Register driver callbacks */
+ if (playback)
+ snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &pcm_ops);
+ if (capture)
+ snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &pcm_ops);
+
+ pcm->info_flags = 0;
+ strcpy(pcm->name, stream->name);
+
+ return pcm;
+}
+
+/**
+ * destroy_snd_avirt_audiopath_obj - destroys an Audio Path object
+ * @name: the Audio Path object
+ */
+static void destroy_snd_avirt_audiopath_obj(struct snd_avirt_audiopath_obj *p)
+{
+ kobject_put(&p->kobj);
+}
+
+/**
+ * snd_avirt_audiopath_get - retrieves the Audio Path by its UID
+ * @uid: Unique ID for the Audio Path
+ * @return: Corresponding Audio Path
+ */
+struct snd_avirt_audiopath *snd_avirt_audiopath_get(const char *uid)
+{
+ struct snd_avirt_audiopath_obj *ap_obj;
+
+ list_for_each_entry(ap_obj, &audiopath_list, list) {
+ // pr_info("get_ap %s\n", ap_obj->path->uid);
+ if (!strcmp(ap_obj->path->uid, uid))
+ return ap_obj->path;
+ }
+
+ return NULL;
+}
+
+/**
+ * snd_avirt_audiopath_register - register Audio Path with AVIRT
+ * @audiopath: Audio Path to be registered
+ * @core: ALSA virtual driver core info
+ * @return: 0 on success or error code otherwise
+ */
+int snd_avirt_audiopath_register(struct snd_avirt_audiopath *audiopath,
+ struct snd_avirt_coreinfo **info)
+{
+ struct snd_avirt_audiopath_obj *audiopath_obj;
+
+ if (!audiopath) {
+ D_ERRORK("Audio Path is NULL!");
+ return -EINVAL;
+ }
+
+ audiopath_obj = create_snd_avirt_audiopath_obj(audiopath->uid);
+ if (!audiopath_obj) {
+ D_INFOK("Failed to alloc driver object");
+ return -ENOMEM;
+ }
+ audiopath_obj->path = audiopath;
+
+ audiopath->context = audiopath_obj;
+ D_INFOK("Registered new Audio Path: %s", audiopath->name);
+
+ list_add_tail(&audiopath_obj->list, &audiopath_list);
+
+ // If we have already sealed the streams, configure this AP
+ if (core.streams_sealed)
+ audiopath->configure(core.card, core.stream_group,
+ core.stream_count);
+
+ *info = &coreinfo;
+
+ return 0;
+}
+EXPORT_SYMBOL_GPL(snd_avirt_audiopath_register);
+
+/**
+ * snd_avirt_audiopath_deregister - deregister Audio Path with AVIRT
+ * @audiopath: Audio Path to be deregistered
+ * @return: 0 on success or error code otherwise
+ */
+int snd_avirt_audiopath_deregister(struct snd_avirt_audiopath *audiopath)
+{
+ struct snd_avirt_audiopath_obj *audiopath_obj;
+
+ // Check if audio path is registered
+ if (!audiopath) {
+ D_ERRORK("Bad Audio Path Driver");
+ return -EINVAL;
+ }
+
+ audiopath_obj = audiopath->context;
+ if (!audiopath_obj) {
+ D_INFOK("driver not registered");
+ return -EINVAL;
+ }
+
+ list_del(&audiopath_obj->list);
+ destroy_snd_avirt_audiopath_obj(audiopath_obj);
+ D_INFOK("Deregistered Audio Path %s", audiopath->uid);
+
+ return 0;
+}
+EXPORT_SYMBOL_GPL(snd_avirt_audiopath_deregister);
+
+/**
+ * snd_avirt_stream_count - get the stream count for the given direction
+ * @direction: The direction to get the stream count for
+ * @return: The stream count
+ */
+int snd_avirt_stream_count(unsigned int direction)
+{
+ struct list_head *entry;
+ struct config_item *item;
+ struct snd_avirt_stream *stream;
+ unsigned int count = 0;
+
+ if (direction > 1)
+ return -ERANGE;
+
+ list_for_each(entry, &core.stream_group->cg_children) {
+ item = container_of(entry, struct config_item, ci_entry);
+ stream = snd_avirt_stream_from_config_item(item);
+ if (!stream)
+ return -EFAULT;
+ if (stream->direction == direction)
+ count++;
+ }
+
+ return count;
+}
+EXPORT_SYMBOL_GPL(snd_avirt_stream_count);
+
+/**
+ * snd_avirt_stream_create - Create audio stream, including it's ALSA PCM device
+ * @name: The name designated to the audio stream
+ * @direction: The PCM direction (SNDRV_PCM_STREAM_PLAYBACK or
+ * SNDRV_PCM_STREAM_CAPTURE)
+ * @return: The newly created audio stream if successful, or an error pointer
+ */
+struct snd_avirt_stream *snd_avirt_stream_create(const char *name,
+ int direction)
+{
+ struct snd_avirt_stream *stream;
+
+ stream = kzalloc(sizeof(*stream), GFP_KERNEL);
+ if (!stream)
+ return ERR_PTR(-ENOMEM);
+
+ strcpy(stream->name, name);
+ strcpy(stream->map, "none");
+ stream->channels = 0;
+ stream->direction = direction;
+ stream->device = core.stream_count++;
+
+ D_INFOK("name: %s device:%d", name, stream->device);
+
+ return stream;
+}
+
+int snd_avirt_streams_seal(void)
+{
+ int err = 0;
+ struct snd_avirt_audiopath_obj *ap_obj;
+ struct snd_avirt_stream *stream;
+ struct config_item *item;
+ struct list_head *entry;
+
+ if (core.streams_sealed) {
+ D_ERRORK("streams are already sealed!");
+ return -1;
+ }
+
+ list_for_each(entry, &core.stream_group->cg_children) {
+ item = container_of(entry, struct config_item, ci_entry);
+ stream = snd_avirt_stream_from_config_item(item);
+ if (!stream)
+ return -EFAULT;
+ stream->pcm = pcm_create(stream);
+ if (IS_ERR_OR_NULL(stream->pcm))
+ return (PTR_ERR(stream->pcm));
+ }
+
+ list_for_each_entry(ap_obj, &audiopath_list, list) {
+ D_INFOK("configure() AP uid: %s", ap_obj->path->uid);
+ ap_obj->path->configure(core.card, core.stream_group,
+ core.stream_count);
+ }
+
+ err = snd_card_register(core.card);
+ if (err < 0) {
+ D_ERRORK("Sound card registration failed!");
+ snd_card_free(core.card);
+ }
+
+ core.streams_sealed = true;
+
+ return err;
+}
+
+bool snd_avirt_streams_sealed(void)
+{
+ return core.streams_sealed;
+}
+
+struct snd_avirt_stream *snd_avirt_stream_find_by_device(unsigned int device)
+{
+ struct snd_avirt_stream *stream;
+ struct config_item *item;
+ struct list_head *entry;
+
+ if (device >= core.stream_count) {
+ D_ERRORK("Stream device number is larger than stream count");
+ return ERR_PTR(-EINVAL);
+ }
+
+ list_for_each(entry, &core.stream_group->cg_children) {
+ item = container_of(entry, struct config_item, ci_entry);
+ stream = snd_avirt_stream_from_config_item(item);
+ if (!stream)
+ return ERR_PTR(-EFAULT);
+ if (stream->device == device)
+ return stream;
+ }
+
+ return NULL;
+}
+
+/**
+ * core_init - Initialize the kernel module
+ */
+static int __init core_init(void)
+{
+ int err;
+
+ D_INFOK("Alsa Virtual Sound Driver avirt-%d.%d.%d", coreinfo.version[0],
+ coreinfo.version[1], coreinfo.version[2]);
+
+ core.avirt_class = class_create(THIS_MODULE, SND_AVIRTUAL_DRIVER);
+ if (IS_ERR(core.avirt_class)) {
+ D_ERRORK("No udev support");
+ return PTR_ERR(core.avirt_class);
+ }
+
+ core.dev = device_create(core.avirt_class, NULL, 0, NULL, "avirtcore");
+ if (IS_ERR(core.dev)) {
+ err = PTR_ERR(core.dev);
+ goto exit_class;
+ }
+
+ // Create the card instance
+ err = snd_card_new(core.dev, SNDRV_DEFAULT_IDX1, "avirt", THIS_MODULE,
+ 0, &core.card);
+ if (err < 0) {
+ D_ERRORK("Failed to create sound card");
+ goto exit_class_container;
+ }
+
+ strncpy(core.card->driver, "avirt-alsa-dev", 16);
+ strncpy(core.card->shortname, "avirt", 32);
+ strncpy(core.card->longname, "A virtual sound card driver for ALSA",
+ 80);
+
+ snd_avirt_audiopath_kset =
+ kset_create_and_add("audiopaths", NULL, &core.dev->kobj);
+ if (!snd_avirt_audiopath_kset) {
+ err = -ENOMEM;
+ goto exit_snd_card;
+ }
+
+ err = snd_avirt_configfs_init(&core);
+ if (err < 0)
+ goto exit_snd_card;
+
+ return 0;
+
+exit_snd_card:
+ snd_card_free(core.card);
+exit_class_container:
+ device_destroy(core.avirt_class, 0);
+exit_class:
+ class_destroy(core.avirt_class);
+
+ return err;
+}
+
+/**
+ * core_exit - Destroy the kernel module
+ */
+static void __exit core_exit(void)
+{
+ snd_avirt_configfs_exit(&core);
+
+ kset_unregister(snd_avirt_audiopath_kset);
+ snd_card_free(core.card);
+ device_destroy(core.avirt_class, 0);
+ class_destroy(core.avirt_class);
+}
+
+module_init(core_init);
+module_exit(core_exit);
diff --git a/core.h b/core.h
new file mode 100644
index 0000000..735df65
--- /dev/null
+++ b/core.h
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * AVIRT - ALSA Virtual Soundcard
+ *
+ * Copyright (c) 2010-2018 Fiberdyne Systems Pty Ltd
+ *
+ * core.h - AVIRT internal header
+ */
+
+#ifndef __SOUND_AVIRT_CORE_H
+#define __SOUND_AVIRT_CORE_H
+
+#include <sound/avirt.h>
+
+#include "utils.h"
+
+extern struct snd_pcm_ops pcm_ops;
+
+struct snd_avirt_core {
+ struct snd_card *card;
+ struct device *dev;
+ struct class *avirt_class;
+ struct config_group *stream_group;
+ unsigned int stream_count;
+ bool streams_sealed;
+};
+
+/**
+ * snd_avirt_configfs_init - Initialise the configfs system
+ * @core: The snd_avirt_core pointer
+ * @return: 0 on success, negative ERRNO on failure
+ */
+int __init snd_avirt_configfs_init(struct snd_avirt_core *core);
+
+/**
+ * snd_avirt_configfs_exit - Clean up and exit the configfs system
+ * @core: The snd_avirt_core pointer
+ */
+void __exit snd_avirt_configfs_exit(struct snd_avirt_core *core);
+
+/**
+ * snd_avirt_streams_seal - Register the sound card to user space
+ * @return: 0 on success, negative ERRNO on failure
+ */
+int snd_avirt_streams_seal(void);
+
+/**
+ * snd_avirt_streams_sealed - Check if the streams have been sealed or not
+ * @return: true if sealed, false otherwise
+ */
+bool snd_avirt_streams_sealed(void);
+
+/**
+ * snd_avirt_stream_find_by_device - Get audio stream from device number
+ * @device: The PCM device number corresponding to the desired stream
+ * @return: The audio stream if found, or an error pointer otherwise
+ */
+struct snd_avirt_stream *snd_avirt_stream_find_by_device(unsigned int device);
+
+/**
+ * snd_avirt_stream_create - Create audio stream, including it's ALSA PCM device
+ * @name: The name designated to the audio stream
+ * @direction: The PCM direction (SNDRV_PCM_STREAM_PLAYBACK or
+ * SNDRV_PCM_STREAM_CAPTURE)
+ * @return: The newly created audio stream if successful, or an error pointer
+ */
+struct snd_avirt_stream *snd_avirt_stream_create(const char *name,
+ int direction);
+
+#endif /* __SOUND_AVIRT_CORE_H */
diff --git a/docs/1.Introduction.md b/docs/1.Introduction.md
new file mode 100644
index 0000000..c36717c
--- /dev/null
+++ b/docs/1.Introduction.md
@@ -0,0 +1,38 @@
+Introduction
+===================
+
+## Problem
+
+The existing audio solution in [AGL](https://www.automotivelinux.org/) (Automotive Grade Linux) utilizes the ALSA loopback module together with [4a-softmixer](https://github.com/iotbzh/4a-softmixer). There are drawbacks to this solution:
+
+1. Non-generic interface for configurable hardware cases
+
+ - Unable to configure streams mapped to outputs
+
+2. Not fully optimized for certain use cases (ie. Routing Audio to DSP vs. aloop)
+
+ - Routing audio to hardware to reduce overhead
+
+3. Inability to secure on all audio streams
+
+ - Substreams cannot have SMACK labels applied, inherently leaving different audio streams insecure, or a single label applied to all.
+
+## The AVIRT Solution
+
+The ALSA Virtual Sound Driver (AVIRT) aims to provide a Linux kernel solution to the issue of audio routing in kernel-space, as well as security per audio stream, and dynamic configuration of audio streams at the kernel level.
+
+AVIRT addresses the aforementioned problems by:
+
+1. Providing a standard user-space interface via `configfs` to configure a variable number of 'streams' which can be mapped to audio paths.
+2. Optimize the audio routing by connecting directly with the desired audio path. This can include routing audio through directly to hardware, to an implemented loopback interface, or to a DSP.
+3. Each 'stream' is separated to its own ALSA PCM device, therefore differing security attributes can be applied to each 'stream'. This means that each of the audio roles can have separate security contexts from one another.
+
+A top-level abstract dynamic audio driver is presented to the user-space via an ALSA middle-layer card. The card's PCM devices are configured using `configfs` via the accompanying userspace library [libavirt](https://github.com/fiberdyne/libavirt). The low-level "real" audio drivers can subscribe to the top-level as an "Audio Path". The Audio Path accepts routed audio streams from the abstracted top-level, and is then able to direct the audio streams accordingly.
+
+![alt text](images/arch-4a.png "AVIRT Architecture")
+
+The following Audio Paths are currently implemented for AVIRT:
+
+- **ap_dummy** - This is provided as an example to show how a low-level audio driver would subscribe to AVIRT, and accept audio routing for playback.
+- **ap_fddsp** - This is the Fiberdyne DSP hardmixer. This is only supported on the Renesas R-Car M3 AGL reference platform, and utilizes the HiFi2 DSP core to provide advanced DSP and audio mixing. An accompanying UI can be used to control the DSP parameters.
+- **ap_loopback** - This is the default loopback for use with the softmixer. This is the stock AGL solution to be used to emulate the hardmixer when not available.
diff --git a/docs/2.Building.md b/docs/2.Building.md
new file mode 100644
index 0000000..5fd9d23
--- /dev/null
+++ b/docs/2.Building.md
@@ -0,0 +1,62 @@
+Building AVIRT
+===================================
+
+## Table of Contents
+
+1. [Introduction](#intro)
+2. [Out of Tree](#out-of-tree)
+3. [In Tree](#in-tree)
+
+<a name="intro"/>
+
+## Introduction
+
+The AVIRT module and submodules can be built using a variety of methods. There are Visual Code build tasks for in and out of tree builds, make file support for CLI building (both in and out of tree), and xds build support.
+
+<a name="out-of-tree"/>
+
+## Out Of Tree
+
+### Building with CLI
+
+To build both AVIRT and the additional Audio Paths out-of-tree, use the following command:
+
+```sh
+$ make
+```
+
+or
+
+```sh
+$ CONFIG_AVIRT=m CONFIG_AVIRT_BUILDLOCAL=y CONFIG_AVIRT_AP_DUMMY=m CONFIG_AVIRT_AP_LOOPBACK=m make -C /lib/modules/$(uname -r)/build/ M=$(pwd)
+```
+
+The latter is executed internally with the make file.
+
+### Building with XDS SDK
+
+To build both AVIRT and the dummy Audio Path out-of-tree for [AGL](http://docs.automotivelinux.org/) (`aarch64` currently supported), use the [XDS](http://docs.automotivelinux.org/docs/devguides/en/dev/reference/xds/part-1/0_Abstract.html) build system together with the `make_agl.sh` script:
+
+```sh
+$ ./make_agl.sh ${XDS_SDK_ID}
+```
+
+<a name="in-tree"/>
+
+## In tree
+
+The kernal modules can be built in tree, dependent on the avirt repository being located in drivers/staging - If using your own fork of the linux kernel, you will need to update the staging Makefiles and Kconfigs accordingly.
+
+To build in tree, use the [Fiberdyne Linux fork](https://github.com/fiberdyne/linux), which will automatically clone the AVIRT Driver and required AudioPath modules to the `drivers/staging` directory. You can then turn AVIRT Support on by setting to `<M>`. The drivers can be found here:
+
+```
+$ make menuconfig
+
+# Navigate to: Device Drivers--->Staging Drivers--->AVIRT Support
+```
+
+Finally build the kernel with the configuration selected by making.
+
+```
+$ make
+```
diff --git a/docs/3.Usage.md b/docs/3.Usage.md
new file mode 100644
index 0000000..ba5c3e6
--- /dev/null
+++ b/docs/3.Usage.md
@@ -0,0 +1,140 @@
+Using AVIRT
+===================================
+
+## Introduction
+
+## Table of Contents
+
+1. [Load/Unload AVIRT](#un-load-avirt)
+2. [Configuring AVIRT](#configuring-avirt)
+3. [Checking AVIRT](#checking-avirt)
+
+<a name="un-load-avirt"/>
+
+## 1. Loading and Unloading AVIRT
+
+### Load Out of Tree
+
+As root, load the required `avirt_core.ko` and subsequent audio path.
+As an example, the Dummy Audiopath is being loaded here.
+
+```sh
+insmod snd-avirt-core.ko
+insmod dummy/snd-avirt-ap-dummy.ko
+insmod loopback/snd-avirt-ap-loopback.ko
+```
+
+### Note:
+
+The loading and unloading of drivers can be performed using the helper scripts.
+To run, we must load the kernel modules using the `scripts/load.sh` script:
+
+```sh
+$ ./scripts/load.sh
+```
+
+To unload the drivers use:
+
+```sh
+$ ./scripts/unload.sh
+```
+
+### Load In Tree
+
+#### Note:
+
+Either build the module in tree, or you can copy the modules manually and then run `depmod` to generate dependencies.
+For example, in AGL:
+
+```sh
+mkdir -p /lib/modules/$(uname -r)/extra
+cp snd-avirt-core.ko snd-avirt-ap-dummy.ko snd-avirt-ap-loopback.ko /lib/modules/$(uname -r)/extra
+depmod
+```
+
+Once the modules are in place, we can load the modules using:
+
+```sh
+modprobe snd-avirt-core
+modprobe snd-avirt-ap-dummy
+modprobe snd-avirt-ap-loopback
+```
+
+<a name="configure-avirt" />
+
+## 2. Configuring AVIRT
+
+AVIRT is configured using configfs.
+
+### Note:
+
+A sample script for the following is supplied inside the `scripts` folder.
+
+First, verify the kernel supports the use of configfs.
+
+```sh
+fgrep configfs /proc/filesystems
+```
+
+The expected output is:
+
+```
+nodev configfs
+```
+
+Once confirmed, we can mount the `configfs` filesystem at the conventional point:
+
+```sh
+# Check configfs is mounted on the system
+mkdir -p /config
+mount -t configfs none /config
+```
+
+Finally, we can configure AVIRT, for example:
+
+```sh
+# Set up each of the cards channels
+mkdir /config/snd-avirt/streams/playback_media
+echo "2">/config/snd-avirt/streams/playback_media/channels
+echo "ap_dummy">/config/snd-avirt/streams/playback_media/map
+
+mkdir /config/snd-avirt/streams/playback_navigation
+echo "1">/config/snd-avirt/streams/playback_navigation/channels
+echo "ap_dummy">/config/snd-avirt/streams/playback_navigation/map
+
+mkdir /config/snd-avirt/streams/playback_emergency
+echo "1">/config/snd-avirt/streams/playback_emergency/channels
+echo "ap_dummy">/config/snd-avirt/streams/playback_emergency/map
+
+mkdir /config/snd-avirt/streams/capture_voice
+echo "1">/config/snd-avirt/streams/capture_voice/channels
+echo "ap_dummy">/config/snd-avirt/streams/capture_voice/map
+
+# Finally, seal the card, and initiate configuration
+echo "1">/config/snd-avirt/streams/sealed
+```
+
+Alternatively, the test script at `scripts/test_configfs.sh` can be used.
+
+The user-space library, [libavirt](https://github.com/fiberdyne/libavirt) can be used to interact with the configfs interface. Please refer to the README in libavirt for further details.
+
+<a name="checking-avirt" />
+
+## 3. Checking AVIRT Loaded Correctly
+
+We can see the newly created streams by using the `aplay` utility. For example, the device list might look a little like this:
+
+```sh
+aplay -l
+...
+card 2: avirt [avirt], device 0: multimedia [multimedia]
+ Subdevices: 1/1
+ Subdevice #0: subdevice #0
+card 2: avirt [avirt], device 1: navigation [navigation]
+ Subdevices: 1/1
+ Subdevice #0: subdevice #0
+card 2: avirt [avirt], device 2: emergency [emergency]
+ Subdevices: 1/1
+ Subdevice #0: subdevice #0
+...
+```
diff --git a/docs/4.4A-Integration.md b/docs/4.4A-Integration.md
new file mode 100644
index 0000000..cb88dd3
--- /dev/null
+++ b/docs/4.4A-Integration.md
@@ -0,0 +1,22 @@
+4A Integration
+===================
+
+AVIRT has been integrated with [4a-softmixer](https://github.com/iotbzh/4a-softmixer)
+and [4a-hal-generic](https://github.com/iotbzh/4a-hal-generic) to provide a smooth
+transition from the existing aloop implementation to the future AVIRT loopback implementation.
+
+### User-space Library
+
+The user-space library [libavirt](https://github.com/fiberdyne/libavirt) can be used to configure AVIRT from within a given AGL 4A binding.
+
+### Softmixer
+
+The AVIRT loopback can be used in-place of the standard aloop module. Modifications are currently underway
+to port the current 4a-softmixer to the new AVIRT loopback.
+
+### Hardmixer
+
+A new 4A mixer controller plugin (`.ctlso`) has been developed to demonstrate the capabilities of the
+Fiberdyne DSP mixer operating on the HiFi2 core on-board the Renesas R-Car M3 M3ULCB
+AGL reference platform. This is called the '**hardmixer**', and is a faster, lower
+latency alternative to the softmixer.
diff --git a/docs/images/arch-4a.png b/docs/images/arch-4a.png
new file mode 100644
index 0000000..6f085db
--- /dev/null
+++ b/docs/images/arch-4a.png
Binary files differ
diff --git a/dummy/Kconfig b/dummy/Kconfig
new file mode 100644
index 0000000..6a706c0
--- /dev/null
+++ b/dummy/Kconfig
@@ -0,0 +1,12 @@
+#
+# AVIRT Dummy Audio Path
+#
+
+config AVIRT_DUMMYAP
+ tristate "DummyAP"
+ select SND_PCM
+ ---help---
+ Say Y here if you want to add dummy audio path.
+
+ To compile this driver as a module, choose M here: the
+ module will be called avirt_dummyap.
diff --git a/dummy/Makefile b/dummy/Makefile
new file mode 100644
index 0000000..11ceceb
--- /dev/null
+++ b/dummy/Makefile
@@ -0,0 +1,6 @@
+obj-$(CONFIG_AVIRT_AP_DUMMY) += snd-avirt-ap-dummy.o
+
+$(info $(src))
+snd-avirt-ap-dummy-objs := dummy.o
+ccflags-y += -Idrivers/staging/
+ccflags-y += -I$(src)/../
diff --git a/dummy/dummy.c b/dummy/dummy.c
new file mode 100644
index 0000000..5f19564
--- /dev/null
+++ b/dummy/dummy.c
@@ -0,0 +1,307 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Dummy Audio Path for AVIRT
+ *
+ * Original systimer code:
+ * Copyright (c) by Jaroslav Kysela <perex@perex.cz>
+ *
+ * Adapt to use AVIRT
+ * Copyright (c) 2010-2018 Fiberdyne Systems Pty Ltd
+ *
+ * dummy.c - Dummy Audio Path driver implementation for AVIRT
+ */
+
+#include <linux/module.h>
+#include <linux/slab.h>
+#include <sound/avirt.h>
+
+MODULE_AUTHOR("James O'Shannessy <james.oshannessy@fiberdyne.com.au>");
+MODULE_AUTHOR("Mark Farrugia <mark.farrugia@fiberdyne.com.au>");
+MODULE_DESCRIPTION("Dummy Audio Path for AVIRT");
+MODULE_LICENSE("GPL v2");
+
+#define AP_UID "ap_dummy"
+
+#define AP_INFOK(fmt, args...) DINFO(AP_UID, fmt, ##args)
+#define AP_PRINTK(fmt, args...) DDEBUG(AP_UID, fmt, ##args)
+#define AP_ERRORK(fmt, args...) DERROR(AP_UID, fmt, ##args)
+
+#define DUMMY_SAMPLE_RATE 48000
+#define DUMMY_BLOCKSIZE 512
+#define DUMMY_PERIODS_MIN 1
+#define DUMMY_PERIODS_MAX 8
+
+#define get_dummy_ops(substream) \
+ (*(const struct dummy_timer_ops **)(substream)->runtime->private_data)
+
+static struct snd_avirt_coreinfo *coreinfo;
+
+/*******************************************************************************
+ * System Timer Interface
+ *
+ * This is used to call the ALSA PCM callbacks required to notify AVIRT of the
+ * 'periods elapsed', so that buffers can keep getting transmitted here
+ *
+ * (Borrowed from the default ALSA 'dummy' driver (sound/driver/dummy.c))
+ ******************************************************************************/
+struct dummy_timer_ops {
+ int (*create)(struct snd_pcm_substream *);
+ void (*free)(struct snd_pcm_substream *);
+ int (*prepare)(struct snd_pcm_substream *);
+ int (*start)(struct snd_pcm_substream *);
+ int (*stop)(struct snd_pcm_substream *);
+ snd_pcm_uframes_t (*pointer)(struct snd_pcm_substream *);
+};
+
+struct dummy_systimer_pcm {
+ /* ops must be the first item */
+ const struct dummy_timer_ops *timer_ops;
+ spinlock_t lock;
+ struct timer_list timer;
+ unsigned long base_time;
+ unsigned int frac_pos; /* fractional sample position (based HZ) */
+ unsigned int frac_period_rest;
+ unsigned int frac_buffer_size; /* buffer_size * HZ */
+ unsigned int frac_period_size; /* period_size * HZ */
+ unsigned int rate;
+ int elapsed;
+ struct snd_pcm_substream *substream;
+};
+
+static void dummy_systimer_rearm(struct dummy_systimer_pcm *dpcm)
+{
+ mod_timer(&dpcm->timer, jiffies + (dpcm->frac_period_rest + dpcm->rate -
+ 1) / dpcm->rate);
+}
+
+static void dummy_systimer_update(struct dummy_systimer_pcm *dpcm)
+{
+ unsigned long delta;
+
+ delta = jiffies - dpcm->base_time;
+ if (!delta)
+ return;
+ dpcm->base_time += delta;
+ delta *= dpcm->rate;
+ dpcm->frac_pos += delta;
+ while (dpcm->frac_pos >= dpcm->frac_buffer_size)
+ dpcm->frac_pos -= dpcm->frac_buffer_size;
+ while (dpcm->frac_period_rest <= delta) {
+ dpcm->elapsed++;
+ dpcm->frac_period_rest += dpcm->frac_period_size;
+ }
+ dpcm->frac_period_rest -= delta;
+}
+
+static int dummy_systimer_start(struct snd_pcm_substream *substream)
+{
+ struct dummy_systimer_pcm *dpcm = substream->runtime->private_data;
+ spin_lock(&dpcm->lock);
+ dpcm->base_time = jiffies;
+ dummy_systimer_rearm(dpcm);
+ spin_unlock(&dpcm->lock);
+ return 0;
+}
+
+static int dummy_systimer_stop(struct snd_pcm_substream *substream)
+{
+ struct dummy_systimer_pcm *dpcm = substream->runtime->private_data;
+ spin_lock(&dpcm->lock);
+ del_timer(&dpcm->timer);
+ spin_unlock(&dpcm->lock);
+ return 0;
+}
+
+static int dummy_systimer_prepare(struct snd_pcm_substream *substream)
+{
+ struct snd_pcm_runtime *runtime = substream->runtime;
+ struct dummy_systimer_pcm *dpcm = runtime->private_data;
+
+ dpcm->frac_pos = 0;
+ dpcm->rate = runtime->rate;
+ dpcm->frac_buffer_size = runtime->buffer_size * HZ;
+ dpcm->frac_period_size = runtime->period_size * HZ;
+ dpcm->frac_period_rest = dpcm->frac_period_size;
+ dpcm->elapsed = 0;
+
+ return 0;
+}
+
+static void dummy_systimer_callback(struct timer_list *t)
+{
+ struct dummy_systimer_pcm *dpcm = from_timer(dpcm, t, timer);
+ unsigned long flags;
+ int elapsed = 0;
+
+ spin_lock_irqsave(&dpcm->lock, flags);
+ dummy_systimer_update(dpcm);
+ dummy_systimer_rearm(dpcm);
+ elapsed = dpcm->elapsed;
+ dpcm->elapsed = 0;
+ spin_unlock_irqrestore(&dpcm->lock, flags);
+ if (elapsed)
+ snd_avirt_pcm_period_elapsed(dpcm->substream);
+}
+
+static snd_pcm_uframes_t
+ dummy_systimer_pointer(struct snd_pcm_substream *substream)
+{
+ struct dummy_systimer_pcm *dpcm = substream->runtime->private_data;
+ snd_pcm_uframes_t pos;
+
+ spin_lock(&dpcm->lock);
+ dummy_systimer_update(dpcm);
+ pos = dpcm->frac_pos / HZ;
+ spin_unlock(&dpcm->lock);
+ return pos;
+}
+
+static int dummy_systimer_create(struct snd_pcm_substream *substream)
+{
+ struct dummy_systimer_pcm *dpcm;
+
+ dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
+ if (!dpcm)
+ return -ENOMEM;
+ substream->runtime->private_data = dpcm;
+ timer_setup(&dpcm->timer, dummy_systimer_callback, 0);
+ spin_lock_init(&dpcm->lock);
+ dpcm->substream = substream;
+ return 0;
+}
+
+static void dummy_systimer_free(struct snd_pcm_substream *substream)
+{
+ kfree(substream->runtime->private_data);
+}
+
+static const struct dummy_timer_ops dummy_systimer_ops = {
+ .create = dummy_systimer_create,
+ .free = dummy_systimer_free,
+ .prepare = dummy_systimer_prepare,
+ .start = dummy_systimer_start,
+ .stop = dummy_systimer_stop,
+ .pointer = dummy_systimer_pointer,
+};
+
+/*******************************************************************************
+ * Audio Path ALSA PCM Callbacks
+ ******************************************************************************/
+static int dummy_pcm_open(struct snd_pcm_substream *substream)
+{
+ const struct dummy_timer_ops *ops;
+ int err;
+
+ ops = &dummy_systimer_ops;
+ err = ops->create(substream);
+ if (err < 0)
+ return err;
+ get_dummy_ops(substream) = ops;
+
+ return 0;
+}
+
+static int dummy_pcm_close(struct snd_pcm_substream *substream)
+{
+ get_dummy_ops(substream)->free(substream);
+ return 0;
+}
+
+static snd_pcm_uframes_t dummy_pcm_pointer(struct snd_pcm_substream *substream)
+{
+ return get_dummy_ops(substream)->pointer(substream);
+}
+
+static int dummy_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
+{
+ switch (cmd) {
+ case SNDRV_PCM_TRIGGER_START:
+ case SNDRV_PCM_TRIGGER_RESUME:
+ return get_dummy_ops(substream)->start(substream);
+ case SNDRV_PCM_TRIGGER_STOP:
+ case SNDRV_PCM_TRIGGER_SUSPEND:
+ return get_dummy_ops(substream)->stop(substream);
+ }
+ return -EINVAL;
+}
+
+static int dummy_pcm_prepare(struct snd_pcm_substream *substream)
+{
+ return get_dummy_ops(substream)->prepare(substream);
+}
+
+static struct snd_pcm_ops dummyap_pcm_ops = {
+ .open = dummy_pcm_open,
+ .close = dummy_pcm_close,
+ .prepare = dummy_pcm_prepare,
+ .pointer = dummy_pcm_pointer,
+ .trigger = dummy_pcm_trigger,
+};
+
+/*******************************************************************************
+ * Dummy Audio Path AVIRT registration
+ ******************************************************************************/
+static int dummy_configure(struct snd_card *card,
+ struct config_group *snd_avirt_stream_group,
+ unsigned int stream_count)
+{
+ // Do something with streams
+
+ struct list_head *entry;
+ list_for_each (entry, &snd_avirt_stream_group->cg_children) {
+ struct config_item *item =
+ container_of(entry, struct config_item, ci_entry);
+ struct snd_avirt_stream *stream =
+ snd_avirt_stream_from_config_item(item);
+ AP_INFOK("stream name:%s device:%d channels:%d", stream->name,
+ stream->device, stream->channels);
+ }
+
+ return 0;
+}
+
+static struct snd_pcm_hardware dummyap_hw = {
+ .formats = SNDRV_PCM_FMTBIT_S16_LE,
+ .info = (SNDRV_PCM_INFO_INTERLEAVED // Channel interleaved audio
+ | SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_MMAP |
+ SNDRV_PCM_INFO_MMAP_VALID),
+ .rates = SNDRV_PCM_RATE_48000,
+ .rate_min = DUMMY_SAMPLE_RATE,
+ .rate_max = DUMMY_SAMPLE_RATE,
+ .periods_min = DUMMY_PERIODS_MIN,
+ .periods_max = DUMMY_PERIODS_MAX,
+};
+
+static struct snd_avirt_audiopath dummyap_module = {
+ .uid = "ap_dummy",
+ .name = "Dummy Audio Path",
+ .version = { 0, 0, 1 },
+ .hw = &dummyap_hw,
+ .pcm_ops = &dummyap_pcm_ops,
+ .configure = dummy_configure,
+};
+
+static int __init dummy_init(void)
+{
+ int err = 0;
+
+ pr_info("init()\n");
+
+ err = snd_avirt_audiopath_register(&dummyap_module, &coreinfo);
+ if ((err < 0) || (!coreinfo)) {
+ pr_err("%s: coreinfo is NULL!\n", __func__);
+ return err;
+ }
+
+ return err;
+}
+
+static void __exit dummy_exit(void)
+{
+ pr_info("exit()\n");
+
+ snd_avirt_audiopath_deregister(&dummyap_module);
+}
+
+module_init(dummy_init);
+module_exit(dummy_exit);
diff --git a/loopback/Kconfig b/loopback/Kconfig
new file mode 100644
index 0000000..6293c5c
--- /dev/null
+++ b/loopback/Kconfig
@@ -0,0 +1,12 @@
+#
+# AVIRT Loopback Audio Path
+#
+
+config AVIRT_LOOPBACKAP
+ tristate "LoopbackAP"
+ select SND_PCM
+ ---help---
+ Say Y here if you want to add loopback audio path.
+
+ To compile this driver as a module, choose M here: the
+ module will be called avirt_loopbackap.
diff --git a/loopback/Makefile b/loopback/Makefile
new file mode 100644
index 0000000..0546168
--- /dev/null
+++ b/loopback/Makefile
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: GPL-2.0
+obj-$(CONFIG_AVIRT_AP_LOOPBACK) += snd-avirt-ap-loopback.o
+
+$(info $(src))
+snd-avirt-ap-loopback-objs := loopback.o
+ccflags-y += -Idrivers/staging/
+ccflags-y += -I$(src)/../
diff --git a/loopback/loopback.c b/loopback/loopback.c
new file mode 100644
index 0000000..b4a82e5
--- /dev/null
+++ b/loopback/loopback.c
@@ -0,0 +1,1111 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Loopback Audio Path for AVIRT
+ *
+ * Original code:
+ * Copyright (c) by Jaroslav Kysela <perex@perex.cz>
+ *
+ * More accurate positioning and full-duplex support:
+ * Copyright (c) Ahmet Ä°nan <ainan at mathematik.uni-freiburg.de>
+ *
+ * Major (almost complete) rewrite:
+ * Copyright (c) by Takashi Iwai <tiwai@suse.de>
+ *
+ * A next major update in 2010 (separate timers for playback and capture):
+ * Copyright (c) Jaroslav Kysela <perex@perex.cz>
+ *
+ * Adapt to use AVIRT, looping is now conducted on the same PCM device
+ * Copyright (c) 2010-2018 Fiberdyne Systems Pty Ltd
+ *
+ * loopback.c - Loopback Audio Path driver implementation for AVIRT
+ */
+
+#include <linux/init.h>
+#include <linux/jiffies.h>
+#include <linux/slab.h>
+#include <linux/time.h>
+#include <linux/wait.h>
+#include <linux/module.h>
+#include <linux/platform_device.h>
+#include <sound/control.h>
+#include <sound/pcm.h>
+#include <sound/pcm_params.h>
+#include <sound/info.h>
+#include <sound/initval.h>
+#include <sound/avirt.h>
+
+MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
+MODULE_DESCRIPTION("Loopback Audio Path for AVIRT");
+MODULE_LICENSE("GPL");
+
+#define AP_UID "ap_loopback"
+
+#define AP_INFOK(fmt, args...) DINFO(AP_UID, fmt, ##args)
+#define AP_PRINTK(fmt, args...) DDEBUG(AP_UID, fmt, ##args)
+#define AP_ERRORK(fmt, args...) DERROR(AP_UID, fmt, ##args)
+
+#define NO_PITCH 100000
+
+static struct snd_avirt_coreinfo *coreinfo;
+static struct loopback *loopback;
+
+struct loopback_pcm;
+
+struct loopback_cable {
+ spinlock_t lock;
+ struct loopback_pcm *streams[2];
+ struct snd_pcm_hardware hw;
+ /* flags */
+ unsigned int valid;
+ unsigned int running;
+ unsigned int pause;
+};
+
+struct loopback_setup {
+ unsigned int notify : 1;
+ unsigned int rate_shift;
+ unsigned int format;
+ unsigned int rate;
+ unsigned int channels;
+ struct snd_ctl_elem_id active_id;
+ struct snd_ctl_elem_id format_id;
+ struct snd_ctl_elem_id rate_id;
+ struct snd_ctl_elem_id channels_id;
+};
+
+struct loopback {
+ struct snd_card *card;
+ struct mutex cable_lock;
+ struct loopback_cable *cables[MAX_STREAMS];
+ struct snd_pcm *pcm[MAX_STREAMS];
+ struct loopback_setup setup[MAX_STREAMS];
+};
+
+struct loopback_pcm {
+ struct loopback *loopback;
+ struct snd_pcm_substream *substream;
+ struct loopback_cable *cable;
+ unsigned int pcm_buffer_size;
+ unsigned int buf_pos; /* position in buffer */
+ unsigned int silent_size;
+ /* PCM parameters */
+ unsigned int pcm_period_size;
+ unsigned int pcm_bps; /* bytes per second */
+ unsigned int pcm_salign; /* bytes per sample * channels */
+ unsigned int pcm_rate_shift; /* rate shift value */
+ /* flags */
+ unsigned int period_update_pending : 1;
+ /* timer stuff */
+ unsigned int irq_pos; /* fractional IRQ position */
+ unsigned int period_size_frac;
+ unsigned int last_drift;
+ unsigned long last_jiffies;
+ struct timer_list timer;
+};
+
+static inline unsigned int byte_pos(struct loopback_pcm *dpcm, unsigned int x)
+{
+ if (dpcm->pcm_rate_shift == NO_PITCH) {
+ x /= HZ;
+ } else {
+ x = div_u64(NO_PITCH * (unsigned long long)x,
+ HZ * (unsigned long long)dpcm->pcm_rate_shift);
+ }
+ return x - (x % dpcm->pcm_salign);
+}
+
+static inline unsigned int frac_pos(struct loopback_pcm *dpcm, unsigned int x)
+{
+ if (dpcm->pcm_rate_shift == NO_PITCH) { /* no pitch */
+ return x * HZ;
+ } else {
+ x = div_u64(dpcm->pcm_rate_shift * (unsigned long long)x * HZ,
+ NO_PITCH);
+ }
+ return x;
+}
+
+static inline struct loopback_setup *get_setup(struct loopback_pcm *dpcm)
+{
+ return &dpcm->loopback->setup[dpcm->substream->pcm->device];
+}
+
+static inline unsigned int get_notify(struct loopback_pcm *dpcm)
+{
+ return get_setup(dpcm)->notify;
+}
+
+static inline unsigned int get_rate_shift(struct loopback_pcm *dpcm)
+{
+ return get_setup(dpcm)->rate_shift;
+}
+
+/* call in cable->lock */
+static void loopback_timer_start(struct loopback_pcm *dpcm)
+{
+ unsigned long tick;
+ unsigned int rate_shift = get_rate_shift(dpcm);
+
+ if (rate_shift != dpcm->pcm_rate_shift) {
+ dpcm->pcm_rate_shift = rate_shift;
+ dpcm->period_size_frac = frac_pos(dpcm, dpcm->pcm_period_size);
+ }
+ if (dpcm->period_size_frac <= dpcm->irq_pos) {
+ dpcm->irq_pos %= dpcm->period_size_frac;
+ dpcm->period_update_pending = 1;
+ }
+ tick = dpcm->period_size_frac - dpcm->irq_pos;
+ tick = (tick + dpcm->pcm_bps - 1) / dpcm->pcm_bps;
+ mod_timer(&dpcm->timer, jiffies + tick);
+}
+
+/* call in cable->lock */
+static inline void loopback_timer_stop(struct loopback_pcm *dpcm)
+{
+ del_timer(&dpcm->timer);
+ dpcm->timer.expires = 0;
+}
+
+static inline void loopback_timer_stop_sync(struct loopback_pcm *dpcm)
+{
+ del_timer_sync(&dpcm->timer);
+}
+
+#define CABLE_VALID_PLAYBACK (1 << SNDRV_PCM_STREAM_PLAYBACK)
+#define CABLE_VALID_CAPTURE (1 << SNDRV_PCM_STREAM_CAPTURE)
+#define CABLE_VALID_BOTH (CABLE_VALID_PLAYBACK | CABLE_VALID_CAPTURE)
+
+static int loopback_check_format(struct loopback_cable *cable, int stream)
+{
+ struct snd_pcm_runtime *runtime, *cruntime;
+ struct loopback_setup *setup;
+ struct snd_card *card;
+ int check;
+
+ if (cable->valid != CABLE_VALID_BOTH) {
+ if (stream == SNDRV_PCM_STREAM_PLAYBACK)
+ goto __notify;
+ return 0;
+ }
+ runtime = cable->streams[SNDRV_PCM_STREAM_PLAYBACK]->substream->runtime;
+ cruntime = cable->streams[SNDRV_PCM_STREAM_CAPTURE]->substream->runtime;
+ check = runtime->format != cruntime->format ||
+ runtime->rate != cruntime->rate ||
+ runtime->channels != cruntime->channels;
+ if (!check)
+ return 0;
+ if (stream == SNDRV_PCM_STREAM_CAPTURE) {
+ return -EIO;
+ } else {
+ snd_pcm_stop(
+ cable->streams[SNDRV_PCM_STREAM_CAPTURE]->substream,
+ SNDRV_PCM_STATE_DRAINING);
+ __notify:
+ runtime = cable->streams[SNDRV_PCM_STREAM_PLAYBACK]
+ ->substream->runtime;
+ setup = get_setup(cable->streams[SNDRV_PCM_STREAM_PLAYBACK]);
+ card = cable->streams[SNDRV_PCM_STREAM_PLAYBACK]->loopback->card;
+ if (setup->format != runtime->format) {
+ snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
+ &setup->format_id);
+ setup->format = runtime->format;
+ }
+ if (setup->rate != runtime->rate) {
+ snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
+ &setup->rate_id);
+ setup->rate = runtime->rate;
+ }
+ if (setup->channels != runtime->channels) {
+ snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
+ &setup->channels_id);
+ setup->channels = runtime->channels;
+ }
+ }
+ return 0;
+}
+
+static void loopback_active_notify(struct loopback_pcm *dpcm)
+{
+ snd_ctl_notify(dpcm->loopback->card, SNDRV_CTL_EVENT_MASK_VALUE,
+ &get_setup(dpcm)->active_id);
+}
+
+static int loopback_trigger(struct snd_pcm_substream *substream, int cmd)
+{
+ struct snd_pcm_runtime *runtime = substream->runtime;
+ struct loopback_pcm *dpcm = runtime->private_data;
+ struct loopback_cable *cable = dpcm->cable;
+ int err, stream = 1 << substream->stream;
+
+ AP_INFOK();
+
+ switch (cmd) {
+ case SNDRV_PCM_TRIGGER_START:
+ err = loopback_check_format(cable, substream->stream);
+ if (err < 0)
+ return err;
+ dpcm->last_jiffies = jiffies;
+ dpcm->pcm_rate_shift = 0;
+ dpcm->last_drift = 0;
+ spin_lock(&cable->lock);
+ cable->running |= stream;
+ cable->pause &= ~stream;
+ loopback_timer_start(dpcm);
+ spin_unlock(&cable->lock);
+ if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
+ loopback_active_notify(dpcm);
+ break;
+ case SNDRV_PCM_TRIGGER_STOP:
+ spin_lock(&cable->lock);
+ cable->running &= ~stream;
+ cable->pause &= ~stream;
+ loopback_timer_stop(dpcm);
+ spin_unlock(&cable->lock);
+ if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
+ loopback_active_notify(dpcm);
+ break;
+ case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
+ case SNDRV_PCM_TRIGGER_SUSPEND:
+ spin_lock(&cable->lock);
+ cable->pause |= stream;
+ loopback_timer_stop(dpcm);
+ spin_unlock(&cable->lock);
+ if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
+ loopback_active_notify(dpcm);
+ break;
+ case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
+ case SNDRV_PCM_TRIGGER_RESUME:
+ spin_lock(&cable->lock);
+ dpcm->last_jiffies = jiffies;
+ cable->pause &= ~stream;
+ loopback_timer_start(dpcm);
+ spin_unlock(&cable->lock);
+ if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
+ loopback_active_notify(dpcm);
+ break;
+ default:
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static void params_change(struct snd_pcm_substream *substream)
+{
+ struct snd_pcm_runtime *runtime = substream->runtime;
+ struct loopback_pcm *dpcm = runtime->private_data;
+ struct loopback_cable *cable = dpcm->cable;
+
+ cable->hw.formats = pcm_format_to_bits(runtime->format);
+ cable->hw.rate_min = runtime->rate;
+ cable->hw.rate_max = runtime->rate;
+ cable->hw.channels_min = runtime->channels;
+ cable->hw.channels_max = runtime->channels;
+}
+
+static int loopback_prepare(struct snd_pcm_substream *substream)
+{
+ struct snd_pcm_runtime *runtime = substream->runtime;
+ struct loopback_pcm *dpcm = runtime->private_data;
+ struct loopback_cable *cable = dpcm->cable;
+ int bps, salign;
+
+ loopback_timer_stop_sync(dpcm);
+
+ salign =
+ (snd_pcm_format_width(runtime->format) * runtime->channels) / 8;
+ bps = salign * runtime->rate;
+ if (bps <= 0 || salign <= 0)
+ return -EINVAL;
+
+ dpcm->buf_pos = 0;
+ dpcm->pcm_buffer_size = frames_to_bytes(runtime, runtime->buffer_size);
+ if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) {
+ /* clear capture buffer */
+ dpcm->silent_size = dpcm->pcm_buffer_size;
+ snd_pcm_format_set_silence(runtime->format, runtime->dma_area,
+ runtime->buffer_size *
+ runtime->channels);
+ }
+
+ dpcm->irq_pos = 0;
+ dpcm->period_update_pending = 0;
+ dpcm->pcm_bps = bps;
+ dpcm->pcm_salign = salign;
+ dpcm->pcm_period_size = frames_to_bytes(runtime, runtime->period_size);
+
+ mutex_lock(&dpcm->loopback->cable_lock);
+ if (!(cable->valid & ~(1 << substream->stream)) ||
+ (get_setup(dpcm)->notify &&
+ substream->stream == SNDRV_PCM_STREAM_PLAYBACK))
+ params_change(substream);
+ cable->valid |= 1 << substream->stream;
+ mutex_unlock(&dpcm->loopback->cable_lock);
+
+ return 0;
+}
+
+static void clear_capture_buf(struct loopback_pcm *dpcm, unsigned int bytes)
+{
+ struct snd_pcm_runtime *runtime = dpcm->substream->runtime;
+ char *dst = runtime->dma_area;
+ unsigned int dst_off = dpcm->buf_pos;
+
+ if (dpcm->silent_size >= dpcm->pcm_buffer_size)
+ return;
+ if (dpcm->silent_size + bytes > dpcm->pcm_buffer_size)
+ bytes = dpcm->pcm_buffer_size - dpcm->silent_size;
+
+ for (;;) {
+ unsigned int size = bytes;
+ if (dst_off + size > dpcm->pcm_buffer_size)
+ size = dpcm->pcm_buffer_size - dst_off;
+ snd_pcm_format_set_silence(runtime->format, dst + dst_off,
+ bytes_to_frames(runtime, size) *
+ runtime->channels);
+ dpcm->silent_size += size;
+ bytes -= size;
+ if (!bytes)
+ break;
+ dst_off = 0;
+ }
+}
+
+static void copy_play_buf(struct loopback_pcm *play, struct loopback_pcm *capt,
+ unsigned int bytes)
+{
+ struct snd_pcm_runtime *runtime = play->substream->runtime;
+ char *src = runtime->dma_area;
+ char *dst = capt->substream->runtime->dma_area;
+ unsigned int src_off = play->buf_pos;
+ unsigned int dst_off = capt->buf_pos;
+ unsigned int clear_bytes = 0;
+
+ /* check if playback is draining, trim the capture copy size
+ * when our pointer is at the end of playback ring buffer */
+ if (runtime->status->state == SNDRV_PCM_STATE_DRAINING &&
+ snd_pcm_playback_hw_avail(runtime) < runtime->buffer_size) {
+ snd_pcm_uframes_t appl_ptr, appl_ptr1, diff;
+ appl_ptr = appl_ptr1 = runtime->control->appl_ptr;
+ appl_ptr1 -= appl_ptr1 % runtime->buffer_size;
+ appl_ptr1 += play->buf_pos / play->pcm_salign;
+ if (appl_ptr < appl_ptr1)
+ appl_ptr1 -= runtime->buffer_size;
+ diff = (appl_ptr - appl_ptr1) * play->pcm_salign;
+ if (diff < bytes) {
+ clear_bytes = bytes - diff;
+ bytes = diff;
+ }
+ }
+
+ for (;;) {
+ unsigned int size = bytes;
+ if (src_off + size > play->pcm_buffer_size)
+ size = play->pcm_buffer_size - src_off;
+ if (dst_off + size > capt->pcm_buffer_size)
+ size = capt->pcm_buffer_size - dst_off;
+ memcpy(dst + dst_off, src + src_off, size);
+ capt->silent_size = 0;
+ bytes -= size;
+ if (!bytes)
+ break;
+ src_off = (src_off + size) % play->pcm_buffer_size;
+ dst_off = (dst_off + size) % capt->pcm_buffer_size;
+ }
+
+ if (clear_bytes > 0) {
+ clear_capture_buf(capt, clear_bytes);
+ capt->silent_size = 0;
+ }
+}
+
+static inline unsigned int bytepos_delta(struct loopback_pcm *dpcm,
+ unsigned int jiffies_delta)
+{
+ unsigned long last_pos;
+ unsigned int delta;
+
+ last_pos = byte_pos(dpcm, dpcm->irq_pos);
+ dpcm->irq_pos += jiffies_delta * dpcm->pcm_bps;
+ delta = byte_pos(dpcm, dpcm->irq_pos) - last_pos;
+ if (delta >= dpcm->last_drift)
+ delta -= dpcm->last_drift;
+ dpcm->last_drift = 0;
+ if (dpcm->irq_pos >= dpcm->period_size_frac) {
+ dpcm->irq_pos %= dpcm->period_size_frac;
+ dpcm->period_update_pending = 1;
+ }
+ return delta;
+}
+
+static inline void bytepos_finish(struct loopback_pcm *dpcm, unsigned int delta)
+{
+ dpcm->buf_pos += delta;
+ dpcm->buf_pos %= dpcm->pcm_buffer_size;
+}
+
+/* call in cable->lock */
+static unsigned int loopback_pos_update(struct loopback_cable *cable)
+{
+ struct loopback_pcm *dpcm_play =
+ cable->streams[SNDRV_PCM_STREAM_PLAYBACK];
+ struct loopback_pcm *dpcm_capt =
+ cable->streams[SNDRV_PCM_STREAM_CAPTURE];
+ unsigned long delta_play = 0, delta_capt = 0;
+ unsigned int running, count1, count2;
+
+ running = cable->running ^ cable->pause;
+ if (running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) {
+ delta_play = jiffies - dpcm_play->last_jiffies;
+ dpcm_play->last_jiffies += delta_play;
+ }
+
+ if (running & (1 << SNDRV_PCM_STREAM_CAPTURE)) {
+ delta_capt = jiffies - dpcm_capt->last_jiffies;
+ dpcm_capt->last_jiffies += delta_capt;
+ }
+
+ if (delta_play == 0 && delta_capt == 0)
+ goto unlock;
+
+ if (delta_play > delta_capt) {
+ count1 = bytepos_delta(dpcm_play, delta_play - delta_capt);
+ bytepos_finish(dpcm_play, count1);
+ delta_play = delta_capt;
+ } else if (delta_play < delta_capt) {
+ count1 = bytepos_delta(dpcm_capt, delta_capt - delta_play);
+ clear_capture_buf(dpcm_capt, count1);
+ bytepos_finish(dpcm_capt, count1);
+ delta_capt = delta_play;
+ }
+
+ if (delta_play == 0 && delta_capt == 0)
+ goto unlock;
+
+ /* note delta_capt == delta_play at this moment */
+ count1 = bytepos_delta(dpcm_play, delta_play);
+ count2 = bytepos_delta(dpcm_capt, delta_capt);
+ if (count1 < count2) {
+ dpcm_capt->last_drift = count2 - count1;
+ count1 = count2;
+ } else if (count1 > count2) {
+ dpcm_play->last_drift = count1 - count2;
+ }
+ copy_play_buf(dpcm_play, dpcm_capt, count1);
+ bytepos_finish(dpcm_play, count1);
+ bytepos_finish(dpcm_capt, count1);
+unlock:
+ return running;
+}
+
+static void loopback_timer_function(struct timer_list *t)
+{
+ struct loopback_pcm *dpcm = from_timer(dpcm, t, timer);
+ unsigned long flags;
+
+ spin_lock_irqsave(&dpcm->cable->lock, flags);
+ if (loopback_pos_update(dpcm->cable) & (1 << dpcm->substream->stream)) {
+ loopback_timer_start(dpcm);
+ if (dpcm->period_update_pending) {
+ dpcm->period_update_pending = 0;
+ spin_unlock_irqrestore(&dpcm->cable->lock, flags);
+ /* need to unlock before calling below */
+ snd_avirt_pcm_period_elapsed(dpcm->substream);
+ return;
+ }
+ }
+ spin_unlock_irqrestore(&dpcm->cable->lock, flags);
+}
+
+static snd_pcm_uframes_t loopback_pointer(struct snd_pcm_substream *substream)
+{
+ struct snd_pcm_runtime *runtime = substream->runtime;
+ struct loopback_pcm *dpcm = runtime->private_data;
+ snd_pcm_uframes_t pos;
+
+ spin_lock(&dpcm->cable->lock);
+ loopback_pos_update(dpcm->cable);
+ pos = dpcm->buf_pos;
+ spin_unlock(&dpcm->cable->lock);
+ return bytes_to_frames(runtime, pos);
+}
+
+static const struct snd_pcm_hardware loopbackap_pcm_hardware = {
+ .info = (SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_MMAP |
+ SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_PAUSE |
+ SNDRV_PCM_INFO_RESUME),
+ .formats = (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE |
+ SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_S32_BE |
+ SNDRV_PCM_FMTBIT_FLOAT_LE | SNDRV_PCM_FMTBIT_FLOAT_BE),
+ .rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_192000,
+ .rate_min = 8000,
+ .rate_max = 192000,
+ .channels_min = 1,
+ .channels_max = 32,
+ .buffer_bytes_max = 2 * 1024 * 1024,
+ .period_bytes_min = 64,
+ /* note check overflow in frac_pos() using pcm_rate_shift before
+ changing period_bytes_max value */
+ .period_bytes_max = 1024 * 1024,
+ .periods_min = 1,
+ .periods_max = 1024,
+ .fifo_size = 0,
+};
+
+static void loopback_runtime_free(struct snd_pcm_runtime *runtime)
+{
+ struct loopback_pcm *dpcm = runtime->private_data;
+ kfree(dpcm);
+}
+
+static int loopback_hw_free(struct snd_pcm_substream *substream)
+{
+ struct snd_pcm_runtime *runtime = substream->runtime;
+ struct loopback_pcm *dpcm = runtime->private_data;
+ struct loopback_cable *cable = dpcm->cable;
+
+ mutex_lock(&dpcm->loopback->cable_lock);
+ cable->valid &= ~(1 << substream->stream);
+ mutex_unlock(&dpcm->loopback->cable_lock);
+
+ return 0;
+}
+
+static int rule_format(struct snd_pcm_hw_params *params,
+ struct snd_pcm_hw_rule *rule)
+{
+ struct loopback_pcm *dpcm = rule->private;
+ struct loopback_cable *cable = dpcm->cable;
+ struct snd_mask m;
+
+ snd_mask_none(&m);
+ mutex_lock(&dpcm->loopback->cable_lock);
+ m.bits[0] = (u_int32_t)cable->hw.formats;
+ m.bits[1] = (u_int32_t)(cable->hw.formats >> 32);
+ mutex_unlock(&dpcm->loopback->cable_lock);
+ return snd_mask_refine(hw_param_mask(params, rule->var), &m);
+}
+
+static int rule_rate(struct snd_pcm_hw_params *params,
+ struct snd_pcm_hw_rule *rule)
+{
+ struct loopback_pcm *dpcm = rule->private;
+ struct loopback_cable *cable = dpcm->cable;
+ struct snd_interval t;
+
+ mutex_lock(&dpcm->loopback->cable_lock);
+ t.min = cable->hw.rate_min;
+ t.max = cable->hw.rate_max;
+ mutex_unlock(&dpcm->loopback->cable_lock);
+ t.openmin = t.openmax = 0;
+ t.integer = 0;
+ return snd_interval_refine(hw_param_interval(params, rule->var), &t);
+}
+
+static int rule_channels(struct snd_pcm_hw_params *params,
+ struct snd_pcm_hw_rule *rule)
+{
+ struct loopback_pcm *dpcm = rule->private;
+ struct loopback_cable *cable = dpcm->cable;
+ struct snd_interval t;
+
+ mutex_lock(&dpcm->loopback->cable_lock);
+ t.min = cable->hw.channels_min;
+ t.max = cable->hw.channels_max;
+ mutex_unlock(&dpcm->loopback->cable_lock);
+ t.openmin = t.openmax = 0;
+ t.integer = 0;
+ return snd_interval_refine(hw_param_interval(params, rule->var), &t);
+}
+
+static void free_cable(struct snd_pcm_substream *substream)
+{
+ struct loopback_cable *cable;
+
+ cable = loopback->cables[substream->pcm->device];
+ if (!cable)
+ return;
+ if (cable->streams[!substream->stream]) {
+ /* other stream is still alive */
+ spin_lock_irq(&cable->lock);
+ cable->streams[substream->stream] = NULL;
+ spin_unlock_irq(&cable->lock);
+ } else {
+ /* free the cable */
+ loopback->cables[substream->pcm->device] = NULL;
+ kfree(cable);
+ }
+}
+
+static int loopback_open(struct snd_pcm_substream *substream)
+{
+ struct snd_pcm_runtime *runtime = substream->runtime;
+ struct loopback_pcm *dpcm;
+ struct loopback_cable *cable = NULL;
+ int err = 0;
+
+ mutex_lock(&loopback->cable_lock);
+ dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
+ if (!dpcm) {
+ err = -ENOMEM;
+ goto unlock;
+ }
+ dpcm->loopback = loopback;
+ dpcm->substream = substream;
+ timer_setup(&dpcm->timer, loopback_timer_function, 0);
+
+ cable = loopback->cables[substream->pcm->device];
+ if (!cable) {
+ cable = kzalloc(sizeof(*cable), GFP_KERNEL);
+ if (!cable) {
+ err = -ENOMEM;
+ goto unlock;
+ }
+ spin_lock_init(&cable->lock);
+ cable->hw = loopbackap_pcm_hardware;
+ loopback->cables[substream->pcm->device] = cable;
+ }
+ dpcm->cable = cable;
+
+ snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
+
+ /* use dynamic rules based on actual runtime->hw values */
+ /* note that the default rules created in the PCM midlevel code */
+ /* are cached -> they do not reflect the actual state */
+ err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
+ rule_format, dpcm, SNDRV_PCM_HW_PARAM_FORMAT,
+ -1);
+ if (err < 0)
+ goto unlock;
+ err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
+ rule_rate, dpcm, SNDRV_PCM_HW_PARAM_RATE, -1);
+ if (err < 0)
+ goto unlock;
+ err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
+ rule_channels, dpcm,
+ SNDRV_PCM_HW_PARAM_CHANNELS, -1);
+ if (err < 0)
+ goto unlock;
+
+ runtime->private_data = dpcm;
+ runtime->private_free = loopback_runtime_free;
+ if (get_notify(dpcm))
+ runtime->hw = loopbackap_pcm_hardware;
+ else
+ runtime->hw = cable->hw;
+
+ spin_lock_irq(&cable->lock);
+ cable->streams[substream->stream] = dpcm;
+ spin_unlock_irq(&cable->lock);
+
+unlock:
+ if (err < 0) {
+ free_cable(substream);
+ kfree(dpcm);
+ }
+ mutex_unlock(&loopback->cable_lock);
+ return err;
+}
+
+static int loopback_close(struct snd_pcm_substream *substream)
+{
+ struct loopback_pcm *dpcm = substream->runtime->private_data;
+
+ loopback_timer_stop_sync(dpcm);
+ mutex_lock(&loopback->cable_lock);
+ free_cable(substream);
+ mutex_unlock(&loopback->cable_lock);
+ return 0;
+}
+
+static const struct snd_pcm_ops loopbackap_pcm_ops = {
+ .open = loopback_open,
+ .close = loopback_close,
+ .hw_free = loopback_hw_free,
+ .prepare = loopback_prepare,
+ .trigger = loopback_trigger,
+ .pointer = loopback_pointer,
+};
+
+static int loopback_rate_shift_info(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_info *uinfo)
+{
+ uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
+ uinfo->count = 1;
+ uinfo->value.integer.min = 80000;
+ uinfo->value.integer.max = 120000;
+ uinfo->value.integer.step = 1;
+ return 0;
+}
+
+static int loopback_rate_shift_get(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_value *ucontrol)
+{
+ struct loopback *loopback = snd_kcontrol_chip(kcontrol);
+
+ mutex_lock(&loopback->cable_lock);
+ ucontrol->value.integer.value[0] =
+ loopback->setup[kcontrol->id.device].rate_shift;
+ mutex_unlock(&loopback->cable_lock);
+ return 0;
+}
+
+static int loopback_rate_shift_put(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_value *ucontrol)
+{
+ struct loopback *loopback = snd_kcontrol_chip(kcontrol);
+ unsigned int val;
+ int change = 0;
+
+ val = ucontrol->value.integer.value[0];
+ if (val < 80000)
+ val = 80000;
+ if (val > 120000)
+ val = 120000;
+ mutex_lock(&loopback->cable_lock);
+ if (val != loopback->setup[kcontrol->id.device].rate_shift) {
+ loopback->setup[kcontrol->id.device].rate_shift = val;
+ change = 1;
+ }
+ mutex_unlock(&loopback->cable_lock);
+ return change;
+}
+
+static int loopback_notify_get(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_value *ucontrol)
+{
+ struct loopback *loopback = snd_kcontrol_chip(kcontrol);
+
+ mutex_lock(&loopback->cable_lock);
+ ucontrol->value.integer.value[0] =
+ loopback->setup[kcontrol->id.device].notify;
+ mutex_unlock(&loopback->cable_lock);
+ return 0;
+}
+
+static int loopback_notify_put(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_value *ucontrol)
+{
+ struct loopback *loopback = snd_kcontrol_chip(kcontrol);
+ unsigned int val;
+ int change = 0;
+ val = ucontrol->value.integer.value[0] ? 1 : 0;
+ mutex_lock(&loopback->cable_lock);
+ if (val != loopback->setup[kcontrol->id.device].notify) {
+ loopback->setup[kcontrol->id.device].notify = val;
+ change = 1;
+ }
+ mutex_unlock(&loopback->cable_lock);
+ return change;
+}
+
+static int loopback_active_get(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_value *ucontrol)
+{
+ struct loopback *loopback = snd_kcontrol_chip(kcontrol);
+ struct loopback_cable *cable;
+
+ unsigned int val = 0;
+
+ mutex_lock(&loopback->cable_lock);
+ cable = loopback->cables[kcontrol->id.device];
+ if (cable != NULL) {
+ unsigned int running = cable->running ^ cable->pause;
+
+ val = (running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) ? 1 : 0;
+ }
+ mutex_unlock(&loopback->cable_lock);
+ ucontrol->value.integer.value[0] = val;
+ return 0;
+}
+
+static int loopback_format_info(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_info *uinfo)
+{
+ uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
+ uinfo->count = 1;
+ uinfo->value.integer.min = 0;
+ uinfo->value.integer.max = SNDRV_PCM_FORMAT_LAST;
+ uinfo->value.integer.step = 1;
+ return 0;
+}
+
+static int loopback_format_get(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_value *ucontrol)
+{
+ struct loopback *loopback = snd_kcontrol_chip(kcontrol);
+
+ ucontrol->value.integer.value[0] =
+ loopback->setup[kcontrol->id.device].format;
+ return 0;
+}
+
+static int loopback_rate_info(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_info *uinfo)
+{
+ uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
+ uinfo->count = 1;
+ uinfo->value.integer.min = 0;
+ uinfo->value.integer.max = 192000;
+ uinfo->value.integer.step = 1;
+ return 0;
+}
+
+static int loopback_rate_get(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_value *ucontrol)
+{
+ struct loopback *loopback = snd_kcontrol_chip(kcontrol);
+ mutex_lock(&loopback->cable_lock);
+ ucontrol->value.integer.value[0] =
+ loopback->setup[kcontrol->id.device].rate;
+ mutex_unlock(&loopback->cable_lock);
+ return 0;
+}
+
+static int loopback_channels_info(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_info *uinfo)
+{
+ uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
+ uinfo->count = 1;
+ uinfo->value.integer.min = 1;
+ uinfo->value.integer.max = 1024;
+ uinfo->value.integer.step = 1;
+ return 0;
+}
+
+static int loopback_channels_get(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_value *ucontrol)
+{
+ struct loopback *loopback = snd_kcontrol_chip(kcontrol);
+
+ mutex_lock(&loopback->cable_lock);
+ ucontrol->value.integer.value[0] =
+ loopback->setup[kcontrol->id.device].channels;
+ mutex_unlock(&loopback->cable_lock);
+ return 0;
+}
+
+static struct snd_kcontrol_new loopback_controls[] = {
+ {
+ .iface = SNDRV_CTL_ELEM_IFACE_PCM,
+ .name = "PCM Rate Shift 100000",
+ .info = loopback_rate_shift_info,
+ .get = loopback_rate_shift_get,
+ .put = loopback_rate_shift_put,
+ },
+ {
+ .iface = SNDRV_CTL_ELEM_IFACE_PCM,
+ .name = "PCM Notify",
+ .info = snd_ctl_boolean_mono_info,
+ .get = loopback_notify_get,
+ .put = loopback_notify_put,
+ },
+#define ACTIVE_IDX 2
+ {
+ .access = SNDRV_CTL_ELEM_ACCESS_READ,
+ .iface = SNDRV_CTL_ELEM_IFACE_PCM,
+ .name = "PCM Slave Active",
+ .info = snd_ctl_boolean_mono_info,
+ .get = loopback_active_get,
+ },
+#define FORMAT_IDX 3
+ { .access = SNDRV_CTL_ELEM_ACCESS_READ,
+ .iface = SNDRV_CTL_ELEM_IFACE_PCM,
+ .name = "PCM Slave Format",
+ .info = loopback_format_info,
+ .get = loopback_format_get },
+#define RATE_IDX 4
+ { .access = SNDRV_CTL_ELEM_ACCESS_READ,
+ .iface = SNDRV_CTL_ELEM_IFACE_PCM,
+ .name = "PCM Slave Rate",
+ .info = loopback_rate_info,
+ .get = loopback_rate_get },
+#define CHANNELS_IDX 5
+ { .access = SNDRV_CTL_ELEM_ACCESS_READ,
+ .iface = SNDRV_CTL_ELEM_IFACE_PCM,
+ .name = "PCM Slave Channels",
+ .info = loopback_channels_info,
+ .get = loopback_channels_get }
+};
+
+static int loopback_mixer_new(struct loopback *loopback, int notify)
+{
+ struct snd_card *card = loopback->card;
+ struct snd_pcm *pcm;
+ struct snd_kcontrol *kctl;
+ struct loopback_setup *setup;
+ int dev, dev_count, idx, err;
+
+ strcpy(card->mixername, "Loopback Mixer");
+ dev_count = snd_avirt_stream_count(SNDRV_PCM_STREAM_PLAYBACK);
+ for (dev = 0; dev < dev_count; dev++) {
+ pcm = loopback->pcm[dev];
+ setup = &loopback->setup[dev];
+ setup->notify = notify;
+ setup->rate_shift = NO_PITCH;
+ setup->format = SNDRV_PCM_FORMAT_S16_LE;
+ setup->rate = 48000;
+ setup->channels = 2;
+ for (idx = 0; idx < ARRAY_SIZE(loopback_controls); idx++) {
+ kctl = snd_ctl_new1(&loopback_controls[idx], loopback);
+ if (!kctl)
+ return -ENOMEM;
+ kctl->id.device = dev;
+ kctl->id.subdevice = 0;
+ switch (idx) {
+ case ACTIVE_IDX:
+ setup->active_id = kctl->id;
+ break;
+ case FORMAT_IDX:
+ setup->format_id = kctl->id;
+ break;
+ case RATE_IDX:
+ setup->rate_id = kctl->id;
+ break;
+ case CHANNELS_IDX:
+ setup->channels_id = kctl->id;
+ break;
+ default:
+ break;
+ }
+ err = snd_ctl_add(card, kctl);
+ if (err < 0)
+ return err;
+ }
+ }
+ return 0;
+}
+
+static void print_dpcm_info(struct snd_info_buffer *buffer,
+ struct loopback_pcm *dpcm, const char *id)
+{
+ snd_iprintf(buffer, " %s\n", id);
+ if (dpcm == NULL) {
+ snd_iprintf(buffer, " inactive\n");
+ return;
+ }
+ snd_iprintf(buffer, " buffer_size:\t%u\n", dpcm->pcm_buffer_size);
+ snd_iprintf(buffer, " buffer_pos:\t\t%u\n", dpcm->buf_pos);
+ snd_iprintf(buffer, " silent_size:\t%u\n", dpcm->silent_size);
+ snd_iprintf(buffer, " period_size:\t%u\n", dpcm->pcm_period_size);
+ snd_iprintf(buffer, " bytes_per_sec:\t%u\n", dpcm->pcm_bps);
+ snd_iprintf(buffer, " sample_align:\t%u\n", dpcm->pcm_salign);
+ snd_iprintf(buffer, " rate_shift:\t\t%u\n", dpcm->pcm_rate_shift);
+ snd_iprintf(buffer, " update_pending:\t%u\n",
+ dpcm->period_update_pending);
+ snd_iprintf(buffer, " irq_pos:\t\t%u\n", dpcm->irq_pos);
+ snd_iprintf(buffer, " period_frac:\t%u\n", dpcm->period_size_frac);
+ snd_iprintf(buffer, " last_jiffies:\t%lu (%lu)\n",
+ dpcm->last_jiffies, jiffies);
+ snd_iprintf(buffer, " timer_expires:\t%lu\n", dpcm->timer.expires);
+}
+
+static void print_substream_info(struct snd_info_buffer *buffer,
+ struct loopback *loopback, int device)
+{
+ struct loopback_cable *cable = loopback->cables[device];
+
+ snd_iprintf(buffer, "Cable device %i:\n", device);
+ if (cable == NULL) {
+ snd_iprintf(buffer, " inactive\n");
+ return;
+ }
+ snd_iprintf(buffer, " valid: %u\n", cable->valid);
+ snd_iprintf(buffer, " running: %u\n", cable->running);
+ snd_iprintf(buffer, " pause: %u\n", cable->pause);
+ print_dpcm_info(buffer, cable->streams[0], "Playback");
+ print_dpcm_info(buffer, cable->streams[1], "Capture");
+}
+
+static void print_cable_info(struct snd_info_entry *entry,
+ struct snd_info_buffer *buffer)
+{
+ struct loopback *loopback = entry->private_data;
+ int device;
+
+ mutex_lock(&loopback->cable_lock);
+ for (device = 0; device < MAX_STREAMS; device++)
+ print_substream_info(buffer, loopback, device);
+ mutex_unlock(&loopback->cable_lock);
+}
+
+static int loopback_proc_new(struct loopback *loopback, int cidx)
+{
+ char name[32];
+ struct snd_info_entry *entry;
+ int err;
+
+ snprintf(name, sizeof(name), "cable#%d", cidx);
+ err = snd_card_proc_new(loopback->card, name, &entry);
+ if (err < 0)
+ return err;
+
+ snd_info_set_text_ops(entry, loopback, print_cable_info);
+ return 0;
+}
+
+static int loopbackap_configure(struct snd_card *card,
+ struct config_group *snd_avirt_stream_group,
+ unsigned int stream_count)
+{
+ int err;
+ struct list_head *entry;
+
+ loopback = kzalloc(sizeof(struct loopback), GFP_KERNEL);
+ if (!loopback)
+ return -ENOMEM;
+ loopback->card = card;
+ mutex_init(&loopback->cable_lock);
+
+ list_for_each (entry, &snd_avirt_stream_group->cg_children) {
+ struct config_item *item =
+ container_of(entry, struct config_item, ci_entry);
+ struct snd_avirt_stream *stream =
+ snd_avirt_stream_from_config_item(item);
+ loopback->pcm[stream->device] = stream->pcm;
+
+ AP_INFOK("stream name:%s device:%d channels:%d", stream->name,
+ stream->device, stream->channels);
+ }
+
+ err = loopback_mixer_new(loopback, 1);
+ if (err < 0)
+ return err;
+
+ loopback_proc_new(loopback, 0);
+ loopback_proc_new(loopback, 1);
+
+ return 0;
+}
+
+/*******************************************************************************
+ * Loopback Audio Path AVIRT registration
+ ******************************************************************************/
+static struct snd_avirt_audiopath loopbackap_module = {
+ .uid = AP_UID,
+ .name = "Loopback Audio Path",
+ .version = { 0, 0, 1 },
+ .hw = &loopbackap_pcm_hardware,
+ .pcm_ops = &loopbackap_pcm_ops,
+ .configure = loopbackap_configure,
+};
+
+static int __init alsa_card_loopback_init(void)
+{
+ int err = 0;
+
+ err = snd_avirt_audiopath_register(&loopbackap_module, &coreinfo);
+ if ((err < 0) || (!coreinfo)) {
+ AP_ERRORK("coreinfo is NULL!");
+ return err;
+ }
+
+ return 0;
+}
+
+static void __exit alsa_card_loopback_exit(void)
+{
+ snd_avirt_audiopath_deregister(&loopbackap_module);
+}
+
+module_init(alsa_card_loopback_init);
+module_exit(alsa_card_loopback_exit)
diff --git a/pcm.c b/pcm.c
new file mode 100644
index 0000000..babc8b6
--- /dev/null
+++ b/pcm.c
@@ -0,0 +1,332 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * AVIRT - ALSA Virtual Soundcard
+ *
+ * Copyright (c) 2010-2018 Fiberdyne Systems Pty Ltd
+ *
+ * pcm.c - AVIRT PCM interface
+ */
+
+#include "core.h"
+
+#define D_LOGNAME "pcm"
+
+#define D_INFOK(fmt, args...) DINFO(D_LOGNAME, fmt, ##args)
+#define D_PRINTK(fmt, args...) DDEBUG(D_LOGNAME, fmt, ##args)
+#define D_ERRORK(fmt, args...) DERROR(D_LOGNAME, fmt, ##args)
+
+#define DO_AUDIOPATH_CB(ap, callback, substream, ...) \
+ (((ap)->pcm_ops->callback) ? \
+ (ap)->pcm_ops->callback((substream), ##__VA_ARGS__) : \
+ 0)
+
+/**
+ * snd_avirt_pcm_period_elapsed - PCM buffer complete callback
+ * @substreamid: pointer to ALSA PCM substream
+ *
+ * This should be called from a child Audio Path once it has finished
+ * processing the pcm buffer
+ */
+void snd_avirt_pcm_period_elapsed(struct snd_pcm_substream *substream)
+{
+ // Notify ALSA middle layer of the elapsed period boundary
+ snd_pcm_period_elapsed(substream);
+}
+EXPORT_SYMBOL_GPL(snd_avirt_pcm_period_elapsed);
+
+/*******************************************************************************
+ * ALSA PCM Callbacks
+ ******************************************************************************/
+/**
+ * pcm_open - Implements 'open' callback for PCM middle layer
+ * @substream: pointer to ALSA PCM substream
+ *
+ * This is called when an ALSA PCM substream is opened. The substream device
+ * is configured here.
+ *
+ * Returns 0 on success or error code otherwise.
+ */
+static int pcm_open(struct snd_pcm_substream *substream)
+{
+ struct snd_avirt_audiopath *audiopath;
+ struct snd_avirt_stream *stream;
+ struct snd_pcm_hardware *hw;
+ unsigned int chans = 0;
+
+ stream = snd_avirt_stream_find_by_device(substream->pcm->device);
+ audiopath = snd_avirt_audiopath_get(stream->map);
+ CHK_NULL_V(audiopath, "Cannot find Audio Path uid: '%s'!", stream->map);
+ substream->private_data = audiopath;
+
+ // Copy the hw params from the audiopath to the pcm
+ hw = &substream->runtime->hw;
+ memcpy(hw, audiopath->hw, sizeof(struct snd_pcm_hardware));
+
+ stream = snd_avirt_stream_find_by_device(substream->pcm->device);
+ if (IS_ERR_VALUE(stream) || !stream)
+ return PTR_ERR(stream);
+
+ // Setup remaining hw properties
+ chans = stream->channels;
+ hw->channels_min = chans;
+ hw->channels_max = chans;
+
+ // Do additional Audio Path 'open' callback
+ return DO_AUDIOPATH_CB(audiopath, open, substream);
+}
+
+/**
+ * pcm_close - Implements 'close' callback for PCM middle layer
+ * @substream: pointer to ALSA PCM substream
+ *
+ * This is called when a PCM substream is closed.
+ *
+ * Returns 0 on success or error code otherwise.
+ */
+static int pcm_close(struct snd_pcm_substream *substream)
+{
+ // Do additional Audio Path 'close' callback
+ return DO_AUDIOPATH_CB(
+ ((struct snd_avirt_audiopath *)substream->private_data), close,
+ substream);
+}
+
+/**
+ * pcm_hw_params - Implements 'hw_params' callback for PCM middle layer
+ * @substream: pointer to ALSA PCM substream
+ * @hw_params: contains the hardware parameters for the PCM
+ *
+ * This is called when the hardware parameters are set, including buffer size,
+ * the period size, the format, etc. The buffer allocation should be done here.
+ *
+ * Returns 0 on success or error code otherwise.
+ */
+static int pcm_hw_params(struct snd_pcm_substream *substream,
+ struct snd_pcm_hw_params *hw_params)
+{
+ int retval;
+ size_t bufsz;
+ struct snd_avirt_audiopath *audiopath;
+ struct snd_avirt_stream *stream;
+
+ stream = snd_avirt_stream_find_by_device(substream->pcm->device);
+ if (IS_ERR_VALUE(stream) || !stream)
+ return PTR_ERR(stream);
+
+ if ((params_channels(hw_params) > stream->channels) ||
+ (params_channels(hw_params) < stream->channels)) {
+ D_ERRORK("Requested number of channels: %d not supported",
+ params_channels(hw_params));
+ return -EINVAL;
+ }
+
+ audiopath = ((struct snd_avirt_audiopath *)substream->private_data);
+ bufsz = params_buffer_bytes(hw_params) * audiopath->hw->periods_max;
+
+ retval = snd_pcm_lib_alloc_vmalloc_buffer(substream, bufsz);
+ if (retval < 0)
+ D_ERRORK("pcm: buffer allocation failed: %d", retval);
+
+ return retval;
+}
+
+/**
+ * pcm_hw_free - Implements 'hw_free' callback for PCM middle layer
+ * @substream: pointer to ALSA PCM substream
+ *
+ * Release the resources allocated via 'hw_params'.
+ * This function is always called before the 'close' callback .
+ *
+ * Returns 0 on success or error code otherwise.
+ */
+static int pcm_hw_free(struct snd_pcm_substream *substream)
+{
+ int err;
+
+ // Do additional Audio Path 'hw_free' callback
+ err = DO_AUDIOPATH_CB(
+ ((struct snd_avirt_audiopath *)substream->private_data),
+ hw_free, substream);
+
+ return snd_pcm_lib_free_vmalloc_buffer(substream);
+}
+
+/**
+ * pcm_prepare - Implements 'prepare' callback for PCM middle layer
+ * @substream: pointer to ALSA PCM substream
+ *
+ * The format rate, sample rate, etc., can be set here. This callback can be
+ * called many times at each setup. This function is also used to handle overrun
+ * and underrun conditions when we try and resync the DMA (if we're using DMA).
+ *
+ * Returns 0 on success or error code otherwise.
+ */
+static int pcm_prepare(struct snd_pcm_substream *substream)
+{
+ // Do additional Audio Path 'prepare' callback
+ return DO_AUDIOPATH_CB(
+ ((struct snd_avirt_audiopath *)substream->private_data),
+ prepare, substream);
+}
+
+/**
+ * pcm_trigger - Implements 'trigger' callback for PCM middle layer
+ * @substream: pointer to ALSA PCM substream
+ * @cmd: action to be performed (start or stop)
+ *
+ * This is called when the PCM is started, stopped or paused. The action
+ * indicated action is specified in the second argument, SNDRV_PCM_TRIGGER_XXX
+ *
+ * Returns 0 on success or error code otherwise.
+ */
+static int pcm_trigger(struct snd_pcm_substream *substream, int cmd)
+{
+ switch (cmd) {
+ case SNDRV_PCM_TRIGGER_START:
+ case SNDRV_PCM_TRIGGER_RESUME:
+ case SNDRV_PCM_TRIGGER_STOP:
+ case SNDRV_PCM_TRIGGER_SUSPEND:
+ break;
+ default:
+ D_ERRORK("Invalid trigger cmd: %d", cmd);
+ return -EINVAL;
+ }
+
+ // Do additional Audio Path 'trigger' callback
+ return DO_AUDIOPATH_CB(
+ ((struct snd_avirt_audiopath *)substream->private_data),
+ trigger, substream, cmd);
+}
+
+/**
+ * pcm_pointer - Implements 'pointer' callback for PCM middle layer
+ * @substream: pointer to ALSA PCM substream
+ *
+ * This gets called when the user space needs a DMA buffer index. IO errors will
+ * be generated if the index does not increment, or drives beyond the frame
+ * threshold of the buffer itself.
+ *
+ * Returns the current hardware buffer frame index.
+ */
+static snd_pcm_uframes_t pcm_pointer(struct snd_pcm_substream *substream)
+{
+ // Do additional Audio Path 'pointer' callback
+ return DO_AUDIOPATH_CB(
+ ((struct snd_avirt_audiopath *)substream->private_data),
+ pointer, substream);
+}
+
+/**
+ * pcm_pointer - Implements 'get_time_info' callback for PCM middle layer
+ * @substream: pointer to ALSA PCM substream
+ * @system_ts
+ * @audio_ts
+ * @audio_tstamp_config
+ * @audio_tstamp_report
+ *
+ * Generic way to get system timestamp and audio timestamp info
+ *
+ * Returns 0 on success or error code otherwise
+ */
+static int pcm_get_time_info(
+ struct snd_pcm_substream *substream, struct timespec *system_ts,
+ struct timespec *audio_ts,
+ struct snd_pcm_audio_tstamp_config *audio_tstamp_config,
+ struct snd_pcm_audio_tstamp_report *audio_tstamp_report)
+{
+ return DO_AUDIOPATH_CB(
+ ((struct snd_avirt_audiopath *)substream->private_data),
+ get_time_info, substream, system_ts, audio_ts,
+ audio_tstamp_config, audio_tstamp_report);
+}
+
+/**
+ * pcm_copy_user - Implements 'copy_user' callback for PCM middle layer
+ * @substream: pointer to ALSA PCM substream
+ * @channel:
+ * @pos: The offset in the DMA
+ * @src: Audio PCM data from the user space
+ * @count:
+ *
+ * This is where we need to copy user audio PCM data into the sound driver
+ *
+ * Returns 0 on success or error code otherwise.
+ *
+ */
+static int pcm_copy_user(struct snd_pcm_substream *substream, int channel,
+ snd_pcm_uframes_t pos, void __user *src,
+ snd_pcm_uframes_t count)
+{
+ // struct snd_pcm_runtime *runtime;
+ // int offset;
+
+ // runtime = substream->runtime;
+ // offset = frames_to_bytes(runtime, pos);
+
+ // Do additional Audio Path 'copy_user' callback
+ return DO_AUDIOPATH_CB(
+ ((struct snd_avirt_audiopath *)substream->private_data),
+ copy_user, substream, channel, pos, src, count);
+}
+
+/**
+ * pcm_copy_kernel - Implements 'copy_kernel' callback for PCM middle layer
+ * @substream: pointer to ALSA PCM substream
+ * @channel:
+ * @pos: The offset in the DMA
+ * @src: Audio PCM data from the user space
+ * @count:
+ *
+ * This is where we need to copy kernel audio PCM data into the sound driver
+ *
+ * Returns 0 on success or error code otherwise.
+ *
+ */
+static int pcm_copy_kernel(struct snd_pcm_substream *substream, int channel,
+ unsigned long pos, void *buf, unsigned long count)
+{
+ return DO_AUDIOPATH_CB(
+ ((struct snd_avirt_audiopath *)substream->private_data),
+ copy_kernel, substream, channel, pos, buf, count);
+}
+
+/**
+ * pcm_ack - Implements 'ack' callback for PCM middle layer
+ * @substream: pointer to ALSA PCM substream
+ *
+ * This is where we need to ack
+ *
+ * Returns 0 on success or error code otherwise.
+ *
+ */
+static int pcm_ack(struct snd_pcm_substream *substream)
+{
+ return DO_AUDIOPATH_CB(
+ ((struct snd_avirt_audiopath *)substream->private_data), ack,
+ substream);
+}
+
+static int pcm_silence(struct snd_pcm_substream *substream, int channel,
+ snd_pcm_uframes_t pos, snd_pcm_uframes_t count)
+{
+ return DO_AUDIOPATH_CB(
+ ((struct snd_avirt_audiopath *)substream->private_data),
+ fill_silence, substream, channel, pos, count);
+}
+
+struct snd_pcm_ops pcm_ops = {
+ .open = pcm_open,
+ .close = pcm_close,
+ .ioctl = snd_pcm_lib_ioctl,
+ .hw_params = pcm_hw_params,
+ .hw_free = pcm_hw_free,
+ .prepare = pcm_prepare,
+ .trigger = pcm_trigger,
+ .pointer = pcm_pointer,
+ .get_time_info = pcm_get_time_info,
+ .fill_silence = pcm_silence,
+ .copy_user = pcm_copy_user,
+ .copy_kernel = pcm_copy_kernel,
+ .page = snd_pcm_lib_get_vmalloc_page,
+ .ack = pcm_ack,
+};
diff --git a/scripts/load.sh b/scripts/load.sh
new file mode 100755
index 0000000..103a63b
--- /dev/null
+++ b/scripts/load.sh
@@ -0,0 +1,13 @@
+#!/bin/sh
+
+# Load the core
+insmod snd-avirt-core.ko
+
+# Load the additional Audio Paths
+insmod dummy/snd-avirt-ap-dummy.ko
+insmod loopback/snd-avirt-ap-loopback.ko
+
+# Run the test script
+./scripts/test_configfs.sh
+
+echo "Drivers Loaded!"
diff --git a/scripts/make-agl.sh b/scripts/make-agl.sh
new file mode 100755
index 0000000..6c94fbb
--- /dev/null
+++ b/scripts/make-agl.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+
+# Get SDK path
+sdk_id=$1 # first arg must be XDS_SDK_ID
+shift 1
+long_sdkpath=$(xds-cli sdks get $sdk_id | grep Path)
+sdkpath=${long_sdkpath:4}
+
+# Build
+/opt/AGL/bin/xds-cli exec --config xds-project.conf -- \
+ LDFLAGS= CONFIG_AVIRT=m CONFIG_AVIRT_BUILDLOCAL=y \
+ CONFIG_AVIRT_AP_DUMMY=m \
+ CONFIG_AVIRT_AP_LOOPBACK=m \
+ make -C $sdkpath/sysroots/aarch64-agl-linux/usr/src/kernel M=$(pwd) $@
diff --git a/scripts/test_configfs.sh b/scripts/test_configfs.sh
new file mode 100755
index 0000000..b6a56f6
--- /dev/null
+++ b/scripts/test_configfs.sh
@@ -0,0 +1,21 @@
+#!/bin/bash
+
+mkdir -p /config && mount -t configfs none /config
+
+mkdir /config/snd-avirt/streams/playback_media
+echo "2">/config/snd-avirt/streams/playback_media/channels
+echo "ap_loopback">/config/snd-avirt/streams/playback_media/map
+
+mkdir /config/snd-avirt/streams/playback_navigation
+echo "1">/config/snd-avirt/streams/playback_navigation/channels
+echo "ap_loopback">/config/snd-avirt/streams/playback_navigation/map
+
+mkdir /config/snd-avirt/streams/playback_emergency
+echo "1">/config/snd-avirt/streams/playback_emergency/channels
+echo "ap_loopback">/config/snd-avirt/streams/playback_emergency/map
+
+mkdir /config/snd-avirt/streams/capture_voice
+echo "1">/config/snd-avirt/streams/capture_voice/channels
+echo "ap_loopback">/config/snd-avirt/streams/capture_voice/map
+
+echo "1">/config/snd-avirt/streams/sealed
diff --git a/scripts/unload.sh b/scripts/unload.sh
new file mode 100755
index 0000000..a18e1f5
--- /dev/null
+++ b/scripts/unload.sh
@@ -0,0 +1,13 @@
+#!/bin/sh
+
+rmdir /config/snd-avirt/streams/playback_*
+rmdir /config/snd-avirt/streams/capture_*
+
+rm_module() {
+ lsmod |grep "^$1\>" && rmmod $1 || true
+}
+
+rm_module snd_avirt_ap_loopback
+rm_module snd_avirt_ap_dummy
+rm_module snd_avirt_core
+echo "Drivers Removed!"
diff --git a/sound/avirt.h b/sound/avirt.h
new file mode 100644
index 0000000..1a5c546
--- /dev/null
+++ b/sound/avirt.h
@@ -0,0 +1,122 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * AVIRT - ALSA Virtual Soundcard
+ *
+ * Copyright (c) 2010-2018 Fiberdyne Systems Pty Ltd
+ *
+ * avirt.h - AVIRT system-level header
+ */
+
+#ifndef __SOUND_AVIRT_H
+#define __SOUND_AVIRT_H
+
+#include <sound/core.h>
+#include <sound/pcm.h>
+#include <linux/configfs.h>
+
+#define MAX_STREAMS 16
+#define MAX_NAME_LEN 80
+
+#define DINFO(logname, fmt, args...) \
+ snd_printk(KERN_INFO "AVIRT: %s: " fmt "\n", logname, ##args)
+
+#define DERROR(logname, fmt, args...) \
+ snd_printk(KERN_ERR "AVIRT: %s: " fmt "\n", logname, ##args)
+
+#define DDEBUG(logname, fmt, args...) \
+ snd_printk(KERN_DEBUG "AVIRT: %s: " fmt "\n", logname, ##args)
+
+/**
+ * AVIRT Audio Path configure function type
+ * Each Audio Path registers this at snd_avirt_audiopath_register time.
+ * It is then called by the core once AVIRT has been configured
+ */
+typedef int (*snd_avirt_audiopath_configure)(struct snd_card *card,
+ struct config_group *stream_group,
+ unsigned int stream_count);
+
+/**
+ * AVIRT Audio Path info
+ */
+struct snd_avirt_audiopath {
+ const char *uid; /* Unique identifier */
+ const char *name; /* Pretty name */
+ unsigned int version[3]; /* Version - Major.Minor.Ext */
+ const struct snd_pcm_hardware *hw; /* ALSA PCM HW conf */
+ const struct snd_pcm_ops *pcm_ops; /* ALSA PCM op table */
+ snd_avirt_audiopath_configure configure; /* Config callback function */
+
+ void *context;
+};
+
+/*
+ * Audio stream configuration
+ */
+struct snd_avirt_stream {
+ char name[MAX_NAME_LEN]; /* Stream name */
+ char map[MAX_NAME_LEN]; /* Stream Audio Path mapping */
+ unsigned int channels; /* Stream channel count */
+ unsigned int device; /* Stream PCM device no. */
+ unsigned int direction; /* Stream direction */
+ struct snd_pcm *pcm; /* ALSA PCM */
+ struct config_item item; /* configfs item reference */
+};
+
+/**
+ * AVIRT core info
+ */
+struct snd_avirt_coreinfo {
+ unsigned int version[3];
+};
+
+/**
+ * snd_avirt_audiopath_register - register Audio Path with AVIRT
+ * @audiopath: Audio Path to be registered
+ * @core: ALSA virtual driver core info
+ * @return: 0 on success or error code otherwise
+ */
+int snd_avirt_audiopath_register(struct snd_avirt_audiopath *audiopath,
+ struct snd_avirt_coreinfo **coreinfo);
+
+/**
+ * snd_avirt_audiopath_deregister - deregister Audio Path with AVIRT
+ * @audiopath: Audio Path to be deregistered
+ * @return: 0 on success or error code otherwise
+ */
+int snd_avirt_audiopath_deregister(struct snd_avirt_audiopath *audiopath);
+
+/**
+ * snd_avirt_audiopath_get - retrieves the Audio Path by it's UID
+ * @uid: Unique ID for the Audio Path
+ * @return: Corresponding Audio Path
+ */
+struct snd_avirt_audiopath *snd_avirt_audiopath_get(const char *uid);
+
+/**
+ * snd_avirt_stream_count - get the stream count for the given direction
+ * @direction: The direction to get the stream count for
+ * @return: The stream count
+ */
+int snd_avirt_stream_count(unsigned int direction);
+
+/**
+ * snd_avirt_stream_from_config_item - Convert config_item to a snd_avirt_stream
+ * @item: The config_item to convert from
+ * @return: The item's snd_avirt_stream if successful, NULL otherwise
+ */
+static inline struct snd_avirt_stream *
+ snd_avirt_stream_from_config_item(struct config_item *item)
+{
+ return item ? container_of(item, struct snd_avirt_stream, item) : NULL;
+}
+
+/**
+ * snd_avirt_pcm_period_elapsed - PCM buffer complete callback
+ * @substream: pointer to ALSA PCM substream
+ *
+ * This should be called from a child Audio Path once it has finished processing
+ * the PCM buffer
+ */
+void snd_avirt_pcm_period_elapsed(struct snd_pcm_substream *substream);
+
+#endif // __SOUND_AVIRT_H
diff --git a/utils.h b/utils.h
new file mode 100644
index 0000000..0931e82
--- /dev/null
+++ b/utils.h
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * AVIRT - ALSA Virtual Soundcard
+ *
+ * Copyright (c) 2010-2018 Fiberdyne Systems Pty Ltd
+ *
+ * utils.h - Some useful macros/utils for AVIRT
+ */
+
+#ifndef __SOUND_AVIRT_UTILS_H
+#define __SOUND_AVIRT_UTILS_H
+
+#define CHK_ERR(errno) \
+ do { \
+ if ((errno) < 0) \
+ return (errno); \
+ } while (0)
+
+#define CHK_ERR_V(errno, fmt, args...) \
+ do { \
+ if ((errno) < 0) { \
+ DERROR(D_LOGNAME, (fmt), ##args) \
+ return (errno); \
+ } \
+ } while (0)
+
+#define CHK_NULL(x) \
+ do { \
+ if (!(x)) \
+ return -EFAULT; \
+ } while (0)
+
+#define CHK_NULL_V(x, fmt, args...) \
+ do { \
+ if (!(x)) { \
+ DERROR(D_LOGNAME, "[ERRNO: %d] " fmt, -EFAULT, \
+ ##args); \
+ return -EFAULT; \
+ } \
+ } while (0)
+
+#endif /* __SOUND_AVIRT_UTILS_H */
diff --git a/xds-project.conf b/xds-project.conf
new file mode 100644
index 0000000..6296119
--- /dev/null
+++ b/xds-project.conf
@@ -0,0 +1,4 @@
+# XDS project settings
+export XDS_AGENT_URL=localhost:8800
+export XDS_PROJECT_ID=1c520c49
+export XDS_SDK_ID=6864c558