diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..ef95a8fd --- /dev/null +++ b/.clang-format @@ -0,0 +1,688 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# clang-format configuration file. Intended for clang-format >= 11. +# +# 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 +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 + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: false +BreakBeforeTernaryOperators: false +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeComma +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: false +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 8 +ContinuationIndentWidth: 8 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: false + +# Taken from: +# git grep -h '^#define [^[:space:]]*for_each[^[:space:]]*(' include/ tools/ \ +# | sed "s,^#define \([^[:space:]]*for_each[^[:space:]]*\)(.*$, - '\1'," \ +# | LC_ALL=C sort -u +ForEachMacros: + - '__ata_qc_for_each' + - '__bio_for_each_bvec' + - '__bio_for_each_segment' + - '__evlist__for_each_entry' + - '__evlist__for_each_entry_continue' + - '__evlist__for_each_entry_from' + - '__evlist__for_each_entry_reverse' + - '__evlist__for_each_entry_safe' + - '__for_each_mem_range' + - '__for_each_mem_range_rev' + - '__for_each_thread' + - '__hlist_for_each_rcu' + - '__map__for_each_symbol_by_name' + - '__perf_evlist__for_each_entry' + - '__perf_evlist__for_each_entry_reverse' + - '__perf_evlist__for_each_entry_safe' + - '__rq_for_each_bio' + - '__shost_for_each_device' + - 'apei_estatus_for_each_section' + - 'ata_for_each_dev' + - 'ata_for_each_link' + - 'ata_qc_for_each' + - 'ata_qc_for_each_raw' + - 'ata_qc_for_each_with_internal' + - 'ax25_for_each' + - 'ax25_uid_for_each' + - 'bio_for_each_bvec' + - 'bio_for_each_bvec_all' + - 'bio_for_each_folio_all' + - 'bio_for_each_integrity_vec' + - 'bio_for_each_segment' + - 'bio_for_each_segment_all' + - 'bio_list_for_each' + - 'bip_for_each_vec' + - 'bond_for_each_slave' + - 'bond_for_each_slave_rcu' + - 'bpf__perf_for_each_map' + - 'bpf__perf_for_each_map_named' + - 'bpf_for_each_spilled_reg' + - 'bpf_object__for_each_map' + - 'bpf_object__for_each_program' + - 'bpf_object__for_each_safe' + - 'bpf_perf_object__for_each' + - '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_efficient_entry_idx' + - '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' + - 'damon_for_each_region' + - 'damon_for_each_region_safe' + - 'damon_for_each_scheme' + - 'damon_for_each_scheme_safe' + - 'damon_for_each_target' + - 'damon_for_each_target_safe' + - 'data__for_each_file' + - 'data__for_each_file_new' + - 'data__for_each_file_start' + - 'device_for_each_child_node' + - 'displayid_iter_for_each' + - 'dma_fence_array_for_each' + - 'dma_fence_chain_for_each' + - 'dma_fence_unwrap_for_each' + - 'dma_resv_for_each_fence' + - 'dma_resv_for_each_fence_unlocked' + - 'do_for_each_ftrace_op' + - 'drm_atomic_crtc_for_each_plane' + - 'drm_atomic_crtc_state_for_each_plane' + - 'drm_atomic_crtc_state_for_each_plane_state' + - 'drm_atomic_for_each_plane_damage' + - 'drm_client_for_each_connector_iter' + - 'drm_client_for_each_modeset' + - 'drm_connector_for_each_possible_encoder' + - 'drm_for_each_bridge_in_chain' + - 'drm_for_each_connector_iter' + - 'drm_for_each_crtc' + - 'drm_for_each_crtc_reverse' + - '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_for_each_privobj' + - 'drm_mm_for_each_hole' + - 'drm_mm_for_each_node' + - 'drm_mm_for_each_node_in_range' + - 'drm_mm_for_each_node_safe' + - 'dsa_switch_for_each_available_port' + - 'dsa_switch_for_each_cpu_port' + - 'dsa_switch_for_each_port' + - 'dsa_switch_for_each_port_continue_reverse' + - 'dsa_switch_for_each_port_safe' + - 'dsa_switch_for_each_user_port' + - 'dsa_tree_for_each_user_port' + - 'dso__for_each_symbol' + - 'dsos__for_each_with_build_id' + - 'elf_hash_for_each_possible' + - 'elf_section__for_each_rel' + - 'elf_section__for_each_rela' + - 'elf_symtab__for_each_symbol' + - 'evlist__for_each_cpu' + - 'evlist__for_each_entry' + - 'evlist__for_each_entry_continue' + - 'evlist__for_each_entry_from' + - 'evlist__for_each_entry_reverse' + - 'evlist__for_each_entry_safe' + - 'flow_action_for_each' + - 'for_each_acpi_dev_match' + - 'for_each_active_dev_scope' + - 'for_each_active_drhd_unit' + - 'for_each_active_iommu' + - 'for_each_active_route' + - 'for_each_aggr_pgid' + - 'for_each_available_child_of_node' + - 'for_each_bench' + - 'for_each_bio' + - 'for_each_board_func_rsrc' + - 'for_each_btf_ext_rec' + - 'for_each_btf_ext_sec' + - 'for_each_bvec' + - 'for_each_card_auxs' + - 'for_each_card_auxs_safe' + - 'for_each_card_components' + - 'for_each_card_dapms' + - 'for_each_card_pre_auxs' + - 'for_each_card_prelinks' + - 'for_each_card_rtds' + - 'for_each_card_rtds_safe' + - 'for_each_card_widgets' + - 'for_each_card_widgets_safe' + - 'for_each_cgroup_storage_type' + - 'for_each_child_of_node' + - 'for_each_clear_bit' + - 'for_each_clear_bit_from' + - 'for_each_clear_bitrange' + - 'for_each_clear_bitrange_from' + - 'for_each_cmd' + - 'for_each_cmsghdr' + - 'for_each_collection' + - 'for_each_comp_order' + - 'for_each_compatible_node' + - 'for_each_component_dais' + - 'for_each_component_dais_safe' + - 'for_each_console' + - 'for_each_console_srcu' + - 'for_each_cpu' + - 'for_each_cpu_and' + - 'for_each_cpu_wrap' + - 'for_each_dapm_widgets' + - 'for_each_dedup_cand' + - 'for_each_dev_addr' + - 'for_each_dev_scope' + - 'for_each_dma_cap_mask' + - 'for_each_dpcm_be' + - 'for_each_dpcm_be_rollback' + - 'for_each_dpcm_be_safe' + - 'for_each_dpcm_fe' + - 'for_each_drhd_unit' + - 'for_each_dss_dev' + - 'for_each_efi_memory_desc' + - 'for_each_efi_memory_desc_in_map' + - 'for_each_element' + - 'for_each_element_extid' + - 'for_each_element_id' + - 'for_each_endpoint_of_node' + - 'for_each_event' + - 'for_each_event_tps' + - 'for_each_evictable_lru' + - 'for_each_fib6_node_rt_rcu' + - 'for_each_fib6_walker_rt' + - 'for_each_free_mem_pfn_range_in_zone' + - 'for_each_free_mem_pfn_range_in_zone_from' + - 'for_each_free_mem_range' + - 'for_each_free_mem_range_reverse' + - 'for_each_func_rsrc' + - 'for_each_group_device' + - 'for_each_group_evsel' + - 'for_each_group_member' + - 'for_each_hstate' + - 'for_each_if' + - 'for_each_inject_fn' + - 'for_each_insn' + - 'for_each_insn_prefix' + - 'for_each_intid' + - 'for_each_iommu' + - 'for_each_ip_tunnel_rcu' + - 'for_each_irq_nr' + - 'for_each_lang' + - 'for_each_link_codecs' + - 'for_each_link_cpus' + - 'for_each_link_platforms' + - 'for_each_lru' + - 'for_each_matching_node' + - 'for_each_matching_node_and_match' + - 'for_each_mem_pfn_range' + - 'for_each_mem_range' + - 'for_each_mem_range_rev' + - 'for_each_mem_region' + - 'for_each_member' + - 'for_each_memory' + - 'for_each_migratetype_order' + - 'for_each_missing_reg' + - 'for_each_net' + - 'for_each_net_continue_reverse' + - 'for_each_net_rcu' + - 'for_each_netdev' + - 'for_each_netdev_continue' + - 'for_each_netdev_continue_rcu' + - 'for_each_netdev_continue_reverse' + - 'for_each_netdev_feature' + - 'for_each_netdev_in_bond_rcu' + - 'for_each_netdev_rcu' + - 'for_each_netdev_reverse' + - 'for_each_netdev_safe' + - 'for_each_new_connector_in_state' + - 'for_each_new_crtc_in_state' + - 'for_each_new_mst_mgr_in_state' + - 'for_each_new_plane_in_state' + - 'for_each_new_plane_in_state_reverse' + - 'for_each_new_private_obj_in_state' + - 'for_each_new_reg' + - '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_nonreserved_multicast_dest_pgid' + - 'for_each_of_allnodes' + - 'for_each_of_allnodes_from' + - 'for_each_of_cpu_node' + - 'for_each_of_pci_range' + - 'for_each_old_connector_in_state' + - 'for_each_old_crtc_in_state' + - 'for_each_old_mst_mgr_in_state' + - 'for_each_old_plane_in_state' + - 'for_each_old_private_obj_in_state' + - 'for_each_oldnew_connector_in_state' + - 'for_each_oldnew_crtc_in_state' + - 'for_each_oldnew_mst_mgr_in_state' + - 'for_each_oldnew_plane_in_state' + - 'for_each_oldnew_plane_in_state_reverse' + - 'for_each_oldnew_private_obj_in_state' + - 'for_each_online_cpu' + - 'for_each_online_node' + - 'for_each_online_pgdat' + - 'for_each_path' + - 'for_each_pci_bridge' + - 'for_each_pci_dev' + - 'for_each_pcm_streams' + - 'for_each_physmem_range' + - 'for_each_populated_zone' + - 'for_each_possible_cpu' + - 'for_each_present_cpu' + - 'for_each_prime_number' + - 'for_each_prime_number_from' + - 'for_each_probe_cache_entry' + - 'for_each_process' + - 'for_each_process_thread' + - 'for_each_prop_codec_conf' + - 'for_each_prop_dai_codec' + - 'for_each_prop_dai_cpu' + - 'for_each_prop_dlc_codecs' + - 'for_each_prop_dlc_cpus' + - 'for_each_prop_dlc_platforms' + - 'for_each_property_of_node' + - 'for_each_reg' + - 'for_each_reg_filtered' + - 'for_each_registered_fb' + - 'for_each_requested_gpio' + - 'for_each_requested_gpio_in_range' + - 'for_each_reserved_mem_range' + - 'for_each_reserved_mem_region' + - 'for_each_rtd_codec_dais' + - 'for_each_rtd_components' + - 'for_each_rtd_cpu_dais' + - 'for_each_rtd_dais' + - 'for_each_script' + - 'for_each_sec' + - 'for_each_set_bit' + - 'for_each_set_bit_from' + - 'for_each_set_bitrange' + - 'for_each_set_bitrange_from' + - 'for_each_set_clump8' + - 'for_each_sg' + - 'for_each_sg_dma_page' + - 'for_each_sg_page' + - 'for_each_sgtable_dma_page' + - 'for_each_sgtable_dma_sg' + - 'for_each_sgtable_page' + - 'for_each_sgtable_sg' + - 'for_each_shell_test' + - 'for_each_sibling_event' + - 'for_each_subelement' + - 'for_each_subelement_extid' + - 'for_each_subelement_id' + - 'for_each_sublist' + - 'for_each_subsystem' + - 'for_each_supported_activate_fn' + - 'for_each_supported_inject_fn' + - 'for_each_test' + - 'for_each_thread' + - 'for_each_token' + - 'for_each_unicast_dest_pgid' + - 'for_each_vsi' + - 'for_each_wakeup_source' + - 'for_each_zone' + - 'for_each_zone_zonelist' + - 'for_each_zone_zonelist_nodemask' + - 'func_for_each_insn' + - 'fwnode_for_each_available_child_node' + - 'fwnode_for_each_child_node' + - 'fwnode_graph_for_each_endpoint' + - 'gadget_for_each_ep' + - 'genradix_for_each' + - 'genradix_for_each_from' + - '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' + - 'hashmap__for_each_entry' + - 'hashmap__for_each_entry_safe' + - 'hashmap__for_each_key_entry' + - 'hashmap__for_each_key_entry_safe' + - 'hctx_for_each_ctx' + - 'hists__for_each_format' + - 'hists__for_each_sort_list' + - '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_entry_srcu' + - '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' + - 'i3c_bus_for_each_i2cdev' + - 'i3c_bus_for_each_i3cdev' + - 'idr_for_each_entry' + - 'idr_for_each_entry_continue' + - 'idr_for_each_entry_continue_ul' + - 'idr_for_each_entry_ul' + - 'in_dev_for_each_ifa_rcu' + - 'in_dev_for_each_ifa_rtnl' + - 'inet_bind_bucket_for_each' + - 'inet_lhash2_for_each_icsk' + - 'inet_lhash2_for_each_icsk_continue' + - 'inet_lhash2_for_each_icsk_rcu' + - 'interval_tree_for_each_double_span' + - 'interval_tree_for_each_span' + - 'intlist__for_each_entry' + - 'intlist__for_each_entry_safe' + - 'iopt_for_each_contig_area' + - 'kcore_copy__for_each_phdr' + - 'key_for_each' + - 'key_for_each_safe' + - 'klp_for_each_func' + - 'klp_for_each_func_safe' + - 'klp_for_each_func_static' + - 'klp_for_each_object' + - 'klp_for_each_object_safe' + - 'klp_for_each_object_static' + - 'kunit_suite_for_each_test_case' + - 'kvm_for_each_memslot' + - 'kvm_for_each_memslot_in_gfn_range' + - 'kvm_for_each_vcpu' + - 'libbpf_nla_for_each_attr' + - 'list_for_each' + - 'list_for_each_codec' + - 'list_for_each_codec_safe' + - 'list_for_each_continue' + - '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_rcu' + - '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_entry_srcu' + - 'list_for_each_from' + - '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' + - 'map__for_each_symbol' + - 'map__for_each_symbol_by_name' + - 'map_for_each_event' + - 'map_for_each_metric' + - 'maps__for_each_entry' + - 'maps__for_each_entry_safe' + - 'mci_for_each_dimm' + - 'media_device_for_each_entity' + - 'media_device_for_each_intf' + - 'media_device_for_each_link' + - 'media_device_for_each_pad' + - 'msi_for_each_desc' + - 'nanddev_io_for_each_page' + - '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' + - 'pci_dev_for_each_resource' + - 'pcl_for_each_chunk' + - 'pcl_for_each_segment' + - 'pcm_for_each_format' + - 'perf_config_items__for_each_entry' + - 'perf_config_sections__for_each_entry' + - 'perf_config_set__for_each_entry' + - 'perf_cpu_map__for_each_cpu' + - 'perf_evlist__for_each_entry' + - 'perf_evlist__for_each_entry_reverse' + - 'perf_evlist__for_each_entry_safe' + - 'perf_evlist__for_each_evsel' + - 'perf_evlist__for_each_mmap' + - 'perf_hpp_list__for_each_format' + - 'perf_hpp_list__for_each_format_safe' + - 'perf_hpp_list__for_each_sort_list' + - 'perf_hpp_list__for_each_sort_list_safe' + - 'perf_pmu__for_each_hybrid_pmu' + - 'ping_portaddr_for_each_entry' + - 'ping_portaddr_for_each_entry_rcu' + - '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_slot' + - 'radix_tree_for_each_tagged' + - 'rb_for_each' + - 'rbtree_postorder_for_each_entry_safe' + - 'rdma_for_each_block' + - 'rdma_for_each_port' + - 'rdma_umem_for_each_dma_block' + - 'resort_rb__for_each_entry' + - '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_entry' + - 'rht_for_each_entry_from' + - 'rht_for_each_entry_rcu' + - 'rht_for_each_entry_rcu_from' + - 'rht_for_each_entry_safe' + - 'rht_for_each_from' + - 'rht_for_each_rcu' + - 'rht_for_each_rcu_from' + - 'rq_for_each_bvec' + - 'rq_for_each_segment' + - 'rq_list_for_each' + - 'rq_list_for_each_safe' + - 'scsi_for_each_prot_sg' + - 'scsi_for_each_sg' + - 'sctp_for_each_hentry' + - 'sctp_skb_for_each' + - 'sec_for_each_insn' + - 'sec_for_each_insn_continue' + - 'sec_for_each_insn_from' + - 'shdma_for_each_chan' + - '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_array_for_each' + - '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' + - 'strlist__for_each_entry' + - 'strlist__for_each_entry_safe' + - 'sym_for_each_insn' + - 'sym_for_each_insn_continue_reverse' + - 'symbols__for_each_entry' + - 'tb_property_for_each' + - 'tcf_act_for_each_action' + - 'tcf_exts_for_each_action' + - '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' + - 'virtio_device_for_each_vq' + - 'while_for_each_ftrace_op' + - 'xa_for_each' + - 'xa_for_each_marked' + - 'xa_for_each_range' + - 'xa_for_each_start' + - 'xas_for_each' + - 'xas_for_each_conflict' + - 'xas_for_each_marked' + - 'xbc_array_for_each_value' + - 'xbc_for_each_key_value' + - 'xbc_node_for_each_array_value' + - 'xbc_node_for_each_child' + - 'xbc_node_for_each_key_value' + - 'xbc_node_for_each_subkey' + - 'zorro_for_each_dev' + +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '.*' + Priority: 1 +IncludeIsMainRegex: '(Test)?$' +IndentCaseLabels: false +IndentGotoLabels: false +IndentPPDirectives: None +IndentWidth: 8 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 8 +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: true + +# Taken from git's rules +PenaltyBreakAssignment: 10 +PenaltyBreakBeforeFirstCallParameter: 30 +PenaltyBreakComment: 10 +PenaltyBreakFirstLessLess: 0 +PenaltyBreakString: 10 +PenaltyExcessCharacter: 100 +PenaltyReturnTypeOnItsOwnLine: 60 + +PointerAlignment: Right +ReflowComments: false +SortIncludes: false +SortUsingDeclarations: false +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatementsExceptForEachMacros +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: false +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp03 +TabWidth: 8 +UseTab: Always \ No newline at end of file diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 00000000..fd8c681c --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,147 @@ +# Generated from CLion Inspection settings +--- +Checks: '-*, +bugprone-argument-comment, +bugprone-assert-side-effect, +bugprone-bad-signal-to-kill-thread, +bugprone-branch-clone, +bugprone-copy-constructor-init, +bugprone-dangling-handle, +bugprone-dynamic-static-initializers, +bugprone-fold-init-type, +bugprone-forward-declaration-namespace, +bugprone-forwarding-reference-overload, +bugprone-inaccurate-erase, +bugprone-incorrect-roundings, +bugprone-integer-division, +bugprone-lambda-function-name, +bugprone-macro-parentheses, +bugprone-macro-repeated-side-effects, +bugprone-misplaced-operator-in-strlen-in-alloc, +bugprone-misplaced-pointer-arithmetic-in-alloc, +bugprone-misplaced-widening-cast, +bugprone-move-forwarding-reference, +bugprone-multiple-statement-macro, +bugprone-no-escape, +bugprone-parent-virtual-call, +bugprone-posix-return, +bugprone-reserved-identifier, +bugprone-sizeof-container, +bugprone-sizeof-expression, +bugprone-spuriously-wake-up-functions, +bugprone-string-constructor, +bugprone-string-integer-assignment, +bugprone-string-literal-with-embedded-nul, +bugprone-suspicious-enum-usage, +bugprone-suspicious-include, +bugprone-suspicious-memset-usage, +bugprone-suspicious-missing-comma, +bugprone-suspicious-semicolon, +bugprone-suspicious-string-compare, +bugprone-suspicious-memory-comparison, +bugprone-suspicious-realloc-usage, +bugprone-swapped-arguments, +bugprone-terminating-continue, +bugprone-throw-keyword-missing, +bugprone-too-small-loop-variable, +bugprone-undefined-memory-manipulation, +bugprone-undelegated-constructor, +bugprone-unhandled-self-assignment, +bugprone-unused-raii, +bugprone-unused-return-value, +bugprone-use-after-move, +bugprone-virtual-near-miss, +cert-dcl21-cpp, +cert-dcl58-cpp, +cert-err34-c, +cert-err52-cpp, +cert-err60-cpp, +cert-flp30-c, +cert-msc50-cpp, +cert-msc51-cpp, +cert-str34-c, +cppcoreguidelines-interfaces-global-init, +cppcoreguidelines-narrowing-conversions, +cppcoreguidelines-pro-type-member-init, +cppcoreguidelines-pro-type-static-cast-downcast, +cppcoreguidelines-slicing, +google-default-arguments, +google-explicit-constructor, +google-runtime-operator, +hicpp-exception-baseclass, +hicpp-multiway-paths-covered, +misc-misplaced-const, +misc-new-delete-overloads, +misc-no-recursion, +misc-non-copyable-objects, +misc-throw-by-value-catch-by-reference, +misc-unconventional-assign-operator, +misc-uniqueptr-reset-release, +modernize-avoid-bind, +modernize-concat-nested-namespaces, +modernize-deprecated-headers, +modernize-deprecated-ios-base-aliases, +modernize-loop-convert, +modernize-make-shared, +modernize-make-unique, +modernize-pass-by-value, +modernize-raw-string-literal, +modernize-redundant-void-arg, +modernize-replace-auto-ptr, +modernize-replace-disallow-copy-and-assign-macro, +modernize-replace-random-shuffle, +modernize-return-braced-init-list, +modernize-shrink-to-fit, +modernize-unary-static-assert, +modernize-use-auto, +modernize-use-bool-literals, +modernize-use-emplace, +modernize-use-equals-default, +modernize-use-equals-delete, +modernize-use-nodiscard, +modernize-use-noexcept, +modernize-use-nullptr, +modernize-use-override, +modernize-use-transparent-functors, +modernize-use-uncaught-exceptions, +mpi-buffer-deref, +mpi-type-mismatch, +openmp-use-default-none, +performance-faster-string-find, +performance-for-range-copy, +performance-implicit-conversion-in-loop, +performance-inefficient-algorithm, +performance-inefficient-string-concatenation, +performance-inefficient-vector-operation, +performance-move-const-arg, +performance-move-constructor-init, +performance-no-automatic-move, +performance-noexcept-move-constructor, +performance-trivially-destructible, +performance-type-promotion-in-math-fn, +performance-unnecessary-copy-initialization, +performance-unnecessary-value-param, +portability-simd-intrinsics, +readability-avoid-const-params-in-decls, +readability-const-return-type, +readability-container-size-empty, +readability-convert-member-functions-to-static, +readability-delete-null-pointer, +readability-deleted-default, +readability-inconsistent-declaration-parameter-name, +readability-make-member-function-const, +readability-misleading-indentation, +readability-misplaced-array-index, +readability-non-const-parameter, +readability-redundant-control-flow, +readability-redundant-declaration, +readability-redundant-function-ptr-dereference, +readability-redundant-smartptr-get, +readability-redundant-string-cstr, +readability-redundant-string-init, +readability-simplify-subscript-expr, +readability-static-accessed-through-instance, +readability-static-definition-in-anonymous-namespace, +readability-string-compare, +readability-uniqueptr-delete-release, +readability-use-anyofallof' \ No newline at end of file diff --git a/.github/workflows/kmod-pagefault-tests.yml b/.github/workflows/kmod-pagefault-tests.yml new file mode 100644 index 00000000..8efc4c75 --- /dev/null +++ b/.github/workflows/kmod-pagefault-tests.yml @@ -0,0 +1,78 @@ +name: Pagefault Kernel Module Tests + +on: + pull_request: + paths: + - "kmod/pagefault/**" + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: "1.22" + check-latest: true + cache: false + + - name: Build Module + working-directory: kmod/pagefault + run: make module + shell: bash + + - name: Generate Test Data + working-directory: kmod/pagefault + run: make tests-generate + shell: bash + + - name: Set 'vm.max_map_count' parameter + run: sudo sysctl -w vm.max_map_count=262144 + shell: bash + + - name: Load Module + working-directory: kmod/pagefault + run: sudo make load + shell: bash + + - name: Run Kernel Module Test + working-directory: kmod/pagefault + run: make tests + shell: bash + + - name: Unload Module + working-directory: kmod/pagefault + run: sudo make unload + shell: bash + + - name: Build Module with Benchmarking + working-directory: kmod/pagefault + run: BENCHMARK=true make module + shell: bash + + - name: Load Module + working-directory: kmod/pagefault + run: sudo make load + shell: bash + + - name: Run Kernel Module Test (With Benchmarking) + working-directory: kmod/pagefault + run: make tests + shell: bash + + - name: Print last 30 dmesg logs + run: sudo dmesg | tail -n 30 | grep silo_pagefault + shell: bash + + - name: Unload Module + working-directory: kmod/pagefault + run: sudo make unload + shell: bash + + - name: Cleanup Module + working-directory: kmod/pagefault + run: make clean + shell: bash \ No newline at end of file diff --git a/MAINTAINERS.md b/MAINTAINERS.md index c3695ab3..6e2cba4d 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -1 +1,3 @@ - James Moore @jimmyaxod +- Shivansh Vij @shivanshvij +- Luiz Aoqui @lgfa29 diff --git a/README.md b/README.md index 56c26680..d3cddfb7 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Logo -[![License: AGPL 3.0](https://img.shields.io/github/license/loopholelabs/silo)](<[https://www.apache.org/licenses/LICENSE-2.0](https://www.gnu.org/licenses/agpl-3.0.en.html)>) +[![License: AGPL 3.0](https://img.shields.io/github/license/loopholelabs/silo)](https://www.gnu.org/licenses/agpl-3.0.en.html) [![Discord](https://dcbadge.vercel.app/api/server/JYmFhtdPeu?style=flat)](https://loopholelabs.io/discord) ![Go Version](https://img.shields.io/badge/go%20version-%3E=1.21-61CFDD.svg) [![Go Reference](https://pkg.go.dev/badge/github.com/loopholelabs/silo.svg)](https://pkg.go.dev/github.com/loopholelabs/silo) diff --git a/docs/kmod-logo-dark.svg b/docs/kmod-logo-dark.svg new file mode 100644 index 00000000..1d19dd9f --- /dev/null +++ b/docs/kmod-logo-dark.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/kmod-logo-light.svg b/docs/kmod-logo-light.svg new file mode 100644 index 00000000..e6ea03c7 --- /dev/null +++ b/docs/kmod-logo-light.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/kmod/README.md b/kmod/README.md new file mode 100644 index 00000000..3c8256f5 --- /dev/null +++ b/kmod/README.md @@ -0,0 +1,32 @@ +
+
+
+ + Logo +
+
+
+ + + Logo + +
+
+ +[![License: AGPL 3.0](https://img.shields.io/github/license/loopholelabs/silo)](https://www.gnu.org/licenses/agpl-3.0.en.html) +[![Discord](https://dcbadge.vercel.app/api/server/JYmFhtdPeu?style=flat)](https://loopholelabs.io/discord) +
+ +## Overview + +This repository contains various kernel modules for use with Silo. + +### Pagefault + +The `pagefault` module allows a userspace process to efficiently multiple segments of memory over a base memory space. + +## License + +All Kernel Modules are available as open source under the terms of +the [GPL v3 License](https://www.gnu.org/licenses/gpl-3.0.en.html). + diff --git a/kmod/pagefault/.gitignore b/kmod/pagefault/.gitignore new file mode 100644 index 00000000..91c78d79 --- /dev/null +++ b/kmod/pagefault/.gitignore @@ -0,0 +1,15 @@ +.idea +.ccls-cache +*.ko +*.cmd +*.symvers +*.order +*.o +*.out +*.o.* +*.mod +*.mod.* +.run +*.img +*.bin +.fuse_hidden* diff --git a/kmod/pagefault/LICENSE b/kmod/pagefault/LICENSE new file mode 100644 index 00000000..e72bfdda --- /dev/null +++ b/kmod/pagefault/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. 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 +them 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 prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. 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. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey 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; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If 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 convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + 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. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +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. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/kmod/pagefault/Makefile b/kmod/pagefault/Makefile new file mode 100644 index 00000000..f57f4a70 --- /dev/null +++ b/kmod/pagefault/Makefile @@ -0,0 +1,50 @@ +obj-m := silo-pagefault.o +silo-pagefault-objs := module.o log.o hashtable.o + +LOG_LEVEL ?= 1 +ccflags-y += -DLOG_LEVEL=${LOG_LEVEL} + +clean-files := *.o *.mod.c *.mod.o *.ko *.symvers *.o.d + +all: module + +.PHONY: module +module: + ${MAKE} -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules + +.PHONY: clean +clean: tests-clean + ${MAKE} -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean + $(RM) $(clean-files) + +.PHONY: load +load: + insmod silo-pagefault.ko + +.PHONY: unload +unload: + rmmod silo_pagefault + +.PHONY: tests +tests: + cd tests && ((${MAKE} all && exit 0) || exit -1) + +.PHONY: tests-benchmark +tests-benchmark: + cd tests && ((${MAKE} page_fault_benchmark && exit 0) || exit -1) + +.PHONY: tests-userspace +tests-userspace: + cd tests && ((${MAKE} userspace && exit 0) || exit -1) + +.PHONY: tests-generate +tests-generate: + cd tests && ((${MAKE} generate && exit 0) || exit -1) + +.PHONY: tests-clean +tests-clean: + cd tests && ((${MAKE} clean && exit 0) || exit -1) + +.PHONY: tests-binaries +tests-binaries: + cd tests && ((${MAKE} binaries && exit 0) || exit -1) diff --git a/kmod/pagefault/README.md b/kmod/pagefault/README.md new file mode 100644 index 00000000..837a1562 --- /dev/null +++ b/kmod/pagefault/README.md @@ -0,0 +1,281 @@ +
+
+ + Logo + +

+ A Kernel Module that allows mapping multiple segments of memory over a base memory space. +

+ +[![License: GPL](https://img.shields.io/badge/License-GPL%20v3-brightgreen.svg)](https://www.gnu.org/licenses/gpl-3.0.en.html) +[![Discord](https://dcbadge.vercel.app/api/server/JYmFhtdPeu?style=flat)](https://loopholelabs.io/discord) +
+ +## Build and Load + +The kernel module requires Linux kernel v6.5+. Use the following command to +build the kernel module. + +```bash +make module +``` + +This command generates a file called `memory-overlay.ko` that you can load into +the kernel using the command `sudo make load` and unload using `sudo make +unload`. + +Set the `LOG_LEVEL` variable when building the kernel module to change log +verbosity. + +```bash +make module LOG_LEVEL=2 +``` + +The following log levels are available. + +* `LOG_LEVEL=1`: `INFO` (default). +* `LOG_LEVEL=2`: `DEBUG`. +* `LOG_LEVEL=3`: `TRACE`. + +## Testing and Examples + +The folder [`tests/page_fault`](tests/page_fault) contains several userspace C +programs that can be used to test the kernel module and as examples on how to +use it. + +The test programs map randomized test files into memory. You can generate them +using the [`tests/generate.go`](tests/generate.go) helper. This program +requires the Go toolchain to be installed. You can execute the helper with the +following command. + +```bash +make tests-generate +``` + +After loading the module and generating the test data, you can build and +execute the test programs using the following command. + +```bash +make tests +``` + +You can retrieve the kernel module output using the `sudo dmesg` command, or +run `sudo dmesg -w` in another window to actively follow the latest log output. + +## Device Driver API + +The kernel module creates a character device driver that is available in the +path `/dev/memory_overlay`. You can interact with the kernel module by sending +[`ioctl`][man_ioctl] commands to this device. + +```c +int syscall_dev = open("/dev/silo_pagefault", O_WRONLY); +if (syscall_dev < 0) { + printf("ERROR: failed to open /dev/silo_pagefault: %s\n", strerror(errno)); + return EXIT_FAILURE; +} + +struct overlay_req req; +// ...generate request... + +int ret = ioctl(syscall_dev, IOCTL_OVERLAY_REQ_CMD, &req); +if (ret) { + printf("ERROR: failed not call 'IOCTL_MMAP_CMD': %s\n", strerror(errno)); + close(syscall_dev); + return EXIT_FAILURE; +} + +// ...before exit... + +struct overlay_cleanup_req cleanup_req = { + .id = req.id, +}; +int ret = ioctl(syscall_dev, IOCTL_OVERLAY_CLEANUP_CMD, &cleanup_req); +if (ret) { + printf("ERROR: could not call 'IOCTL_MMAP_CMD': %s\n", strerror(errno)); + close(syscall_dev); + return EXIT_FAILURE; +} +``` + +The device driver uses the following commands, which are defined in the +[`device.h`](device.h) file. + +### `IOCTL_OVERLAY_REQ_CMD` Command + +The `IOCTL_OVERLAY_REQ_CMD` takes a `overlay_req` as input and is used +to register a new set of memory overlays for a base memory area. + +Each base memory can only be registered once. + +#### `overlay_req` Fields + +```c +struct overlay_req { + unsigned long id; + + unsigned long base_addr; + unsigned long overlay_addr; + + unsigned int segments_size; + struct overlay_segment_req *segments; +}; +``` + +* `id`: Request identifier. This value is set by the kernel module if the + command succeeds and should not be set when making the request. +* `base_addr`: Virtual address where the base file is mapped in memory. +* `overlay_addr`: Virtual address where the overlay file is mapped in memory. +* `segments_size`: The number of memory segments to overlay. +* `segments`: Array of memory segments to overlay. + +#### `overlay_segment_req` Fields + +```c +struct overlay_segment_req { + unsigned long start_pgoff; + unsigned long end_pgoff; +}; +``` + +* `start_pgoff`: Page offset of where the segment start (inclusive). +* `end_pgoff`: Page offset of where the segment ends (inclusive). + +#### Return Value + +On success, a `0` is returned. On error, `-1` is returned, and +[`errno`][man_errno] is set to indicate the error. + +#### Errors + +* `EFAULT`: Internal module error. Refer to the kernel module logs for more + information. +* `EINVAL`: Invalid base or overlay virtual memory address. +* `EEXIST`: Base file is already registered. +* `ENOMEM`: Failed to allocate memory. + +### `IOCTL_OVERLAY_CLEANUP_CMD` Command + +The `IOCTL_OVERLAY_CLEANUP_CMD` takes a `overlay_cleanup_req` as input +and is used to remove a previous memory overlay request from the kernel module. + +Every call to `IOCTL_OVERLAY_REQ_CMD` MUST be have a corresponding +`IOCTL_OVERLAY_CLEANUP_CMD` before the program exits. Fail to do so may +result kernel panics due to invalid memory pages left in the system. + +#### `overlay_cleanup_req` fields + +```c +struct overlay_cleanup_req { + unsigned long id; +}; +``` + +* `id`: Request identifier returned from a call to `IOCTL_OVERLAY_REQ_CMD`. + +#### Return value + +On success, a `0` is returned. On error, `-1` is returned, and +[`errno`][man_errno] is set to indicate the error. + +#### Errors + +* `EFAULT`: Internal module error. Refer to the kernel module logs for more + information. +* `ENOENT`: Request ID not found. + +## Known Issues + +### Unsupported CPU architectures + +The only CPU architecture currently supported is `x86-64`. + +### Loading data from a FUSE file system + +If the test files are stored in a FUSE file system, the kernel module may panic +with the following error. + +``` +[ 937.417750] kernel BUG at mm/truncate.c:667! +[ 937.418572] invalid opcode: 0000 [#1] PREEMPT SMP PTI +[ 937.418927] CPU: 1 PID: 859139 Comm: page_fault_mult Tainted: G OE 6.5.13-debug-v1 #6 +[ 937.419296] Hardware name: VMware, Inc. VMware Virtual Platform/440BX Desktop Reference Platform, BIOS 6.00 05/28/2020 +[ 937.419712] RIP: 0010:invalidate_inode_pages2_range+0x265/0x4d0 +[ 937.420160] Code: 85 c0 0f 8e 12 01 00 00 4c 89 ff e8 a5 9c 04 00 49 8b 07 a9 00 00 01 00 0f 84 c6 fe ff ff 41 8b 47 58 85 c0 0f 8e 01 01 00 00 <0f> 0b 4d 3b 67 18 0f 85 d2 fe ff ff be c0 0c 00 00 4c 89 ff e8 c2 +[ 937.421253] RSP: 0018:ffff99f3c1bf7ab8 EFLAGS: 00010246 +[ 937.421857] RAX: 0000000000000000 RBX: 0000000000000000 RCX: 0000000000000000 +[ 937.422444] RDX: 0000000000000000 RSI: 0000000000000000 RDI: 0000000000000000 +[ 937.423032] RBP: ffff99f3c1bf7c08 R08: 0000000000000000 R09: 0000000000000000 +[ 937.423669] R10: 0000000000000000 R11: 0000000000000000 R12: ffff8951cd68aef8 +[ 937.424284] R13: 0000000000000001 R14: 0000000000000000 R15: ffffed5884f9b040 +[ 937.424907] FS: 00007cfa2a7ec640(0000) GS:ffff8954efc80000(0000) knlGS:0000000000000000 +[ 937.425572] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 +[ 937.426239] CR2: 000072bd02ffd658 CR3: 0000000116ff0002 CR4: 00000000003706e0 +[ 937.427030] Call Trace: +[ 937.427747] +[ 937.428474] ? show_regs+0x72/0x90 +[ 937.429195] ? die+0x38/0xb0 +[ 937.429918] ? do_trap+0xe3/0x100 +[ 937.430687] ? do_error_trap+0x75/0xb0 +[ 937.431426] ? invalidate_inode_pages2_range+0x265/0x4d0 +[ 937.432190] ? exc_invalid_op+0x53/0x80 +[ 937.432962] ? invalidate_inode_pages2_range+0x265/0x4d0 +[ 937.433791] ? asm_exc_invalid_op+0x1b/0x20 +[ 937.434633] ? invalidate_inode_pages2_range+0x265/0x4d0 +[ 937.435458] ? invalidate_inode_pages2_range+0x24b/0x4d0 +[ 937.436277] ? fuse_put_request+0x9d/0x110 +[ 937.437106] invalidate_inode_pages2+0x17/0x30 +[ 937.437722] fuse_open_common+0x1cc/0x220 +[ 937.438313] ? __pfx_fuse_open+0x10/0x10 +[ 937.438909] fuse_open+0x10/0x20 +[ 937.439508] do_dentry_open+0x187/0x590 +[ 937.440140] vfs_open+0x33/0x50 +[ 937.440755] path_openat+0xaed/0x10a0 +[ 937.441379] ? asm_sysvec_call_function_single+0x1b/0x20 +[ 937.442034] do_filp_open+0xb2/0x160 +[ 937.442525] ? __pfx_autoremove_wake_function+0x10/0x10 +[ 937.443040] ? alloc_fd+0xad/0x1a0 +[ 937.443547] do_sys_openat2+0xa1/0xd0 +[ 937.444068] __x64_sys_openat+0x55/0xa0 +[ 937.444585] x64_sys_call+0xee8/0x2570 +[ 937.445104] do_syscall_64+0x56/0x90 +[ 937.445631] entry_SYSCALL_64_after_hwframe+0x73/0xdd +[ 937.446167] RIP: 0033:0x7cfac49145b4 +[ 937.446715] Code: 24 20 eb 8f 66 90 44 89 54 24 0c e8 56 c4 f7 ff 44 8b 54 24 0c 44 89 e2 48 89 ee 41 89 c0 bf 9c ff ff ff b8 01 01 00 00 0f 05 <48> 3d 00 f0 ff ff 77 34 44 89 c7 89 44 24 0c e8 98 c4 f7 ff 8b 44 +[ 937.447783] RSP: 002b:00007cfa2a7ebd90 EFLAGS: 00000293 ORIG_RAX: 0000000000000101 +[ 937.448308] RAX: ffffffffffffffda RBX: 00007cfa2a7ec640 RCX: 00007cfac49145b4 +[ 937.448812] RDX: 0000000000000000 RSI: 000063bc9c8be020 RDI: 00000000ffffff9c +[ 937.449316] RBP: 000063bc9c8be020 R08: 0000000000000000 R09: 000000007fffffff +[ 937.449817] R10: 0000000000000000 R11: 0000000000000293 R12: 0000000000000000 +[ 937.450307] R13: 0000000000000000 R14: 00007cfac48947d0 R15: 00007ffd47198540 +[ 937.450799] +[ 937.451256] Modules linked in: batch_syscalls(OE) vsock_loopback(E) vmw_vsock_virtio_transport_common(E) vmw_vsock_vmci_transport(E) vsock(E) binfmt_misc(E) intel_rapl_msr(E) intel_rapl_common(E) vmw_balloon(E) rapl(E) joydev(E) input_leds(E) serio_raw(E) vmw_vmci(E) mac_hid(E) sch_fq_codel(E) dm_multipath(E) scsi_dh_rdac(E) scsi_dh_emc(E) scsi_dh_alua(E) msr(E) efi_pstore(E) ip_tables(E) x_tables(E) autofs4(E) btrfs(E) blake2b_generic(E) raid10(E) raid456(E) async_raid6_recov(E) async_memcpy(E) async_pq(E) async_xor(E) async_tx(E) xor(E) raid6_pq(E) libcrc32c(E) raid1(E) raid0(E) multipath(E) linear(E) hid_generic(E) crct10dif_pclmul(E) crc32_pclmul(E) polyval_clmulni(E) polyval_generic(E) ghash_clmulni_intel(E) sha256_ssse3(E) sha1_ssse3(E) aesni_intel(E) crypto_simd(E) cryptd(E) usbhid(E) hid(E) vmwgfx(E) drm_ttm_helper(E) psmouse(E) ttm(E) drm_kms_helper(E) vmxnet3(E) mptspi(E) drm(E) ahci(E) mptscsih(E) libahci(E) mptbase(E) scsi_transport_spi(E) i2c_piix4(E) pata_acpi(E) +[ 937.454514] ---[ end trace 0000000000000000 ]--- +[ 937.454974] RIP: 0010:invalidate_inode_pages2_range+0x265/0x4d0 +[ 937.455442] Code: 85 c0 0f 8e 12 01 00 00 4c 89 ff e8 a5 9c 04 00 49 8b 07 a9 00 00 01 00 0f 84 c6 fe ff ff 41 8b 47 58 85 c0 0f 8e 01 01 00 00 <0f> 0b 4d 3b 67 18 0f 85 d2 fe ff ff be c0 0c 00 00 4c 89 ff e8 c2 +[ 937.456403] RSP: 0018:ffff99f3c1bf7ab8 EFLAGS: 00010246 +[ 937.456897] RAX: 0000000000000000 RBX: 0000000000000000 RCX: 0000000000000000 +[ 937.457354] RDX: 0000000000000000 RSI: 0000000000000000 RDI: 0000000000000000 +[ 937.457893] RBP: ffff99f3c1bf7c08 R08: 0000000000000000 R09: 0000000000000000 +[ 937.458363] R10: 0000000000000000 R11: 0000000000000000 R12: ffff8951cd68aef8 +[ 937.458813] R13: 0000000000000001 R14: 0000000000000000 R15: ffffed5884f9b040 +[ 937.459255] FS: 00007cfa2a7ec640(0000) GS:ffff8954efc80000(0000) knlGS:0000000000000000 +[ 937.459694] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 +[ 937.460133] CR2: 000072bd02ffd658 CR3: 0000000116ff0002 CR4: 00000000003706e0 +``` + +To avoid this issue, run the tests from a non-FUSE file system. + +## License + +This Kernel Module is available as open source under the terms of +the [GPL v3 License](https://www.gnu.org/licenses/gpl-3.0.en.html). + +## Project Managed By: + +[![https://loopholelabs.io][loopholelabs]](https://loopholelabs.io) + +[loopholelabs]: https://cdn.loopholelabs.io/loopholelabs/LoopholeLabsLogo.svg +[loophomepage]: https://loopholelabs.io +[man_errno]: https://man7.org/linux/man-pages/man3/errno.3.html +[man_ioctl]: https://www.man7.org/linux/man-pages/man2/ioctl.2.html diff --git a/kmod/pagefault/device.h b/kmod/pagefault/device.h new file mode 100644 index 00000000..3c24b57a --- /dev/null +++ b/kmod/pagefault/device.h @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-3.0 + +#ifndef SILO_DEVICE_H +#define SILO_DEVICE_H + +#define MAGIC 'p' +#define IOCTL_OVERLAY_REQ_CMD _IOWR(MAGIC, 1, struct overlay_req *) +#define IOCTL_OVERLAY_CLEANUP_CMD _IOWR(MAGIC, 2, struct overlay_cleanup_req *) + +static const char device_path[] = "/dev/silo_pagefault"; + +struct overlay_segment_req { + unsigned long start_pgoff; + unsigned long end_pgoff; +}; + +struct overlay_req { + unsigned long id; + + unsigned long base_addr; + unsigned long overlay_addr; + + unsigned int segments_size; + struct overlay_segment_req *segments; +}; + +struct overlay_cleanup_req { + unsigned long id; +}; + +#endif //SILO_DEVICE_H diff --git a/kmod/pagefault/hashtable.c b/kmod/pagefault/hashtable.c new file mode 100644 index 00000000..52c2508f --- /dev/null +++ b/kmod/pagefault/hashtable.c @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: GPL-3.0 + +#include +#include +#include + +#include "hashtable.h" +#include "log.h" + +const static struct rhashtable_params hashtable_object_params = { + .key_len = sizeof(unsigned long), + .key_offset = offsetof(struct hashtable_object, key), + .head_offset = offsetof(struct hashtable_object, linkage), +}; + +void hashtable_object_free_fn(void *ptr, void *arg) +{ + START_FOLLOW; + kvfree(ptr); + END_FOLLOW; +} + +struct hashtable *hashtable_setup(void (*free)(void *data)) +{ + START_FOLLOW; + struct hashtable *hashtable = kvmalloc(sizeof(struct hashtable), GFP_KERNEL); + if (!hashtable) { + log_crit("unable to allocate memory for hashtable"); + END_FOLLOW; + return NULL; + } + generate_random_uuid(hashtable->id); + hashtable->free = free; + int ret = rhashtable_init(&hashtable->rhashtable, &hashtable_object_params); + if (ret) { + log_crit("unable to initialize hashtable with id '%pUB': '%d'", hashtable->id, ret); + kvfree(hashtable); + END_FOLLOW; + return NULL; + } + END_FOLLOW; + return hashtable; +} + +int hashtable_insert(struct hashtable *hashtable, const unsigned long key, void *data) +{ + START_FOLLOW; + struct hashtable_object *object = kvmalloc(sizeof(struct hashtable_object), GFP_KERNEL); + if (!object) { + log_error("unable to allocate memory for hashtable object for hashtable with id '%pUB'", hashtable->id); + END_FOLLOW; + return -ENOMEM; + } + object->data = data; + object->key = key; + log_debug("inserting hashtable object with key '%lu' for hashtable with id '%pUB'", key, hashtable->id); + int ret = rhashtable_lookup_insert_fast(&hashtable->rhashtable, &object->linkage, hashtable_object_params); + END_FOLLOW; + return ret; +} + +void *hashtable_lookup(struct hashtable *hashtable, const unsigned long key) +{ + START_FOLLOW; + void *data = NULL; + rcu_read_lock(); + struct hashtable_object *object = rhashtable_lookup(&hashtable->rhashtable, &key, hashtable_object_params); + if (object) { + data = object->data; + } else { + log_debug("hashtable object with key '%lu' not found for hashtable with id '%pUB'", key, hashtable->id); + } + rcu_read_unlock(); + END_FOLLOW; + return data; +} + +void *hashtable_delete(struct hashtable *hashtable, const unsigned long key) +{ + START_FOLLOW; + void *ret = NULL; + rcu_read_lock(); + struct hashtable_object *object = rhashtable_lookup(&hashtable->rhashtable, &key, hashtable_object_params); + if (object) { + if (!rhashtable_remove_fast(&hashtable->rhashtable, &object->linkage, hashtable_object_params)) { + ret = object->data; + kvfree_rcu(object, rcu_read); + log_debug("removed hashtable object '%lu' for hashtable with id '%pUB'", key, hashtable->id); + } else { + log_error("unable to remove hashtable object '%lu' for hashtable with id '%pUB'", key, + hashtable->id); + } + } else { + log_debug("hashtable object with key '%lu' not found for hashtable with id '%pUB'", key, hashtable->id); + } + rcu_read_unlock(); + END_FOLLOW; + return ret; +} + +void hashtable_cleanup(struct hashtable *hashtable) +{ + START_FOLLOW; + if (hashtable->free) { + log_debug("freeing hashtable with id '%pUB'", hashtable->id); + struct rhashtable_iter iter; + struct hashtable_object *object; + rhashtable_walk_enter(&hashtable->rhashtable, &iter); + rhashtable_walk_start(&iter); + while ((object = rhashtable_walk_next(&iter)) != NULL) { + if (IS_ERR(object)) { + log_warn("found an error object while walking through hashtable with id '%pUB'", + hashtable->id); + continue; + } + rhashtable_walk_stop(&iter); + log_debug("freeing hashtable object with key '%lu' for hashtable with id '%pUB'", object->key, + hashtable->id); + hashtable->free(object->data); + rhashtable_walk_start(&iter); + } + rhashtable_walk_stop(&iter); + rhashtable_walk_exit(&iter); + } + rhashtable_free_and_destroy(&hashtable->rhashtable, &hashtable_object_free_fn, NULL); + kvfree(hashtable); + END_FOLLOW; +} diff --git a/kmod/pagefault/hashtable.h b/kmod/pagefault/hashtable.h new file mode 100644 index 00000000..b12ead8b --- /dev/null +++ b/kmod/pagefault/hashtable.h @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-3.0 + +#ifndef SILO_HASHTABLE_H +#define SILO_HASHTABLE_H + +#ifndef UUID_SIZE +#define UUID_SIZE 16 +#endif + +#include +#include + +struct hashtable_object { + unsigned long key; + struct rhash_head linkage; + void *data; + struct rcu_head rcu_read; +}; + +struct hashtable { + unsigned char id[UUID_SIZE]; + struct rhashtable rhashtable; + void (*free)(void *ptr); +}; + +struct hashtable *hashtable_setup(void (*free)(void *ptr)); +int hashtable_insert(struct hashtable *hashtable, const unsigned long key, void *data); +void *hashtable_lookup(struct hashtable *hashtable, const unsigned long key); +void *hashtable_delete(struct hashtable *hashtable, const unsigned long key); +void hashtable_cleanup(struct hashtable *hashtable); + +#endif //SILO_HASHTABLE_H diff --git a/kmod/pagefault/log.c b/kmod/pagefault/log.c new file mode 100644 index 00000000..4e74c24e --- /dev/null +++ b/kmod/pagefault/log.c @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: GPL-3.0 + +#include "log.h" diff --git a/kmod/pagefault/log.h b/kmod/pagefault/log.h new file mode 100644 index 00000000..0c2c35a8 --- /dev/null +++ b/kmod/pagefault/log.h @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-3.0 + +#ifndef SILO_LOG_H +#define SILO_LOG_H + +#define _log_prepend_crit "[silo_pagefault (CRIT)]:" +#define _log_prepend_error "[silo_pagefault (ERROR)]:" +#define _log_prepend_warn "[silo_pagefault (WARN)]:" +#define _log_prepend_info "[silo_pagefault (INFO)]:" +#define _log_prepend_debug "[silo_pagefault (DEBUG)]:" +#define _log_prepend_trace "[silo_pagefault (TRACE)]:" +#define _log_prepend_follow "[silo_pagefault (FOLLOW)]:" + +#define log_crit(fmt, ...) \ + printk(KERN_CRIT _log_prepend_crit " " fmt "\n" __VA_OPT__(, ) \ + __VA_ARGS__) +#define log_error(fmt, ...) \ + printk(KERN_ERR _log_prepend_error " " fmt "\n" __VA_OPT__(, ) \ + __VA_ARGS__) +#define log_warn(fmt, ...) \ + printk(KERN_WARNING _log_prepend_warn " " fmt "\n" __VA_OPT__(, ) \ + __VA_ARGS__) + +#if LOG_LEVEL > 0 +#define log_info(fmt, ...) \ + printk(KERN_INFO _log_prepend_info " " fmt "\n" __VA_OPT__(, ) \ + __VA_ARGS__) +#else +#define log_info(fmt, ...) +#endif + +#if LOG_LEVEL > 1 +#define log_debug(fmt, ...) \ + printk(KERN_DEBUG _log_prepend_debug " " fmt "\n" __VA_OPT__(, ) \ + __VA_ARGS__) +#else +#define log_debug(fmt, ...) +#endif + +#if LOG_LEVEL > 2 +#define log_trace(fmt, ...) \ + printk(KERN_DEBUG _log_prepend_trace " " fmt "\n" __VA_OPT__(, ) \ + __VA_ARGS__) +#else +#define log_trace(fmt, ...) +#endif + +#if LOG_LEVEL > 3 +#define log_follow(fmt, ...) \ + printk(KERN_DEBUG _log_prepend_follow " " fmt "\n" __VA_OPT__(, ) \ + __VA_ARGS__) +#else +#define log_follow(fmt, ...) +#endif + +#define START_FOLLOW log_follow("start '%s'", __func__) +#define END_FOLLOW log_follow("end '%s'", __func__) + +#endif //SILO_LOG_H diff --git a/kmod/pagefault/module.c b/kmod/pagefault/module.c new file mode 100644 index 00000000..f76029bd --- /dev/null +++ b/kmod/pagefault/module.c @@ -0,0 +1,388 @@ +// SPDX-License-Identifier: GPL-3.0 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "module.h" +#include "device.h" +#include "hashtable.h" +#include "log.h" + +MODULE_AUTHOR("Loophole Labs (Shivansh Vij, Luiz Aoqui)"); +MODULE_DESCRIPTION("Silo Page Fault Handler"); +MODULE_LICENSE("GPL"); + +static struct hashtable *overlays; + +static vm_fault_t hijacked_map_pages(struct vm_fault *vmf, pgoff_t start_pgoff, pgoff_t end_pgoff) +{ + unsigned long id = (unsigned long)vmf->vma; + log_debug("page fault page=%lu start=%lu end=%lu id=%lu", vmf->pgoff, start_pgoff, end_pgoff, id); + struct overlay *overlay = hashtable_lookup(overlays, id); + if (!overlay) { + log_error("unable to find overlay id=%lu", id); + return VM_FAULT_SIGBUS; + } + + XA_STATE(xas, &overlay->segments, start_pgoff); + struct overlay_segment *seg; + vm_fault_t ret; + pgoff_t end; + + rcu_read_lock(); + for (pgoff_t start = start_pgoff; start <= end_pgoff; start = end + 1) { + do { + seg = xas_find(&xas, end_pgoff); + } while (xas_retry(&xas, seg)); + + // The range doesn't overlap with any segment, so handle it like a + // normal page fault. + if (seg == NULL) { + end = end_pgoff; + log_debug("handling base page fault start=%lu end=%lu id=%lu", start, end, id); + ret = filemap_map_pages(vmf, start, end); + break; + } + + // Handle any non-overlay range before the next segment. + if (start < seg->start_pgoff) { + end = seg->start_pgoff - 1; + log_debug("handling base page fault start=%lu end=%lu id=%lu", start, end, id); + ret = filemap_map_pages(vmf, start, end); + if (ret & VM_FAULT_ERROR) { + break; + } + start = end + 1; + } + + // Handle fault over overlay range. + end = min(seg->end_pgoff, end_pgoff); + log_debug("handling overlay page fault start=%lu end=%lu id=%lu", start, end, id); + + // Make a copy of the target VMA to change its source file without + // affecting any potential concurrent reader. + struct vm_area_struct *vma_orig = vmf->vma; + struct vm_area_struct vma_copy; + memcpy(&vma_copy, vmf->vma, sizeof(struct vm_area_struct)); + vma_copy.vm_file = seg->overlay_vma->vm_file; + + // Use a pointer to the vmf->vma pointer to alter its reference since + // this field is marked as a const. + struct vm_area_struct **vma_p = (struct vm_area_struct **)&vmf->vma; + *vma_p = &vma_copy; + ret = filemap_map_pages(vmf, start, end); + *vma_p = vma_orig; + if (ret & VM_FAULT_ERROR) { + break; + } + } + rcu_read_unlock(); + return ret; +} + +static void cleanup_overlay_segments(struct xarray segments) +{ + unsigned long i; + struct overlay_segment *seg; + xa_for_each(&segments, i, seg) { + kvfree(seg); + i = seg->end_pgoff + 1; + } + xa_destroy(&segments); +} + +/* + * Free memory used by an overlay entry. If the process that owns the + * memory can be assumed to still be running, a mm mmap write lock should be + * held before calling this function. + */ +static void cleanup_overlay(void *data) +{ + struct overlay *overlay = (struct overlay *)data; + + // Revert base VMA vm_ops to its original value in case the VMA is used + // after cleanup (usually to call ->close() on unmap). + const struct vm_operations_struct *vm_ops = overlay->base_vma->vm_ops; + if (vm_ops != NULL && vm_ops->map_pages == hijacked_map_pages) { + overlay->base_vma->vm_ops = overlay->original_vm_ops; + } + + kvfree(overlay->hijacked_vm_ops); + cleanup_overlay_segments(overlay->segments); + kvfree(overlay); +} + +static int device_open(struct inode *device_file, struct file *instance) +{ + return 0; +} + +static int device_close(struct inode *device_file, struct file *instance) +{ + return 0; +} + +static long int unlocked_ioctl_handle_overlay_req(unsigned long arg) +{ + long int res = 0; + + // Read request data from userspace. + struct overlay_req req; + unsigned long ret = copy_from_user(&req, (struct overlay_req *)arg, sizeof(struct overlay_req)); + if (ret) { + log_error("failed to copy overlay request from user: %lu", ret); + return -EFAULT; + } + + // Acquire mm write lock since we expect to mutate the base VMA. + // TODO: support per-VMA locking (https://lwn.net/Articles/937943/). + mmap_write_lock(current->mm); + + // Find base and overlay VMAs. + struct vm_area_struct *overlay_vma = find_vma(current->mm, req.overlay_addr); + if (overlay_vma == NULL || overlay_vma->vm_start > req.overlay_addr) { + log_error("failed to find overlay VMA"); + res = -EINVAL; + goto out; + } + + struct vm_area_struct *base_vma = find_vma(current->mm, req.base_addr); + if (base_vma == NULL || base_vma->vm_start > req.base_addr) { + log_error("failed to find base VMA"); + res = -EINVAL; + goto out; + } + unsigned long id = (unsigned long)base_vma; + + // Check if VMA is already stored. + struct overlay *overlay = hashtable_lookup(overlays, id); + if (overlay) { + if (base_vma->vm_ops->map_pages == hijacked_map_pages) { + log_error("overlay already exists"); + res = -EEXIST; + goto out; + } + + // Leftover overlay, delete from state and proceed. + cleanup_overlay(overlay); + hashtable_delete(overlays, id); + overlay = NULL; + } + + // Read overlay segments from request. + struct overlay_segment_req *segs = kvzalloc(sizeof(struct overlay_segment) * req.segments_size, GFP_KERNEL); + if (!segs) { + log_error("failed to allocate segments"); + res = -ENOMEM; + goto out; + } + ret = copy_from_user(segs, req.segments, sizeof(struct overlay_segment_req) * req.segments_size); + if (ret) { + log_error("failed to copy overlay segments request from user: %lu", ret); + res = -EFAULT; + goto free_segs; + } + + log_debug("received overlay request base_addr=%lu overlay_addr=%lu", req.base_addr, req.overlay_addr); + + // Create new overlay instance. + overlay = kvzalloc(sizeof(struct overlay), GFP_KERNEL); + if (!overlay) { + log_error("failed to allocate memory for overlay"); + res = -ENOMEM; + goto free_segs; + } + + overlay->base_addr = req.base_addr; + xa_init(&(overlay->segments)); + + struct overlay_segment *seg; + for (int i = 0; i < req.segments_size; i++) { + unsigned long start = segs[i].start_pgoff; + unsigned long end = segs[i].end_pgoff; + + seg = kvzalloc(sizeof(struct overlay_segment), GFP_KERNEL); + if (!seg) { + log_error("failed to allocate memory for overlay segment start=%lu end=%lu", start, end); + res = -ENOMEM; + goto cleanup_segments; + } + + seg->start_pgoff = start; + seg->end_pgoff = end; + seg->overlay_addr = req.overlay_addr; + seg->overlay_vma = overlay_vma; + + log_debug("inserting segment to overlay start=%lu end=%lu", start, end); + xa_store_range(&overlay->segments, start, end, seg, GFP_KERNEL); + } + + // Hijack page fault handler for base VMA. + log_info("hijacking vm_ops for base VMA addr=0x%lu", req.base_addr); + overlay->hijacked_vm_ops = kvzalloc(sizeof(struct vm_operations_struct), GFP_KERNEL); + if (!overlay->hijacked_vm_ops) { + log_error("failed to allocate memory for hijacked vm_ops"); + res = -ENOMEM; + goto cleanup_segments; + } + + // Store base VMA and original vm_ops (so we can restore it on cleanup). + overlay->base_vma = base_vma; + overlay->original_vm_ops = base_vma->vm_ops; + + memcpy(overlay->hijacked_vm_ops, base_vma->vm_ops, sizeof(struct vm_operations_struct)); + overlay->hijacked_vm_ops->map_pages = hijacked_map_pages; + base_vma->vm_ops = overlay->hijacked_vm_ops; + log_info("done hijacking vm_ops addr=0x%lu", req.base_addr); + + // Save overlay into hashtable. + int iret = hashtable_insert(overlays, id, overlay); + if (iret) { + log_error("failed to insert overlay into hashtable: %d", iret); + res = -EFAULT; + goto revert_vm_ops; + } + + // Return ID to userspace request. + req.id = id; + ret = copy_to_user((struct overlay_req *)arg, &req, sizeof(struct overlay_req)); + if (ret) { + log_error("failed to copy overlay ID to user: %lu", ret); + res = -EFAULT; + goto revert_vm_ops; + } + + log_info("overlay created successfully id=%lu", id); + goto free_segs; + +revert_vm_ops: + base_vma->vm_ops = overlay->original_vm_ops; + kvfree(overlay->hijacked_vm_ops); +cleanup_segments: + cleanup_overlay_segments(overlay->segments); + kvfree(overlay); +free_segs: + kvfree(segs); +out: + mmap_write_unlock(current->mm); + return res; +} + +static long int unlocked_ioctl_handle_overlay_cleanup_req(unsigned long arg) +{ + struct overlay_cleanup_req req; + unsigned long ret = + copy_from_user(&req, (struct overlay_cleanup_req *)arg, sizeof(struct overlay_cleanup_req)); + if (ret) { + log_error("failed to copy overlay cleanup request from user: %lu", ret); + return -EFAULT; + } + + struct overlay *overlay = hashtable_delete(overlays, req.id); + if (!overlay) { + log_error("failed to cleanup overlay id=%lu", req.id); + return -ENOENT; + } + + struct mm_struct *mm = overlay->base_vma->vm_mm; + mmap_write_lock(mm); + cleanup_overlay(overlay); + mmap_write_unlock(mm); + + log_info("overlay removed successfully id=%lu", req.id); + return 0; +} + +static long int unlocked_ioctl(struct file *file, unsigned cmd, unsigned long arg) +{ + switch (cmd) { + case IOCTL_OVERLAY_REQ_CMD: + log_debug("called IOCTL_OVERLAY_REQ_CMD"); + return unlocked_ioctl_handle_overlay_req(arg); + case IOCTL_OVERLAY_CLEANUP_CMD: + log_debug("called IOCTL_OVERLAY_CLEANUP_CMD"); + return unlocked_ioctl_handle_overlay_cleanup_req(arg); + default: + log_error("unknown ioctl cmd %x", cmd); + } + return -EINVAL; +} + +static struct file_operations file_ops = { .owner = THIS_MODULE, + .open = device_open, + .release = device_close, + .unlocked_ioctl = unlocked_ioctl }; + +static unsigned int major; +static dev_t device_number; +static struct class *device_class; + +static int __init init_mod(void) +{ + START_FOLLOW; + overlays = hashtable_setup(&cleanup_overlay); + log_info("registering device with major %u and ID '%s'", (unsigned int)MAJOR_DEV, DEVICE_ID); + int ret = register_chrdev(MAJOR_DEV, DEVICE_ID, &file_ops); + if (!ret) { + major = MAJOR_DEV; + log_info("registered device (major %d, minor %d)", major, 0); + device_number = MKDEV(major, 0); + } else if (ret > 0) { + major = ret >> 20; + log_info("registered device (major %d, minor %d)", major, ret & 0xfffff); + device_number = MKDEV(major, ret & 0xfffff); + } else { + log_error("unable to register device: %d", ret); + return ret; + } + + log_debug("creating device class with ID '%s'", DEVICE_ID); + device_class = class_create(DEVICE_ID); + if (IS_ERR(device_class)) { + log_error("unable to create device class"); + unregister_chrdev(major, DEVICE_ID); + return -EINVAL; + } + + log_debug("creating device with id '%s'", DEVICE_ID); + struct device *device = device_create(device_class, NULL, device_number, NULL, DEVICE_ID); + if (IS_ERR(device)) { + log_error("unable to create device"); + class_destroy(device_class); + unregister_chrdev(major, DEVICE_ID); + return -EINVAL; + } + END_FOLLOW; + return 0; +} + +static void __exit exit_mod(void) +{ + START_FOLLOW; + if (overlays) { + log_info("cleaning up overlays hashtable"); + hashtable_cleanup(overlays); + overlays = NULL; + } + log_info("unregistering device with major %u and ID '%s'", (unsigned int)major, DEVICE_ID); + device_destroy(device_class, device_number); + class_destroy(device_class); + unregister_chrdev(major, DEVICE_ID); + END_FOLLOW; +} + +module_init(init_mod); +module_exit(exit_mod); diff --git a/kmod/pagefault/module.h b/kmod/pagefault/module.h new file mode 100644 index 00000000..c728b71f --- /dev/null +++ b/kmod/pagefault/module.h @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-3.0 + +#include + +#ifndef SILO_MODULE_H +#define SILO_MODULE_H + +#define MAJOR_DEV 64 +#define DEVICE_ID "silo_pagefault" + +struct overlay_segment { + unsigned long overlay_addr; + struct vm_area_struct *overlay_vma; + + unsigned long start_pgoff; + unsigned long end_pgoff; +}; + +struct overlay { + unsigned long base_addr; + struct vm_area_struct *base_vma; + struct xarray segments; + + const struct vm_operations_struct *original_vm_ops; + struct vm_operations_struct *hijacked_vm_ops; +}; + +#endif //SILO_MODULE_H diff --git a/kmod/pagefault/tests/Makefile b/kmod/pagefault/tests/Makefile new file mode 100644 index 00000000..38d183e9 --- /dev/null +++ b/kmod/pagefault/tests/Makefile @@ -0,0 +1,56 @@ +tests = page_fault \ + page_fault_multithread \ + page_fault_multithread_ioctl \ + page_fault_benchmark \ + page_fault_fork \ + page_fault_ioctl_error + +all: $(tests) + +ifdef VERIFY + CFLAGS += -DVERIFY +endif + +%.out: page_fault/%.c ../device.h + gcc ${CFLAGS} $< -I../ -o $@ + +.PHONY: binaries +binaries: $(addsuffix .out,$(tests)) + +.PHONY: page_fault +page_fault: page_fault.out + sudo sysctl -w vm.max_map_count=8388608 + sudo ./page_fault.out + +.PHONY: page_fault_multithread +page_fault_multithread: page_fault_multithread.out + sudo sysctl -w vm.max_map_count=8388608 + sudo ./page_fault_multithread.out + +.PHONY: page_fault_multithread_ioctl +page_fault_multithread_ioctl: page_fault_multithread_ioctl.out + sudo sysctl -w vm.max_map_count=8388608 + sudo ./page_fault_multithread_ioctl.out + +.PHONY: page_fault_fork +page_fault_fork: page_fault_fork.out + sudo sysctl -w vm.max_map_count=8388608 + sudo ./page_fault_fork.out + +.PHONY: page_fault_benchmark +page_fault_benchmark: page_fault_benchmark.out + sudo sysctl -w vm.max_map_count=8388608 + sudo ./page_fault_benchmark.out + +.PHONY: page_fault_ioctl_error +page_fault_ioctl_error: page_fault_ioctl_error.out + sudo sysctl -w vm.max_map_count=8388608 + sudo ./page_fault_ioctl_error.out + +.PHONY: generate +generate: + go run generate.go + +.PHONY: clean +clean: + rm -rf *.out *.bin diff --git a/kmod/pagefault/tests/generate.go b/kmod/pagefault/tests/generate.go new file mode 100644 index 00000000..847bb177 --- /dev/null +++ b/kmod/pagefault/tests/generate.go @@ -0,0 +1,117 @@ +/* + Copyright (C) 2024 Loophole Labs + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +package main + +import ( + "encoding/binary" + "fmt" + "io" + "os" +) + +func main() { + pageSize := os.Getpagesize() + smallSize := pageSize * 1024 + xlSize := smallSize * 1024 + + fmt.Printf("using page size %d bytes with small size %d bytes (%d mB) and XL size %d bytes (%d mB)\n", + pageSize, smallSize, smallSize/1024/1024, xlSize, xlSize/1024/1024) + + files := []struct { + name string + size int + }{ + { + name: "base.bin", + size: smallSize, + }, + { + name: "base2.bin", + size: smallSize, + }, + { + name: "overlay.bin", + size: smallSize, + }, + { + name: "baseXL.bin", + size: xlSize, + }, + { + name: "baseXL2.bin", + size: xlSize, + }, + { + name: "overlayXL.bin", + size: xlSize, + }, + } + + for _, f := range files { + fmt.Printf("creating '%s'\n", f.name) + out, err := os.OpenFile(f.name, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, os.ModePerm) + if err != nil { + panic(err) + } + defer out.Close() + + in, err := os.Open("/dev/random") + if err != nil { + panic(err) + } + defer in.Close() + + if _, err := io.CopyN(out, in, int64(f.size)); err != nil { + panic(err) + } + } + + fmt.Println("creating 'overlay_zebra.bin'") + { + out, err := os.OpenFile("overlay_zebra.bin", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, os.ModePerm) + if err != nil { + panic(err) + } + defer out.Close() + + bufferSize := pageSize + + var one uint8 = 0xFF + var zero uint8 = 0x00 + ones := make([]byte, bufferSize) + zeros := make([]byte, bufferSize) + for i := 0; i < bufferSize; i++ { + ones[i] = one + zeros[i] = zero + } + + for i := 0; i < smallSize/bufferSize; i++ { + if i%2 == 0 { + err = binary.Write(out, binary.LittleEndian, zeros) + if err != nil { + panic(err) + } + } else { + err = binary.Write(out, binary.LittleEndian, ones) + if err != nil { + panic(err) + } + } + } + } +} diff --git a/kmod/pagefault/tests/page_fault/page_fault.c b/kmod/pagefault/tests/page_fault/page_fault.c new file mode 100644 index 00000000..2caed0b0 --- /dev/null +++ b/kmod/pagefault/tests/page_fault/page_fault.c @@ -0,0 +1,345 @@ +// SPDX-License-Identifier: GPL-3.0 + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "../../device.h" + +struct test_case { + unsigned long pgoff; + int fd; + char *data; +}; + +size_t PAGE_SIZE, TOTAL_SIZE; + +bool verify_test_cases(struct test_case *tcs, int tcs_nr, int base_fd, char *base_map) +{ + char *buffer = malloc(PAGE_SIZE); + memset(buffer, 0, PAGE_SIZE); + bool valid = true; + + for (unsigned long pgoff = 0; pgoff < TOTAL_SIZE / PAGE_SIZE; pgoff++) { + size_t offset = pgoff * PAGE_SIZE; + + struct test_case *tc = NULL; + for (int i = 0; i < tcs_nr; i++) { + if (tcs[i].pgoff == pgoff) { + tc = &tcs[i]; + break; + } + } + + int fd = base_fd; + if (tc != NULL) { + if (tc->fd > 0) { + fd = tc->fd; + printf("checking if page %lu is from overlay\n", pgoff); + } else if (tc->data) { + printf("checking if page %lu has expected data\n", pgoff); + memcpy(buffer, tc->data, PAGE_SIZE); + fd = -1; + } + } + + if (fd > 0) { + lseek(fd, offset, SEEK_SET); + read(fd, buffer, PAGE_SIZE); + } + + if (memcmp(base_map + offset, buffer, PAGE_SIZE)) { + printf("== ERROR: base memory does not match the file contents at page %lu\n", pgoff); + valid = false; + break; + } + memset(buffer, 0, PAGE_SIZE); + } + + free(buffer); + return valid; +} + +void clear_cache() +{ + sync(); + int cache_fd = open("/proc/sys/vm/drop_caches", O_WRONLY); + write(cache_fd, "3", 1); + close(cache_fd); +} + +int mmap_file(char *filename, size_t size, int *fd, char **mmap_addr) +{ + *fd = open(filename, O_RDONLY); + if (*fd < 0) { + printf("ERROR: could not open file %s: %s\n", filename, strerror(errno)); + return EXIT_FAILURE; + } + + *mmap_addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, *fd, 0); + if (*mmap_addr == MAP_FAILED) { + printf("ERROR: could not mmap file %s: %s\n", filename, strerror(errno)); + close(*fd); + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} + +int call_kmod(unsigned long cmd, void *req) +{ + int syscall_dev = open(device_path, O_WRONLY); + if (syscall_dev < 0) { + printf("ERROR: could not open %s: %s\n", device_path, strerror(errno)); + return EXIT_FAILURE; + } + + int result = ioctl(syscall_dev, cmd, req); + if (result) { + printf("ERROR: could not call command %lu: %s\n", cmd, strerror(errno)); + close(syscall_dev); + return EXIT_FAILURE; + } + + close(syscall_dev); + return EXIT_SUCCESS; +} + +int test_memory_read() +{ + clear_cache(); + + // Read base.bin test file and map it into memory. + int base_fd; + char *base_mmap; + if (mmap_file("base.bin", TOTAL_SIZE, &base_fd, &base_mmap)) { + return EXIT_FAILURE; + } + + int res = EXIT_SUCCESS; + // mmap base.bin test file again in an area that will not be modified. + char *clean_base_mmap = mmap(NULL, TOTAL_SIZE, PROT_READ, MAP_PRIVATE, base_fd, 0); + if (clean_base_mmap == MAP_FAILED) { + printf("ERROR: could not map clean base file %s: %s\n", "base.bin", strerror(errno)); + res = EXIT_FAILURE; + goto unmap_base; + } + printf("mapped clean base file %s\n", "base.bin"); + + // Read overlay.bin test file and map it into memory. + int overlay_fd; + char *overlay_mmap; + if (mmap_file("overlay.bin", TOTAL_SIZE, &overlay_fd, &overlay_mmap)) { + res = EXIT_FAILURE; + goto unmap_clean_base; + } + + // Create test memory overlay request with several overlay scenarios. + struct overlay_req req; + req.base_addr = *(unsigned long *)(&base_mmap); + req.overlay_addr = *(unsigned long *)(&overlay_mmap); + req.segments_size = 6; + req.segments = calloc(sizeof(struct overlay_segment_req), req.segments_size); + + // Overlay single page. + req.segments[0].start_pgoff = 0; + req.segments[0].end_pgoff = 0; + + // Overlay multiple pages. + req.segments[1].start_pgoff = 4; + req.segments[1].end_pgoff = 6; + + // Two overlays back-to-back. + req.segments[2].start_pgoff = 20; + req.segments[2].end_pgoff = 20; + req.segments[3].start_pgoff = 21; + req.segments[3].end_pgoff = 21; + + // Large overlay that crosses fault-around and xa_store_range limits. + req.segments[4].start_pgoff = 30; + req.segments[4].end_pgoff = 70; + + // Another large overlay to make sure both ranges are cleaned up properly. + req.segments[5].start_pgoff = 80; + req.segments[5].end_pgoff = 140; + + if (call_kmod(IOCTL_OVERLAY_REQ_CMD, &req)) { + res = EXIT_FAILURE; + goto free_segments; + } + + // Create expected read results. + // Every page in a segment range should have data from the overlay file. + int tcs_nr = 0; + for (int i = 0; i < req.segments_size; i++) { + struct overlay_segment_req seg = req.segments[i]; + tcs_nr += seg.end_pgoff - seg.start_pgoff + 1; + } + + struct test_case *tcs = calloc(sizeof(struct test_case), tcs_nr); + int tcs_n = 0; + for (int i = 0; i < req.segments_size; i++) { + struct overlay_segment_req seg = req.segments[i]; + + for (int pgoff = seg.start_pgoff; pgoff <= seg.end_pgoff; pgoff++) { + tcs[tcs_n].pgoff = pgoff; + tcs[tcs_n].fd = overlay_fd; + tcs_n++; + } + } + + // Verify memory overlays properly. + printf("= TEST: checking memory contents with overlay\n"); + if (!verify_test_cases(tcs, tcs_nr, base_fd, base_mmap)) { + res = EXIT_FAILURE; + goto free_tcs; + } + printf("== OK: overlay memory verification completed successfully!\n"); + + // Verify clean base map was not modified. + printf("= TEST: checking memory contents without overlay\n"); + if (!verify_test_cases(NULL, 0, base_fd, clean_base_mmap)) { + res = EXIT_FAILURE; + goto free_tcs; + } + printf("== OK: non-overlay memory verification completed successfully!\n"); + +free_tcs: + free(tcs); + + struct overlay_cleanup_req cleanup_req = { + .id = req.id, + }; + if (call_kmod(IOCTL_OVERLAY_CLEANUP_CMD, &cleanup_req)) + res = EXIT_FAILURE; +free_segments: + free(req.segments); + munmap(overlay_mmap, TOTAL_SIZE); +unmap_clean_base: + munmap(clean_base_mmap, TOTAL_SIZE); +unmap_base: + munmap(base_mmap, TOTAL_SIZE); + close(base_fd); + + return res; +} + +int test_memory_write() +{ + clear_cache(); + int res = EXIT_SUCCESS; + + // Read base.bin test file and map it into memory. + int base_fd; + char *base_mmap; + if (mmap_file("base.bin", TOTAL_SIZE, &base_fd, &base_mmap)) { + return EXIT_FAILURE; + } + + // Read overlay.bin test file and map it into memory. + int overlay_fd; + char *overlay_mmap; + if (mmap_file("overlay.bin", TOTAL_SIZE, &overlay_fd, &overlay_mmap)) { + res = EXIT_FAILURE; + goto unmap_base; + } + + // Create test memory overlay request with an overlay that covers multiple + // pages so we can write in the middle of the area. + struct overlay_req req; + req.base_addr = *(unsigned long *)(&base_mmap); + req.overlay_addr = *(unsigned long *)(&overlay_mmap); + req.segments_size = 1; + req.segments = calloc(sizeof(struct overlay_segment_req), req.segments_size); + + req.segments[0].start_pgoff = 4; + req.segments[0].end_pgoff = 6; + + if (call_kmod(IOCTL_OVERLAY_REQ_CMD, &req)) { + res = EXIT_FAILURE; + goto free_segments; + }; + + // Write random data to different areas of the base memory map. + int rand_fd = open("/dev/random", O_RDONLY); + if (rand_fd < 0) { + printf("ERROR: could not open /dev/random: %d\n", rand_fd); + res = EXIT_FAILURE; + goto cleanup_kmod; + } + + char *rand = calloc(PAGE_SIZE, 1); + if (read(rand_fd, rand, PAGE_SIZE) < 0) { + printf("ERROR: failed to read /dev/random: %s\n", strerror(errno)); + res = EXIT_FAILURE; + goto close_rand; + } + + // Write to overlay page. + memcpy(base_mmap + PAGE_SIZE * 5, rand, PAGE_SIZE); + // Write to non-overlay page. + memcpy(base_mmap + PAGE_SIZE * 10, rand, PAGE_SIZE); + + // Create expected results. + // Pages 5 and 10 should have the random data. + // Pages 4 and 6 should have overlay data. + int tcs_nr = 4; + struct test_case *tcs = calloc(sizeof(struct test_case), tcs_nr); + tcs[0].pgoff = 4; + tcs[0].fd = overlay_fd; + tcs[1].pgoff = 5; + tcs[1].data = rand; + tcs[2].pgoff = 6; + tcs[2].fd = overlay_fd; + tcs[3].pgoff = 10; + tcs[3].data = rand; + + printf("= TEST: checking memory write\n"); + if (!verify_test_cases(tcs, tcs_nr, base_fd, base_mmap)) { + res = EXIT_FAILURE; + goto free_tcs; + } + printf("== OK: memory write verification completed successfully!\n"); + +free_tcs: + free(tcs); + free(rand); +close_rand: + close(rand_fd); +cleanup_kmod:; + struct overlay_cleanup_req cleanup_req = { + .id = req.id, + }; + if (call_kmod(IOCTL_OVERLAY_CLEANUP_CMD, &cleanup_req)) + res = EXIT_FAILURE; +free_segments: + free(req.segments); + munmap(overlay_mmap, TOTAL_SIZE); +unmap_base: + munmap(base_mmap, TOTAL_SIZE); + close(base_fd); + + return res; +} + +int main() +{ + PAGE_SIZE = sysconf(_SC_PAGESIZE); + TOTAL_SIZE = PAGE_SIZE * 1024; + printf("Using pagesize %lu with total size %lu\n", PAGE_SIZE, TOTAL_SIZE); + + if (test_memory_read()) + return EXIT_FAILURE; + if (test_memory_write()) + return EXIT_FAILURE; + + // TODO: parse /proc//smaps to verify memory sharing. + + return EXIT_SUCCESS; +} diff --git a/kmod/pagefault/tests/page_fault/page_fault_benchmark.c b/kmod/pagefault/tests/page_fault/page_fault_benchmark.c new file mode 100644 index 00000000..7dbb2f1b --- /dev/null +++ b/kmod/pagefault/tests/page_fault/page_fault_benchmark.c @@ -0,0 +1,255 @@ +// SPDX-License-Identifier: GPL-3.0 + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include "../../device.h" + +// N represents a memory overlay fragmentation factor. The benchmark setup code +// splits the base memory area into groups of N pages and overlays every other +// group. +// +// The higher the value of N, the larger each memory overlay segment is, and +// fewer segments are created. +// +// The examples below illustrate how the base memory is overlaid for different +// values of N (X marks overlaid pages). +// +// N=2 +// 1 2 3 4 5 6 7 8 +// +---+---+---+---+---+---+---+---+ +// | x | x | | | x | x | | | +// +---+---+---+---+---+---+---+---+ +// | x | x | | | x | x | | | +// +---+---+---+---+---+---+---+---+ +// | x | x | | | x | x | | | +// +---+---+---+---+---+---+---+---+ +// : : : : : : : : : +// +// N=5 +// 1 2 3 4 5 6 7 8 +// +---+---+---+---+---+---+---+---+ +// | x | x | x | x | x | | | | +// +---+---+---+---+---+---+---+---+ +// | | | x | x | x | x | x | | +// +---+---+---+---+---+---+---+---+ +// | | | | | x | x | x | x | +// +---+---+---+---+---+---+---+---+ +// : : : : : : : : : +// +static const int N = 10; + +size_t PAGE_SIZE, TOTAL_SIZE, TOTAL_PAGES; + +static const char BASE_FILE[] = "baseXL.bin"; +static const char CLEAN_BASE_FILE[] = "baseXL2.bin"; +static const char OVERLAY_FILE[] = "overlayXL.bin"; +static const int PAGE_SIZE_FACTOR = 1024 * 1024; + +bool verify_test_cases(int overlay_fd, int base_fd, char *base_map) +{ + char *buffer = calloc(PAGE_SIZE, 1); + bool valid = true; + + struct timespec before, after; + if (clock_gettime(CLOCK_MONOTONIC, &before) < 0) { + printf("ERROR: could not measure 'before' time for base mmap: %s\n", strerror(errno)); + valid = false; + goto out; + } + + printf("%ld.%.9ld: starting memory check\n", before.tv_sec, before.tv_nsec); + + for (unsigned long pgoff = 0; pgoff < TOTAL_PAGES; pgoff++) { + size_t offset = pgoff * PAGE_SIZE; + + int fd = base_fd; + bool is_overlay = pgoff % (2 * N) >= 0 && pgoff % (2 * N) < N; + if (overlay_fd > 0 && is_overlay) { + fd = overlay_fd; + } + lseek(fd, offset, SEEK_SET); + read(fd, buffer, PAGE_SIZE); + + if (memcmp(base_map + offset, buffer, PAGE_SIZE)) { + printf("== ERROR: base memory does not match the file contents at page %lu\n", pgoff); + valid = false; + break; + } + memset(buffer, 0, PAGE_SIZE); + } + + if (clock_gettime(CLOCK_MONOTONIC, &after) < 0) { + printf("ERROR: could not measure 'after' time for base mmap: %s\n", strerror(errno)); + valid = false; + goto out; + } + + printf("%ld.%.9ld: finished memory check\n", after.tv_sec, after.tv_nsec); + + long secs_diff = after.tv_sec - before.tv_sec; + long nsecs_diff = after.tv_nsec; + if (secs_diff == 0) { + nsecs_diff = after.tv_nsec - before.tv_nsec; + } + printf("test verification took %ld.%.9lds\n", secs_diff, nsecs_diff); + +out: + free(buffer); + return valid; +} + +void clear_cache() +{ + sync(); + int cache_fd = open("/proc/sys/vm/drop_caches", O_WRONLY); + write(cache_fd, "3", 1); + close(cache_fd); +} + +int main() +{ + int res = EXIT_SUCCESS; + + PAGE_SIZE = sysconf(_SC_PAGESIZE); + TOTAL_SIZE = PAGE_SIZE * PAGE_SIZE_FACTOR; + TOTAL_PAGES = TOTAL_SIZE / PAGE_SIZE; + printf("Page size: %lu bytes\n", PAGE_SIZE); + printf("Overlay size: %d pages\n", N); + printf("Total size: %lu bytes\n", TOTAL_SIZE); + printf("Total pages: %lu pages\n", TOTAL_PAGES); + + // Read base.bin test file and mmap it into memory. + int base_fd = open(BASE_FILE, O_RDONLY); + if (base_fd < 0) { + printf("ERROR: could not open base file %s: %s\n", BASE_FILE, strerror(errno)); + return EXIT_FAILURE; + } + + int clean_base_fd = open(CLEAN_BASE_FILE, O_RDONLY); + if (clean_base_fd < 0) { + printf("ERROR: could not open clean base file %s: %s\n", CLEAN_BASE_FILE, strerror(errno)); + close(base_fd); + return EXIT_FAILURE; + } + + char *base_mmap = mmap(NULL, TOTAL_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE, base_fd, 0); + if (base_mmap == MAP_FAILED) { + printf("ERROR: could not mmap base file %s: %s\n", BASE_FILE, strerror(errno)); + res = EXIT_FAILURE; + goto close_base; + } + + char *clean_base_mmap = mmap(NULL, TOTAL_SIZE, PROT_READ, MAP_PRIVATE, clean_base_fd, 0); + if (clean_base_mmap == MAP_FAILED) { + printf("ERROR: could not mmap second base file %s: %s\n", CLEAN_BASE_FILE, strerror(errno)); + res = EXIT_FAILURE; + goto close_base; + } + + // Read overlay test file and create memory overlay request. + int overlay_fd = open(OVERLAY_FILE, O_RDONLY); + if (overlay_fd < 0) { + printf("ERROR: could not open overlay file %s: %s\n", OVERLAY_FILE, strerror(errno)); + res = EXIT_FAILURE; + goto unmap_base; + } + + char *overlay_map = mmap(NULL, TOTAL_SIZE, PROT_READ, MAP_PRIVATE, overlay_fd, 0); + if (overlay_map == MAP_FAILED) { + printf("ERROR: could not mmap overlay file %s: %s\n", OVERLAY_FILE, strerror(errno)); + res = EXIT_FAILURE; + goto close_overlay; + } + + struct overlay_req req; + req.base_addr = *(unsigned long *)(&base_mmap); + req.overlay_addr = *(unsigned long *)(&overlay_map); + req.segments_size = (TOTAL_PAGES + (2 * N - 1)) / (2 * N); + req.segments = calloc(sizeof(struct overlay_segment_req), req.segments_size); + + printf("Requesting %u operations and sending %lu bytes worth of mmap segments\n", req.segments_size, + sizeof(struct overlay_segment_req) * req.segments_size); + + // Overlay every other N pages. + for (int i = 0; i < req.segments_size; i++) { + req.segments[i].start_pgoff = 2 * N * i; + + // Cap segment end to the number of pages in the base memory area. + unsigned long end = 2 * N * i + (N - 1); + end = end > TOTAL_PAGES ? TOTAL_PAGES : end; + req.segments[i].end_pgoff = end; + } + + // Call kernel module with ioctl call to the character device. + int syscall_dev = open(device_path, O_WRONLY); + if (syscall_dev < 0) { + printf("ERROR: could not open %s: %s\n", device_path, strerror(errno)); + res = EXIT_FAILURE; + goto free_segments; + } + + int ret = ioctl(syscall_dev, IOCTL_OVERLAY_REQ_CMD, &req); + if (ret) { + printf("ERROR: could not call 'IOCTL_MMAP_CMD': %s\n", strerror(errno)); + res = EXIT_FAILURE; + goto close_syscall_dev; + } + + printf("= TEST: checking memory contents with overlay\n"); + clear_cache(); + if (!verify_test_cases(overlay_fd, base_fd, base_mmap)) { + res = EXIT_FAILURE; + goto cleanup; + } + printf("== OK: overlay memory verification completed successfully!\n"); + + printf("= TEST: checking memory contents without overlay\n"); + clear_cache(); + if (!verify_test_cases(-1, clean_base_fd, clean_base_mmap)) { + res = EXIT_FAILURE; + goto cleanup; + } + printf("== OK: non-overlay memory verification completed successfully!\n"); + +cleanup: + // Clean up memory overlay. + printf("calling IOCTL_OVERLAY_CLEANUP_CMD\n"); + struct overlay_cleanup_req cleanup_req = { + .id = req.id, + }; + ret = ioctl(syscall_dev, IOCTL_OVERLAY_CLEANUP_CMD, &cleanup_req); + if (ret) { + printf("ERROR: could not call 'IOCTL_MMAP_CMD': %s\n", strerror(errno)); + res = EXIT_FAILURE; + goto close_syscall_dev; + } + res = EXIT_SUCCESS; +close_syscall_dev: + close(syscall_dev); +free_segments: + free(req.segments); + munmap(overlay_map, TOTAL_SIZE); +close_overlay: + close(overlay_fd); +unmap_base: + munmap(clean_base_mmap, TOTAL_SIZE); + munmap(base_mmap, TOTAL_SIZE); +close_base: + close(clean_base_fd); + close(base_fd); + printf("done\n"); + return res; +} diff --git a/kmod/pagefault/tests/page_fault/page_fault_fork.c b/kmod/pagefault/tests/page_fault/page_fault_fork.c new file mode 100644 index 00000000..b8af3051 --- /dev/null +++ b/kmod/pagefault/tests/page_fault/page_fault_fork.c @@ -0,0 +1,347 @@ +// SPDX-License-Identifier: GPL-3.0 + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "../../device.h" + +struct test_case { + unsigned long pgoff; + int fd; + char *data; +}; + +size_t page_size, total_size; + +const static int nr_forks = 100; +static const char base_file[] = "base.bin"; +static const char overlay_file[] = "overlay.bin"; +static const int page_size_factor = 1024; + +bool verify_test_cases(struct test_case *tcs, int tcs_nr, int base_fd, + char *base_map) +{ + char *buffer = malloc(page_size); + memset(buffer, 0, page_size); + bool valid = true; + pid_t pid = getpid(); + + for (unsigned long pgoff = 0; pgoff < total_size / page_size; pgoff++) { + size_t offset = pgoff * page_size; + + struct test_case *tc = NULL; + for (int i = 0; i < tcs_nr; i++) { + if (tcs[i].pgoff == pgoff) { + tc = &tcs[i]; + break; + } + } + + int fd = base_fd; + if (tc != NULL) { + if (tc->fd > 0) { + fd = tc->fd; + printf("[%d] checking if page %lu is from overlay\n", + pid, pgoff); + } else if (tc->data) { + printf("[%d] checking if page %lu has expected data\n", + pid, pgoff); + memcpy(buffer, tc->data, page_size); + fd = -1; + } + } + + if (fd > 0) { + lseek(fd, offset, SEEK_SET); + read(fd, buffer, page_size); + } + + if (memcmp(base_map + offset, buffer, page_size)) { + printf("[%d] == ERROR: base memory does not match the file contents at page %lu\n", + pid, pgoff); + valid = false; + break; + } + memset(buffer, 0, page_size); + } + + free(buffer); + return valid; +} + +int main() +{ + int res = EXIT_SUCCESS; + pid_t child_pid; + + for (int i = 0; i < nr_forks; i++) { + if ((child_pid = fork()) == 0) { + // Child process exits the loop. + break; + } + } + + pid_t pid = getpid(); + if (child_pid != 0) { + printf("[%d] parent process\n", pid); + goto wait; + } + + page_size = sysconf(_SC_PAGESIZE); + total_size = page_size * page_size_factor; + printf("[%d] Using pagesize %lu with total size %lu\n", pid, page_size, + total_size); + + // Read base.bin test file and mmap it into memory. + int base_fd = open(base_file, O_RDONLY); + if (base_fd < 0) { + printf("[%d] ERROR: could not open base file %s: %s\n", pid, + base_file, strerror(errno)); + return EXIT_FAILURE; + } + printf("[%d] opened base file %s\n", pid, base_file); + + char *base_mmap = mmap(NULL, total_size, PROT_READ | PROT_WRITE, + MAP_PRIVATE, base_fd, 0); + if (base_mmap == MAP_FAILED) { + printf("[%d] ERROR: could not mmap base file %s: %s\n", pid, + base_file, strerror(errno)); + res = EXIT_FAILURE; + goto close_base; + } + printf("[%d] mapped base file %s\n", pid, base_file); + + char *clean_base_mmap = + mmap(NULL, total_size, PROT_READ, MAP_PRIVATE, base_fd, 0); + if (clean_base_mmap == MAP_FAILED) { + printf("[%d] ERROR: could not mmap clean base file %s: %s\n", + pid, base_file, strerror(errno)); + res = EXIT_FAILURE; + goto close_base; + } + printf("[%d] mapped clean base file %s\n", pid, overlay_file); + + // Read overlay test file and create memory overlay request. + int overlay_fd = open(overlay_file, O_RDONLY); + if (overlay_fd < 0) { + printf("[%d] ERROR: could not open overlay file %s: %s\n", pid, + overlay_file, strerror(errno)); + res = EXIT_FAILURE; + goto unmap_base; + } + printf("[%d] opened overlay file %s\n", pid, overlay_file); + + char *overlay_map = + mmap(NULL, total_size, PROT_READ, MAP_PRIVATE, overlay_fd, 0); + if (overlay_map == MAP_FAILED) { + printf("[%d] ERROR: could not mmap overlay file %s: %s\n", pid, + overlay_file, strerror(errno)); + res = EXIT_FAILURE; + goto close_overlay; + } + printf("[%d] mapped overlay file %s\n", pid, overlay_file); + + struct overlay_req req; + req.base_addr = *(unsigned long *)(&base_mmap); + req.overlay_addr = *(unsigned long *)(&overlay_map); + req.segments_size = 5; + req.segments = malloc(sizeof(struct overlay_segment_req) * + req.segments_size); + memset(req.segments, 0, + sizeof(struct overlay_segment_req) * req.segments_size); + + printf("[%d] requesting %u operations and sending %lu bytes worth of mmap segments\n", + pid, req.segments_size, + sizeof(struct overlay_segment_req) * req.segments_size); + + // Overlay single page. + req.segments[0].start_pgoff = 0; + req.segments[0].end_pgoff = 0; + + // Overlay multiple pages. + req.segments[1].start_pgoff = 4; + req.segments[1].end_pgoff = 6; + + // Two overlays back-to-back. + req.segments[2].start_pgoff = 20; + req.segments[2].end_pgoff = 20; + req.segments[3].start_pgoff = 21; + req.segments[3].end_pgoff = 21; + + // Large overlay that crosses fault-around borders. + req.segments[4].start_pgoff = 30; + req.segments[4].end_pgoff = 50; + + // Call kernel module with ioctl call to the character device. + int syscall_dev = open(device_path, O_WRONLY); + if (syscall_dev < 0) { + printf("[%d] ERROR: could not open %s: %d\n", pid, + device_path, syscall_dev); + res = EXIT_FAILURE; + goto free_segments; + } + + int ret; + ret = ioctl(syscall_dev, IOCTL_OVERLAY_REQ_CMD, &req); + if (ret) { + printf("[%d] ERROR: could not call 'IOCTL_MMAP_CMD': %s\n", pid, + strerror(errno)); + res = EXIT_FAILURE; + goto close_syscall_dev; + } + + // Verify reading memory. + int tcs_nr = 27; + struct test_case *tcs = malloc(sizeof(struct test_case) * tcs_nr); + tcs[0].pgoff = 0; + tcs[0].fd = overlay_fd; + tcs[1].pgoff = 4; + tcs[1].fd = overlay_fd; + tcs[2].pgoff = 5; + tcs[2].fd = overlay_fd; + tcs[3].pgoff = 6; + tcs[3].fd = overlay_fd; + tcs[4].pgoff = 20; + tcs[4].fd = overlay_fd; + tcs[5].pgoff = 21; + tcs[5].fd = overlay_fd; + for (int i = 6, j = 30; j <= 50; i++, j++) { + tcs[i].pgoff = j; + tcs[i].fd = overlay_fd; + } + + printf("[%d] = TEST: checking memory contents with overlay\n", pid); + if (!verify_test_cases(tcs, tcs_nr, base_fd, base_mmap)) { + res = EXIT_FAILURE; + free(tcs); + goto cleanup; + } + printf("[%d] == OK: overlay memory verification completed successfully!\n", + pid); + + printf("[%d] = TEST: checking memory contents without overlay\n", pid); + if (!verify_test_cases(NULL, 0, base_fd, clean_base_mmap)) { + res = EXIT_FAILURE; + free(tcs); + goto cleanup; + } + free(tcs); + printf("[%d] == OK: non-overlay memory verification completed successfully!\n", + pid); + + // TODO: parse /proc//smaps to verify memory sharing. + + // Verify writing to memory. + int rand_fd = open("/dev/random", O_RDONLY); + if (rand_fd < 0) { + printf("[%d] ERROR: could not open /dev/random: %d\n", pid, + rand_fd); + res = EXIT_FAILURE; + goto cleanup; + } + + char *rand = malloc(page_size); + memset(rand, 0, page_size); + read(rand_fd, rand, page_size); + close(rand_fd); + + // Write to non-overlay page. + memcpy(base_mmap + page_size * 10, rand, page_size); + // Write to overlay page. + memcpy(base_mmap + page_size * 4, rand, page_size); + + tcs_nr = 28; + tcs = malloc(sizeof(struct test_case) * tcs_nr); + tcs[0].pgoff = 0; + tcs[0].fd = overlay_fd; + tcs[1].pgoff = 4; + tcs[1].data = rand; + tcs[2].pgoff = 5; + tcs[2].fd = overlay_fd; + tcs[3].pgoff = 6; + tcs[3].fd = overlay_fd; + tcs[4].pgoff = 10; + tcs[4].data = rand; + tcs[5].pgoff = 20; + tcs[5].fd = overlay_fd; + tcs[6].pgoff = 21; + tcs[6].fd = overlay_fd; + for (int i = 7, j = 30; j <= 50; i++, j++) { + tcs[i].pgoff = j; + tcs[i].fd = overlay_fd; + } + + printf("[%d] = TEST: checking memory write\n", pid); + if (!verify_test_cases(tcs, tcs_nr, base_fd, base_mmap)) { + res = EXIT_FAILURE; + free(tcs); + free(rand); + goto cleanup; + } + free(tcs); + free(rand); + printf("[%d] == OK: memory write verification completed successfully!\n", + pid); + +cleanup: + // Clean up memory overlay. + printf("[%d] calling IOCTL_OVERLAY_CLEANUP_CMD\n", pid); + struct overlay_cleanup_req cleanup_req = { + .id = req.id, + }; + ret = ioctl(syscall_dev, IOCTL_OVERLAY_CLEANUP_CMD, &cleanup_req); + if (ret) { + printf("[%d] ERROR: could not call 'IOCTL_MMAP_CMD': %s\n", pid, + strerror(errno)); + res = EXIT_FAILURE; + goto close_syscall_dev; + } + res = EXIT_SUCCESS; +close_syscall_dev: + close(syscall_dev); + printf("[%d] closed device driver\n", pid); +free_segments: + free(req.segments); + munmap(overlay_map, total_size); + printf("[%d] unmapped overlay file\n", pid); +close_overlay: + close(overlay_fd); + printf("[%d] closed overlay file\n", pid); +unmap_base: + munmap(clean_base_mmap, total_size); + printf("[%d] unmapped clean base file\n", pid); + munmap(base_mmap, total_size); + printf("[%d] unmapped base file\n", pid); +close_base: + close(base_fd); + printf("[%d] closed base file\n", pid); +wait: + // Wait for child processes results if parent. + if (child_pid != 0) { + int child_rc; + int success = 0, fail = 0; + while (wait(&child_rc) > 0) { + if (!WIFEXITED(child_rc) && WEXITSTATUS(child_rc) > 0) { + fail++; + continue; + } + success++; + } + printf("[%d] done success=%d fail=%d\n", pid, success, fail); + if (fail > 0) { + res = EXIT_FAILURE; + } + } else { + printf("[%d] done\n", pid); + } + return res; +} diff --git a/kmod/pagefault/tests/page_fault/page_fault_ioctl_error.c b/kmod/pagefault/tests/page_fault/page_fault_ioctl_error.c new file mode 100644 index 00000000..9a60fe26 --- /dev/null +++ b/kmod/pagefault/tests/page_fault/page_fault_ioctl_error.c @@ -0,0 +1,217 @@ +// SPDX-License-Identifier: GPL-3.0 + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include "../../device.h" + +struct test_case { + unsigned long pgoff; + int fd; + char *data; +}; + +size_t page_size, total_size; + +static const char base_file[] = "base.bin"; +static const char overlay_file[] = "overlay.bin"; +static const int page_size_factor = 1024; + +bool verify_test_cases(struct test_case *tcs, int tcs_nr, int base_fd, + char *base_map) +{ + char *buffer = malloc(page_size); + memset(buffer, 0, page_size); + bool valid = true; + + for (unsigned long pgoff = 0; pgoff < total_size / page_size; pgoff++) { + size_t offset = pgoff * page_size; + + struct test_case *tc = NULL; + for (int i = 0; i < tcs_nr; i++) { + if (tcs[i].pgoff == pgoff) { + tc = &tcs[i]; + break; + } + } + + int fd = base_fd; + if (tc != NULL) { + if (tc->fd > 0) { + fd = tc->fd; + printf("checking if page %lu is from overlay\n", + pgoff); + } else if (tc->data) { + printf("checking if page %lu has expected data\n", + pgoff); + memcpy(buffer, tc->data, page_size); + fd = -1; + } + } + + if (fd > 0) { + lseek(fd, offset, SEEK_SET); + read(fd, buffer, page_size); + } + + if (memcmp(base_map + offset, buffer, page_size)) { + printf("== ERROR: base memory does not match the file contents at page %lu\n", + pgoff); + valid = false; + break; + } + memset(buffer, 0, page_size); + } + + free(buffer); + return valid; +} + +int main() +{ + int res = EXIT_SUCCESS; + + page_size = sysconf(_SC_PAGESIZE); + total_size = page_size * page_size_factor; + printf("Using pagesize %lu with total size %lu\n", page_size, + total_size); + + // Read base.bin test file and mmap it into memory. + int base_fd = open(base_file, O_RDONLY); + if (base_fd < 0) { + printf("ERROR: could not open base file %s: %s\n", base_file, + strerror(errno)); + return EXIT_FAILURE; + } + printf("opened base file %s\n", base_file); + + char *base_mmap = mmap(NULL, total_size, PROT_READ | PROT_WRITE, + MAP_PRIVATE, base_fd, 0); + if (base_mmap == MAP_FAILED) { + printf("ERROR: could not mmap base file %s: %s\n", base_file, + strerror(errno)); + res = EXIT_FAILURE; + goto close_base; + } + printf("mapped base file %s\n", base_file); + + // Read overlay test file and create memory overlay request. + int overlay_fd = open(overlay_file, O_RDONLY); + if (overlay_fd < 0) { + printf("ERROR: could not open overlay file %s: %s\n", + overlay_file, strerror(errno)); + res = EXIT_FAILURE; + goto unmap_base; + } + printf("opened overlay file %s\n", overlay_file); + + char *overlay_map = + mmap(NULL, total_size, PROT_READ, MAP_PRIVATE, overlay_fd, 0); + if (overlay_map == MAP_FAILED) { + printf("ERROR: could not mmap overlay file %s: %s\n", + overlay_file, strerror(errno)); + res = EXIT_FAILURE; + goto close_overlay; + } + printf("mapped overlay file %s\n", overlay_file); + + struct overlay_req req; + req.base_addr = *(unsigned long *)(&base_mmap); + req.overlay_addr = *(unsigned long *)(&overlay_map); + req.segments_size = 1; + req.segments = malloc(sizeof(struct overlay_segment_req) * + req.segments_size); + memset(req.segments, 0, + sizeof(struct overlay_segment_req) * req.segments_size); + + // Overlay single page. + req.segments[0].start_pgoff = 0; + req.segments[0].end_pgoff = 0; + + // Call kernel module with ioctl call to the character device. + int syscall_dev = open(device_path, O_WRONLY); + if (syscall_dev < 0) { + printf("ERROR: could not open %s: %d\n", device_path, + syscall_dev); + res = EXIT_FAILURE; + goto free_segments; + } + + printf("= TEST: verify IOCTL_OVERLAY_REQ_CMD succeeds\n"); + int ret; + ret = ioctl(syscall_dev, IOCTL_OVERLAY_REQ_CMD, &req); + if (ret) { + printf("== ERROR: could not call 'IOCTL_MMAP_CMD': %s\n", + strerror(errno)); + res = EXIT_FAILURE; + goto close_syscall_dev; + } + printf("== OK: called IOCTL_OVERLAY_REQ_CMD successfully!\n"); + + // Call the kernel module a second time and verify it fails. + printf("= TEST: verify second call to IOCTL_OVERLAY_REQ_CMD fails\n"); + ret = ioctl(syscall_dev, IOCTL_OVERLAY_REQ_CMD, &req); + if (errno != EEXIST) { + printf("== ERROR: expected call to 'IOCTL_MMAP_CMD' to return %d, got %d.\n", + EEXIST, errno); + res = EXIT_FAILURE; + goto close_syscall_dev; + } + printf("== OK: second call to IOCTL_OVERLAY_REQ_CMD failed successfully!\n"); + + // Clean up memory overlay. + printf("= TEST: verify IOCTL_OVERLAY_CLEANUP_CMD succeeds\n"); + struct overlay_cleanup_req cleanup_req = { + .id = req.id, + }; + ret = ioctl(syscall_dev, IOCTL_OVERLAY_CLEANUP_CMD, &cleanup_req); + if (ret) { + printf("== ERROR: could not call 'IOCTL_MMAP_CMD': %s\n", + strerror(errno)); + res = EXIT_FAILURE; + goto close_syscall_dev; + + } + printf("== OK: called IOCTL_OVERLAY_CLEANUP_CMD successfully!\n"); + + printf("= TEST: verify second call to IOCTL_OVERLAY_CLEANUP_CMD fails\n"); + ret = ioctl(syscall_dev, IOCTL_OVERLAY_CLEANUP_CMD, &cleanup_req); + if (errno != ENOENT) { + printf("== ERROR: expected call to 'IOCTL_MMAP_CMD' to return %d, got %d\n", + ENOENT, errno); + res = EXIT_FAILURE; + goto close_syscall_dev; + } + printf("== OK: called IOCTL_OVERLAY_CLEANUP_CMD successfully!\n"); + res = EXIT_SUCCESS; +close_syscall_dev: + close(syscall_dev); + printf("closed device driver\n"); +free_segments: + free(req.segments); + munmap(overlay_map, total_size); + printf("unmapped overlay file\n"); +close_overlay: + close(overlay_fd); + printf("closed overlay file\n"); +unmap_base: + munmap(base_mmap, total_size); + printf("unmapped base file\n"); +close_base: + close(base_fd); + printf("closed base file\n"); + printf("done\n"); + return res; +} diff --git a/kmod/pagefault/tests/page_fault/page_fault_multithread.c b/kmod/pagefault/tests/page_fault/page_fault_multithread.c new file mode 100644 index 00000000..208be962 --- /dev/null +++ b/kmod/pagefault/tests/page_fault/page_fault_multithread.c @@ -0,0 +1,206 @@ +// SPDX-License-Identifier: GPL-3.0 + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "../../device.h" + +const static int nr_threads = 200; +size_t page_size, total_size; +char *base_mmap; + +char base_file[] = "base.bin"; +char overlay_file[] = "overlay.bin"; + +void *page_fault(void *idx) +{ + int ret = EXIT_SUCCESS; + printf("[%03ld] verifying base memory\n", (long)idx); + + char *buffer = malloc(page_size); + memset(buffer, 0, page_size); + + int base_fd = open(base_file, O_RDONLY); + if (base_fd < 0) { + printf("[%03ld] ERROR: could not open base file: %s\n", + (long)idx, strerror(errno)); + ret = EXIT_FAILURE; + goto out; + } + printf("[%03ld] opened base file %s\n", (long)idx, base_file); + + int overlay_fd = open(overlay_file, O_RDONLY); + if (overlay_fd < 0) { + printf("[%03ld] ERROR: could not open overlay file: %s\n", + (long)idx, strerror(errno)); + ret = EXIT_FAILURE; + goto out; + } + printf("[%03ld] opened overlay file %s\n", (long)idx, overlay_file); + + int fd; + for (unsigned long pgoff = 0; pgoff < total_size / page_size; pgoff++) { + size_t offset = pgoff * page_size; + + fd = base_fd; + if (pgoff % 2 == 0) { + fd = overlay_fd; + } + lseek(fd, offset, SEEK_SET); + read(fd, buffer, page_size); + + if (memcmp(base_mmap + offset, buffer, page_size)) { + printf("== [%03ld] ERROR: base memory does not match the file contents at page %lu\n", + (long)idx, pgoff); + ret = EXIT_FAILURE; + goto out; + } + memset(buffer, 0, page_size); + } + printf("== [%03ld] OK: base memory verification complete\n", (long)idx); + +out: + free(buffer); + return (void *)(long)ret; +} + +int main() +{ + int res = EXIT_SUCCESS; + page_size = sysconf(_SC_PAGESIZE); + total_size = page_size * 1024; + pthread_t tid[nr_threads]; + + int base_fd = open(base_file, O_RDONLY); + if (base_fd < 0) { + printf("ERROR: could not open base file: %d\n", base_fd); + return EXIT_FAILURE; + } + printf("base file %s opened\n", base_file); + + base_mmap = mmap(NULL, total_size, PROT_READ, MAP_PRIVATE, base_fd, 0); + if (base_mmap == MAP_FAILED) { + printf("ERROR: could not mmap base file\n"); + res = EXIT_FAILURE; + goto close_base; + } + printf("base file %s mapped\n", base_file); + + int overlay_fd = open(overlay_file, O_RDONLY); + if (overlay_fd < 0) { + printf("ERROR: could not open overlay file: %d\n", overlay_fd); + res = EXIT_FAILURE; + goto unmap_base; + } + printf("overlay file %s opened\n", overlay_file); + + char *overlay_map = + mmap(NULL, total_size, PROT_READ, MAP_PRIVATE, overlay_fd, 0); + if (overlay_map == MAP_FAILED) { + printf("ERROR: could not mmap overlay file\n"); + res = EXIT_FAILURE; + goto close_overlay; + } + printf("overlay file %s mapped\n", overlay_file); + + struct overlay_req req; + req.base_addr = *(unsigned long *)(&base_mmap); + req.overlay_addr = *(unsigned long *)(&overlay_map); + req.segments_size = total_size / (page_size * 2); + req.segments = malloc(sizeof(struct overlay_segment_req) * + req.segments_size); + memset(req.segments, 0, + sizeof(struct overlay_segment_req) * req.segments_size); + + // Overlay half of the pages. + for (int i = 0; i < req.segments_size; i++) { + req.segments[i].start_pgoff = 2 * i; + req.segments[i].end_pgoff = 2 * i; + } + printf("generated memory overlay request\n"); + + int syscall_dev = open(device_path, O_WRONLY); + if (syscall_dev < 0) { + printf("ERROR: could not open %s: %d\n", device_path, + syscall_dev); + res = EXIT_FAILURE; + goto free_segments; + } + printf("opened %s device\n", device_path); + + int ret = ioctl(syscall_dev, IOCTL_OVERLAY_REQ_CMD, &req); + if (ret) { + printf("ERROR: could not call 'IOCTL_MMAP_CMD': %s\n", + strerror(errno)); + res = EXIT_FAILURE; + goto close_syscall_dev; + } + printf("called IOCTL_OVERLAY_REQ_CMD\n"); + + printf("= TEST: generate concurrent page faults\n"); + for (long i = 0; i < nr_threads; i++) { + pthread_create(&tid[i], NULL, page_fault, (void *)i); + } + + int success = 0, fail = 0; + for (int i = 0; i < nr_threads; i++) { + void *res; + pthread_join(tid[i], &res); + switch ((long)res) { + case EXIT_SUCCESS: + success += 1; + break; + default: + fail += 1; + break; + } + } + if (fail != 0) { + printf("== ERROR: expected all threads to succeed, got %d failures\n", + fail); + res = EXIT_FAILURE; + goto cleanup; + } + printf("== OK: all threads completed successfully! success=%d fail=%d\n", + success, fail); + res = EXIT_SUCCESS; +cleanup: + struct overlay_cleanup_req cleanup_req = { + .id = req.id, + }; + ret = ioctl(syscall_dev, IOCTL_OVERLAY_CLEANUP_CMD, &cleanup_req); + if (ret) { + printf("ERROR: could not call 'IOCTL_MMAP_CMD': %s\n", + strerror(errno)); + res = EXIT_FAILURE; + goto close_syscall_dev; + } + printf("called IOCTL_OVERLAY_CLEANUP_CMD\n"); +close_syscall_dev: + close(syscall_dev); + printf("closed device driver\n"); +free_segments: + free(req.segments); + printf("freed segments\n"); + munmap(overlay_map, total_size); + printf("unmapped overlay\n"); +close_overlay: + close(overlay_fd); + printf("closed overlay\n"); +unmap_base: + munmap(base_mmap, total_size); + printf("unmapped base\n"); +close_base: + close(base_fd); + printf("closed base\n"); + printf("done\n"); + return res; +} diff --git a/kmod/pagefault/tests/page_fault/page_fault_multithread_ioctl.c b/kmod/pagefault/tests/page_fault/page_fault_multithread_ioctl.c new file mode 100644 index 00000000..28c1aefd --- /dev/null +++ b/kmod/pagefault/tests/page_fault/page_fault_multithread_ioctl.c @@ -0,0 +1,261 @@ +// SPDX-License-Identifier: GPL-3.0 + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "../../device.h" + +const static int nr_threads = 2000; +size_t page_size, total_size; +char *base_mmap; + +char base_file[] = "base.bin"; +char overlay_file[] = "overlay.bin"; + +void *page_fault(void *idx) +{ + int ret = EXIT_SUCCESS; + printf("[%03ld] verifying base memory\n", (long)idx); + + char *buffer = malloc(page_size); + memset(buffer, 0, page_size); + + int base_fd = open(base_file, O_RDONLY); + if (base_fd < 0) { + printf("[%03ld] ERROR: could not open base file: %s\n", + (long)idx, strerror(errno)); + ret = EXIT_FAILURE; + goto out; + } + printf("[%03ld] opened base file %s\n", (long)idx, base_file); + + int overlay_fd = open(overlay_file, O_RDONLY); + if (overlay_fd < 0) { + printf("[%03ld] ERROR: could not open overlay file: %s\n", + (long)idx, strerror(errno)); + ret = EXIT_FAILURE; + goto out; + } + printf("[%03ld] opened overlay file %s\n", (long)idx, overlay_file); + + int fd; + for (unsigned long pgoff = 0; pgoff < total_size / page_size; pgoff++) { + size_t offset = pgoff * page_size; + + fd = base_fd; + if (pgoff % 2 == 0) { + fd = overlay_fd; + } + lseek(fd, offset, SEEK_SET); + read(fd, buffer, page_size); + + if (memcmp(base_mmap + offset, buffer, page_size)) { + printf("== [%03ld] ERROR: base memory does not match the file contents at page %lu\n", + (long)idx, pgoff); + ret = EXIT_FAILURE; + goto out; + } + memset(buffer, 0, page_size); + } + printf("== [%03ld] OK: base memory verification complete\n", (long)idx); + +out: + free(buffer); + return (void *)(long)ret; +} + +void *ioctl_overlay(void *args) +{ + pid_t tid = syscall(SYS_gettid); + int res = EXIT_SUCCESS; + struct overlay_req *req = args; + + int syscall_dev = open(device_path, O_WRONLY); + if (syscall_dev < 0) { + printf("[%d] ERROR: could not open %s: %d\n", tid, + device_path, syscall_dev); + res = EXIT_FAILURE; + goto out; + } + + int ret = ioctl(syscall_dev, IOCTL_OVERLAY_REQ_CMD, req); + if (ret) { + printf("[%d] ERROR: could not call 'IOCTL_MMAP_CMD': %s\n", tid, + strerror(errno)); + res = EXIT_FAILURE; + } + close(syscall_dev); +out: + return (void *)(long)res; +} + +void *ioctl_cleanup(void *args) +{ + pid_t tid = syscall(SYS_gettid); + int res = EXIT_SUCCESS; + struct overlay_cleanup_req *req = args; + + int syscall_dev = open(device_path, O_WRONLY); + if (syscall_dev < 0) { + printf("[%d] ERROR: could not open %s: %d\n", tid, + device_path, syscall_dev); + res = EXIT_FAILURE; + goto out; + } + + int ret = ioctl(syscall_dev, IOCTL_OVERLAY_CLEANUP_CMD, req); + if (ret) { + printf("[%d] ERROR: could not call 'IOCTL_MMAP_CMD': %s\n", tid, + strerror(errno)); + res = EXIT_FAILURE; + } + close(syscall_dev); +out: + return (void *)(long)res; +} + +int main() +{ + int res = EXIT_SUCCESS; + page_size = sysconf(_SC_PAGESIZE); + total_size = page_size * 1024; + pthread_t tid[nr_threads]; + + int base_fd = open(base_file, O_RDONLY); + if (base_fd < 0) { + printf("ERROR: could not open base file %s: %s\n", base_file, + strerror(errno)); + return EXIT_FAILURE; + } + printf("base file %s opened\n", base_file); + + base_mmap = mmap(NULL, total_size, PROT_READ, MAP_PRIVATE, base_fd, 0); + if (base_mmap == MAP_FAILED) { + printf("ERROR: could not mmap base file %s: %s\n", base_file, + strerror(errno)); + res = EXIT_FAILURE; + goto close_base; + } + printf("base file %s mapped\n", base_file); + + int overlay_fd = open(overlay_file, O_RDONLY); + if (overlay_fd < 0) { + printf("ERROR: could not open overlay file %s: %s\n", + overlay_file, strerror(errno)); + res = EXIT_FAILURE; + goto unmap_base; + } + printf("overlay file %s opened\n", overlay_file); + + char *overlay_map = + mmap(NULL, total_size, PROT_READ, MAP_PRIVATE, overlay_fd, 0); + if (overlay_map == MAP_FAILED) { + printf("ERROR: could not mmap overlay file %s: %s\n", + overlay_file, strerror(errno)); + res = EXIT_FAILURE; + goto close_overlay; + } + printf("overlay file %s mapped\n", overlay_file); + + struct overlay_req req; + req.base_addr = *(unsigned long *)(&base_mmap); + req.overlay_addr = *(unsigned long *)(&overlay_map); + req.segments_size = total_size / (page_size * 2); + req.segments = malloc(sizeof(struct overlay_segment_req) * + req.segments_size); + memset(req.segments, 0, + sizeof(struct overlay_segment_req) * req.segments_size); + + // Overlay half of the pages. + for (int i = 0; i < req.segments_size; i++) { + req.segments[i].start_pgoff = 2 * i; + req.segments[i].end_pgoff = 2 * i; + } + printf("generated memory overlay request\n"); + + // Call memory overlay ioctl multiple times. + printf("= TEST: call IOCTL_OVERLAY_REQ_CMD multiple times\n"); + for (long i = 0; i < nr_threads; i++) { + pthread_create(&tid[i], NULL, ioctl_overlay, (void *)&req); + } + + int success = 0, fail = 0; + for (int i = 0; i < nr_threads; i++) { + void *res; + pthread_join(tid[i], &res); + switch ((long)res) { + case EXIT_SUCCESS: + success += 1; + break; + default: + fail += 1; + break; + } + } + if (success != 1) { + printf("== ERROR: expected one thread to succeed in calling IOCTL_OVERLAY_REQ_CMD, got %d\n", + success); + res = EXIT_FAILURE; + goto free_segments; + } + printf("== OK: calls to IOCTL_OVERLAY_REQ_CMD completed successfully! success=%d fail=%d\n", + success, fail); + + // Call cleanup ioctl multiple times. + printf("= TEST: call IOCTL_OVERLAY_CLEANUP_CMD multiple times\n"); + struct overlay_cleanup_req cleanup_req = { + .id = req.id, + }; + for (long i = 0; i < nr_threads; i++) { + pthread_create(&tid[i], NULL, ioctl_cleanup, + (void *)&cleanup_req); + } + + success = 0, fail = 0; + for (int i = 0; i < nr_threads; i++) { + void *res; + pthread_join(tid[i], &res); + switch ((long)res) { + case EXIT_SUCCESS: + success += 1; + break; + default: + fail += 1; + break; + } + } + if (success != 1) { + printf("ERROR: expected one thread to succeed in calling IOCTL_OVERLAY_CLEANUP_CMD success=%d fail=%d\n", + success, fail); + res = EXIT_FAILURE; + goto free_segments; + } + printf("== OK: calls to IOCTL_OVERLAY_CLEANUP_CMD completed successfully! success=%d fail=%d\n", + success, fail); + res = EXIT_SUCCESS; +free_segments: + free(req.segments); + printf("freed segments\n"); + munmap(overlay_map, total_size); + printf("unmapped overlay\n"); +close_overlay: + close(overlay_fd); + printf("closed overlay\n"); +unmap_base: + munmap(base_mmap, total_size); + printf("unmapped base\n"); +close_base: + close(base_fd); + printf("closed base\n"); + printf("done\n"); + return res; +}