[
  {
    "path": ".ci/build-n-run.sh",
    "content": "#!/usr/bin/env bash\n\nfunction build_example()\n{   \n    make -C examples || exit 1\n}\n\nfunction list_mod()\n{\n    # Filter out the modules specified in non-working\n    ls examples/*.ko | awk -F \"[/|.]\" '{print $2}' | grep -vFxf .ci/non-working\n}\n\nfunction run_mod()\n{\n    # insert/remove twice to ensure resource allocations\n    ( sudo insmod \"examples/$1.ko\" && sudo rmmod \"$1\" ) || exit 1\n    ( sudo insmod \"examples/$1.ko\" && sudo rmmod \"$1\" ) || exit 1\n}\n\nfunction run_examples()\n{\n    for module in $(list_mod); do\n        echo \"Running $module\"\n        run_mod \"$module\"\n    done\n}\n\nbuild_example\nrun_examples\n"
  },
  {
    "path": ".ci/check-format.sh",
    "content": "#!/usr/bin/env bash\n\nSOURCES=$(find $(git rev-parse --show-toplevel) | grep -E \"\\.(cpp|cc|c|h)\\$\")\n\nCLANG_FORMAT=$(which clang-format)\nif [ $? -ne 0 ]; then\n    CLANG_FORMAT=$(which clang-format)\n    if [ $? -ne 0 ]; then\n        echo \"[!] clang-format not installed. Unable to check source file format policy.\" >&2\n        exit 1\n    fi\nfi\n\nset -x\n\nfor file in ${SOURCES};\ndo\n    $CLANG_FORMAT ${file} > expected-format\n    diff -u -p --label=\"${file}\" --label=\"expected coding style\" ${file} expected-format\ndone\nexit $($CLANG_FORMAT --output-replacements-xml ${SOURCES} | grep -E -c \"</replacement>\")\n"
  },
  {
    "path": ".ci/check-newline.sh",
    "content": "#!/usr/bin/env bash\n\nset -e -u -o pipefail\n\nret=0\nshow=0\n# Reference: https://medium.com/@alexey.inkin/how-to-force-newline-at-end-of-files-and-why-you-should-do-it-fdf76d1d090e\nwhile IFS= read -rd '' f; do\n    if file --mime-encoding \"$f\" | grep -qv binary; then\n        tail -c1 < \"$f\" | read -r _ || show=1\n        if [ $show -eq 1 ]; then\n            echo \"Warning: No newline at end of file $f\"\n            ret=1\n            show=0\n        fi\n    fi\ndone < <(git ls-files -z examples)\n\nexit $ret\n"
  },
  {
    "path": ".ci/non-working",
    "content": "bottomhalf\nbh_threaded\nintrpt\nvkbd\nsyscall-steal\nled\ndht11\n"
  },
  {
    "path": ".ci/static-analysis.sh",
    "content": "#!/usr/bin/env bash\n\nfunction do_cppcheck()\n{\n    local SOURCES=$(find $(git rev-parse --show-toplevel) | grep -E \"\\.(cpp|cc|c|h)\\$\")\n\n    local CPPCHECK=$(which cppcheck)\n    if [ $? -ne 0 ]; then\n        echo \"[!] cppcheck not installed. Failed to run static analysis the source code.\" >&2\n        exit 1\n    fi\n\n    ## Suppression list ##\n    # This list will explain the detail of suppressed warnings.\n    # The prototype of the item should be like:\n    # \"- [{file}] {spec}: {reason}\"\n    #\n    # - [hello-1.c] unusedFunction: False positive of init_module and cleanup_module.\n    # - [*.c] missingIncludeSystem: Focus on the example code, not the kernel headers.\n\n    local OPTS=\"\n            --enable=warning,performance,information\n            --suppress=unusedFunction:hello-1.c\n            --suppress=missingIncludeSystem\n            --std=c89 \"\n\n    $CPPCHECK $OPTS --xml ${SOURCES} 2> cppcheck.xml\n    local ERROR_COUNT=$(cat cppcheck.xml | grep -E -c \"</error>\" )\n\n    if [ $ERROR_COUNT -gt 0 ]; then\n        echo \"Cppcheck failed: $ERROR_COUNT error(s)\"\n        cat cppcheck.xml\n        exit 1\n    fi\n}\n\nfunction do_sparse()\n{\n    git clone git://git.kernel.org/pub/scm/devel/sparse/sparse.git --depth=1\n    if [ $? -ne 0 ]; then\n        echo \"Failed to download sparse.\"\n        exit 1\n    fi\n    pushd sparse\n    make sparse || exit 1\n    sudo make INST_PROGRAMS=sparse PREFIX=/usr install || exit 1\n    popd\n    local SPARSE=$(which sparse)\n\n    make -C examples C=2 CHECK=\"$SPARSE\" 2> sparse.log\n\n    local WARNING_COUNT=$(cat sparse.log | grep -E -c \" warning:\" )\n    local ERROR_COUNT=$(cat sparse.log | grep -E -c \" error:\" )\n    local COUNT=`expr $WARNING_COUNT + $ERROR_COUNT`\n    if [ $COUNT -gt 0 ]; then\n        echo \"Sparse failed: $WARNING_COUNT warning(s), $ERROR_COUNT error(s)\"\n        cat sparse.log\n        exit 1\n    fi\n    make -C examples clean\n}\n\nfunction do_gcc()\n{\n    local GCC=$(which gcc)\n    if [ $? -ne 0 ]; then\n        echo \"[!] gcc is not installed. Failed to run static analysis with GCC.\" >&2\n        exit 1\n    fi\n\n    make -C examples CONFIG_STATUS_CHECK_GCC=y STATUS_CHECK_GCC=$GCC 2> gcc.log\n\n    local WARNING_COUNT=$(cat gcc.log | grep -E -c \" warning:\" )\n    local ERROR_COUNT=$(cat gcc.log | grep -E -c \" error:\" )\n    local COUNT=`expr $WARNING_COUNT + $ERROR_COUNT`\n    if [ $COUNT -gt 0 ]; then\n        echo \"gcc failed: $WARNING_COUNT warning(s), $ERROR_COUNT error(s)\"\n        cat gcc.log\n        exit 1\n    fi\n    make -C examples CONFIG_STATUS_CHECK_GCC=y STATUS_CHECK_GCC=$GCC clean\n}\n\nfunction do_smatch()\n{\n    git clone https://github.com/error27/smatch.git --depth=1\n    if [ $? -ne 0 ]; then\n        echo \"Failed to download smatch.\"\n        exit 1\n    fi\n    pushd smatch\n    make smatch || exit 1\n    local SMATCH=$(pwd)/smatch\n    popd\n\n    make -C examples C=2 CHECK=\"$SMATCH -p=kernel\" > smatch.log\n    local WARNING_COUNT=$(cat smatch.log | egrep -c \" warn:\" )\n    local ERROR_COUNT=$(cat smatch.log | egrep -c \" error:\" )\n    local COUNT=`expr $WARNING_COUNT + $ERROR_COUNT`\n    if [ $COUNT -gt 0 ]; then\n        echo \"Smatch failed: $WARNING_COUNT warning(s), $ERROR_COUNT error(s)\"\n        cat smatch.log | grep \"warn:\\|error:\"\n        exit 1\n    fi\n    make -C examples clean\n}\n\ndo_cppcheck\ndo_sparse\ndo_gcc\ndo_smatch\nexit 0\n"
  },
  {
    "path": ".github/workflows/build-deploy-assets.yaml",
    "content": "name: build-deploy-assets\n\non:\n  push:\n    branches: [ master ]\n\n  workflow_dispatch:\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    container: twtug/lkmpg\n\n    steps:\n      - uses: actions/checkout@v4\n      - name: Build\n        run: |\n          make all\n          make html\n          tar zcvf lkmpg-html.tar.gz ./html\n      - name: Delete old release\n        uses: cb80/delrel@latest\n        with:\n          tag: latest\n      - name: Tag\n        run: |\n          git tag latest\n          git push -f --tags\n      - name: Release\n        uses: softprops/action-gh-release@v2\n        with:\n          files: |\n            lkmpg.pdf\n            lkmpg-html.tar.gz\n          tag_name: \"latest\"\n          prerelease: true\n"
  },
  {
    "path": ".github/workflows/deploy-github-page.yaml",
    "content": "name: deploy-github-page\n\non:\n  push:\n    branches: [ master ]\n\n  workflow_dispatch:\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    container: twtug/lkmpg\n\n    steps:\n      - uses: actions/checkout@v4\n      - name: Build\n        run: |\n          make html\n      - name: Deploy to gh-pages branch\n        uses: peaceiris/actions-gh-pages@v4\n        with:\n          github_token: ${{ secrets.GITHUB_TOKEN }}\n          publish_dir: ./html\n          publish_branch: gh-pages\n"
  },
  {
    "path": ".github/workflows/status-check.yaml",
    "content": "name: status-checks\n\non:\n  push:\n    branches: [ master ]\n  pull_request:\n    branches: [ master ]\n\n  workflow_dispatch:\n\njobs:\n  validate:\n    runs-on: ubuntu-24.04\n    steps:\n      - name: checkout code\n        uses: actions/checkout@v4\n      - name: Test changed source files\n        id: changed-files\n        uses: tj-actions/changed-files@v45\n        with:\n          files: examples/**\n      - name: validate coding style and functionality\n        if: ${{ steps.changed-files.outputs.any_changed == 'true' ||\n                github.event_name == 'workflow_dispatch' }}\n        run: |\n            sudo apt install -q -y clang-format cppcheck gcc libsqlite3-dev\n            .ci/check-newline.sh\n            .ci/check-format.sh\n            .ci/static-analysis.sh\n            .ci/build-n-run.sh\n        shell: bash\n"
  },
  {
    "path": ".gitignore",
    "content": "# Linux kernel build system\n*.o\n*.o.d\n*.ko\n*cmd\n*.dwo\n*.swp\n*.symvers\n*.mod\n*.mod.c\nmodules.order\n\n# LaTeX\n_minted-lkmpg\n_minted\n*.aux\n*.log\n*.out\nlkmpg.pdf\n*.toc\n*.bbl\n*.blg\n*.fdb_latexmk\n*.fls\nlkmpg.synctex.gz\n\n# make4ht\n*.html\n*.svg\n*.tmp\n*.css\n*.4ct\n*.4tc\n*.dvi\n*.lg\n*.idv\n*.xref\n*.ttf\n*.png\n\n# format checks\nexpected-format\n"
  },
  {
    "path": ".mailmap",
    "content": "Jian-Xing Wu <fdgkhdkgh@gmail.com> 吳建興\nMeng-Zong Tsai <hwahwa649@gmail.com> fennecJ   <58484289+fennecJ@users.noreply.github.com>\nMeng-Zong Tsai <hwahwa649@gmail.com> fennecJ   <hwahwa649@gmail.com>\nJim Huang   <jserv.tw@gmail.com> Jim Huang  <jserv@ccns.ncku.edu.tw>\nJim Huang   <jserv.tw@gmail.com> Jim Huang  <jserv@biilabs.io>\nChih-En Lin <shiyn.lin@gmail.com> linD026   <shiyn.lin@gmail.com> \nChih-En Lin <shiyn.lin@gmail.com> linD026   <66012716+linD026@users.noreply.github.com>\nChih-En Lin <shiyn.lin@gmail.com> linD026   <0086d026@email.ntou.edu.tw>\nChih-En Lin <shiyn.lin@gmail.com> linzhien  <0086d026@email.ntou.edu.tw>\nmengxinayan <31788564+mengxinayan@users.noreply.github.com> 萌新阿岩\nEthan Chan  <F04066028@gs.ncku.edu.tw> tzuyichan\nPeter Lin   <peterlin@qilai.dev> lyctw       <lyctw.ee@gmail.com>\nPeter Lin   <peterlin@qilai.dev> Peter Lin   <peterlin.tw@protonmail.com>\nChe-Chia Chang <vivahavey@gmail.com> gagachang\nShao-Tse Hung <ccs100203@gmail.com> ccs100203\nYi-Wei Lin <s921975628@gmail.com> RinHizakura\nChih-Hsuan Yang <zxc25077667@gmail.com> 25077667\nYin-Chiuan Chen <leovincentseles@gmail.com> leovincentseles\nXatierlike Lee <xatierlike@gmail.com> xatier\nChin Yik Ming <yikming2222@gmail.com> ChinYikMing\nTse-Wei Lin <20110901eric@outlook.com> 2011eric\nYu-Hsiang Tseng <asas1asas200@gmail.com> asas1asas200\nKuan-Wei Chiu <visitorckw@gmail.com> visitorckw\nI-Hsin Cheng <richard120310@gmail.com> vax-r\nWei-Hsin Yeh <weihsinyeh168@gmail.com> weihsinyeh <weihsinyeh168@gmail.com>\nWei-Hsin Yeh <weihsinyeh168@gmail.com> weihsinyeh <90430653+weihsinyeh@users.noreply.github.com>\nCheng-Shian Yeh <yehchanshen@gmail.com> yeh-sudo\nYo-Jung Lin <0xff07@gmail.com> <leo.lin@canonical.com> 0xff07\nYYGO <srayuws@users.noreply.github.com> srayuws\nYen-Yu Chen <matt162162162@gmail.com> <69316865+YLowy@users.noreply.github.com> Ylowy\nYan-Jie Chan <51120603+jouae@users.noreply.github.com>\nHung-Jen Pao <ginn0122@gmail.com>\nChung-Han Tsai <jeremy90307@gmail.com>\n"
  },
  {
    "path": "GPL-2",
    "content": "\t\t    GNU GENERAL PUBLIC LICENSE\n\t\t       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.\n                       51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n\t\t\t    Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Library General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\f\n\t\t    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\f\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\f\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\f\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n\t\t\t    NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n\t\t     END OF TERMS AND CONDITIONS\n\f\n\t    How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  <signature of Ty Coon>, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Library General\nPublic License instead of this License.\n"
  },
  {
    "path": "LICENSE",
    "content": "OPEN SOFTWARE LICENSE 3.0 (OSL-3.0)\n\nThis Open Software License (the \"License\") applies to any original work\nof authorship (the \"Original Work\") whose owner (the \"Licensor\") has\nplaced the following licensing notice adjacent to the copyright notice\nfor the Original Work:\n\nLicensed under the Open Software License version 3.0\n\n1) Grant of Copyright License. Licensor grants You a worldwide,\nroyalty-free, non-exclusive, sublicensable license, for the duration of\nthe copyright, to do the following:\n\na) to reproduce the Original Work in copies, either alone or as part of\na collective work;\n\nb) to translate, adapt, alter, transform, modify, or arrange the\nOriginal Work, thereby creating derivative works (\"Derivative Works\")\nbased upon the Original Work;\n\nc) to distribute or communicate copies of the Original Work and\nDerivative Works to the public, with the proviso that copies of Original\nWork or Derivative Works that You distribute or communicate shall be\nlicensed under this Open Software License;\n\nd) to perform the Original Work publicly; and\n\ne) to display the Original Work publicly.\n\n2) Grant of Patent License. Licensor grants You a worldwide, royalty-free,\nnon-exclusive, sublicensable license, under patent claims owned or\ncontrolled by the Licensor that are embodied in the Original Work as\nfurnished by the Licensor, for the duration of the patents, to make, use,\nsell, offer for sale, have made, and import the Original Work and\nDerivative Works.\n\n3) Grant of Source Code License. The term \"Source Code\" means the preferred\nform of the Original Work for making modifications to it and all available\ndocumentation describing how to modify the Original Work. Licensor agrees\nto provide a machine-readable copy of the Source Code of the Original Work\nalong with each copy of the Original Work that Licensor distributes.\nLicensor reserves the right to satisfy this obligation by placing a\nmachine-readable copy of the Source Code in an information repository\nreasonably calculated to permit inexpensive and convenient access by You\nfor as long as Licensor continues to distribute the Original Work.\n\n4) Exclusions From License Grant. Neither the names of Licensor, nor the\nnames of any contributors to the Original Work, nor any of their\ntrademarks or service marks, may be used to endorse or promote products\nderived from this Original Work without express prior permission of the\nLicensor. Except as expressly stated herein, nothing in this License\ngrants any license to Licensor's trademarks, copyrights, patents, trade\nsecrets or any other intellectual property. No patent license is granted\nto make, use, sell, offer for sale, have made, or import embodiments of\nany patent claims other than the licensed claims defined in Section 2.\nNo license is granted to the trademarks of Licensor even if such marks\nare included in the Original Work. Nothing in this License shall be\ninterpreted to prohibit Licensor from licensing under terms different from\nthis License any Original Work that Licensor otherwise would have a right\nto license.\n\n5) External Deployment. The term \"External Deployment\" means the use,\ndistribution, or communication of the Original Work or Derivative Works in\nany way such that the Original Work or Derivative Works may be used by\nanyone other than You, whether those works are distributed or communicated\nto those persons or made available as an application intended for use over\na network. As an express condition for the grants of license hereunder, You\nmust treat any External Deployment by You of the Original Work or a\nDerivative Work as a distribution under section 1(c).\n\n6) Attribution Rights. You must retain, in the Source Code of any Derivative\nWorks that You create, all copyright, patent, or trademark notices from the\nSource Code of the Original Work, as well as any notices of licensing and\nany descriptive text identified therein as an \"Attribution Notice.\" You must\ncause the Source Code for any Derivative Works that You create to carry a\nprominent Attribution Notice reasonably calculated to inform recipients that\nYou have modified the Original Work.\n\n7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that\nthe copyright in and to the Original Work and the patent rights granted\nherein by Licensor are owned by the Licensor or are sublicensed to You under\nthe terms of this License with the permission of the contributor(s) of those\ncopyrights and patent rights. Except as expressly stated in the immediately\npreceding sentence, the Original Work is provided under this License on an\n\"AS IS\" BASIS and WITHOUT WARRANTY, either express or implied, including,\nwithout limitation, the warranties of non-infringement, merchantability or\nfitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE\nORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an\nessential part of this License. No license to the Original Work is granted\nby this License except under this disclaimer.\n\n8) Limitation of Liability. Under no circumstances and under no legal theory,\nwhether in tort (including negligence), contract, or otherwise, shall the\nLicensor be liable to anyone for any indirect, special, incidental, or\nconsequential damages of any character arising as a result of this License or\nthe use of the Original Work including, without limitation, damages for loss\nof goodwill, work stoppage, computer failure or malfunction, or any and all\nother commercial damages or losses. This limitation of liability shall not\napply to the extent applicable law prohibits such limitation.\n\n9) Acceptance and Termination. If, at any time, You expressly assented to\nthis License, that assent indicates your clear and irrevocable acceptance of\nthis License and all of its terms and conditions. If You distribute or\ncommunicate copies of the Original Work or a Derivative Work, You must make\na reasonable effort under the circumstances to obtain the express assent of\nrecipients to the terms of this License. This License conditions your rights\nto undertake the activities listed in Section 1, including your right to\ncreate Derivative Works based upon the Original Work, and doing so without\nhonoring these terms and conditions is prohibited by copyright law and\ninternational treaty. Nothing in this License is intended to affect copyright\nexceptions and limitations (including \"fair use\" or \"fair dealing\"). This\nLicense shall terminate immediately and You may no longer exercise any of the\nrights granted to You by this License upon your failure to honor the\nconditions in Section 1(c).\n\n10) Termination for Patent Action. This License shall terminate automatically\nand You may no longer exercise any of the rights granted to You by this\nLicense as of the date You commence an action, including a cross-claim or\ncounterclaim, against Licensor or any licensee alleging that the Original\nWork infringes a patent. This termination provision shall not apply for an\naction alleging patent infringement by combinations of the Original Work with\nother software or hardware.\n\n11) Jurisdiction, Venue and Governing Law. Any action or suit relating to\nthis License may be brought only in the courts of a jurisdiction wherein the\nLicensor resides or in which Licensor conducts its primary business, and\nunder the laws of that jurisdiction excluding its conflict-of-law provisions.\nThe application of the United Nations Convention on Contracts for the\nInternational Sale of Goods is expressly excluded. Any use of the Original\nWork outside the scope of this License or after its termination shall be\nsubject to the requirements and penalties of copyright or patent law in the\nappropriate jurisdiction. This section shall survive the termination of this\nLicense.\n\n12) Attorneys' Fees. In any action to enforce the terms of this License or\nseeking damages relating thereto, the prevailing party shall be entitled to\nrecover its costs and expenses, including, without limitation, reasonable\nattorneys' fees and costs incurred in connection with such action, including\nany appeal of such action. This section shall survive the termination of\nthis License.\n\n13) Miscellaneous. If any provision of this License is held to be\nunenforceable, such provision shall be reformed only to the extent\nnecessary to make it enforceable.\n\n14) Definition of \"You\" in This License. \"You\" throughout this License,\nwhether in upper or lower case, means an individual or a legal entity\nexercising rights under, and complying with all of the terms of, this\nLicense. For legal entities, \"You\" includes any entity that controls,\nis controlled by, or is under common control with you. For purposes of\nthis definition, \"control\" means (i) the power, direct or indirect, to\ncause the direction or management of such entity, whether by contract or\notherwise, or (ii) ownership of fifty percent (50%) or more of the\noutstanding shares, or (iii) beneficial ownership of such entity.\n\n15) Right to Use. You may use the Original Work in all ways not\notherwise restricted or conditioned by this License or by law, and\nLicensor promises not to interfere with or be responsible for such\nuses by You.\n\n16) Modification of This License. This License is Copyright © 2005\nLawrence Rosen. Permission is granted to copy, distribute, or\ncommunicate this License without modification. Nothing in this License\npermits You to modify this License as applied to the Original Work or\nto Derivative Works. However, You may modify the text of this License\nand copy, distribute or communicate your modified version (the \"Modified\nLicense\") and apply it to other original works of authorship subject to\nthe following conditions: (i) You may not indicate in any way that your\nModified License is the \"Open Software License\" or \"OSL\" and you may not\nuse those names in the name of your Modified License; (ii) You must replace\nthe notice specified in the first paragraph above with the notice\n\"Licensed under <insert your license name here>\" or with a notice of your\nown that is not confusingly similar to the notice in this License; and\n(iii) You may not claim that your original works are open source software\nunless your Modified License has been approved by Open Source Initiative\n(OSI) and You comply with its license review and certification process.\n"
  },
  {
    "path": "Makefile",
    "content": "PROJ = lkmpg\nall: $(PROJ).pdf\n\n$(PROJ).pdf: lkmpg.tex\n\t@if ! hash latexmk; then echo \"No Latexmk found. See https://mg.readthedocs.io/latexmk.html for installation.\"; exit 1; fi\n\trm -rf _minted-$(PROJ)\n\tlatexmk -shell-escape lkmpg.tex -pdf\n\nhtml: lkmpg.tex html.cfg assets/Manrope_variable.ttf\n\tsed $ 's/\\t/    /g' lkmpg.tex > lkmpg-for-ht.tex\n\tmake4ht --shell-escape --utf8 --format html5 --config html.cfg --output-dir html  lkmpg-for-ht.tex \"fn-in\"\n\tln -sf lkmpg-for-ht.html html/index.html\n\tcp assets/Manrope_variable.ttf html/Manrope_variable.ttf\n\trm -f  lkmpg-for-ht.tex lkmpg-for-ht.xref lkmpg-for-ht.tmp lkmpg-for-ht.html lkmpg-for-ht.css lkmpg-for-ht.4ct lkmpg-for-ht.4tc lkmpg-for-ht.dvi lkmpg-for-ht.lg lkmpg-for-ht.idv lkmpg*.svg lkmpg-for-ht.log lkmpg-for-ht.aux\n\trm -rf _minted-$(PROJ) _minted-lkmpg-for-ht\n\nindent:\n\t(cd examples; find . -name '*.[ch]' | xargs clang-format -i)\n\nclean:\n\trm -f *.dvi *.aux *.log *.ps *.pdf *.out lkmpg.bbl lkmpg.blg lkmpg.lof lkmpg.toc lkmpg.fdb_latexmk lkmpg.fls\n\trm -rf html\n\n.PHONY: html\n"
  },
  {
    "path": "README.md",
    "content": "# The Linux Kernel Module Programming Guide\n\nThis project keeps the Linux Kernel Module Programming Guide up to date, with [working examples](examples/) for recent 5.x and 6.x kernel versions.\nThe guide has been around since 2001 and most copies of it on the web only describe old 2.6.x kernels.\n\nThe book can be freely accessed via https://sysprog21.github.io/lkmpg/ or [latest PDF file](https://github.com/sysprog21/lkmpg/releases).\nThe original guide may be found at [Linux Documentation Project](http://www.tldp.org/LDP/lkmpg/).\nYou may check other [freely available programming books](https://ebookfoundation.github.io/free-programming-books-search/) listed by The [Free Ebook Foundation](https://ebookfoundation.org/) or [Linux online books](https://onlinebooks.library.upenn.edu/webbin/book/browse?type=lcsubc&key=Linux) collected by [The Online Books Page](https://onlinebooks.library.upenn.edu/).\n\n## Getting Started\n\n### Summary\n1. Get the latest source code from the [GitHub page](https://github.com/sysprog21/lkmpg).\n2. Install the prerequisites.\n3. Generate PDF and/or HTML documents.\n\n### Step 1: Get the latest source code\n\nMake sure you can run `git` with an Internet connection.\n\n```shell\n$ git clone https://github.com/sysprog21/lkmpg.git && cd lkmpg\n```\n\n### Step 2: Install the prerequisites\n\nTo generate the book from source, [TeXLive](https://www.tug.org/texlive/) ([MacTeX](https://www.tug.org/mactex/)) is required.\n\nFor Ubuntu Linux, macOS, and other Unix-like systems, run the following command(s):\n\n```bash\n# Debian / Ubuntu\n$ sudo apt install make texlive-full\n\n# Arch / Manjaro\n$ sudo pacman -S make texlive-binextra texlive-bin\n\n# macOS\n$ brew install mactex\n$ sudo tlmgr update --self\n```\n\nNote that `latexmk` is required to generated PDF, and it probably has been installed on your OS already. If not, please follow the [installation guide](https://mg.readthedocs.io/latexmk.html#installation).\n\nIn macOS systems, package `Pygments` may not be pre-installed. If not, please refer to the [installation guide](https://pygments.org/download/) before generate documents.\n\nAlternatively, using [Docker](https://docs.docker.com/) is recommended, as it guarantees the same dependencies with our GitHub Actions workflow.\nAfter install [docker engine](https://docs.docker.com/engine/install/) on your machine, pull the docker image [twtug/lkmpg](https://hub.docker.com/r/twtug/lkmpg) and run in isolated containers.\n\n```shell\n# pull docker image and run it as container\n$ docker pull twtug/lkmpg\n$ docker run --rm -it -v $(pwd):/workdir twtug/lkmpg\n```\n\n[nerdctl](https://github.com/containerd/nerdctl) is a Docker-compatible command line tool for [containerd](https://containerd.io/), and you can replace the above `docker` commands with `nerdctl` counterparts.\n\n### Step 3: Generate PDF and/or HTML documents\n\nNow we could build document with following commands:\n\n```bash\n$ make all              # Generate PDF document\n$ make html             # Convert TeX to HTML\n$ make clean            # Delete generated files\n```\n\n## License\n\nThe Linux Kernel Module Programming Guide is a free book; you may reproduce and/or modify it under the terms of the [Open Software License](https://opensource.org/licenses/OSL-3.0).\nUse of this work is governed by a copyleft license that can be found in the `LICENSE` file.\n\nThe complementary sample code is licensed under GNU GPL version 2, as same as Linux kernel.\n"
  },
  {
    "path": "contrib.tex",
    "content": "Amit Dhingra,                  % <mechanicalamit@gmail.com>\nAndrew Kreimer,                % <algonell@gmail.com>\nAndrew Lin,                    % <35786166+classAndrew@users.noreply.github.com>\nAndy Shevchenko,               % <andriy.shevchenko@linux.intel.com>\nArush Sharma,                  % <46960231+arushsharma24@users.noreply.github.com>\nAykhan Hagverdili,             % <aykhanhagverdili@gmail.com>\nBenno Bielmeier,               % <32938211+bbenno@users.noreply.github.com>\nBob Lee,                       % <defru04002@gmail.com>\nBrad Baker,                    % <brad@brdbkr.com>\nChe-Chia Chang,                % <vivahavey@gmail.com>\nCheng-Shian Yeh,               % <yehchanshen@gmail.com>\nCheng-Yang Chou,               % <yphbchou0911@gmail.com>\nChih-En Lin,                   % <shiyn.lin@gmail.com>\nChih-Hsuan Yang,               % <zxc25077667@gmail.com>\nChih-Yu Chen,                  % <34228283+chihyu1206@users.noreply.github.com>\nChing-Hua (Vivian) Lin,        % <jkrvivian@gmail.com>\nChin Yik Ming,                 % <yikming2222@gmail.com>\nChung-Han Tsai,                % <jeremy90307@gmail.com>\ncvvletter,                     % <cvvletter@pm.me>\nCyril Brulebois,               % <cyril@debamax.com>\nDaniele Paolo Scarpazza,       % <>\nDavid Porter,                  % <>\ndemonsome,                     % <horseradish1208@gmail.com>\nDimo Velev,                    % <>\nEkang Monyet,                  % <ekangmonyet@posteo.net>\nEthan Chan,                    % <F04066028@gs.ncku.edu.tw>\nFrancois Audeon,               % <>\nGilad Reti,                    % <gilad.reti@gmail.com>\nHao.Dong,                      % <hao.dong.nj@outlook.com>\nheartofrain,                   % <heartofrain@outlook.com>\nHorst Schirmeier,              % <>\nHsin-Hsiang Peng,              % <hsinspeng@gmail.com>\nHung-Jen Pao,                  % <ginn0122@gmail.com>\nIgnacio Martin,                % <>\nI-Hsin Cheng,                  % <richard120310@gmail.com>\nIntegral,                      % <integral@member.fsf.org>\nIûnn Kiàn-îng,                 % <black.yangcr@gmail.com>\nJian-Xing Wu,                  % <fdgkhdkgh@gmail.com>\nJimmy Ma,                      % <jimmatw@gmail.com>\nJohan Calle,                   % <43998967+jcallemc@users.noreply.github.com>\nkeytouch,                      % <qsytech@126.com>\nKohei Otsuka,                  % <13173186+rjhcnf@users.noreply.github.com>\nKuan-Wei Chiu,                 % <visitorckw@gmail.com>\nmanbing,                       % <manbing3@gmail.com>\nMarconi Jiang,                 % <marconi1964@yahoo.com>\nmengxinayan,                   % <31788564+mengxinayan@users.noreply.github.com>\nMeng-Zong Tsai,                % <hwahwa649@gmail.com>\nPeter Lin,                     % <peterlin@qilai.dev>\nRoman Lakeev,                  % <>\nSam Erickson,                  % <samuelerickson977@gmail.com>\nShao-Tse Hung,                 % <ccs100203@gmail.com>\nShih-Sheng Yang,               % <james1qaz2wsx12qw@gmail.com>\nStacy Prowell,                 % <sprowell@gmail.com>\nSteven Lung,                   % <1030steven@gmail.com>\nTristan Lelong,                % <tristan.lelong@blunderer.org>\nTse-Wei Lin,                   % <20110901eric@outlook.com>\nTucker Polomik,                % <tucker.polomik@inficon.com>\nTyler Fanelli,                 % <tfanelli@redhat.com>\nVxTeemo,                       % <tcccvvv123@gmail.com>\nWei-Hsin Yeh,                  % <weihsinyeh168@gmail.com>\nWei-Lun Tsai,                  % <alan23273850@gmail.com>\nXatierlike Lee,                % <xatierlike@gmail.com>\nYan-Jie Chan,                  % <51120603+jouae@users.noreply.github.com>\nYen-Yu Chen,                   % <matt162162162@gmail.com>\nYin-Chiuan Chen,               % <leovincentseles@gmail.com>\nYi-Wei Lin,                    % <s921975628@gmail.com>\nYo-Jung Lin,                   % <0xff07@gmail.com>\nYu-Chun Lin,                   % <eleanor15x@gmail.com>\nYu-Hsiang Tseng,               % <asas1asas200@gmail.com>\nYYGO.                          % <srayuws@users.noreply.github.com>\n"
  },
  {
    "path": "examples/.clang-format",
    "content": "Language: Cpp\n\nAccessModifierOffset: -4\nAlignAfterOpenBracket: Align\nAlignConsecutiveAssignments: false\nAlignConsecutiveDeclarations: false\nAlignOperands: true\nAlignTrailingComments: false\nAllowAllParametersOfDeclarationOnNextLine: false\nAllowShortBlocksOnASingleLine: false\nAllowShortCaseLabelsOnASingleLine: false\nAllowShortFunctionsOnASingleLine: None\nAllowShortIfStatementsOnASingleLine: false\nAllowShortLoopsOnASingleLine: false\nAlwaysBreakAfterDefinitionReturnType: None\nAlwaysBreakAfterReturnType: None\nAlwaysBreakBeforeMultilineStrings: false\nAlwaysBreakTemplateDeclarations: false\nBinPackArguments: true\nBinPackParameters: true\n\nBraceWrapping:\n  AfterClass: false\n  AfterControlStatement: false\n  AfterEnum: false\n  AfterFunction: true\n  AfterNamespace: true\n  AfterObjCDeclaration: false\n  AfterStruct: false\n  AfterUnion: false\n  AfterExternBlock: false\n  BeforeCatch: false\n  BeforeElse: false\n  IndentBraces: false\n  SplitEmptyFunction: true\n  SplitEmptyRecord: true\n  SplitEmptyNamespace: true\n\nBreakBeforeBinaryOperators: None\nBreakBeforeBraces: Custom\nBreakBeforeInheritanceComma: false\nBreakBeforeTernaryOperators: false\nBreakConstructorInitializersBeforeComma: false\nBreakConstructorInitializers: BeforeComma\nBreakAfterJavaFieldAnnotations: false\nBreakStringLiterals: false\nColumnLimit: 80\nCommentPragmas: '^ IWYU pragma:'\nCompactNamespaces: false\nConstructorInitializerAllOnOneLineOrOnePerLine: false\nConstructorInitializerIndentWidth: 4\nContinuationIndentWidth: 4\nCpp11BracedListStyle: false\nDerivePointerAlignment: false\nDisableFormat: false\nExperimentalAutoDetectBinPacking: false\nFixNamespaceComments: false\n\nForEachMacros:\n  - 'list_for_each'\n  - 'list_for_each_safe'\n\nIncludeBlocks: Preserve\nIncludeCategories:\n  - Regex: '.*'\n    Priority: 1\nIncludeIsMainRegex: '(Test)?$'\nIndentCaseLabels: false\nIndentPPDirectives: None\nIndentWidth: 4\nIndentWrappedFunctionNames: false\nKeepEmptyLinesAtTheStartOfBlocks: false\nMacroBlockBegin: ''\nMacroBlockEnd: ''\nMaxEmptyLinesToKeep: 1\nNamespaceIndentation: None\n\nPointerAlignment: Right\nReflowComments: false\nSortIncludes: false\nSortUsingDeclarations: false\nSpaceAfterCStyleCast: false\nSpaceAfterTemplateKeyword: true\nSpaceBeforeAssignmentOperators: true\nSpaceBeforeCtorInitializerColon: true\nSpaceBeforeInheritanceColon: true\nSpaceBeforeParens: ControlStatements\nSpaceBeforeRangeBasedForLoopColon: true\nSpaceInEmptyParentheses: false\nSpacesBeforeTrailingComments: 1\nSpacesInAngles: false\nSpacesInContainerLiterals: false\nSpacesInCStyleCastParentheses: false\nSpacesInParentheses: false\nSpacesInSquareBrackets: false\nStandard: Cpp03\nTabWidth: 4\nUseTab: Never\n"
  },
  {
    "path": "examples/Makefile",
    "content": "obj-m += hello-1.o\nobj-m += hello-2.o\nobj-m += hello-3.o\nobj-m += hello-4.o\nobj-m += hello-5.o\nobj-m += startstop.o\nstartstop-objs := start.o stop.o\nobj-m += chardev.o\nobj-m += procfs1.o\nobj-m += procfs2.o\nobj-m += procfs3.o\nobj-m += procfs4.o\nobj-m += hello-sysfs.o\nobj-m += sleep.o\nobj-m += print_string.o\nobj-m += kbleds.o\nobj-m += sched.o\nobj-m += chardev2.o\nobj-m += syscall-steal.o\nobj-m += intrpt.o\nobj-m += completions.o\nobj-m += example_tasklet.o\nobj-m += devicemodel.o\nobj-m += example_spinlock.o\nobj-m += example_rwlock.o\nobj-m += example_atomic.o\nobj-m += example_mutex.o\nobj-m += bottomhalf.o\nobj-m += bh_threaded.o\nobj-m += ioctl.o\nobj-m += vinput.o\nobj-m += vkbd.o\nobj-m += static_key.o\nobj-m += led.o\nobj-m += dht11.o\nobj-m += devicetree.o\n\nKDIR ?= /lib/modules/$(shell uname -r)/build\nPWD := $(CURDIR)\n\nifeq ($(CONFIG_STATUS_CHECK_GCC),y)\nCC=$(STATUS_CHECK_GCC)\nccflags-y += -fanalyzer\nendif\n\nall:\n\t$(MAKE) -C $(KDIR) CC=$(CC) M=$(PWD) modules\n\nclean:\n\t$(MAKE) -C $(KDIR) CC=$(CC) M=$(PWD) clean\n\t$(RM) other/cat_nonblock *.plist\n\nindent:\n\tclang-format -i *.[ch]\n\tclang-format -i other/*.[ch]\n"
  },
  {
    "path": "examples/bh_threaded.c",
    "content": "/*\n * bh_thread.c - Top and bottom half interrupt handling\n *\n * Based upon the RPi example by Stefan Wendler (devnull@kaltpost.de)\n * from:\n *    https://github.com/wendlers/rpi-kmod-samples\n *\n * Press one button to turn on a LED and another to turn it off\n */\n\n#include <linux/module.h>\n#include <linux/kernel.h>\n#include <linux/gpio.h>\n#include <linux/delay.h>\n#include <linux/interrupt.h>\n#include <linux/version.h>\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 10, 0)\n#define NO_GPIO_REQUEST_ARRAY\n#endif\n\nstatic int button_irqs[] = { -1, -1 };\n\n/* Define GPIOs for LEDs.\n * FIXME: Change the numbers for the GPIO on your board.\n */\nstatic struct gpio leds[] = { { 4, GPIOF_OUT_INIT_LOW, \"LED 1\" } };\n\n/* Define GPIOs for BUTTONS\n * FIXME: Change the numbers for the GPIO on your board.\n */\nstatic struct gpio buttons[] = {\n    { 17, GPIOF_IN, \"LED 1 ON BUTTON\" },\n    { 18, GPIOF_IN, \"LED 1 OFF BUTTON\" },\n};\n\n/* This happens immediately, when the IRQ is triggered */\nstatic irqreturn_t button_top_half(int irq, void *ident)\n{\n    return IRQ_WAKE_THREAD;\n}\n\n/* This can happen at leisure, freeing up IRQs for other high priority task */\nstatic irqreturn_t button_bottom_half(int irq, void *ident)\n{\n    pr_info(\"Bottom half task starts\\n\");\n    mdelay(500); /* do something which takes a while */\n    pr_info(\"Bottom half task ends\\n\");\n    return IRQ_HANDLED;\n}\n\nstatic int __init bottomhalf_init(void)\n{\n    int ret = 0;\n\n    pr_info(\"%s\\n\", __func__);\n\n/* register LED gpios */\n#ifdef NO_GPIO_REQUEST_ARRAY\n    ret = gpio_request(leds[0].gpio, leds[0].label);\n#else\n    ret = gpio_request_array(leds, ARRAY_SIZE(leds));\n#endif\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for LEDs: %d\\n\", ret);\n        return ret;\n    }\n\n/* register BUTTON gpios */\n#ifdef NO_GPIO_REQUEST_ARRAY\n    ret = gpio_request(buttons[0].gpio, buttons[0].label);\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for BUTTONs: %d\\n\", ret);\n        goto fail1;\n    }\n\n    ret = gpio_request(buttons[1].gpio, buttons[1].label);\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for BUTTONs: %d\\n\", ret);\n        goto fail2;\n    }\n#else\n    ret = gpio_request_array(buttons, ARRAY_SIZE(buttons));\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for BUTTONs: %d\\n\", ret);\n        goto fail1;\n    }\n#endif\n\n    pr_info(\"Current button1 value: %d\\n\", gpio_get_value(buttons[0].gpio));\n\n    ret = gpio_to_irq(buttons[0].gpio);\n\n    if (ret < 0) {\n        pr_err(\"Unable to request IRQ: %d\\n\", ret);\n#ifdef NO_GPIO_REQUEST_ARRAY\n        goto fail3;\n#else\n        goto fail2;\n#endif\n    }\n\n    button_irqs[0] = ret;\n\n    pr_info(\"Successfully requested BUTTON1 IRQ # %d\\n\", button_irqs[0]);\n\n    ret = request_threaded_irq(button_irqs[0], button_top_half,\n                               button_bottom_half,\n                               IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,\n                               \"gpiomod#button1\", &buttons[0]);\n\n    if (ret) {\n        pr_err(\"Unable to request IRQ: %d\\n\", ret);\n#ifdef NO_GPIO_REQUEST_ARRAY\n        goto fail3;\n#else\n        goto fail2;\n#endif\n    }\n\n    ret = gpio_to_irq(buttons[1].gpio);\n\n    if (ret < 0) {\n        pr_err(\"Unable to request IRQ: %d\\n\", ret);\n#ifdef NO_GPIO_REQUEST_ARRAY\n        goto fail3;\n#else\n        goto fail2;\n#endif\n    }\n\n    button_irqs[1] = ret;\n\n    pr_info(\"Successfully requested BUTTON2 IRQ # %d\\n\", button_irqs[1]);\n\n    ret = request_threaded_irq(button_irqs[1], button_top_half,\n                               button_bottom_half,\n                               IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,\n                               \"gpiomod#button2\", &buttons[1]);\n\n    if (ret) {\n        pr_err(\"Unable to request IRQ: %d\\n\", ret);\n#ifdef NO_GPIO_REQUEST_ARRAY\n        goto fail4;\n#else\n        goto fail3;\n#endif\n    }\n\n    return 0;\n\n/* cleanup what has been setup so far */\n#ifdef NO_GPIO_REQUEST_ARRAY\nfail4:\n    free_irq(button_irqs[0], &buttons[0]);\n\nfail3:\n    gpio_free(buttons[1].gpio);\n\nfail2:\n    gpio_free(buttons[0].gpio);\n\nfail1:\n    gpio_free(leds[0].gpio);\n#else\nfail3:\n    free_irq(button_irqs[0], &buttons[0]);\n\nfail2:\n    gpio_free_array(buttons, ARRAY_SIZE(buttons));\n\nfail1:\n    gpio_free_array(leds, ARRAY_SIZE(leds));\n#endif\n\n    return ret;\n}\n\nstatic void __exit bottomhalf_exit(void)\n{\n    pr_info(\"%s\\n\", __func__);\n\n    /* free irqs */\n    free_irq(button_irqs[0], &buttons[0]);\n    free_irq(button_irqs[1], &buttons[1]);\n\n/* turn all LEDs off */\n#ifdef NO_GPIO_REQUEST_ARRAY\n    gpio_set_value(leds[0].gpio, 0);\n#else\n    int i;\n    for (i = 0; i < ARRAY_SIZE(leds); i++)\n        gpio_set_value(leds[i].gpio, 0);\n#endif\n\n/* unregister */\n#ifdef NO_GPIO_REQUEST_ARRAY\n    gpio_free(leds[0].gpio);\n    gpio_free(buttons[0].gpio);\n    gpio_free(buttons[1].gpio);\n#else\n    gpio_free_array(leds, ARRAY_SIZE(leds));\n    gpio_free_array(buttons, ARRAY_SIZE(buttons));\n#endif\n}\n\nmodule_init(bottomhalf_init);\nmodule_exit(bottomhalf_exit);\n\nMODULE_LICENSE(\"GPL\");\nMODULE_DESCRIPTION(\"Interrupt with top and bottom half\");\n"
  },
  {
    "path": "examples/bottomhalf.c",
    "content": "/*\n * bottomhalf.c - Top and bottom half interrupt handling\n *\n * Based upon the RPi example by Stefan Wendler (devnull@kaltpost.de)\n * from:\n *    https://github.com/wendlers/rpi-kmod-samples\n *\n * Press one button to turn on an LED and another to turn it off\n */\n\n#include <linux/delay.h>\n#include <linux/gpio.h>\n#include <linux/interrupt.h>\n#include <linux/module.h>\n#include <linux/printk.h>\n#include <linux/init.h>\n#include <linux/version.h>\n#include <linux/workqueue.h>\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 10, 0)\n#define NO_GPIO_REQUEST_ARRAY\n#endif\n\nstatic int button_irqs[] = { -1, -1 };\n\n/* Define GPIOs for LEDs.\n * TODO: Change the numbers for the GPIO on your board.\n */\nstatic struct gpio leds[] = { { 4, GPIOF_OUT_INIT_LOW, \"LED 1\" } };\n\n/* Define GPIOs for BUTTONS\n * TODO: Change the numbers for the GPIO on your board.\n */\nstatic struct gpio buttons[] = {\n    { 17, GPIOF_IN, \"LED 1 ON BUTTON\" },\n    { 18, GPIOF_IN, \"LED 1 OFF BUTTON\" },\n};\n\n/* Workqueue function containing some non-trivial amount of processing */\nstatic void bottomhalf_work_fn(struct work_struct *work)\n{\n    pr_info(\"Bottom half workqueue starts\\n\");\n    /* do something which takes a while */\n    msleep(500);\n\n    pr_info(\"Bottom half workqueue ends\\n\");\n}\n\nstatic DECLARE_WORK(bottomhalf_work, bottomhalf_work_fn);\n\n/* interrupt function triggered when a button is pressed */\nstatic irqreturn_t button_isr(int irq, void *data)\n{\n    /* Do something quickly right now */\n    if (irq == button_irqs[0] && !gpio_get_value(leds[0].gpio))\n        gpio_set_value(leds[0].gpio, 1);\n    else if (irq == button_irqs[1] && gpio_get_value(leds[0].gpio))\n        gpio_set_value(leds[0].gpio, 0);\n\n    /* Do the rest at leisure via the scheduler */\n    schedule_work(&bottomhalf_work);\n    return IRQ_HANDLED;\n}\n\nstatic int __init bottomhalf_init(void)\n{\n    int ret = 0;\n\n    pr_info(\"%s\\n\", __func__);\n\n    /* register LED gpios */\n#ifdef NO_GPIO_REQUEST_ARRAY\n    ret = gpio_request(leds[0].gpio, leds[0].label);\n#else\n    ret = gpio_request_array(leds, ARRAY_SIZE(leds));\n#endif\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for LEDs: %d\\n\", ret);\n        return ret;\n    }\n\n    /* register BUTTON gpios */\n#ifdef NO_GPIO_REQUEST_ARRAY\n    ret = gpio_request(buttons[0].gpio, buttons[0].label);\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for BUTTONs: %d\\n\", ret);\n        goto fail1;\n    }\n\n    ret = gpio_request(buttons[1].gpio, buttons[1].label);\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for BUTTONs: %d\\n\", ret);\n        goto fail2;\n    }\n#else\n    ret = gpio_request_array(buttons, ARRAY_SIZE(buttons));\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for BUTTONs: %d\\n\", ret);\n        goto fail1;\n    }\n#endif\n\n    pr_info(\"Current button1 value: %d\\n\", gpio_get_value(buttons[0].gpio));\n\n    ret = gpio_to_irq(buttons[0].gpio);\n\n    if (ret < 0) {\n        pr_err(\"Unable to request IRQ: %d\\n\", ret);\n#ifdef NO_GPIO_REQUEST_ARRAY\n        goto fail3;\n#else\n        goto fail2;\n#endif\n    }\n\n    button_irqs[0] = ret;\n\n    pr_info(\"Successfully requested BUTTON1 IRQ # %d\\n\", button_irqs[0]);\n\n    ret = request_irq(button_irqs[0], button_isr,\n                      IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,\n                      \"gpiomod#button1\", NULL);\n\n    if (ret) {\n        pr_err(\"Unable to request IRQ: %d\\n\", ret);\n#ifdef NO_GPIO_REQUEST_ARRAY\n        goto fail3;\n#else\n        goto fail2;\n#endif\n    }\n\n    ret = gpio_to_irq(buttons[1].gpio);\n\n    if (ret < 0) {\n        pr_err(\"Unable to request IRQ: %d\\n\", ret);\n#ifdef NO_GPIO_REQUEST_ARRAY\n        goto fail3;\n#else\n        goto fail2;\n#endif\n    }\n\n    button_irqs[1] = ret;\n\n    pr_info(\"Successfully requested BUTTON2 IRQ # %d\\n\", button_irqs[1]);\n\n    ret = request_irq(button_irqs[1], button_isr,\n                      IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,\n                      \"gpiomod#button2\", NULL);\n\n    if (ret) {\n        pr_err(\"Unable to request IRQ: %d\\n\", ret);\n#ifdef NO_GPIO_REQUEST_ARRAY\n        goto fail4;\n#else\n        goto fail3;\n#endif\n    }\n\n    return 0;\n\n/* cleanup what has been setup so far */\n#ifdef NO_GPIO_REQUEST_ARRAY\nfail4:\n    free_irq(button_irqs[0], NULL);\n\nfail3:\n    gpio_free(buttons[1].gpio);\n\nfail2:\n    gpio_free(buttons[0].gpio);\n\nfail1:\n    gpio_free(leds[0].gpio);\n#else\nfail3:\n    free_irq(button_irqs[0], NULL);\n\nfail2:\n    gpio_free_array(buttons, ARRAY_SIZE(buttons));\n\nfail1:\n    gpio_free_array(leds, ARRAY_SIZE(leds));\n#endif\n\n    return ret;\n}\n\nstatic void __exit bottomhalf_exit(void)\n{\n    pr_info(\"%s\\n\", __func__);\n\n    /* free irqs */\n    free_irq(button_irqs[0], NULL);\n    free_irq(button_irqs[1], NULL);\n\n    /* turn all LEDs off */\n#ifdef NO_GPIO_REQUEST_ARRAY\n    gpio_set_value(leds[0].gpio, 0);\n#else\n    int i;\n    for (i = 0; i < ARRAY_SIZE(leds); i++)\n        gpio_set_value(leds[i].gpio, 0);\n#endif\n\n    /* unregister */\n#ifdef NO_GPIO_REQUEST_ARRAY\n    gpio_free(leds[0].gpio);\n    gpio_free(buttons[0].gpio);\n    gpio_free(buttons[1].gpio);\n#else\n    gpio_free_array(leds, ARRAY_SIZE(leds));\n    gpio_free_array(buttons, ARRAY_SIZE(buttons));\n#endif\n}\n\nmodule_init(bottomhalf_init);\nmodule_exit(bottomhalf_exit);\n\nMODULE_LICENSE(\"GPL\");\nMODULE_DESCRIPTION(\"Interrupt with top and bottom half\");\n"
  },
  {
    "path": "examples/chardev.c",
    "content": "/*\n * chardev.c: Creates a read-only char device that says how many times\n * you have read from the dev file\n */\n\n#include <linux/atomic.h>\n#include <linux/cdev.h>\n#include <linux/delay.h>\n#include <linux/device.h>\n#include <linux/fs.h>\n#include <linux/init.h>\n#include <linux/kernel.h> /* for sprintf() */\n#include <linux/module.h>\n#include <linux/printk.h>\n#include <linux/types.h>\n#include <linux/uaccess.h> /* for get_user and put_user */\n#include <linux/version.h>\n\n#include <asm/errno.h>\n\n/*  Prototypes - this would normally go in a .h file */\nstatic int device_open(struct inode *, struct file *);\nstatic int device_release(struct inode *, struct file *);\nstatic ssize_t device_read(struct file *, char __user *, size_t, loff_t *);\nstatic ssize_t device_write(struct file *, const char __user *, size_t,\n                            loff_t *);\n\n#define DEVICE_NAME \"chardev\" /* Dev name as it appears in /proc/devices   */\n#define BUF_LEN 80 /* Max length of the message from the device */\n\n/* Global variables are declared as static, so are global within the file. */\n\nstatic int major; /* major number assigned to our device driver */\n\nenum {\n    CDEV_NOT_USED,\n    CDEV_EXCLUSIVE_OPEN,\n};\n\n/* Is device open? Used to prevent multiple access to device */\nstatic atomic_t already_open = ATOMIC_INIT(CDEV_NOT_USED);\n\nstatic char msg[BUF_LEN + 1]; /* The msg the device will give when asked */\n\nstatic struct class *cls;\n\nstatic struct file_operations chardev_fops = {\n    .read = device_read,\n    .write = device_write,\n    .open = device_open,\n    .release = device_release,\n};\n\nstatic int __init chardev_init(void)\n{\n    major = register_chrdev(0, DEVICE_NAME, &chardev_fops);\n\n    if (major < 0) {\n        pr_alert(\"Registering char device failed with %d\\n\", major);\n        return major;\n    }\n\n    pr_info(\"I was assigned major number %d.\\n\", major);\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 4, 0)\n    cls = class_create(DEVICE_NAME);\n#else\n    cls = class_create(THIS_MODULE, DEVICE_NAME);\n#endif\n    if (IS_ERR(cls)) {\n        pr_err(\"Failed to create class for device\\n\");\n        unregister_chrdev(major, DEVICE_NAME);\n        return PTR_ERR(cls);\n    }\n    device_create(cls, NULL, MKDEV(major, 0), NULL, DEVICE_NAME);\n\n    pr_info(\"Device created on /dev/%s\\n\", DEVICE_NAME);\n\n    return 0;\n}\n\nstatic void __exit chardev_exit(void)\n{\n    device_destroy(cls, MKDEV(major, 0));\n    class_destroy(cls);\n\n    /* Unregister the device */\n    unregister_chrdev(major, DEVICE_NAME);\n}\n\n/* Methods */\n\n/* Called when a process tries to open the device file, like\n * \"sudo cat /dev/chardev\"\n */\nstatic int device_open(struct inode *inode, struct file *file)\n{\n    static int counter = 0;\n\n    if (atomic_cmpxchg(&already_open, CDEV_NOT_USED, CDEV_EXCLUSIVE_OPEN))\n        return -EBUSY;\n\n    sprintf(msg, \"I already told you %d times Hello world!\\n\", counter++);\n\n    return 0;\n}\n\n/* Called when a process closes the device file. */\nstatic int device_release(struct inode *inode, struct file *file)\n{\n    /* We're now ready for our next caller */\n    atomic_set(&already_open, CDEV_NOT_USED);\n\n    return 0;\n}\n\n/* Called when a process, which already opened the dev file, attempts to\n * read from it.\n */\nstatic ssize_t device_read(struct file *filp, /* see include/linux/fs.h   */\n                           char __user *buffer, /* buffer to fill with data */\n                           size_t length, /* length of the buffer     */\n                           loff_t *offset)\n{\n    /* Number of bytes actually written to the buffer */\n    int bytes_read = 0;\n    const char *msg_ptr = msg;\n\n    if (!*(msg_ptr + *offset)) { /* we are at the end of message */\n        *offset = 0; /* reset the offset */\n        return 0; /* signify end of file */\n    }\n\n    msg_ptr += *offset;\n\n    /* Actually put the data into the buffer */\n    while (length && *msg_ptr) {\n        /* The buffer is in the user data segment, not the kernel\n         * segment so \"*\" assignment won't work.  We have to use\n         * put_user which copies data from the kernel data segment to\n         * the user data segment.\n         */\n        put_user(*(msg_ptr++), buffer++);\n        length--;\n        bytes_read++;\n    }\n\n    *offset += bytes_read;\n\n    /* Most read functions return the number of bytes put into the buffer. */\n    return bytes_read;\n}\n\n/* Called when a process writes to dev file: echo \"hi\" | sudo tee /dev/chardev */\nstatic ssize_t device_write(struct file *filp, const char __user *buff,\n                            size_t len, loff_t *off)\n{\n    pr_alert(\"Sorry, this operation is not supported.\\n\");\n    return -EINVAL;\n}\n\nmodule_init(chardev_init);\nmodule_exit(chardev_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/chardev.h",
    "content": "/*\n * chardev.h - the header file with the ioctl definitions.\n *\n * The declarations here have to be in a header file, because they need\n * to be known both to the kernel module (in chardev2.c) and the process\n * calling ioctl() (in userspace_ioctl.c).\n */\n\n#ifndef CHARDEV_H\n#define CHARDEV_H\n\n#include <linux/ioctl.h>\n\n/* The major device number. We can not rely on dynamic registration\n * any more, because ioctls need to know it.\n */\n#define MAJOR_NUM 100\n\n/* Set the message of the device driver */\n#define IOCTL_SET_MSG _IOW(MAJOR_NUM, 0, char *)\n/* _IOW means that we are creating an ioctl command number for passing\n * information from a user process to the kernel module.\n *\n * The first arguments, MAJOR_NUM, is the major device number we are using.\n *\n * The second argument is the number of the command (there could be several\n * with different meanings).\n *\n * The third argument is the type we want to get from the process to the\n * kernel.\n */\n\n/* Get the message of the device driver */\n#define IOCTL_GET_MSG _IOR(MAJOR_NUM, 1, char *)\n/* This IOCTL is used for output, to get the message of the device driver.\n * However, we still need the buffer to place the message in to be input,\n * as it is allocated by the process.\n */\n\n/* Get the n'th byte of the message */\n#define IOCTL_GET_NTH_BYTE _IOWR(MAJOR_NUM, 2, int)\n/* The IOCTL is used for both input and output. It receives from the user\n * a number, n, and returns message[n].\n */\n\n/* The name of the device file */\n#define DEVICE_FILE_NAME \"char_dev\"\n#define DEVICE_PATH \"/dev/char_dev\"\n\n#endif\n"
  },
  {
    "path": "examples/chardev2.c",
    "content": "/*\n * chardev2.c - Create an input/output character device\n */\n\n#include <linux/atomic.h>\n#include <linux/cdev.h>\n#include <linux/delay.h>\n#include <linux/device.h>\n#include <linux/fs.h>\n#include <linux/init.h>\n#include <linux/module.h> /* Specifically, a module */\n#include <linux/printk.h>\n#include <linux/types.h>\n#include <linux/uaccess.h> /* for get_user and put_user */\n#include <linux/version.h>\n\n#include <asm/errno.h>\n\n#include \"chardev.h\"\n#define DEVICE_NAME \"char_dev\"\n#define BUF_LEN 80\n\nenum {\n    CDEV_NOT_USED,\n    CDEV_EXCLUSIVE_OPEN,\n};\n\n/* Is the device open right now? Used to prevent concurrent access into\n * the same device\n */\nstatic atomic_t already_open = ATOMIC_INIT(CDEV_NOT_USED);\n\n/* The message the device will give when asked */\nstatic char message[BUF_LEN + 1];\n\nstatic struct class *cls;\n\n/* This is called whenever a process attempts to open the device file */\nstatic int device_open(struct inode *inode, struct file *file)\n{\n    pr_info(\"device_open(%p)\\n\", file);\n\n    return 0;\n}\n\nstatic int device_release(struct inode *inode, struct file *file)\n{\n    pr_info(\"device_release(%p,%p)\\n\", inode, file);\n\n    return 0;\n}\n\n/* This function is called whenever a process which has already opened the\n * device file attempts to read from it.\n */\nstatic ssize_t device_read(struct file *file, /* see include/linux/fs.h   */\n                           char __user *buffer, /* buffer to be filled  */\n                           size_t length, /* length of the buffer     */\n                           loff_t *offset)\n{\n    /* Number of bytes actually written to the buffer */\n    int bytes_read = 0;\n    /* How far did the process reading the message get? Useful if the message\n     * is larger than the size of the buffer we get to fill in device_read.\n     */\n    const char *message_ptr = message;\n\n    if (!*(message_ptr + *offset)) { /* we are at the end of message */\n        *offset = 0; /* reset the offset */\n        return 0; /* signify end of file */\n    }\n\n    message_ptr += *offset;\n\n    /* Actually put the data into the buffer */\n    while (length && *message_ptr) {\n        /* Because the buffer is in the user data segment, not the kernel\n         * data segment, assignment would not work. Instead, we have to\n         * use put_user which copies data from the kernel data segment to\n         * the user data segment.\n         */\n        put_user(*(message_ptr++), buffer++);\n        length--;\n        bytes_read++;\n    }\n\n    pr_info(\"Read %d bytes, %ld left\\n\", bytes_read, length);\n\n    *offset += bytes_read;\n\n    /* Read functions are supposed to return the number of bytes actually\n     * inserted into the buffer.\n     */\n    return bytes_read;\n}\n\n/* called when somebody tries to write into our device file. */\nstatic ssize_t device_write(struct file *file, const char __user *buffer,\n                            size_t length, loff_t *offset)\n{\n    int i;\n\n    pr_info(\"device_write(%p,%p,%ld)\", file, buffer, length);\n\n    for (i = 0; i < length && i < BUF_LEN; i++)\n        get_user(message[i], buffer + i);\n\n    /* Again, return the number of input characters used. */\n    return i;\n}\n\n/* This function is called whenever a process tries to do an ioctl on our\n * device file. We get two extra parameters (additional to the inode and file\n * structures, which all device functions get): the number of the ioctl called\n * and the parameter given to the ioctl function.\n *\n * If the ioctl is write or read/write (meaning output is returned to the\n * calling process), the ioctl call returns the output of this function.\n */\nstatic long\ndevice_ioctl(struct file *file, /* ditto */\n             unsigned int ioctl_num, /* number and param for ioctl */\n             unsigned long ioctl_param)\n{\n    int i;\n    long ret = 0;\n\n    /* We don't want to talk to two processes at the same time. */\n    if (atomic_cmpxchg(&already_open, CDEV_NOT_USED, CDEV_EXCLUSIVE_OPEN))\n        return -EBUSY;\n\n    /* Switch according to the ioctl called */\n    switch (ioctl_num) {\n    case IOCTL_SET_MSG: {\n        /* Receive a pointer to a message (in user space) and set that to\n         * be the device's message. Get the parameter given to ioctl by\n         * the process.\n         */\n        char __user *tmp = (char __user *)ioctl_param;\n        char ch;\n\n        /* Find the length of the message */\n        get_user(ch, tmp);\n        for (i = 0; ch && i < BUF_LEN; i++, tmp++)\n            get_user(ch, tmp);\n\n        device_write(file, (char __user *)ioctl_param, i, NULL);\n        break;\n    }\n    case IOCTL_GET_MSG: {\n        loff_t offset = 0;\n\n        /* Give the current message to the calling process - the parameter\n         * we got is a pointer, fill it.\n         */\n        i = device_read(file, (char __user *)ioctl_param, 99, &offset);\n\n        /* Put a zero at the end of the buffer, so it will be properly\n         * terminated.\n         */\n        put_user('\\0', (char __user *)ioctl_param + i);\n        break;\n    }\n    case IOCTL_GET_NTH_BYTE:\n        /* This ioctl is both input (ioctl_param) and output (the return\n         * value of this function).\n         */\n        ret = (long)message[ioctl_param];\n        break;\n    }\n\n    /* We're now ready for our next caller */\n    atomic_set(&already_open, CDEV_NOT_USED);\n\n    return ret;\n}\n\n/* Module Declarations */\n\n/* This structure will hold the functions to be called when a process does\n * something to the device we created. Since a pointer to this structure\n * is kept in the devices table, it can't be local to init_module. NULL is\n * for unimplemented functions.\n */\nstatic struct file_operations fops = {\n    .read = device_read,\n    .write = device_write,\n    .unlocked_ioctl = device_ioctl,\n    .open = device_open,\n    .release = device_release, /* a.k.a. close */\n};\n\n/* Initialize the module - Register the character device */\nstatic int __init chardev2_init(void)\n{\n    /* Register the character device (at least try) */\n    int ret_val = register_chrdev(MAJOR_NUM, DEVICE_NAME, &fops);\n\n    /* Negative values signify an error */\n    if (ret_val < 0) {\n        pr_alert(\"%s failed with %d\\n\",\n                 \"Sorry, registering the character device \", ret_val);\n        return ret_val;\n    }\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 4, 0)\n    cls = class_create(DEVICE_FILE_NAME);\n#else\n    cls = class_create(THIS_MODULE, DEVICE_FILE_NAME);\n#endif\n    if (IS_ERR(cls)) {\n        pr_err(\"Failed to create class for device\\n\");\n        unregister_chrdev(MAJOR_NUM, DEVICE_NAME);\n        return PTR_ERR(cls);\n    }\n    device_create(cls, NULL, MKDEV(MAJOR_NUM, 0), NULL, DEVICE_FILE_NAME);\n\n    pr_info(\"Device created on /dev/%s\\n\", DEVICE_FILE_NAME);\n\n    return 0;\n}\n\n/* Cleanup - unregister the appropriate file from /proc */\nstatic void __exit chardev2_exit(void)\n{\n    device_destroy(cls, MKDEV(MAJOR_NUM, 0));\n    class_destroy(cls);\n\n    /* Unregister the device */\n    unregister_chrdev(MAJOR_NUM, DEVICE_NAME);\n}\n\nmodule_init(chardev2_init);\nmodule_exit(chardev2_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/completions.c",
    "content": "/*\n * completions.c\n */\n#include <linux/completion.h>\n#include <linux/err.h> /* for IS_ERR() */\n#include <linux/init.h>\n#include <linux/kthread.h>\n#include <linux/module.h>\n#include <linux/printk.h>\n#include <linux/version.h>\n\nstatic struct completion crank_comp;\nstatic struct completion flywheel_comp;\n\nstatic int machine_crank_thread(void *arg)\n{\n    pr_info(\"Turn the crank\\n\");\n\n    complete_all(&crank_comp);\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 17, 0)\n    kthread_complete_and_exit(&crank_comp, 0);\n#else\n    complete_and_exit(&crank_comp, 0);\n#endif\n}\n\nstatic int machine_flywheel_spinup_thread(void *arg)\n{\n    wait_for_completion(&crank_comp);\n\n    pr_info(\"Flywheel spins up\\n\");\n\n    complete_all(&flywheel_comp);\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 17, 0)\n    kthread_complete_and_exit(&flywheel_comp, 0);\n#else\n    complete_and_exit(&flywheel_comp, 0);\n#endif\n}\n\nstatic int __init completions_init(void)\n{\n    struct task_struct *crank_thread;\n    struct task_struct *flywheel_thread;\n\n    pr_info(\"completions example\\n\");\n\n    init_completion(&crank_comp);\n    init_completion(&flywheel_comp);\n\n    crank_thread = kthread_create(machine_crank_thread, NULL, \"KThread Crank\");\n    if (IS_ERR(crank_thread))\n        goto ERROR_THREAD_1;\n\n    flywheel_thread = kthread_create(machine_flywheel_spinup_thread, NULL,\n                                     \"KThread Flywheel\");\n    if (IS_ERR(flywheel_thread))\n        goto ERROR_THREAD_2;\n\n    wake_up_process(flywheel_thread);\n    wake_up_process(crank_thread);\n\n    return 0;\n\nERROR_THREAD_2:\n    kthread_stop(crank_thread);\nERROR_THREAD_1:\n\n    return -1;\n}\n\nstatic void __exit completions_exit(void)\n{\n    wait_for_completion(&crank_comp);\n    wait_for_completion(&flywheel_comp);\n\n    pr_info(\"completions exit\\n\");\n}\n\nmodule_init(completions_init);\nmodule_exit(completions_exit);\n\nMODULE_DESCRIPTION(\"Completions example\");\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/devicemodel.c",
    "content": "/*\n * devicemodel.c\n */\n#include <linux/kernel.h>\n#include <linux/module.h>\n#include <linux/platform_device.h>\n#include <linux/version.h>\n\nstruct devicemodel_data {\n    char *greeting;\n    int number;\n};\n\nstatic int devicemodel_probe(struct platform_device *dev)\n{\n    struct devicemodel_data *pd =\n        (struct devicemodel_data *)(dev->dev.platform_data);\n\n    pr_info(\"devicemodel probe\\n\");\n    pr_info(\"devicemodel greeting: %s; %d\\n\", pd->greeting, pd->number);\n\n    /* Your device initialization code */\n\n    return 0;\n}\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 11, 0)\nstatic void devicemodel_remove(struct platform_device *dev)\n{\n    pr_info(\"devicemodel example removed\\n\");\n    /* Your device removal code */\n}\n#else\nstatic int devicemodel_remove(struct platform_device *dev)\n{\n    pr_info(\"devicemodel example removed\\n\");\n    /* Your device removal code */\n    return 0;\n}\n#endif\n\nstatic int devicemodel_suspend(struct device *dev)\n{\n    pr_info(\"devicemodel example suspend\\n\");\n\n    /* Your device suspend code */\n\n    return 0;\n}\n\nstatic int devicemodel_resume(struct device *dev)\n{\n    pr_info(\"devicemodel example resume\\n\");\n\n    /* Your device resume code */\n\n    return 0;\n}\n\nstatic const struct dev_pm_ops devicemodel_pm_ops = {\n    .suspend = devicemodel_suspend,\n    .resume = devicemodel_resume,\n    .poweroff = devicemodel_suspend,\n    .freeze = devicemodel_suspend,\n    .thaw = devicemodel_resume,\n    .restore = devicemodel_resume,\n};\n\nstatic struct platform_driver devicemodel_driver = {\n    .driver =\n        {\n            .name = \"devicemodel_example\",\n            .pm = &devicemodel_pm_ops,\n        },\n    .probe = devicemodel_probe,\n    .remove = devicemodel_remove,\n};\n\nstatic int __init devicemodel_init(void)\n{\n    int ret;\n\n    pr_info(\"devicemodel init\\n\");\n\n    ret = platform_driver_register(&devicemodel_driver);\n\n    if (ret) {\n        pr_err(\"Unable to register driver\\n\");\n        return ret;\n    }\n\n    return 0;\n}\n\nstatic void __exit devicemodel_exit(void)\n{\n    pr_info(\"devicemodel exit\\n\");\n    platform_driver_unregister(&devicemodel_driver);\n}\n\nmodule_init(devicemodel_init);\nmodule_exit(devicemodel_exit);\n\nMODULE_LICENSE(\"GPL\");\nMODULE_DESCRIPTION(\"Linux Device Model example\");\n"
  },
  {
    "path": "examples/devicetree.c",
    "content": "/* devicetree.c - Demonstrates device tree interaction with kernel modules */\n\n#include <linux/init.h>\n#include <linux/kernel.h>\n#include <linux/module.h>\n#include <linux/of.h>\n#include <linux/of_device.h>\n#include <linux/platform_device.h>\n#include <linux/version.h>\n\n#define DRIVER_NAME \"lkmpg_devicetree\"\n\n/* Structure to hold device-specific data */\nstruct dt_device_data {\n    const char *label;\n    u32 reg_value;\n    u32 custom_value;\n    bool has_clock;\n};\n\n/* Probe function - called when device tree node matches */\nstatic int dt_probe(struct platform_device *pdev)\n{\n    struct device *dev = &pdev->dev;\n    struct device_node *np = dev->of_node;\n    struct dt_device_data *data;\n    const char *string_prop;\n    u32 value;\n    int ret;\n\n    pr_info(\"%s: Device tree probe called for %s\\n\", DRIVER_NAME,\n            np->full_name);\n\n    /* Allocate memory for device data */\n    data = devm_kzalloc(dev, sizeof(*data), GFP_KERNEL);\n    if (!data)\n        return -ENOMEM;\n\n    /* Read a string property */\n    ret = of_property_read_string(np, \"label\", &string_prop);\n    if (ret == 0) {\n        data->label = string_prop;\n        pr_info(\"%s: Found label property: %s\\n\", DRIVER_NAME, data->label);\n    } else {\n        data->label = \"unnamed\";\n        pr_info(\"%s: No label property found, using default\\n\", DRIVER_NAME);\n    }\n\n    /* Read a u32 property */\n    ret = of_property_read_u32(np, \"reg\", &value);\n    if (ret == 0) {\n        data->reg_value = value;\n        pr_info(\"%s: Found reg property: 0x%x\\n\", DRIVER_NAME, data->reg_value);\n    }\n\n    /* Read a custom u32 property */\n    ret = of_property_read_u32(np, \"lkmpg,custom-value\", &value);\n    if (ret == 0) {\n        data->custom_value = value;\n        pr_info(\"%s: Found custom-value property: %u\\n\", DRIVER_NAME,\n                data->custom_value);\n    } else {\n        data->custom_value = 42; /* Default value */\n        pr_info(\"%s: No custom-value found, using default: %u\\n\", DRIVER_NAME,\n                data->custom_value);\n    }\n\n    /* Check for presence of a property */\n    data->has_clock = of_property_read_bool(np, \"lkmpg,has-clock\");\n    pr_info(\"%s: has-clock property: %s\\n\", DRIVER_NAME,\n            data->has_clock ? \"present\" : \"absent\");\n\n    /* Store device data for later use */\n    platform_set_drvdata(pdev, data);\n\n    pr_info(\"%s: Device probe successful\\n\", DRIVER_NAME);\n    return 0;\n}\n\n/* Remove function - called when device is removed */\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 11, 0)\nstatic void dt_remove(struct platform_device *pdev)\n{\n    struct dt_device_data *data = platform_get_drvdata(pdev);\n\n    pr_info(\"%s: Removing device %s\\n\", DRIVER_NAME, data->label);\n    /* Cleanup is handled automatically by devm_* functions */\n}\n#else\nstatic int dt_remove(struct platform_device *pdev)\n{\n    struct dt_device_data *data = platform_get_drvdata(pdev);\n\n    pr_info(\"%s: Removing device %s\\n\", DRIVER_NAME, data->label);\n    /* Cleanup is handled automatically by devm_* functions */\n    return 0;\n}\n#endif\n\n/* Device tree match table - defines compatible strings this driver supports */\nstatic const struct of_device_id dt_match_table[] = {\n    {\n        .compatible = \"lkmpg,example-device\",\n    },\n    {\n        .compatible = \"lkmpg,another-device\",\n    },\n    {} /* Sentinel */\n};\nMODULE_DEVICE_TABLE(of, dt_match_table);\n\n/* Platform driver structure */\nstatic struct platform_driver dt_driver = {\n    .probe = dt_probe,\n    .remove = dt_remove,\n    .driver = {\n        .name = DRIVER_NAME,\n        .of_match_table = dt_match_table,\n    },\n};\n\n/* Module initialization */\nstatic int __init dt_init(void)\n{\n    int ret;\n\n    pr_info(\"%s: Initializing device tree example module\\n\", DRIVER_NAME);\n\n    /* Register the platform driver */\n    ret = platform_driver_register(&dt_driver);\n    if (ret) {\n        pr_err(\"%s: Failed to register platform driver\\n\", DRIVER_NAME);\n        return ret;\n    }\n\n    pr_info(\"%s: Module loaded successfully\\n\", DRIVER_NAME);\n    return 0;\n}\n\n/* Module cleanup */\nstatic void __exit dt_exit(void)\n{\n    pr_info(\"%s: Cleaning up device tree example module\\n\", DRIVER_NAME);\n    platform_driver_unregister(&dt_driver);\n}\n\nmodule_init(dt_init);\nmodule_exit(dt_exit);\n\nMODULE_LICENSE(\"GPL\");\nMODULE_DESCRIPTION(\"Device tree interaction example for LKMPG\");\n"
  },
  {
    "path": "examples/dht11.c",
    "content": "/*\n *  dht11.c - Using GPIO to read temperature and humidity from DHT11 sensor.\n */\n\n#include <linux/cdev.h>\n#include <linux/delay.h>\n#include <linux/device.h>\n#include <linux/fs.h>\n#include <linux/gpio.h>\n#include <linux/init.h>\n#include <linux/module.h>\n#include <linux/printk.h>\n#include <linux/types.h>\n#include <linux/uaccess.h>\n#include <linux/version.h>\n\n#include <asm/errno.h>\n\n#define GPIO_PIN_4 575\n#define DEVICE_NAME \"dht11\"\n#define DEVICE_CNT 1\n\nstatic char msg[64];\n\nstruct dht11_dev {\n    dev_t dev_num;\n    int major_num, minor_num;\n    struct cdev cdev;\n    struct class *cls;\n    struct device *dev;\n};\n\nstatic struct dht11_dev dht11_device;\n\n/* Define GPIOs for LEDs.\n * TODO: According to the requirements, search /sys/kernel/debug/gpio to \n * find the corresponding GPIO location.\n */\nstatic struct gpio dht11[] = { { GPIO_PIN_4, GPIOF_OUT_INIT_HIGH, \"Signal\" } };\n\nstatic int dht11_read_data(void)\n{\n    int timeout;\n    uint8_t sensor_data[5] = { 0 };\n    uint8_t i, j;\n\n    gpio_set_value(dht11[0].gpio, 0);\n    mdelay(20);\n    gpio_set_value(dht11[0].gpio, 1);\n    udelay(30);\n    gpio_direction_input(dht11[0].gpio);\n    udelay(2);\n\n    timeout = 300;\n    while (gpio_get_value(dht11[0].gpio) && timeout--)\n        udelay(1);\n\n    if (timeout == -1)\n        return -ETIMEDOUT;\n\n    timeout = 300;\n    while (!gpio_get_value(dht11[0].gpio) && timeout--)\n        udelay(1);\n\n    if (timeout == -1)\n        return -ETIMEDOUT;\n\n    timeout = 300;\n    while (gpio_get_value(dht11[0].gpio) && timeout--)\n        udelay(1);\n\n    if (timeout == -1)\n        return -ETIMEDOUT;\n\n    for (j = 0; j < 5; j++) {\n        uint8_t byte = 0;\n        for (i = 0; i < 8; i++) {\n            timeout = 300;\n            while (gpio_get_value(dht11[0].gpio) && timeout--)\n                udelay(1);\n\n            if (timeout == -1)\n                return -ETIMEDOUT;\n\n            timeout = 300;\n            while (!gpio_get_value(dht11[0].gpio) && timeout--)\n                udelay(1);\n\n            if (timeout == -1)\n                return -ETIMEDOUT;\n\n            udelay(50);\n            byte <<= 1;\n            if (gpio_get_value(dht11[0].gpio))\n                byte |= 0x01;\n        }\n        sensor_data[j] = byte;\n    }\n\n    if (sensor_data[4] != (uint8_t)(sensor_data[0] + sensor_data[1] +\n                                    sensor_data[2] + sensor_data[3]))\n        return -EIO;\n\n    gpio_direction_output(dht11[0].gpio, 1);\n    sprintf(msg, \"Humidity: %d%%\\nTemperature: %d deg C\\n\", sensor_data[0],\n            sensor_data[2]);\n\n    return 0;\n}\n\nstatic int device_open(struct inode *inode, struct file *file)\n{\n    int ret, retry;\n\n    for (retry = 0; retry < 5; ++retry) {\n        ret = dht11_read_data();\n        if (ret == 0)\n            return 0;\n        msleep(10);\n    }\n    gpio_direction_output(dht11[0].gpio, 1);\n\n    return ret;\n}\n\nstatic int device_release(struct inode *inode, struct file *file)\n{\n    return 0;\n}\n\nstatic ssize_t device_read(struct file *filp, char __user *buffer,\n                           size_t length, loff_t *offset)\n{\n    int msg_len = strlen(msg);\n\n    if (*offset >= msg_len)\n        return 0;\n\n    size_t remain = msg_len - *offset;\n    size_t bytes_read = min(length, remain);\n\n    if (copy_to_user(buffer, msg + *offset, bytes_read))\n        return -EFAULT;\n\n    *offset += bytes_read;\n\n    return bytes_read;\n}\n\nstatic struct file_operations fops = {\n    .owner = THIS_MODULE,\n    .open = device_open,\n    .release = device_release,\n    .read = device_read,\n};\n\n/* Initialize the module - Register the character device */\nstatic int __init dht11_init(void)\n{\n    int ret = 0;\n\n    /* Determine whether dynamic allocation of the device number is needed. */\n    if (dht11_device.major_num) {\n        dht11_device.dev_num =\n            MKDEV(dht11_device.major_num, dht11_device.minor_num);\n        ret = register_chrdev_region(dht11_device.dev_num, DEVICE_CNT,\n                                     DEVICE_NAME);\n    } else {\n        ret = alloc_chrdev_region(&dht11_device.dev_num, 0, DEVICE_CNT,\n                                  DEVICE_NAME);\n    }\n\n    /* Negative values signify an error */\n    if (ret < 0) {\n        pr_alert(\"Failed to register character device, error: %d\\n\", ret);\n        return ret;\n    }\n\n    pr_info(\"Major = %d, Minor = %d\\n\", MAJOR(dht11_device.dev_num),\n            MINOR(dht11_device.dev_num));\n\n    /* Prevents module unloading while operations are in use */\n    dht11_device.cdev.owner = THIS_MODULE;\n\n    cdev_init(&dht11_device.cdev, &fops);\n    ret = cdev_add(&dht11_device.cdev, dht11_device.dev_num, 1);\n    if (ret) {\n        pr_err(\"Failed to add the device to the system\\n\");\n        goto fail1;\n    }\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 4, 0)\n    dht11_device.cls = class_create(DEVICE_NAME);\n#else\n    dht11_device.cls = class_create(THIS_MODULE, DEVICE_NAME);\n#endif\n    if (IS_ERR(dht11_device.cls)) {\n        pr_err(\"Failed to create class for device\\n\");\n        ret = PTR_ERR(dht11_device.cls);\n        goto fail2;\n    }\n\n    dht11_device.dev = device_create(dht11_device.cls, NULL,\n                                     dht11_device.dev_num, NULL, DEVICE_NAME);\n    if (IS_ERR(dht11_device.dev)) {\n        pr_err(\"Failed to create the device file\\n\");\n        ret = PTR_ERR(dht11_device.dev);\n        goto fail3;\n    }\n\n    pr_info(\"Device created on /dev/%s\\n\", DEVICE_NAME);\n\n    ret = gpio_request(dht11[0].gpio, dht11[0].label);\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for dht11: %d\\n\", ret);\n        goto fail4;\n    }\n\n    ret = gpio_direction_output(dht11[0].gpio, 1);\n\n    if (ret) {\n        pr_err(\"Failed to set GPIO %d direction\\n\", dht11[0].gpio);\n        goto fail5;\n    }\n\n    return 0;\n\nfail5:\n    gpio_free(dht11[0].gpio);\n\nfail4:\n    device_destroy(dht11_device.cls, dht11_device.dev_num);\n\nfail3:\n    class_destroy(dht11_device.cls);\n\nfail2:\n    cdev_del(&dht11_device.cdev);\n\nfail1:\n    unregister_chrdev_region(dht11_device.dev_num, DEVICE_CNT);\n\n    return ret;\n}\n\nstatic void __exit dht11_exit(void)\n{\n    gpio_set_value(dht11[0].gpio, 0);\n    gpio_free(dht11[0].gpio);\n\n    device_destroy(dht11_device.cls, dht11_device.dev_num);\n    class_destroy(dht11_device.cls);\n    cdev_del(&dht11_device.cdev);\n    unregister_chrdev_region(dht11_device.dev_num, DEVICE_CNT);\n}\n\nmodule_init(dht11_init);\nmodule_exit(dht11_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/dt-overlay.dts",
    "content": "/*\n * Device Tree Overlay for LKMPG Device Tree Example\n * \n * This overlay can be compiled and loaded on systems that support\n * runtime device tree overlays (like Raspberry Pi).\n *\n * Compile with:\n *   dtc -@ -I dts -O dtb -o dt-overlay.dtbo dt-overlay.dts\n *\n * Load with (on Raspberry Pi):\n *   sudo dtoverlay dt-overlay.dtbo\n */\n\n/dts-v1/;\n/plugin/;\n\n/ {\n    compatible = \"brcm,bcm2835\";\n\n    fragment@0 {\n        target-path = \"/\";\n        __overlay__ {\n            lkmpg_device@0 {\n                compatible = \"lkmpg,example-device\";\n                reg = <0x40000000 0x1000>;\n                label = \"LKMPG Test Device\";\n                lkmpg,custom-value = <100>;\n                lkmpg,has-clock;\n                status = \"okay\";\n            };\n\n            lkmpg_device@1 {\n                compatible = \"lkmpg,another-device\";\n                reg = <0x40001000 0x1000>;\n                label = \"LKMPG Secondary Device\";\n                lkmpg,custom-value = <200>;\n                /* no has-clock property for this one */\n                status = \"okay\";\n            };\n        };\n    };\n};\n"
  },
  {
    "path": "examples/example_atomic.c",
    "content": "/*\n * example_atomic.c\n */\n#include <linux/atomic.h>\n#include <linux/bitops.h>\n#include <linux/module.h>\n#include <linux/printk.h>\n\n#define BYTE_TO_BINARY_PATTERN \"%c%c%c%c%c%c%c%c\"\n#define BYTE_TO_BINARY(byte)                                                   \\\n    ((byte & 0x80) ? '1' : '0'), ((byte & 0x40) ? '1' : '0'),                  \\\n        ((byte & 0x20) ? '1' : '0'), ((byte & 0x10) ? '1' : '0'),              \\\n        ((byte & 0x08) ? '1' : '0'), ((byte & 0x04) ? '1' : '0'),              \\\n        ((byte & 0x02) ? '1' : '0'), ((byte & 0x01) ? '1' : '0')\n\nstatic void atomic_add_subtract(void)\n{\n    atomic_t debbie;\n    atomic_t chris = ATOMIC_INIT(50);\n\n    atomic_set(&debbie, 45);\n\n    /* subtract one */\n    atomic_dec(&debbie);\n\n    atomic_add(7, &debbie);\n\n    /* add one */\n    atomic_inc(&debbie);\n\n    pr_info(\"chris: %d, debbie: %d\\n\", atomic_read(&chris),\n            atomic_read(&debbie));\n}\n\nstatic void atomic_bitwise(void)\n{\n    unsigned long word = 0;\n\n    pr_info(\"Bits 0: \" BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));\n    set_bit(3, &word);\n    set_bit(5, &word);\n    pr_info(\"Bits 1: \" BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));\n    clear_bit(5, &word);\n    pr_info(\"Bits 2: \" BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));\n    change_bit(3, &word);\n\n    pr_info(\"Bits 3: \" BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));\n    if (test_and_set_bit(3, &word))\n        pr_info(\"wrong\\n\");\n    pr_info(\"Bits 4: \" BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));\n\n    word = 255;\n    pr_info(\"Bits 5: \" BYTE_TO_BINARY_PATTERN \"\\n\", BYTE_TO_BINARY(word));\n}\n\nstatic int __init example_atomic_init(void)\n{\n    pr_info(\"example_atomic started\\n\");\n\n    atomic_add_subtract();\n    atomic_bitwise();\n\n    return 0;\n}\n\nstatic void __exit example_atomic_exit(void)\n{\n    pr_info(\"example_atomic exit\\n\");\n}\n\nmodule_init(example_atomic_init);\nmodule_exit(example_atomic_exit);\n\nMODULE_DESCRIPTION(\"Atomic operations example\");\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/example_mutex.c",
    "content": "/*\n * example_mutex.c\n */\n#include <linux/module.h>\n#include <linux/mutex.h>\n#include <linux/printk.h>\n\nstatic DEFINE_MUTEX(mymutex);\n\nstatic int __init example_mutex_init(void)\n{\n    int ret;\n\n    pr_info(\"example_mutex init\\n\");\n\n    ret = mutex_trylock(&mymutex);\n    if (ret != 0) {\n        pr_info(\"mutex is locked\\n\");\n\n        if (mutex_is_locked(&mymutex) == 0)\n            pr_info(\"The mutex failed to lock!\\n\");\n\n        mutex_unlock(&mymutex);\n        pr_info(\"mutex is unlocked\\n\");\n    } else\n        pr_info(\"Failed to lock\\n\");\n\n    return 0;\n}\n\nstatic void __exit example_mutex_exit(void)\n{\n    pr_info(\"example_mutex exit\\n\");\n}\n\nmodule_init(example_mutex_init);\nmodule_exit(example_mutex_exit);\n\nMODULE_DESCRIPTION(\"Mutex example\");\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/example_rwlock.c",
    "content": "/*\n * example_rwlock.c\n */\n#include <linux/module.h>\n#include <linux/printk.h>\n#include <linux/rwlock.h>\n\nstatic DEFINE_RWLOCK(myrwlock);\n\nstatic void example_read_lock(void)\n{\n    unsigned long flags;\n\n    read_lock_irqsave(&myrwlock, flags);\n    pr_info(\"Read Locked\\n\");\n\n    /* Read from something */\n\n    read_unlock_irqrestore(&myrwlock, flags);\n    pr_info(\"Read Unlocked\\n\");\n}\n\nstatic void example_write_lock(void)\n{\n    unsigned long flags;\n\n    write_lock_irqsave(&myrwlock, flags);\n    pr_info(\"Write Locked\\n\");\n\n    /* Write to something */\n\n    write_unlock_irqrestore(&myrwlock, flags);\n    pr_info(\"Write Unlocked\\n\");\n}\n\nstatic int __init example_rwlock_init(void)\n{\n    pr_info(\"example_rwlock started\\n\");\n\n    example_read_lock();\n    example_write_lock();\n\n    return 0;\n}\n\nstatic void __exit example_rwlock_exit(void)\n{\n    pr_info(\"example_rwlock exit\\n\");\n}\n\nmodule_init(example_rwlock_init);\nmodule_exit(example_rwlock_exit);\n\nMODULE_DESCRIPTION(\"Read/Write locks example\");\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/example_spinlock.c",
    "content": "/*\n * example_spinlock.c\n */\n#include <linux/init.h>\n#include <linux/module.h>\n#include <linux/printk.h>\n#include <linux/spinlock.h>\n\nstatic DEFINE_SPINLOCK(sl_static);\nstatic spinlock_t sl_dynamic;\n\nstatic void example_spinlock_static(void)\n{\n    unsigned long flags;\n\n    spin_lock_irqsave(&sl_static, flags);\n    pr_info(\"Locked static spinlock\\n\");\n\n    /* Do something or other safely. Because this uses 100% CPU time, this\n     * code should take no more than a few milliseconds to run.\n     */\n\n    spin_unlock_irqrestore(&sl_static, flags);\n    pr_info(\"Unlocked static spinlock\\n\");\n}\n\nstatic void example_spinlock_dynamic(void)\n{\n    unsigned long flags;\n\n    spin_lock_init(&sl_dynamic);\n    spin_lock_irqsave(&sl_dynamic, flags);\n    pr_info(\"Locked dynamic spinlock\\n\");\n\n    /* Do something or other safely. Because this uses 100% CPU time, this\n     * code should take no more than a few milliseconds to run.\n     */\n\n    spin_unlock_irqrestore(&sl_dynamic, flags);\n    pr_info(\"Unlocked dynamic spinlock\\n\");\n}\n\nstatic int __init example_spinlock_init(void)\n{\n    pr_info(\"example spinlock started\\n\");\n\n    example_spinlock_static();\n    example_spinlock_dynamic();\n\n    return 0;\n}\n\nstatic void __exit example_spinlock_exit(void)\n{\n    pr_info(\"example spinlock exit\\n\");\n}\n\nmodule_init(example_spinlock_init);\nmodule_exit(example_spinlock_exit);\n\nMODULE_DESCRIPTION(\"Spinlock example\");\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/example_tasklet.c",
    "content": "/*\n * example_tasklet.c\n */\n#include <linux/delay.h>\n#include <linux/interrupt.h>\n#include <linux/module.h>\n#include <linux/printk.h>\n\n/* Macro DECLARE_TASKLET_OLD exists for compatibility.\n * See https://lwn.net/Articles/830964/\n */\n#ifndef DECLARE_TASKLET_OLD\n#define DECLARE_TASKLET_OLD(arg1, arg2) DECLARE_TASKLET(arg1, arg2, 0L)\n#endif\n\nstatic void tasklet_fn(unsigned long data)\n{\n    pr_info(\"Example tasklet starts\\n\");\n    mdelay(5000);\n    pr_info(\"Example tasklet ends\\n\");\n}\n\nstatic DECLARE_TASKLET_OLD(mytask, tasklet_fn);\n\nstatic int __init example_tasklet_init(void)\n{\n    pr_info(\"tasklet example init\\n\");\n    tasklet_schedule(&mytask);\n    mdelay(200);\n    pr_info(\"Example tasklet init continues...\\n\");\n    return 0;\n}\n\nstatic void __exit example_tasklet_exit(void)\n{\n    pr_info(\"tasklet example exit\\n\");\n    tasklet_kill(&mytask);\n}\n\nmodule_init(example_tasklet_init);\nmodule_exit(example_tasklet_exit);\n\nMODULE_DESCRIPTION(\"Tasklet example\");\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/hello-1.c",
    "content": "/*\n * hello-1.c - The simplest kernel module.\n */\n#include <linux/module.h> /* Needed by all modules */\n#include <linux/printk.h> /* Needed for pr_info() */\n\nint init_module(void)\n{\n    pr_info(\"Hello world 1.\\n\");\n\n    /* A nonzero return means init_module failed; module can't be loaded. */\n    return 0;\n}\n\nvoid cleanup_module(void)\n{\n    pr_info(\"Goodbye world 1.\\n\");\n}\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/hello-2.c",
    "content": "/*\n * hello-2.c - Demonstrating the module_init() and module_exit() macros.\n * This is preferred over using init_module() and cleanup_module().\n */\n#include <linux/init.h> /* Needed for the macros */\n#include <linux/module.h> /* Needed by all modules */\n#include <linux/printk.h> /* Needed for pr_info() */\n\nstatic int __init hello_2_init(void)\n{\n    pr_info(\"Hello, world 2\\n\");\n    return 0;\n}\n\nstatic void __exit hello_2_exit(void)\n{\n    pr_info(\"Goodbye, world 2\\n\");\n}\n\nmodule_init(hello_2_init);\nmodule_exit(hello_2_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/hello-3.c",
    "content": "/*\n * hello-3.c - Illustrating the __init, __initdata and __exit macros.\n */\n#include <linux/init.h> /* Needed for the macros */\n#include <linux/module.h> /* Needed by all modules */\n#include <linux/printk.h> /* Needed for pr_info() */\n\nstatic int hello3_data __initdata = 3;\n\nstatic int __init hello_3_init(void)\n{\n    pr_info(\"Hello, world %d\\n\", hello3_data);\n    return 0;\n}\n\nstatic void __exit hello_3_exit(void)\n{\n    pr_info(\"Goodbye, world 3\\n\");\n}\n\nmodule_init(hello_3_init);\nmodule_exit(hello_3_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/hello-4.c",
    "content": "/*\n * hello-4.c - Demonstrates module documentation.\n */\n#include <linux/init.h> /* Needed for the macros */\n#include <linux/module.h> /* Needed by all modules */\n#include <linux/printk.h> /* Needed for pr_info() */\n\nMODULE_LICENSE(\"GPL\");\nMODULE_AUTHOR(\"LKMPG\");\nMODULE_DESCRIPTION(\"A sample driver\");\n\nstatic int __init init_hello_4(void)\n{\n    pr_info(\"Hello, world 4\\n\");\n    return 0;\n}\n\nstatic void __exit cleanup_hello_4(void)\n{\n    pr_info(\"Goodbye, world 4\\n\");\n}\n\nmodule_init(init_hello_4);\nmodule_exit(cleanup_hello_4);\n"
  },
  {
    "path": "examples/hello-5.c",
    "content": "/*\n * hello-5.c - Demonstrates command line argument passing to a module.\n */\n#include <linux/init.h>\n#include <linux/kernel.h> /* for ARRAY_SIZE() */\n#include <linux/module.h>\n#include <linux/moduleparam.h>\n#include <linux/printk.h>\n#include <linux/stat.h>\n\nMODULE_LICENSE(\"GPL\");\n\nstatic short int myshort = 1;\nstatic int myint = 420;\nstatic long int mylong = 9999;\nstatic char *mystring = \"blah\";\nstatic int myintarray[2] = { 420, 420 };\nstatic int arr_argc = 0;\n\n/* module_param(foo, int, 0000)\n * The first param is the parameter's name.\n * The second param is its data type.\n * The final argument is the permissions bits,\n * for exposing parameters in sysfs (if non-zero) at a later stage.\n */\nmodule_param(myshort, short, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);\nMODULE_PARM_DESC(myshort, \"A short integer\");\nmodule_param(myint, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\nMODULE_PARM_DESC(myint, \"An integer\");\nmodule_param(mylong, long, S_IRUSR);\nMODULE_PARM_DESC(mylong, \"A long integer\");\nmodule_param(mystring, charp, 0000);\nMODULE_PARM_DESC(mystring, \"A character string\");\n\n/* module_param_array(name, type, num, perm);\n * The first param is the parameter's (in this case the array's) name.\n * The second param is the data type of the elements of the array.\n * The third argument is a pointer to the variable that will store the number\n * of elements of the array initialized by the user at module loading time.\n * The fourth argument is the permission bits.\n */\nmodule_param_array(myintarray, int, &arr_argc, 0000);\nMODULE_PARM_DESC(myintarray, \"An array of integers\");\n\nstatic int __init hello_5_init(void)\n{\n    int i;\n\n    pr_info(\"Hello, world 5\\n=============\\n\");\n    pr_info(\"myshort is a short integer: %hd\\n\", myshort);\n    pr_info(\"myint is an integer: %d\\n\", myint);\n    pr_info(\"mylong is a long integer: %ld\\n\", mylong);\n    pr_info(\"mystring is a string: %s\\n\", mystring);\n\n    for (i = 0; i < ARRAY_SIZE(myintarray); i++)\n        pr_info(\"myintarray[%d] = %d\\n\", i, myintarray[i]);\n\n    pr_info(\"got %d arguments for myintarray.\\n\", arr_argc);\n    return 0;\n}\n\nstatic void __exit hello_5_exit(void)\n{\n    pr_info(\"Goodbye, world 5\\n\");\n}\n\nmodule_init(hello_5_init);\nmodule_exit(hello_5_exit);\n"
  },
  {
    "path": "examples/hello-sysfs.c",
    "content": "/*\n * hello-sysfs.c sysfs example\n */\n#include <linux/fs.h>\n#include <linux/init.h>\n#include <linux/kobject.h>\n#include <linux/module.h>\n#include <linux/string.h>\n#include <linux/sysfs.h>\n\nstatic struct kobject *mymodule;\n\n/* the variable you want to be able to change */\nstatic int myvariable = 0;\n\nstatic ssize_t myvariable_show(struct kobject *kobj,\n                               struct kobj_attribute *attr, char *buf)\n{\n    return sprintf(buf, \"%d\\n\", myvariable);\n}\n\nstatic ssize_t myvariable_store(struct kobject *kobj,\n                                struct kobj_attribute *attr, const char *buf,\n                                size_t count)\n{\n    sscanf(buf, \"%d\", &myvariable);\n    return count;\n}\n\nstatic struct kobj_attribute myvariable_attribute =\n    __ATTR(myvariable, 0660, myvariable_show, myvariable_store);\n\nstatic int __init mymodule_init(void)\n{\n    int error = 0;\n\n    pr_info(\"mymodule: initialized\\n\");\n\n    mymodule = kobject_create_and_add(\"mymodule\", kernel_kobj);\n    if (!mymodule)\n        return -ENOMEM;\n\n    error = sysfs_create_file(mymodule, &myvariable_attribute.attr);\n    if (error) {\n        kobject_put(mymodule);\n        pr_info(\"failed to create the myvariable file \"\n                \"in /sys/kernel/mymodule\\n\");\n    }\n\n    return error;\n}\n\nstatic void __exit mymodule_exit(void)\n{\n    pr_info(\"mymodule: Exit success\\n\");\n    kobject_put(mymodule);\n}\n\nmodule_init(mymodule_init);\nmodule_exit(mymodule_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/intrpt.c",
    "content": "/*\n * intrpt.c - Handling GPIO with interrupts\n *\n * Based upon the RPi example by Stefan Wendler (devnull@kaltpost.de)\n * from:\n *   https://github.com/wendlers/rpi-kmod-samples\n *\n * Press one button to turn on a LED and another to turn it off.\n */\n\n#include <linux/gpio.h>\n#include <linux/interrupt.h>\n#include <linux/kernel.h> /* for ARRAY_SIZE() */\n#include <linux/module.h>\n#include <linux/printk.h>\n#include <linux/version.h>\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 10, 0)\n#define NO_GPIO_REQUEST_ARRAY\n#endif\n\nstatic int button_irqs[] = { -1, -1 };\n\n/* Define GPIOs for LEDs.\n * TODO: Change the numbers for the GPIO on your board.\n */\nstatic struct gpio leds[] = { { 4, GPIOF_OUT_INIT_LOW, \"LED 1\" } };\n\n/* Define GPIOs for BUTTONS\n * TODO: Change the numbers for the GPIO on your board.\n */\nstatic struct gpio buttons[] = { { 17, GPIOF_IN, \"LED 1 ON BUTTON\" },\n                                 { 18, GPIOF_IN, \"LED 1 OFF BUTTON\" } };\n\n/* interrupt function triggered when a button is pressed. */\nstatic irqreturn_t button_isr(int irq, void *data)\n{\n    /* first button */\n    if (irq == button_irqs[0] && !gpio_get_value(leds[0].gpio))\n        gpio_set_value(leds[0].gpio, 1);\n    /* second button */\n    else if (irq == button_irqs[1] && gpio_get_value(leds[0].gpio))\n        gpio_set_value(leds[0].gpio, 0);\n\n    return IRQ_HANDLED;\n}\n\nstatic int __init intrpt_init(void)\n{\n    int ret = 0;\n\n    pr_info(\"%s\\n\", __func__);\n\n    /* register LED gpios */\n#ifdef NO_GPIO_REQUEST_ARRAY\n    ret = gpio_request(leds[0].gpio, leds[0].label);\n#else\n    ret = gpio_request_array(leds, ARRAY_SIZE(leds));\n#endif\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for LEDs: %d\\n\", ret);\n        return ret;\n    }\n\n    /* register BUTTON gpios */\n#ifdef NO_GPIO_REQUEST_ARRAY\n    ret = gpio_request(buttons[0].gpio, buttons[0].label);\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for BUTTONs: %d\\n\", ret);\n        goto fail1;\n    }\n\n    ret = gpio_request(buttons[1].gpio, buttons[1].label);\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for BUTTONs: %d\\n\", ret);\n        goto fail2;\n    }\n#else\n    ret = gpio_request_array(buttons, ARRAY_SIZE(buttons));\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for BUTTONs: %d\\n\", ret);\n        goto fail1;\n    }\n#endif\n\n    pr_info(\"Current button1 value: %d\\n\", gpio_get_value(buttons[0].gpio));\n\n    ret = gpio_to_irq(buttons[0].gpio);\n\n    if (ret < 0) {\n        pr_err(\"Unable to request IRQ: %d\\n\", ret);\n#ifdef NO_GPIO_REQUEST_ARRAY\n        goto fail3;\n#else\n        goto fail2;\n#endif\n    }\n\n    button_irqs[0] = ret;\n\n    pr_info(\"Successfully requested BUTTON1 IRQ # %d\\n\", button_irqs[0]);\n\n    ret = request_irq(button_irqs[0], button_isr,\n                      IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,\n                      \"gpiomod#button1\", NULL);\n\n    if (ret) {\n        pr_err(\"Unable to request IRQ: %d\\n\", ret);\n#ifdef NO_GPIO_REQUEST_ARRAY\n        goto fail3;\n#else\n        goto fail2;\n#endif\n    }\n\n    ret = gpio_to_irq(buttons[1].gpio);\n\n    if (ret < 0) {\n        pr_err(\"Unable to request IRQ: %d\\n\", ret);\n#ifdef NO_GPIO_REQUEST_ARRAY\n        goto fail3;\n#else\n        goto fail2;\n#endif\n    }\n\n    button_irqs[1] = ret;\n\n    pr_info(\"Successfully requested BUTTON2 IRQ # %d\\n\", button_irqs[1]);\n\n    ret = request_irq(button_irqs[1], button_isr,\n                      IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,\n                      \"gpiomod#button2\", NULL);\n\n    if (ret) {\n        pr_err(\"Unable to request IRQ: %d\\n\", ret);\n#ifdef NO_GPIO_REQUEST_ARRAY\n        goto fail4;\n#else\n        goto fail3;\n#endif\n    }\n\n    return 0;\n\n/* cleanup what has been setup so far */\n#ifdef NO_GPIO_REQUEST_ARRAY\nfail4:\n    free_irq(button_irqs[0], NULL);\n\nfail3:\n    gpio_free(buttons[1].gpio);\n\nfail2:\n    gpio_free(buttons[0].gpio);\n\nfail1:\n    gpio_free(leds[0].gpio);\n#else\nfail3:\n    free_irq(button_irqs[0], NULL);\n\nfail2:\n    gpio_free_array(buttons, ARRAY_SIZE(buttons));\n\nfail1:\n    gpio_free_array(leds, ARRAY_SIZE(leds));\n#endif\n\n    return ret;\n}\n\nstatic void __exit intrpt_exit(void)\n{\n    pr_info(\"%s\\n\", __func__);\n\n    /* free irqs */\n    free_irq(button_irqs[0], NULL);\n    free_irq(button_irqs[1], NULL);\n\n    /* turn all LEDs off */\n#ifdef NO_GPIO_REQUEST_ARRAY\n    gpio_set_value(leds[0].gpio, 0);\n#else\n    int i;\n    for (i = 0; i < ARRAY_SIZE(leds); i++)\n        gpio_set_value(leds[i].gpio, 0);\n#endif\n\n    /* unregister */\n#ifdef NO_GPIO_REQUEST_ARRAY\n    gpio_free(leds[0].gpio);\n    gpio_free(buttons[0].gpio);\n    gpio_free(buttons[1].gpio);\n#else\n    gpio_free_array(leds, ARRAY_SIZE(leds));\n    gpio_free_array(buttons, ARRAY_SIZE(buttons));\n#endif\n}\n\nmodule_init(intrpt_init);\nmodule_exit(intrpt_exit);\n\nMODULE_LICENSE(\"GPL\");\nMODULE_DESCRIPTION(\"Handle some GPIO interrupts\");\n"
  },
  {
    "path": "examples/ioctl.c",
    "content": "/*\n * ioctl.c\n */\n#include <linux/cdev.h>\n#include <linux/fs.h>\n#include <linux/init.h>\n#include <linux/ioctl.h>\n#include <linux/module.h>\n#include <linux/slab.h>\n#include <linux/uaccess.h>\n#include <linux/version.h>\n\nstruct ioctl_arg {\n    unsigned int val;\n};\n\n/* Documentation/userspace-api/ioctl/ioctl-number.rst */\n#define IOC_MAGIC '\\x66'\n\n#define IOCTL_VALSET _IOW(IOC_MAGIC, 0, struct ioctl_arg)\n#define IOCTL_VALGET _IOR(IOC_MAGIC, 1, struct ioctl_arg)\n#define IOCTL_VALGET_NUM _IOR(IOC_MAGIC, 2, int)\n#define IOCTL_VALSET_NUM _IO(IOC_MAGIC, 3)\n\n#define IOCTL_VAL_MAXNR 3\n#define DRIVER_NAME \"ioctltest\"\n\nstatic unsigned int test_ioctl_major = 0;\nstatic unsigned int num_of_dev = 1;\nstatic struct cdev test_ioctl_cdev;\nstatic int ioctl_num = 0;\n\nstruct test_ioctl_data {\n    unsigned char val;\n    rwlock_t lock;\n};\n\nstatic long test_ioctl_ioctl(struct file *filp, unsigned int cmd,\n                             unsigned long arg)\n{\n    struct test_ioctl_data *ioctl_data = filp->private_data;\n    int retval = 0;\n    unsigned char val;\n    struct ioctl_arg data;\n    memset(&data, 0, sizeof(data));\n\n    switch (cmd) {\n    case IOCTL_VALSET:\n        if (copy_from_user(&data, (int __user *)arg, sizeof(data))) {\n            retval = -EFAULT;\n            goto done;\n        }\n\n        pr_alert(\"IOCTL set val:%x .\\n\", data.val);\n        write_lock(&ioctl_data->lock);\n        ioctl_data->val = data.val;\n        write_unlock(&ioctl_data->lock);\n        break;\n\n    case IOCTL_VALGET:\n        read_lock(&ioctl_data->lock);\n        val = ioctl_data->val;\n        read_unlock(&ioctl_data->lock);\n        data.val = val;\n\n        if (copy_to_user((int __user *)arg, &data, sizeof(data))) {\n            retval = -EFAULT;\n            goto done;\n        }\n\n        break;\n\n    case IOCTL_VALGET_NUM:\n        retval = __put_user(ioctl_num, (int __user *)arg);\n        break;\n\n    case IOCTL_VALSET_NUM:\n        ioctl_num = arg;\n        break;\n\n    default:\n        retval = -ENOTTY;\n    }\n\ndone:\n    return retval;\n}\n\nstatic ssize_t test_ioctl_read(struct file *filp, char __user *buf,\n                               size_t count, loff_t *f_pos)\n{\n    struct test_ioctl_data *ioctl_data = filp->private_data;\n    unsigned char val;\n    int retval;\n    int i = 0;\n\n    read_lock(&ioctl_data->lock);\n    val = ioctl_data->val;\n    read_unlock(&ioctl_data->lock);\n\n    for (; i < count; i++) {\n        if (copy_to_user(&buf[i], &val, 1)) {\n            retval = -EFAULT;\n            goto out;\n        }\n    }\n\n    retval = count;\nout:\n    return retval;\n}\n\nstatic int test_ioctl_close(struct inode *inode, struct file *filp)\n{\n    pr_alert(\"%s call.\\n\", __func__);\n\n    if (filp->private_data) {\n        kfree(filp->private_data);\n        filp->private_data = NULL;\n    }\n\n    return 0;\n}\n\nstatic int test_ioctl_open(struct inode *inode, struct file *filp)\n{\n    struct test_ioctl_data *ioctl_data;\n\n    pr_alert(\"%s call.\\n\", __func__);\n    ioctl_data = kmalloc(sizeof(struct test_ioctl_data), GFP_KERNEL);\n\n    if (ioctl_data == NULL)\n        return -ENOMEM;\n\n    rwlock_init(&ioctl_data->lock);\n    ioctl_data->val = 0xFF;\n    filp->private_data = ioctl_data;\n\n    return 0;\n}\n\nstatic struct file_operations fops = {\n    .owner = THIS_MODULE,\n    .open = test_ioctl_open,\n    .release = test_ioctl_close,\n    .read = test_ioctl_read,\n    .unlocked_ioctl = test_ioctl_ioctl,\n};\n\nstatic int __init ioctl_init(void)\n{\n    dev_t dev;\n    int ret;\n\n    ret = alloc_chrdev_region(&dev, 0, num_of_dev, DRIVER_NAME);\n\n    if (ret)\n        return ret;\n\n    test_ioctl_major = MAJOR(dev);\n    cdev_init(&test_ioctl_cdev, &fops);\n    ret = cdev_add(&test_ioctl_cdev, dev, num_of_dev);\n\n    if (ret) {\n        unregister_chrdev_region(dev, num_of_dev);\n        return ret;\n    }\n\n    pr_alert(\"%s driver(major: %d) installed.\\n\", DRIVER_NAME,\n             test_ioctl_major);\n    return 0;\n}\n\nstatic void __exit ioctl_exit(void)\n{\n    dev_t dev = MKDEV(test_ioctl_major, 0);\n\n    cdev_del(&test_ioctl_cdev);\n    unregister_chrdev_region(dev, num_of_dev);\n    pr_alert(\"%s driver removed.\\n\", DRIVER_NAME);\n}\n\nmodule_init(ioctl_init);\nmodule_exit(ioctl_exit);\n\nMODULE_LICENSE(\"GPL\");\nMODULE_DESCRIPTION(\"This is test_ioctl module\");\n"
  },
  {
    "path": "examples/kbleds.c",
    "content": "/*\n * kbleds.c - Blink keyboard leds until the module is unloaded.\n */\n\n#include <linux/init.h>\n#include <linux/kd.h> /* For KDSETLED */\n#include <linux/module.h>\n#include <linux/tty.h> /* For tty_struct */\n#include <linux/vt.h> /* For MAX_NR_CONSOLES */\n#include <linux/vt_kern.h> /* for fg_console */\n#include <linux/console_struct.h> /* For vc_cons */\n\nMODULE_DESCRIPTION(\"Example module illustrating the use of Keyboard LEDs.\");\n\nstatic struct timer_list my_timer;\nstatic struct tty_driver *my_driver;\nstatic unsigned long kbledstatus = 0;\n\n#define BLINK_DELAY HZ / 5\n#define ALL_LEDS_ON 0x07\n#define RESTORE_LEDS 0xFF\n\n/* Function my_timer_func blinks the keyboard LEDs periodically by invoking\n * command KDSETLED of ioctl() on the keyboard driver. To learn more on virtual\n * terminal ioctl operations, please see file:\n *   drivers/tty/vt/vt_ioctl.c, function vt_ioctl().\n *\n * The argument to KDSETLED is alternatively set to 7 (thus causing the led\n * mode to be set to LED_SHOW_IOCTL, and all the leds are lit) and to 0xFF\n * (any value above 7 switches back the led mode to LED_SHOW_FLAGS, thus\n * the LEDs reflect the actual keyboard status).  To learn more on this,\n * please see file: drivers/tty/vt/keyboard.c, function setledstate().\n */\nstatic void my_timer_func(struct timer_list *unused)\n{\n    struct tty_struct *t = vc_cons[fg_console].d->port.tty;\n\n    if (kbledstatus == ALL_LEDS_ON)\n        kbledstatus = RESTORE_LEDS;\n    else\n        kbledstatus = ALL_LEDS_ON;\n\n    (my_driver->ops->ioctl)(t, KDSETLED, kbledstatus);\n\n    my_timer.expires = jiffies + BLINK_DELAY;\n    add_timer(&my_timer);\n}\n\nstatic int __init kbleds_init(void)\n{\n    int i;\n\n    pr_info(\"kbleds: loading\\n\");\n    pr_info(\"kbleds: fgconsole is %x\\n\", fg_console);\n    for (i = 0; i < MAX_NR_CONSOLES; i++) {\n        if (!vc_cons[i].d)\n            break;\n        pr_info(\"poet_atkm: console[%i/%i] #%i, tty %p\\n\", i, MAX_NR_CONSOLES,\n                vc_cons[i].d->vc_num, (void *)vc_cons[i].d->port.tty);\n    }\n    pr_info(\"kbleds: finished scanning consoles\\n\");\n\n    my_driver = vc_cons[fg_console].d->port.tty->driver;\n    pr_info(\"kbleds: tty driver name %s\\n\", my_driver->driver_name);\n\n    /* Set up the LED blink timer the first time. */\n    timer_setup(&my_timer, my_timer_func, 0);\n    my_timer.expires = jiffies + BLINK_DELAY;\n    add_timer(&my_timer);\n\n    return 0;\n}\n\nstatic void __exit kbleds_cleanup(void)\n{\n    pr_info(\"kbleds: unloading...\\n\");\n    del_timer(&my_timer);\n    (my_driver->ops->ioctl)(vc_cons[fg_console].d->port.tty, KDSETLED,\n                            RESTORE_LEDS);\n}\n\nmodule_init(kbleds_init);\nmodule_exit(kbleds_cleanup);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/led.c",
    "content": "/*\n * led.c - Using GPIO to control the LED on/off\n */\n\n#include <linux/cdev.h>\n#include <linux/delay.h>\n#include <linux/device.h>\n#include <linux/fs.h>\n#include <linux/gpio.h>\n#include <linux/init.h>\n#include <linux/module.h>\n#include <linux/printk.h>\n#include <linux/types.h>\n#include <linux/uaccess.h>\n#include <linux/version.h>\n\n#include <asm/errno.h>\n\n#define DEVICE_NAME \"gpio_led\"\n#define DEVICE_CNT 1\n#define BUF_LEN 2\n\nstatic char control_signal[BUF_LEN];\nstatic unsigned long device_buffer_size = 0;\n\nstruct LED_dev {\n    dev_t dev_num;\n    int major_num, minor_num;\n    struct cdev cdev;\n    struct class *cls;\n    struct device *dev;\n};\n\nstatic struct LED_dev led_device;\n\n/* Define GPIOs for LEDs.\n * TODO: According to the requirements, search /sys/kernel/debug/gpio to \n * find the corresponding GPIO location.\n */\nstatic struct gpio leds[] = { { 4, GPIOF_OUT_INIT_LOW, \"LED 1\" } };\n\n/* This is called whenever a process attempts to open the device file */\nstatic int device_open(struct inode *inode, struct file *file)\n{\n    return 0;\n}\n\nstatic int device_release(struct inode *inode, struct file *file)\n{\n    return 0;\n}\n\nstatic ssize_t device_write(struct file *file, const char __user *buffer,\n                            size_t length, loff_t *offset)\n{\n    device_buffer_size = min(BUF_LEN, length);\n\n    if (copy_from_user(control_signal, buffer, device_buffer_size)) {\n        return -EFAULT;\n    }\n\n    /* Determine the received signal to decide the LED on/off state. */\n    switch (control_signal[0]) {\n    case '0':\n        gpio_set_value(leds[0].gpio, 0);\n        pr_info(\"LED OFF\");\n        break;\n    case '1':\n        gpio_set_value(leds[0].gpio, 1);\n        pr_info(\"LED ON\");\n        break;\n    default:\n        pr_warn(\"Invalid value!\\n\");\n        break;\n    }\n\n    *offset += device_buffer_size;\n\n    /* Again, return the number of input characters used. */\n    return device_buffer_size;\n}\n\nstatic struct file_operations fops = {\n#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 4, 0)\n    .owner = THIS_MODULE,\n#endif\n    .write = device_write,\n    .open = device_open,\n    .release = device_release,\n};\n\n/* Initialize the module - Register the character device */\nstatic int __init led_init(void)\n{\n    int ret = 0;\n\n    /* Determine whether dynamic allocation of the device number is needed. */\n    if (led_device.major_num) {\n        led_device.dev_num = MKDEV(led_device.major_num, led_device.minor_num);\n        ret =\n            register_chrdev_region(led_device.dev_num, DEVICE_CNT, DEVICE_NAME);\n    } else {\n        ret = alloc_chrdev_region(&led_device.dev_num, 0, DEVICE_CNT,\n                                  DEVICE_NAME);\n    }\n\n    /* Negative values signify an error */\n    if (ret < 0) {\n        pr_alert(\"Failed to register character device, error: %d\\n\", ret);\n        return ret;\n    }\n\n    pr_info(\"Major = %d, Minor = %d\\n\", MAJOR(led_device.dev_num),\n            MINOR(led_device.dev_num));\n\n    /* Prevents module unloading while operations are in use */\n#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 4, 0)\n    led_device.cdev.owner = THIS_MODULE;\n#endif\n\n    cdev_init(&led_device.cdev, &fops);\n    ret = cdev_add(&led_device.cdev, led_device.dev_num, 1);\n    if (ret) {\n        pr_err(\"Failed to add the device to the system\\n\");\n        goto fail1;\n    }\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 4, 0)\n    led_device.cls = class_create(DEVICE_NAME);\n#else\n    led_device.cls = class_create(THIS_MODULE, DEVICE_NAME);\n#endif\n    if (IS_ERR(led_device.cls)) {\n        pr_err(\"Failed to create class for device\\n\");\n        ret = PTR_ERR(led_device.cls);\n        goto fail2;\n    }\n\n    led_device.dev = device_create(led_device.cls, NULL, led_device.dev_num,\n                                   NULL, DEVICE_NAME);\n    if (IS_ERR(led_device.dev)) {\n        pr_err(\"Failed to create the device file\\n\");\n        ret = PTR_ERR(led_device.dev);\n        goto fail3;\n    }\n\n    pr_info(\"Device created on /dev/%s\\n\", DEVICE_NAME);\n\n    ret = gpio_request(leds[0].gpio, leds[0].label);\n\n    if (ret) {\n        pr_err(\"Unable to request GPIOs for LEDs: %d\\n\", ret);\n        goto fail4;\n    }\n\n    ret = gpio_direction_output(leds[0].gpio, leds[0].flags);\n\n    if (ret) {\n        pr_err(\"Failed to set GPIO %d direction\\n\", leds[0].gpio);\n        goto fail5;\n    }\n\n    return 0;\n\nfail5:\n    gpio_free(leds[0].gpio);\n\nfail4:\n    device_destroy(led_device.cls, led_device.dev_num);\n\nfail3:\n    class_destroy(led_device.cls);\n\nfail2:\n    cdev_del(&led_device.cdev);\n\nfail1:\n    unregister_chrdev_region(led_device.dev_num, DEVICE_CNT);\n\n    return ret;\n}\n\nstatic void __exit led_exit(void)\n{\n    gpio_set_value(leds[0].gpio, 0);\n    gpio_free(leds[0].gpio);\n\n    device_destroy(led_device.cls, led_device.dev_num);\n    class_destroy(led_device.cls);\n    cdev_del(&led_device.cdev);\n    unregister_chrdev_region(led_device.dev_num, DEVICE_CNT);\n}\n\nmodule_init(led_init);\nmodule_exit(led_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/other/cat_nonblock.c",
    "content": "/*\n *  cat_nonblock.c - open a file and display its contents, but exit rather than\n *  wait for input.\n */\n#include <errno.h> /* for errno */\n#include <fcntl.h> /* for open */\n#include <stdio.h> /* standard I/O */\n#include <stdlib.h> /* for exit */\n#include <unistd.h> /* for read */\n\n#define MAX_BYTES 1024 * 4\n\nint main(int argc, char *argv[])\n{\n    int fd; /* The file descriptor for the file to read */\n    size_t bytes; /* The number of bytes read */\n    char buffer[MAX_BYTES]; /* The buffer for the bytes */\n\n    /* Usage */\n    if (argc != 2) {\n        printf(\"Usage: %s <filename>\\n\", argv[0]);\n        puts(\"Reads the content of a file, but doesn't wait for input\");\n        exit(EXIT_FAILURE);\n    }\n\n    /* Open the file for reading in non blocking mode */\n    fd = open(argv[1], O_RDONLY | O_NONBLOCK);\n\n    /* If open failed */\n    if (fd == -1) {\n        puts(errno == EAGAIN ? \"Open would block\" : \"Open failed\");\n        exit(EXIT_FAILURE);\n    }\n\n    /* Read the file and output its contents */\n    do {\n        /* Read characters from the file */\n        bytes = read(fd, buffer, MAX_BYTES);\n\n        /* If there's an error, report it and die */\n        if (bytes == -1) {\n            if (errno == EAGAIN)\n                puts(\"Normally I'd block, but you told me not to\");\n            else\n                puts(\"Another read error\");\n            exit(EXIT_FAILURE);\n        }\n\n        /* Print the characters */\n        if (bytes > 0) {\n            for (int i = 0; i < bytes; i++)\n                putchar(buffer[i]);\n        }\n\n        /* While there are no errors and the file isn't over */\n    } while (bytes > 0);\n\n    close(fd);\n    return 0;\n}\n"
  },
  {
    "path": "examples/other/userspace_ioctl.c",
    "content": "\n/*  userspace_ioctl.c - the process to use ioctl's to control the kernel module\n *\n *  Until now we could have used cat for input and output.  But now\n *  we need to do ioctl's, which require writing our own process. \n */\n\n/* device specifics, such as ioctl numbers and the \n * major device file. */\n#include \"../chardev.h\"\n\n#include <stdio.h> /* standard I/O */\n#include <fcntl.h> /* open */\n#include <unistd.h> /* close */\n#include <stdlib.h> /* exit */\n#include <sys/ioctl.h> /* ioctl */\n\n/* Functions for the ioctl calls */\n\nint ioctl_set_msg(int file_desc, char *message)\n{\n    int ret_val;\n\n    ret_val = ioctl(file_desc, IOCTL_SET_MSG, message);\n\n    if (ret_val < 0) {\n        printf(\"ioctl_set_msg failed:%d\\n\", ret_val);\n    }\n\n    return ret_val;\n}\n\nint ioctl_get_msg(int file_desc)\n{\n    int ret_val;\n    char message[100] = { 0 };\n\n    /* Warning - this is dangerous because we don't tell \n   * the kernel how far it's allowed to write, so it \n   * might overflow the buffer. In a real production \n   * program, we would have used two ioctls - one to tell\n   * the kernel the buffer length and another to give \n   * it the buffer to fill\n   */\n    ret_val = ioctl(file_desc, IOCTL_GET_MSG, message);\n\n    if (ret_val < 0) {\n        printf(\"ioctl_get_msg failed:%d\\n\", ret_val);\n    }\n    printf(\"get_msg message:%s\", message);\n\n    return ret_val;\n}\n\nint ioctl_get_nth_byte(int file_desc)\n{\n    int i, c;\n\n    printf(\"get_nth_byte message:\");\n\n    i = 0;\n    do {\n        c = ioctl(file_desc, IOCTL_GET_NTH_BYTE, i++);\n\n        if (c < 0) {\n            printf(\"\\nioctl_get_nth_byte failed at the %d'th byte:\\n\", i);\n            return c;\n        }\n\n        putchar(c);\n    } while (c != 0);\n\n    return 0;\n}\n\n/* Main - Call the ioctl functions */\nint main(void)\n{\n    int file_desc, ret_val;\n    char *msg = \"Message passed by ioctl\\n\";\n\n    file_desc = open(DEVICE_PATH, O_RDWR);\n    if (file_desc < 0) {\n        printf(\"Can't open device file: %s, error:%d\\n\", DEVICE_PATH,\n               file_desc);\n        exit(EXIT_FAILURE);\n    }\n\n    ret_val = ioctl_set_msg(file_desc, msg);\n    if (ret_val)\n        goto error;\n    ret_val = ioctl_get_nth_byte(file_desc);\n    if (ret_val)\n        goto error;\n    ret_val = ioctl_get_msg(file_desc);\n    if (ret_val)\n        goto error;\n\n    close(file_desc);\n    return 0;\nerror:\n    close(file_desc);\n    exit(EXIT_FAILURE);\n}\n"
  },
  {
    "path": "examples/print_string.c",
    "content": "/*\n * print_string.c - Send output to the tty we're running on, regardless if\n * it is through X11, telnet, etc.  We do this by printing the string to the\n * tty associated with the current task.\n */\n#include <linux/init.h>\n#include <linux/kernel.h>\n#include <linux/module.h>\n#include <linux/sched.h> /* For current */\n#include <linux/tty.h> /* For the tty declarations */\n\nstatic void print_string(char *str)\n{\n    /* The tty for the current task */\n    struct tty_struct *my_tty = get_current_tty();\n\n    /* If my_tty is NULL, the current task has no tty you can print to (i.e.,\n     * if it is a daemon). If so, there is nothing we can do.\n     */\n    if (my_tty) {\n        const struct tty_operations *ttyops = my_tty->driver->ops;\n        /* my_tty->driver is a struct which holds the tty's functions,\n         * one of which (write) is used to write strings to the tty.\n         * It can be used to take a string either from the user's or\n         * kernel's memory segment.\n         *\n         * The function's 1st parameter is the tty to write to, because the\n         * same function would normally be used for all tty's of a certain\n         * type.\n         * The 2nd parameter is a pointer to a string.\n         * The 3rd parameter is the length of the string.\n         *\n         * As you will see below, sometimes it's necessary to use\n         * preprocessor stuff to create code that works for different\n         * kernel versions. The (naive) approach we've taken here does not\n         * scale well. The right way to deal with this is described in\n         * section 2 of\n         * linux/Documentation/SubmittingPatches\n         */\n        (ttyops->write)(my_tty, /* The tty itself */\n                        str, /* String */\n                        strlen(str)); /* Length */\n\n        /* ttys were originally hardware devices, which (usually) strictly\n         * followed the ASCII standard. In ASCII, to move to a new line you\n         * need two characters, a carriage return and a line feed. On Unix,\n         * the ASCII line feed is used for both purposes - so we can not\n         * just use \\n, because it would not have a carriage return and the\n         * next line will start at the column right after the line feed.\n         *\n         * This is why text files are different between Unix and MS Windows.\n         * In CP/M and derivatives, like MS-DOS and MS Windows, the ASCII\n         * standard was strictly adhered to, and therefore a newline requires\n         * both a LF and a CR.\n         */\n        (ttyops->write)(my_tty, \"\\015\\012\", 2);\n    }\n}\n\nstatic int __init print_string_init(void)\n{\n    print_string(\"The module has been inserted.  Hello world!\");\n    return 0;\n}\n\nstatic void __exit print_string_exit(void)\n{\n    print_string(\"The module has been removed.  Farewell world!\");\n}\n\nmodule_init(print_string_init);\nmodule_exit(print_string_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/procfs1.c",
    "content": "/*\n * procfs1.c\n */\n\n#include <linux/kernel.h>\n#include <linux/module.h>\n#include <linux/proc_fs.h>\n#include <linux/uaccess.h>\n#include <linux/version.h>\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0)\n#define HAVE_PROC_OPS\n#endif\n\n#define procfs_name \"helloworld\"\n\nstatic struct proc_dir_entry *our_proc_file;\n\nstatic ssize_t procfile_read(struct file *file_pointer, char __user *buffer,\n                             size_t buffer_length, loff_t *offset)\n{\n    char s[13] = \"HelloWorld!\\n\";\n    int len = sizeof(s);\n    ssize_t ret = len;\n\n    if (*offset >= len || copy_to_user(buffer, s, len)) {\n        pr_info(\"copy_to_user failed\\n\");\n        ret = 0;\n    } else {\n        pr_info(\"procfile read %s\\n\", file_pointer->f_path.dentry->d_name.name);\n        *offset += len;\n    }\n\n    return ret;\n}\n\n#ifdef HAVE_PROC_OPS\nstatic const struct proc_ops proc_file_fops = {\n    .proc_read = procfile_read,\n};\n#else\nstatic const struct file_operations proc_file_fops = {\n    .read = procfile_read,\n};\n#endif\n\nstatic int __init procfs1_init(void)\n{\n    our_proc_file = proc_create(procfs_name, 0644, NULL, &proc_file_fops);\n    if (NULL == our_proc_file) {\n        pr_alert(\"Error:Could not initialize /proc/%s\\n\", procfs_name);\n        return -ENOMEM;\n    }\n\n    pr_info(\"/proc/%s created\\n\", procfs_name);\n    return 0;\n}\n\nstatic void __exit procfs1_exit(void)\n{\n    proc_remove(our_proc_file);\n    pr_info(\"/proc/%s removed\\n\", procfs_name);\n}\n\nmodule_init(procfs1_init);\nmodule_exit(procfs1_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/procfs2.c",
    "content": "/*\n * procfs2.c -  create a \"file\" in /proc\n */\n\n#include <linux/kernel.h> /* We're doing kernel work */\n#include <linux/module.h> /* Specifically, a module */\n#include <linux/proc_fs.h> /* Necessary because we use the proc fs */\n#include <linux/uaccess.h> /* for copy_from_user */\n#include <linux/version.h>\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0)\n#define HAVE_PROC_OPS\n#endif\n\n#define PROCFS_MAX_SIZE 1024\n#define PROCFS_NAME \"buffer1k\"\n\n/* This structure hold information about the /proc file */\nstatic struct proc_dir_entry *our_proc_file;\n\n/* The buffer used to store character for this module */\nstatic char procfs_buffer[PROCFS_MAX_SIZE];\n\n/* The size of the buffer */\nstatic unsigned long procfs_buffer_size = 0;\n\n/* This function is called then the /proc file is read */\nstatic ssize_t procfile_read(struct file *file_pointer, char __user *buffer,\n                             size_t buffer_length, loff_t *offset)\n{\n    char s[13] = \"HelloWorld!\\n\";\n    int len = sizeof(s);\n    ssize_t ret = len;\n\n    if (*offset >= len || copy_to_user(buffer, s, len)) {\n        pr_info(\"copy_to_user failed\\n\");\n        ret = 0;\n    } else {\n        pr_info(\"procfile read %s\\n\", file_pointer->f_path.dentry->d_name.name);\n        *offset += len;\n    }\n\n    return ret;\n}\n\n/* This function is called with the /proc file is written. */\nstatic ssize_t procfile_write(struct file *file, const char __user *buff,\n                              size_t len, loff_t *off)\n{\n    procfs_buffer_size = len;\n    if (procfs_buffer_size >= PROCFS_MAX_SIZE)\n        procfs_buffer_size = PROCFS_MAX_SIZE - 1;\n\n    if (copy_from_user(procfs_buffer, buff, procfs_buffer_size))\n        return -EFAULT;\n\n    procfs_buffer[procfs_buffer_size] = '\\0';\n    *off += procfs_buffer_size;\n    pr_info(\"procfile write %s\\n\", procfs_buffer);\n\n    return procfs_buffer_size;\n}\n\n#ifdef HAVE_PROC_OPS\nstatic const struct proc_ops proc_file_fops = {\n    .proc_read = procfile_read,\n    .proc_write = procfile_write,\n};\n#else\nstatic const struct file_operations proc_file_fops = {\n    .read = procfile_read,\n    .write = procfile_write,\n};\n#endif\n\nstatic int __init procfs2_init(void)\n{\n    our_proc_file = proc_create(PROCFS_NAME, 0644, NULL, &proc_file_fops);\n    if (NULL == our_proc_file) {\n        pr_alert(\"Error:Could not initialize /proc/%s\\n\", PROCFS_NAME);\n        return -ENOMEM;\n    }\n\n    pr_info(\"/proc/%s created\\n\", PROCFS_NAME);\n    return 0;\n}\n\nstatic void __exit procfs2_exit(void)\n{\n    proc_remove(our_proc_file);\n    pr_info(\"/proc/%s removed\\n\", PROCFS_NAME);\n}\n\nmodule_init(procfs2_init);\nmodule_exit(procfs2_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/procfs3.c",
    "content": "/*\n * procfs3.c\n */\n\n#include <linux/kernel.h>\n#include <linux/module.h>\n#include <linux/proc_fs.h>\n#include <linux/sched.h>\n#include <linux/uaccess.h>\n#include <linux/version.h>\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 10, 0)\n#include <linux/minmax.h>\n#endif\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0)\n#define HAVE_PROC_OPS\n#endif\n\n#define PROCFS_MAX_SIZE 2048UL\n#define PROCFS_ENTRY_FILENAME \"buffer2k\"\n\nstatic struct proc_dir_entry *our_proc_file;\nstatic char procfs_buffer[PROCFS_MAX_SIZE];\nstatic unsigned long procfs_buffer_size = 0;\n\nstatic ssize_t procfs_read(struct file *filp, char __user *buffer,\n                           size_t length, loff_t *offset)\n{\n    if (*offset || procfs_buffer_size == 0) {\n        pr_debug(\"procfs_read: END\\n\");\n        *offset = 0;\n        return 0;\n    }\n    procfs_buffer_size = min(procfs_buffer_size, length);\n    if (copy_to_user(buffer, procfs_buffer, procfs_buffer_size))\n        return -EFAULT;\n    *offset += procfs_buffer_size;\n\n    pr_debug(\"procfs_read: read %lu bytes\\n\", procfs_buffer_size);\n    return procfs_buffer_size;\n}\nstatic ssize_t procfs_write(struct file *file, const char __user *buffer,\n                            size_t len, loff_t *off)\n{\n    procfs_buffer_size = min(PROCFS_MAX_SIZE, len);\n    if (copy_from_user(procfs_buffer, buffer, procfs_buffer_size))\n        return -EFAULT;\n    *off += procfs_buffer_size;\n\n    pr_debug(\"procfs_write: write %lu bytes\\n\", procfs_buffer_size);\n    return procfs_buffer_size;\n}\nstatic int procfs_open(struct inode *inode, struct file *file)\n{\n    return 0;\n}\nstatic int procfs_close(struct inode *inode, struct file *file)\n{\n    return 0;\n}\n\n#ifdef HAVE_PROC_OPS\nstatic struct proc_ops file_ops_4_our_proc_file = {\n    .proc_read = procfs_read,\n    .proc_write = procfs_write,\n    .proc_open = procfs_open,\n    .proc_release = procfs_close,\n};\n#else\nstatic const struct file_operations file_ops_4_our_proc_file = {\n    .read = procfs_read,\n    .write = procfs_write,\n    .open = procfs_open,\n    .release = procfs_close,\n};\n#endif\n\nstatic int __init procfs3_init(void)\n{\n    our_proc_file = proc_create(PROCFS_ENTRY_FILENAME, 0644, NULL,\n                                &file_ops_4_our_proc_file);\n    if (our_proc_file == NULL) {\n        pr_debug(\"Error: Could not initialize /proc/%s\\n\",\n                 PROCFS_ENTRY_FILENAME);\n        return -ENOMEM;\n    }\n    proc_set_size(our_proc_file, 80);\n    proc_set_user(our_proc_file, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID);\n\n    pr_debug(\"/proc/%s created\\n\", PROCFS_ENTRY_FILENAME);\n    return 0;\n}\n\nstatic void __exit procfs3_exit(void)\n{\n    remove_proc_entry(PROCFS_ENTRY_FILENAME, NULL);\n    pr_debug(\"/proc/%s removed\\n\", PROCFS_ENTRY_FILENAME);\n}\n\nmodule_init(procfs3_init);\nmodule_exit(procfs3_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/procfs4.c",
    "content": "/*\n * procfs4.c -  create a \"file\" in /proc\n * This program uses the seq_file library to manage the /proc file.\n */\n\n#include <linux/kernel.h> /* We are doing kernel work */\n#include <linux/module.h> /* Specifically, a module */\n#include <linux/proc_fs.h> /* Necessary because we use proc fs */\n#include <linux/seq_file.h> /* for seq_file */\n#include <linux/version.h>\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0)\n#define HAVE_PROC_OPS\n#endif\n\n#define PROC_NAME \"iter\"\n\n/* This function is called at the beginning of a sequence.\n * ie, when:\n *   - the /proc file is read (first time)\n *   - after the function stop (end of sequence)\n */\nstatic void *my_seq_start(struct seq_file *s, loff_t *pos)\n{\n    static unsigned long counter = 0;\n\n    /* beginning a new sequence? */\n    if (*pos == 0) {\n        /* yes => return a non null value to begin the sequence */\n        return &counter;\n    }\n\n    /* no => it is the end of the sequence, return end to stop reading */\n    *pos = 0;\n    return NULL;\n}\n\n/* This function is called after the beginning of a sequence.\n * It is called until the return is NULL (this ends the sequence).\n */\nstatic void *my_seq_next(struct seq_file *s, void *v, loff_t *pos)\n{\n    unsigned long *tmp_v = (unsigned long *)v;\n    (*tmp_v)++;\n    (*pos)++;\n    return NULL;\n}\n\n/* This function is called at the end of a sequence. */\nstatic void my_seq_stop(struct seq_file *s, void *v)\n{\n    /* nothing to do, we use a static value in start() */\n}\n\n/* This function is called for each \"step\" of a sequence. */\nstatic int my_seq_show(struct seq_file *s, void *v)\n{\n    loff_t *spos = (loff_t *)v;\n\n    seq_printf(s, \"%Ld\\n\", *spos);\n    return 0;\n}\n\n/* This structure gather \"function\" to manage the sequence */\nstatic struct seq_operations my_seq_ops = {\n    .start = my_seq_start,\n    .next = my_seq_next,\n    .stop = my_seq_stop,\n    .show = my_seq_show,\n};\n\n/* This function is called when the /proc file is open. */\nstatic int my_open(struct inode *inode, struct file *file)\n{\n    return seq_open(file, &my_seq_ops);\n};\n\n/* This structure gather \"function\" that manage the /proc file */\n#ifdef HAVE_PROC_OPS\nstatic const struct proc_ops my_file_ops = {\n    .proc_open = my_open,\n    .proc_read = seq_read,\n    .proc_lseek = seq_lseek,\n    .proc_release = seq_release,\n};\n#else\nstatic const struct file_operations my_file_ops = {\n    .open = my_open,\n    .read = seq_read,\n    .llseek = seq_lseek,\n    .release = seq_release,\n};\n#endif\n\nstatic int __init procfs4_init(void)\n{\n    struct proc_dir_entry *entry;\n\n    entry = proc_create(PROC_NAME, 0, NULL, &my_file_ops);\n    if (entry == NULL) {\n        pr_debug(\"Error: Could not initialize /proc/%s\\n\", PROC_NAME);\n        return -ENOMEM;\n    }\n\n    return 0;\n}\n\nstatic void __exit procfs4_exit(void)\n{\n    remove_proc_entry(PROC_NAME, NULL);\n    pr_debug(\"/proc/%s removed\\n\", PROC_NAME);\n}\n\nmodule_init(procfs4_init);\nmodule_exit(procfs4_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/sched.c",
    "content": "/*\n * sched.c\n */\n#include <linux/init.h>\n#include <linux/module.h>\n#include <linux/workqueue.h>\n\nstatic struct workqueue_struct *queue = NULL;\nstatic struct work_struct work;\n\nstatic void work_handler(struct work_struct *data)\n{\n    pr_info(\"work handler function.\\n\");\n}\n\nstatic int __init sched_init(void)\n{\n    queue = alloc_workqueue(\"HELLOWORLD\", WQ_UNBOUND, 1);\n    if (!queue) {\n        pr_err(\"Failed to allocate workqueue\\n\");\n        return -ENOMEM;\n    }\n    INIT_WORK(&work, work_handler);\n    queue_work(queue, &work);\n    return 0;\n}\n\nstatic void __exit sched_exit(void)\n{\n    flush_workqueue(queue);\n    destroy_workqueue(queue);\n}\n\nmodule_init(sched_init);\nmodule_exit(sched_exit);\n\nMODULE_LICENSE(\"GPL\");\nMODULE_DESCRIPTION(\"Workqueue example\");\n"
  },
  {
    "path": "examples/sleep.c",
    "content": "/*\n * sleep.c - create a /proc file, and if several processes try to open it\n * at the same time, put all but one to sleep.\n */\n\n#include <linux/atomic.h>\n#include <linux/fs.h>\n#include <linux/kernel.h> /* for sprintf() */\n#include <linux/module.h> /* Specifically, a module */\n#include <linux/printk.h>\n#include <linux/proc_fs.h> /* Necessary because we use proc fs */\n#include <linux/types.h>\n#include <linux/uaccess.h> /* for get_user and put_user */\n#include <linux/version.h>\n#include <linux/wait.h> /* For putting processes to sleep and\n                                   waking them up */\n\n#include <asm/current.h>\n#include <asm/errno.h>\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0)\n#define HAVE_PROC_OPS\n#endif\n\n/* Here we keep the last message received, to prove that we can process our\n * input.\n */\n#define MESSAGE_LENGTH 80\nstatic char message[MESSAGE_LENGTH];\n\nstatic struct proc_dir_entry *our_proc_file;\n#define PROC_ENTRY_FILENAME \"sleep\"\n\n/* Since we use the file operations struct, we can't use the special proc\n * output provisions - we have to use a standard read function, which is this\n * function.\n */\nstatic ssize_t module_output(struct file *file, /* see include/linux/fs.h   */\n                             char __user *buf, /* The buffer to put data to\n                                                   (in the user segment)    */\n                             size_t len, /* The length of the buffer */\n                             loff_t *offset)\n{\n    static int finished = 0;\n    int i;\n    char output_msg[MESSAGE_LENGTH + 30];\n\n    /* Return 0 to signify end of file - that we have nothing more to say\n     * at this point.\n     */\n    if (finished) {\n        finished = 0;\n        return 0;\n    }\n\n    sprintf(output_msg, \"Last input:%s\\n\", message);\n    for (i = 0; i < len && output_msg[i]; i++)\n        put_user(output_msg[i], buf + i);\n\n    finished = 1;\n    return i; /* Return the number of bytes \"read\" */\n}\n\n/* This function receives input from the user when the user writes to the\n * /proc file.\n */\nstatic ssize_t module_input(struct file *file, /* The file itself */\n                            const char __user *buf, /* The buffer with input */\n                            size_t length, /* The buffer's length */\n                            loff_t *offset) /* offset to file - ignore */\n{\n    int i;\n\n    /* Put the input into message, where module_output will later be able\n     * to use it.\n     */\n    for (i = 0; i < MESSAGE_LENGTH - 1 && i < length; i++)\n        get_user(message[i], buf + i);\n    /* we want a standard, zero terminated string */\n    message[i] = '\\0';\n\n    /* We need to return the number of input characters used */\n    return i;\n}\n\n/* 1 if the file is currently open by somebody */\nstatic atomic_t already_open = ATOMIC_INIT(0);\n\n/* Queue of processes who want our file */\nstatic DECLARE_WAIT_QUEUE_HEAD(waitq);\n\n/* Called when the /proc file is opened */\nstatic int module_open(struct inode *inode, struct file *file)\n{\n    /* Try to get without blocking  */\n    if (!atomic_cmpxchg(&already_open, 0, 1)) {\n        /* Success without blocking, allow the access */\n        return 0;\n    }\n    /* If the file's flags include O_NONBLOCK, it means the process does not\n     * want to wait for the file. In this case, because the file is already open,\n     * we should fail with -EAGAIN, meaning \"you will have to try again\",\n     * instead of blocking a process which would rather stay awake.\n     */\n    if (file->f_flags & O_NONBLOCK)\n        return -EAGAIN;\n\n    while (atomic_cmpxchg(&already_open, 0, 1)) {\n        int i, is_sig = 0;\n\n        /* This function puts the current process, including any system\n         * calls, such as us, to sleep.  Execution will be resumed right\n         * after the function call, either because somebody called\n         * wake_up(&waitq) (only module_close does that, when the file\n         * is closed) or when a signal, such as Ctrl-C, is sent\n         * to the process\n         */\n        wait_event_interruptible(waitq, !atomic_read(&already_open));\n\n        /* If we woke up because we got a signal we're not blocking,\n         * return -EINTR (fail the system call).  This allows processes\n         * to be killed or stopped.\n         */\n        for (i = 0; i < _NSIG_WORDS && !is_sig; i++)\n            is_sig = current->pending.signal.sig[i] & ~current->blocked.sig[i];\n\n        if (is_sig) {\n            /* Return -EINTR if we got a signal */\n            return -EINTR;\n        }\n    }\n\n    return 0; /* Allow the access */\n}\n\n/* Called when the /proc file is closed */\nstatic int module_close(struct inode *inode, struct file *file)\n{\n    /* Set already_open to zero, so one of the processes in the waitq will\n     * be able to set already_open back to one and to open the file. All\n     * the other processes will be called when already_open is back to one,\n     * so they'll go back to sleep.\n     */\n    atomic_set(&already_open, 0);\n\n    /* Wake up all the processes in waitq, so if anybody is waiting for the\n     * file, they can have it.\n     */\n    wake_up(&waitq);\n\n    return 0; /* success */\n}\n\n/* Structures to register as the /proc file, with pointers to all the relevant\n * functions.\n */\n\n/* File operations for our /proc file. This is where we place pointers to all\n * the functions called when somebody tries to do something to our file. NULL\n * means we don't want to deal with something.\n */\n#ifdef HAVE_PROC_OPS\nstatic const struct proc_ops file_ops_4_our_proc_file = {\n    .proc_read = module_output, /* \"read\" from the file */\n    .proc_write = module_input, /* \"write\" to the file */\n    .proc_open = module_open, /* called when the /proc file is opened */\n    .proc_release = module_close, /* called when it's closed */\n    .proc_lseek = noop_llseek, /* return file->f_pos */\n};\n#else\nstatic const struct file_operations file_ops_4_our_proc_file = {\n    .read = module_output,\n    .write = module_input,\n    .open = module_open,\n    .release = module_close,\n    .llseek = noop_llseek,\n};\n#endif\n\n/* Initialize the module - register the /proc file */\nstatic int __init sleep_init(void)\n{\n    our_proc_file =\n        proc_create(PROC_ENTRY_FILENAME, 0644, NULL, &file_ops_4_our_proc_file);\n    if (our_proc_file == NULL) {\n        pr_debug(\"Error: Could not initialize /proc/%s\\n\", PROC_ENTRY_FILENAME);\n        return -ENOMEM;\n    }\n    proc_set_size(our_proc_file, 80);\n    proc_set_user(our_proc_file, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID);\n\n    pr_info(\"/proc/%s created\\n\", PROC_ENTRY_FILENAME);\n\n    return 0;\n}\n\n/* Cleanup - unregister our file from /proc.  This could get dangerous if\n * there are still processes waiting in waitq, because they are inside our\n * open function, which will get unloaded. I'll explain how to avoid removal\n * of a kernel module in such a case in chapter 10.\n */\nstatic void __exit sleep_exit(void)\n{\n    remove_proc_entry(PROC_ENTRY_FILENAME, NULL);\n    pr_debug(\"/proc/%s removed\\n\", PROC_ENTRY_FILENAME);\n}\n\nmodule_init(sleep_init);\nmodule_exit(sleep_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/start.c",
    "content": "/*\n * start.c - Illustration of multi filed modules\n */\n\n#include <linux/kernel.h> /* We are doing kernel work */\n#include <linux/module.h> /* Specifically, a module */\n\nint init_module(void)\n{\n    pr_info(\"Hello, world - this is the kernel speaking\\n\");\n    return 0;\n}\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/static_key.c",
    "content": "/*\n * static_key.c\n */\n\n#include <linux/atomic.h>\n#include <linux/device.h>\n#include <linux/fs.h>\n#include <linux/kernel.h> /* for sprintf() */\n#include <linux/module.h>\n#include <linux/printk.h>\n#include <linux/types.h>\n#include <linux/uaccess.h> /* for get_user and put_user */\n#include <linux/jump_label.h> /* for static key macros */\n#include <linux/version.h>\n\n#include <asm/errno.h>\n\nstatic int device_open(struct inode *inode, struct file *file);\nstatic int device_release(struct inode *inode, struct file *file);\nstatic ssize_t device_read(struct file *file, char __user *buf, size_t count,\n                           loff_t *ppos);\nstatic ssize_t device_write(struct file *file, const char __user *buf,\n                            size_t count, loff_t *ppos);\n\n#define DEVICE_NAME \"key_state\"\n#define BUF_LEN 10\n\nstatic int major;\n\nenum {\n    CDEV_NOT_USED,\n    CDEV_EXCLUSIVE_OPEN,\n};\n\nstatic atomic_t already_open = ATOMIC_INIT(CDEV_NOT_USED);\n\nstatic char msg[BUF_LEN + 1];\n\nstatic struct class *cls;\n\nstatic DEFINE_STATIC_KEY_FALSE(fkey);\n\nstatic struct file_operations chardev_fops = {\n    .owner = THIS_MODULE,\n    .open = device_open,\n    .release = device_release,\n    .read = device_read,\n    .write = device_write,\n};\n\nstatic int __init chardev_init(void)\n{\n    major = register_chrdev(0, DEVICE_NAME, &chardev_fops);\n    if (major < 0) {\n        pr_alert(\"Registering char device failed with %d\\n\", major);\n        return major;\n    }\n\n    pr_info(\"I was assigned major number %d\\n\", major);\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 4, 0)\n    cls = class_create(DEVICE_NAME);\n#else\n    cls = class_create(THIS_MODULE, DEVICE_NAME);\n#endif\n    if (IS_ERR(cls)) {\n        pr_err(\"Failed to create class for device\\n\");\n        unregister_chrdev(major, DEVICE_NAME);\n        return PTR_ERR(cls);\n    }\n    device_create(cls, NULL, MKDEV(major, 0), NULL, DEVICE_NAME);\n\n    pr_info(\"Device created on /dev/%s\\n\", DEVICE_NAME);\n\n    return 0;\n}\n\nstatic void __exit chardev_exit(void)\n{\n    device_destroy(cls, MKDEV(major, 0));\n    class_destroy(cls);\n\n    /* Unregister the device */\n    unregister_chrdev(major, DEVICE_NAME);\n}\n\n/* Methods */\n\n/**\n * Called when a process tried to open the device file, like\n * cat /dev/key_state\n */\nstatic int device_open(struct inode *inode, struct file *file)\n{\n    if (atomic_cmpxchg(&already_open, CDEV_NOT_USED, CDEV_EXCLUSIVE_OPEN))\n        return -EBUSY;\n\n    sprintf(msg, static_key_enabled(&fkey) ? \"enabled\\n\" : \"disabled\\n\");\n\n    pr_info(\"fastpath 1\\n\");\n    if (static_branch_unlikely(&fkey))\n        pr_alert(\"do unlikely thing\\n\");\n    pr_info(\"fastpath 2\\n\");\n\n    return 0;\n}\n\n/**\n * Called when a process closes the device file\n */\nstatic int device_release(struct inode *inode, struct file *file)\n{\n    /* We are now ready for our next caller. */\n    atomic_set(&already_open, CDEV_NOT_USED);\n\n    return 0;\n}\n\n/**\n * Called when a process, which already opened the dev file, attempts to\n * read from it.\n */\nstatic ssize_t device_read(struct file *filp, /* see include/linux/fs.h */\n                           char __user *buffer, /* buffer to fill with data */\n                           size_t length, /* length of the buffer */\n                           loff_t *offset)\n{\n    /* Number of the bytes actually written to the buffer */\n    int bytes_read = 0;\n    const char *msg_ptr = msg;\n\n    if (!*(msg_ptr + *offset)) { /* We are at the end of the message */\n        *offset = 0; /* reset the offset */\n        return 0; /* signify end of file */\n    }\n\n    msg_ptr += *offset;\n\n    /* Actually put the data into the buffer */\n    while (length && *msg_ptr) {\n        /**\n         * The buffer is in the user data segment, not the kernel\n         * segment so \"*\" assignment won't work. We have to use\n         * put_user which copies data from the kernel data segment to\n         * the user data segment.\n         */\n        put_user(*(msg_ptr++), buffer++);\n        length--;\n        bytes_read++;\n    }\n\n    *offset += bytes_read;\n\n    /* Most read functions return the number of bytes put into the buffer. */\n    return bytes_read;\n}\n\n/* Called when a process writes to dev file; echo \"enable\" > /dev/key_state */\nstatic ssize_t device_write(struct file *filp, const char __user *buffer,\n                            size_t length, loff_t *offset)\n{\n    char command[10];\n\n    if (length > 10) {\n        pr_err(\"command exceeded 10 char\\n\");\n        return -EINVAL;\n    }\n\n    if (copy_from_user(command, buffer, length))\n        return -EFAULT;\n\n    if (strncmp(command, \"enable\", strlen(\"enable\")) == 0)\n        static_branch_enable(&fkey);\n    else if (strncmp(command, \"disable\", strlen(\"disable\")) == 0)\n        static_branch_disable(&fkey);\n    else {\n        pr_err(\"Invalid command: %s\\n\", command);\n        return -EINVAL;\n    }\n\n    /* Again, return the number of input characters used. */\n    return length;\n}\n\nmodule_init(chardev_init);\nmodule_exit(chardev_exit);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/stop.c",
    "content": "/*\n * stop.c - Illustration of multi filed modules\n */\n\n#include <linux/kernel.h> /* We are doing kernel work */\n#include <linux/module.h> /* Specifically, a module  */\n\nvoid cleanup_module(void)\n{\n    pr_info(\"Short is the life of a kernel module\\n\");\n}\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/syscall-steal.c",
    "content": "/*\n * syscall-steal.c\n *\n * System call \"stealing\" sample.\n *\n * Disables page protection at a processor level by changing the 16th bit\n * in the cr0 register (could be Intel specific).\n */\n\n#include <linux/delay.h>\n#include <linux/kernel.h>\n#include <linux/module.h>\n#include <linux/moduleparam.h> /* which will have params */\n#include <linux/unistd.h> /* The list of system calls */\n#include <linux/cred.h> /* For current_uid() */\n#include <linux/uidgid.h> /* For __kuid_val() */\n#include <linux/version.h>\n\n/* For the current (process) structure, we need this to know who the\n * current user is.\n */\n#include <linux/sched.h>\n#include <linux/uaccess.h>\n\n/* The way we access \"sys_call_table\" varies as kernel internal changes.\n * - Prior to v5.4 : manual symbol lookup\n * - v5.5 to v5.6  : use kallsyms_lookup_name()\n * - v5.7+         : Kprobes or specific kernel module parameter\n */\n\n/* The in-kernel calls to the ksys_close() syscall were removed in Linux v5.11+.\n */\n#if (LINUX_VERSION_CODE >= KERNEL_VERSION(5, 7, 0))\n\n#if defined(CONFIG_KPROBES)\n#define HAVE_KPROBES 1\n#if defined(CONFIG_X86_64)\n/* If you have tried to use the syscall table to intercept syscalls and it \n * doesn't work, you can try to use Kprobes to intercept syscalls.\n * Set USE_KPROBES_PRE_HANDLER_BEFORE_SYSCALL to 1 to register a pre-handler\n * before the syscall.\n */\n#define USE_KPROBES_PRE_HANDLER_BEFORE_SYSCALL 0\n#endif\n#include <linux/kprobes.h>\n#else\n#define HAVE_PARAM 1\n#include <linux/kallsyms.h> /* For sprint_symbol */\n/* The address of the sys_call_table, which can be obtained with looking up\n * \"/boot/System.map\" or \"/proc/kallsyms\". When the kernel version is v5.7+,\n * without CONFIG_KPROBES, you can input the parameter or the module will look\n * up all the memory.\n */\nstatic unsigned long sym = 0;\nmodule_param(sym, ulong, 0644);\n#endif /* CONFIG_KPROBES */\n\n#else\n\n#if LINUX_VERSION_CODE <= KERNEL_VERSION(5, 4, 0)\n#define HAVE_KSYS_CLOSE 1\n#include <linux/syscalls.h> /* For ksys_close() */\n#else\n#include <linux/kallsyms.h> /* For kallsyms_lookup_name */\n#endif\n\n#endif /* Version >= v5.7 */\n\n/* UID we want to spy on - will be filled from the command line. */\nstatic uid_t uid = -1;\nmodule_param(uid, int, 0644);\n\n#if USE_KPROBES_PRE_HANDLER_BEFORE_SYSCALL\n\n/* syscall_sym is the symbol name of the syscall to spy on. The default is\n * \"__x64_sys_openat\", which can be changed by the module parameter. You can \n * look up the symbol name of a syscall in /proc/kallsyms.\n */\nstatic char *syscall_sym = \"__x64_sys_openat\";\nmodule_param(syscall_sym, charp, 0644);\n\nstatic int sys_call_kprobe_pre_handler(struct kprobe *p, struct pt_regs *regs)\n{\n    if (__kuid_val(current_uid()) != uid) {\n        return 0;\n    }\n\n    pr_info(\"%s called by %d\\n\", syscall_sym, uid);\n    return 0;\n}\n\nstatic struct kprobe syscall_kprobe = {\n    .symbol_name = \"__x64_sys_openat\",\n    .pre_handler = sys_call_kprobe_pre_handler,\n};\n\n#else\n\nstatic unsigned long **sys_call_table_stolen;\n\n/* A pointer to the original system call. The reason we keep this, rather\n * than call the original function (sys_openat), is because somebody else\n * might have replaced the system call before us. Note that this is not\n * 100% safe, because if another module replaced sys_openat before us,\n * then when we are inserted, we will call the function in that module -\n * and it might be removed before we are.\n *\n * Another reason for this is that we can not get sys_openat.\n * It is a static variable, so it is not exported.\n */\n#ifdef CONFIG_ARCH_HAS_SYSCALL_WRAPPER\nstatic asmlinkage long (*original_call)(const struct pt_regs *);\n#else\nstatic asmlinkage long (*original_call)(int, const char __user *, int, umode_t);\n#endif\n\n/* The function we will replace sys_openat (the function called when you\n * call the open system call) with. To find the exact prototype, with\n * the number and type of arguments, we find the original function first\n * (it is at fs/open.c).\n *\n * In theory, this means that we are tied to the current version of the\n * kernel. In practice, the system calls almost never change (it would\n * wreck havoc and require programs to be recompiled, since the system\n * calls are the interface between the kernel and the processes).\n */\n#ifdef CONFIG_ARCH_HAS_SYSCALL_WRAPPER\nstatic asmlinkage long our_sys_openat(const struct pt_regs *regs)\n#else\nstatic asmlinkage long our_sys_openat(int dfd, const char __user *filename,\n                                      int flags, umode_t mode)\n#endif\n{\n    int i = 0;\n    char ch;\n\n    if (__kuid_val(current_uid()) != uid)\n        goto orig_call;\n\n    /* Report the file, if relevant */\n    pr_info(\"Opened file by %d: \", uid);\n    do {\n#ifdef CONFIG_ARCH_HAS_SYSCALL_WRAPPER\n        get_user(ch, (char __user *)regs->si + i);\n#else\n        get_user(ch, (char __user *)filename + i);\n#endif\n        i++;\n        pr_info(\"%c\", ch);\n    } while (ch != 0);\n    pr_info(\"\\n\");\n\norig_call:\n    /* Call the original sys_openat - otherwise, we lose the ability to\n     * open files.\n     */\n#ifdef CONFIG_ARCH_HAS_SYSCALL_WRAPPER\n    return original_call(regs);\n#else\n    return original_call(dfd, filename, flags, mode);\n#endif\n}\n\nstatic unsigned long **acquire_sys_call_table(void)\n{\n#ifdef HAVE_KSYS_CLOSE\n    unsigned long int offset = PAGE_OFFSET;\n    unsigned long **sct;\n\n    while (offset < ULLONG_MAX) {\n        sct = (unsigned long **)offset;\n\n        if (sct[__NR_close] == (unsigned long *)ksys_close)\n            return sct;\n\n        offset += sizeof(void *);\n    }\n\n    return NULL;\n#endif\n\n#ifdef HAVE_PARAM\n    const char sct_name[15] = \"sys_call_table\";\n    char symbol[40] = { 0 };\n\n    if (sym == 0) {\n        pr_alert(\"For Linux v5.7+, Kprobes is the preferable way to get \"\n                 \"symbol.\\n\");\n        pr_info(\"If Kprobes is absent, you have to specify the address of \"\n                \"sys_call_table symbol\\n\");\n        pr_info(\"by /boot/System.map or /proc/kallsyms, which contains all the \"\n                \"symbol addresses, into sym parameter.\\n\");\n        return NULL;\n    }\n    sprint_symbol(symbol, sym);\n    if (!strncmp(sct_name, symbol, sizeof(sct_name) - 1))\n        return (unsigned long **)sym;\n\n    return NULL;\n#endif\n\n#ifdef HAVE_KPROBES\n    unsigned long (*kallsyms_lookup_name)(const char *name);\n    struct kprobe kp = {\n        .symbol_name = \"kallsyms_lookup_name\",\n    };\n\n    if (register_kprobe(&kp) < 0)\n        return NULL;\n    kallsyms_lookup_name = (unsigned long (*)(const char *name))kp.addr;\n    unregister_kprobe(&kp);\n#endif\n\n    return (unsigned long **)kallsyms_lookup_name(\"sys_call_table\");\n}\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 3, 0)\nstatic inline void __write_cr0(unsigned long cr0)\n{\n    asm volatile(\"mov %0,%%cr0\" : \"+r\"(cr0) : : \"memory\");\n}\n#else\n#define __write_cr0 write_cr0\n#endif\n\nstatic void enable_write_protection(void)\n{\n    unsigned long cr0 = read_cr0();\n    set_bit(16, &cr0);\n    __write_cr0(cr0);\n}\n\nstatic void disable_write_protection(void)\n{\n    unsigned long cr0 = read_cr0();\n    clear_bit(16, &cr0);\n    __write_cr0(cr0);\n}\n#endif\n\nstatic int __init syscall_steal_start(void)\n{\n#if USE_KPROBES_PRE_HANDLER_BEFORE_SYSCALL\n    int err;\n    /* use symbol name from the module parameter */\n    syscall_kprobe.symbol_name = syscall_sym;\n    err = register_kprobe(&syscall_kprobe);\n    if (err) {\n        pr_err(\"register_kprobe() on %s failed: %d\\n\", syscall_sym, err);\n        pr_err(\"Please check the symbol name from 'syscall_sym' parameter.\\n\");\n        return err;\n    }\n#else\n    if (!(sys_call_table_stolen = acquire_sys_call_table()))\n        return -1;\n\n    disable_write_protection();\n\n    /* keep track of the original open function */\n    original_call = (void *)sys_call_table_stolen[__NR_openat];\n\n    /* use our openat function instead */\n    sys_call_table_stolen[__NR_openat] = (unsigned long *)our_sys_openat;\n\n    enable_write_protection();\n#endif\n\n    pr_info(\"Spying on UID:%d\\n\", uid);\n    return 0;\n}\n\nstatic void __exit syscall_steal_end(void)\n{\n#if USE_KPROBES_PRE_HANDLER_BEFORE_SYSCALL\n    unregister_kprobe(&syscall_kprobe);\n#else\n    if (!sys_call_table_stolen)\n        return;\n\n    /* Return the system call back to normal */\n    if (sys_call_table_stolen[__NR_openat] != (unsigned long *)our_sys_openat) {\n        pr_alert(\"Somebody else also played with the \");\n        pr_alert(\"open system call\\n\");\n        pr_alert(\"The system may be left in \");\n        pr_alert(\"an unstable state.\\n\");\n    }\n\n    disable_write_protection();\n    sys_call_table_stolen[__NR_openat] = (unsigned long *)original_call;\n    enable_write_protection();\n#endif\n\n    msleep(2000);\n}\n\nmodule_init(syscall_steal_start);\nmodule_exit(syscall_steal_end);\n\nMODULE_LICENSE(\"GPL\");\n"
  },
  {
    "path": "examples/vinput.c",
    "content": "/*\n * vinput.c\n */\n\n#include <linux/cdev.h>\n#include <linux/input.h>\n#include <linux/module.h>\n#include <linux/slab.h>\n#include <linux/spinlock.h>\n#include <linux/version.h>\n\n#include <asm/uaccess.h>\n\n#include \"vinput.h\"\n\n#define DRIVER_NAME \"vinput\"\n\n#define dev_to_vinput(dev) container_of(dev, struct vinput, dev)\n\nstatic DECLARE_BITMAP(vinput_ids, VINPUT_MINORS);\n\nstatic LIST_HEAD(vinput_devices);\nstatic LIST_HEAD(vinput_vdevices);\n\nstatic int vinput_dev;\nstatic struct spinlock vinput_lock;\nstatic struct class vinput_class;\n\n/* Search the name of vinput device in the vinput_devices linked list,\n * which added at vinput_register().\n */\nstatic struct vinput_device *vinput_get_device_by_type(const char *type)\n{\n    int found = 0;\n    struct vinput_device *vinput;\n    struct list_head *curr;\n\n    spin_lock(&vinput_lock);\n    list_for_each (curr, &vinput_devices) {\n        vinput = list_entry(curr, struct vinput_device, list);\n        if (vinput && strncmp(type, vinput->name, strlen(vinput->name)) == 0) {\n            found = 1;\n            break;\n        }\n    }\n    spin_unlock(&vinput_lock);\n\n    if (found)\n        return vinput;\n    return ERR_PTR(-ENODEV);\n}\n\n/* Search the id of virtual device in the vinput_vdevices linked list,\n * which added at vinput_alloc_vdevice().\n */\nstatic struct vinput *vinput_get_vdevice_by_id(long id)\n{\n    struct vinput *vinput = NULL;\n    struct list_head *curr;\n\n    spin_lock(&vinput_lock);\n    list_for_each (curr, &vinput_vdevices) {\n        vinput = list_entry(curr, struct vinput, list);\n        if (vinput && vinput->id == id)\n            break;\n    }\n    spin_unlock(&vinput_lock);\n\n    if (vinput && vinput->id == id)\n        return vinput;\n    return ERR_PTR(-ENODEV);\n}\n\nstatic int vinput_open(struct inode *inode, struct file *file)\n{\n    int err = 0;\n    struct vinput *vinput = NULL;\n\n    vinput = vinput_get_vdevice_by_id(iminor(inode));\n\n    if (IS_ERR(vinput))\n        err = PTR_ERR(vinput);\n    else\n        file->private_data = vinput;\n\n    return err;\n}\n\nstatic int vinput_release(struct inode *inode, struct file *file)\n{\n    return 0;\n}\n\nstatic ssize_t vinput_read(struct file *file, char __user *buffer, size_t count,\n                           loff_t *offset)\n{\n    int len;\n    char buff[VINPUT_MAX_LEN + 1];\n    struct vinput *vinput = file->private_data;\n\n    len = vinput->type->ops->read(vinput, buff, count);\n\n    if (*offset > len)\n        count = 0;\n    else if (count + *offset > VINPUT_MAX_LEN)\n        count = len - *offset;\n\n    if (raw_copy_to_user(buffer, buff + *offset, count))\n        return -EFAULT;\n\n    *offset += count;\n\n    return count;\n}\n\nstatic ssize_t vinput_write(struct file *file, const char __user *buffer,\n                            size_t count, loff_t *offset)\n{\n    char buff[VINPUT_MAX_LEN + 1];\n    struct vinput *vinput = file->private_data;\n\n    memset(buff, 0, sizeof(char) * (VINPUT_MAX_LEN + 1));\n\n    if (count > VINPUT_MAX_LEN) {\n        dev_warn(&vinput->dev, \"Too long. %d bytes allowed\\n\", VINPUT_MAX_LEN);\n        return -EINVAL;\n    }\n\n    if (raw_copy_from_user(buff, buffer, count))\n        return -EFAULT;\n\n    return vinput->type->ops->send(vinput, buff, count);\n}\n\nstatic const struct file_operations vinput_fops = {\n    .owner = THIS_MODULE,\n    .open = vinput_open,\n    .release = vinput_release,\n    .read = vinput_read,\n    .write = vinput_write,\n};\n\nstatic void vinput_unregister_vdevice(struct vinput *vinput)\n{\n    input_unregister_device(vinput->input);\n    if (vinput->type->ops->kill)\n        vinput->type->ops->kill(vinput);\n}\n\nstatic void vinput_destroy_vdevice(struct vinput *vinput)\n{\n    /* Remove from the list first */\n    spin_lock(&vinput_lock);\n    list_del(&vinput->list);\n    clear_bit(vinput->id, vinput_ids);\n    spin_unlock(&vinput_lock);\n\n    kfree(vinput);\n}\n\nstatic void vinput_release_dev(struct device *dev)\n{\n    struct vinput *vinput = dev_to_vinput(dev);\n    int id = vinput->id;\n\n    vinput_destroy_vdevice(vinput);\n\n    pr_debug(\"released vinput%d.\\n\", id);\n}\n\nstatic struct vinput *vinput_alloc_vdevice(void)\n{\n    int err;\n    struct vinput *vinput = kzalloc(sizeof(struct vinput), GFP_KERNEL);\n\n    if (!vinput) {\n        pr_err(\"vinput: Cannot allocate vinput input device\\n\");\n        return ERR_PTR(-ENOMEM);\n    }\n\n    spin_lock_init(&vinput->lock);\n\n    spin_lock(&vinput_lock);\n    vinput->id = find_first_zero_bit(vinput_ids, VINPUT_MINORS);\n    if (vinput->id >= VINPUT_MINORS) {\n        err = -ENOBUFS;\n        goto fail_id;\n    }\n    set_bit(vinput->id, vinput_ids);\n    list_add(&vinput->list, &vinput_vdevices);\n    spin_unlock(&vinput_lock);\n\n    /* allocate the input device */\n    vinput->input = input_allocate_device();\n    if (vinput->input == NULL) {\n        pr_err(\"vinput: Cannot allocate vinput input device\\n\");\n        err = -ENOMEM;\n        goto fail_input_dev;\n    }\n\n    /* initialize device */\n    vinput->dev.class = &vinput_class;\n    vinput->dev.release = vinput_release_dev;\n    vinput->dev.devt = MKDEV(vinput_dev, vinput->id);\n    dev_set_name(&vinput->dev, DRIVER_NAME \"%lu\", vinput->id);\n\n    return vinput;\n\nfail_input_dev:\n    spin_lock(&vinput_lock);\n    list_del(&vinput->list);\nfail_id:\n    spin_unlock(&vinput_lock);\n    kfree(vinput);\n\n    return ERR_PTR(err);\n}\n\nstatic int vinput_register_vdevice(struct vinput *vinput)\n{\n    int err = 0;\n\n    /* register the input device */\n    vinput->input->name = vinput->type->name;\n    vinput->input->phys = \"vinput\";\n    vinput->input->dev.parent = &vinput->dev;\n\n    vinput->input->id.bustype = BUS_VIRTUAL;\n    vinput->input->id.product = 0x0000;\n    vinput->input->id.vendor = 0x0000;\n    vinput->input->id.version = 0x0000;\n\n    err = vinput->type->ops->init(vinput);\n\n    if (err == 0)\n        dev_info(&vinput->dev, \"Registered virtual input %s %ld\\n\",\n                 vinput->type->name, vinput->id);\n\n    return err;\n}\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 4, 0)\nstatic ssize_t export_store(const struct class *class,\n                            const struct class_attribute *attr,\n#else\nstatic ssize_t export_store(struct class *class, struct class_attribute *attr,\n#endif\n                            const char *buf, size_t len)\n{\n    int err;\n    struct vinput *vinput;\n    struct vinput_device *device;\n\n    device = vinput_get_device_by_type(buf);\n    if (IS_ERR(device)) {\n        pr_info(\"vinput: This virtual device isn't registered\\n\");\n        err = PTR_ERR(device);\n        goto fail;\n    }\n\n    vinput = vinput_alloc_vdevice();\n    if (IS_ERR(vinput)) {\n        err = PTR_ERR(vinput);\n        goto fail;\n    }\n\n    vinput->type = device;\n    err = device_register(&vinput->dev);\n    if (err < 0)\n        goto fail_register;\n\n    err = vinput_register_vdevice(vinput);\n    if (err < 0)\n        goto fail_register_vinput;\n\n    return len;\n\nfail_register_vinput:\n    input_free_device(vinput->input);\n    device_unregister(&vinput->dev);\n    /* avoid calling vinput_destroy_vdevice() twice */\n    return err;\nfail_register:\n    input_free_device(vinput->input);\n    vinput_destroy_vdevice(vinput);\nfail:\n    return err;\n}\n/* This macro generates class_attr_export structure and export_store() */\nstatic CLASS_ATTR_WO(export);\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 4, 0)\nstatic ssize_t unexport_store(const struct class *class,\n                              const struct class_attribute *attr,\n#else\nstatic ssize_t unexport_store(struct class *class, struct class_attribute *attr,\n#endif\n                              const char *buf, size_t len)\n{\n    int err;\n    unsigned long id;\n    struct vinput *vinput;\n\n    err = kstrtol(buf, 10, &id);\n    if (err) {\n        err = -EINVAL;\n        goto failed;\n    }\n\n    vinput = vinput_get_vdevice_by_id(id);\n    if (IS_ERR(vinput)) {\n        pr_err(\"vinput: No such vinput device %ld\\n\", id);\n        err = PTR_ERR(vinput);\n        goto failed;\n    }\n\n    vinput_unregister_vdevice(vinput);\n    device_unregister(&vinput->dev);\n\n    return len;\nfailed:\n    return err;\n}\n/* This macro generates class_attr_unexport structure and unexport_store() */\nstatic CLASS_ATTR_WO(unexport);\n\nstatic struct attribute *vinput_class_attrs[] = {\n    &class_attr_export.attr,\n    &class_attr_unexport.attr,\n    NULL,\n};\n\n/* This macro generates vinput_class_groups structure */\nATTRIBUTE_GROUPS(vinput_class);\n\nstatic struct class vinput_class = {\n    .name = \"vinput\",\n/* .owner was removed in Linux v6.4 via upstream commit 6e30a66433af (\"driver core: class: remove\n * struct module owner out of struct class\")\n */\n#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 4, 0)\n    .owner = THIS_MODULE,\n#endif\n    .class_groups = vinput_class_groups,\n};\n\nint vinput_register(struct vinput_device *dev)\n{\n    spin_lock(&vinput_lock);\n    list_add(&dev->list, &vinput_devices);\n    spin_unlock(&vinput_lock);\n\n    pr_info(\"vinput: registered new virtual input device '%s'\\n\", dev->name);\n\n    return 0;\n}\nEXPORT_SYMBOL(vinput_register);\n\nvoid vinput_unregister(struct vinput_device *dev)\n{\n    struct list_head *curr, *next;\n\n    /* Remove from the list first */\n    spin_lock(&vinput_lock);\n    list_del(&dev->list);\n    spin_unlock(&vinput_lock);\n\n    /* unregister all devices of this type */\n    list_for_each_safe (curr, next, &vinput_vdevices) {\n        struct vinput *vinput = list_entry(curr, struct vinput, list);\n        if (vinput && vinput->type == dev) {\n            vinput_unregister_vdevice(vinput);\n            device_unregister(&vinput->dev);\n        }\n    }\n\n    pr_info(\"vinput: unregistered virtual input device '%s'\\n\", dev->name);\n}\nEXPORT_SYMBOL(vinput_unregister);\n\nstatic int __init vinput_init(void)\n{\n    int err = 0;\n\n    pr_info(\"vinput: Loading virtual input driver\\n\");\n\n    vinput_dev = register_chrdev(0, DRIVER_NAME, &vinput_fops);\n    if (vinput_dev < 0) {\n        pr_err(\"vinput: Unable to allocate char dev region\\n\");\n        err = vinput_dev;\n        goto failed_alloc;\n    }\n\n    spin_lock_init(&vinput_lock);\n\n    err = class_register(&vinput_class);\n    if (err < 0) {\n        pr_err(\"vinput: Unable to register vinput class\\n\");\n        goto failed_class;\n    }\n\n    return 0;\nfailed_class:\n    unregister_chrdev(vinput_dev, DRIVER_NAME);\nfailed_alloc:\n    return err;\n}\n\nstatic void __exit vinput_end(void)\n{\n    pr_info(\"vinput: Unloading virtual input driver\\n\");\n\n    unregister_chrdev(vinput_dev, DRIVER_NAME);\n    class_unregister(&vinput_class);\n}\n\nmodule_init(vinput_init);\nmodule_exit(vinput_end);\n\nMODULE_LICENSE(\"GPL\");\nMODULE_DESCRIPTION(\"Emulate input events\");\n"
  },
  {
    "path": "examples/vinput.h",
    "content": "/*\n * vinput.h\n */\n\n#ifndef VINPUT_H\n#define VINPUT_H\n\n#include <linux/input.h>\n#include <linux/spinlock.h>\n\n#define VINPUT_MAX_LEN 128\n#define MAX_VINPUT 32\n#define VINPUT_MINORS MAX_VINPUT\n\n#define dev_to_vinput(dev) container_of(dev, struct vinput, dev)\n\nstruct vinput_device;\n\nstruct vinput {\n    long id;\n    long devno;\n    long last_entry;\n    spinlock_t lock;\n\n    void *priv_data;\n\n    struct device dev;\n    struct list_head list;\n    struct input_dev *input;\n    struct vinput_device *type;\n};\n\nstruct vinput_ops {\n    int (*init)(struct vinput *);\n    int (*kill)(struct vinput *);\n    int (*send)(struct vinput *, char *, int);\n    int (*read)(struct vinput *, char *, int);\n};\n\nstruct vinput_device {\n    char name[16];\n    struct list_head list;\n    struct vinput_ops *ops;\n};\n\nint vinput_register(struct vinput_device *dev);\nvoid vinput_unregister(struct vinput_device *dev);\n\n#endif\n"
  },
  {
    "path": "examples/vkbd.c",
    "content": "/*\n * vkbd.c\n */\n\n#include <linux/init.h>\n#include <linux/input.h>\n#include <linux/module.h>\n#include <linux/spinlock.h>\n\n#include \"vinput.h\"\n\n#define VINPUT_KBD \"vkbd\"\n#define VINPUT_RELEASE 0\n#define VINPUT_PRESS 1\n\nstatic unsigned short vkeymap[KEY_MAX];\n\nstatic int vinput_vkbd_init(struct vinput *vinput)\n{\n    int i;\n\n    /* Set up the input bitfield */\n    vinput->input->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP);\n    vinput->input->keycodesize = sizeof(unsigned short);\n    vinput->input->keycodemax = KEY_MAX;\n    vinput->input->keycode = vkeymap;\n\n    for (i = 0; i < KEY_MAX; i++)\n        set_bit(vkeymap[i], vinput->input->keybit);\n\n    /* vinput will help us allocate new input device structure via\n     * input_allocate_device(). So, we can register it straightforwardly.\n     */\n    return input_register_device(vinput->input);\n}\n\nstatic int vinput_vkbd_read(struct vinput *vinput, char *buff, int len)\n{\n    spin_lock(&vinput->lock);\n    len = snprintf(buff, len, \"%+ld\\n\", vinput->last_entry);\n    spin_unlock(&vinput->lock);\n\n    return len;\n}\n\nstatic int vinput_vkbd_send(struct vinput *vinput, char *buff, int len)\n{\n    int ret;\n    long key = 0;\n    short type = VINPUT_PRESS;\n\n    /* Determine which event was received (press or release)\n     * and store the state.\n     */\n    if (buff[0] == '+')\n        ret = kstrtol(buff + 1, 10, &key);\n    else\n        ret = kstrtol(buff, 10, &key);\n    if (ret)\n        dev_err(&vinput->dev, \"error during kstrtol: -%d\\n\", ret);\n    spin_lock(&vinput->lock);\n    vinput->last_entry = key;\n    spin_unlock(&vinput->lock);\n\n    if (key < 0) {\n        type = VINPUT_RELEASE;\n        key = -key;\n    }\n\n    dev_info(&vinput->dev, \"Event %s code %ld\\n\",\n             (type == VINPUT_RELEASE) ? \"VINPUT_RELEASE\" : \"VINPUT_PRESS\", key);\n\n    /* Report the state received to input subsystem. */\n    input_report_key(vinput->input, key, type);\n    /* Tell input subsystem that it finished the report. */\n    input_sync(vinput->input);\n\n    return len;\n}\n\nstatic struct vinput_ops vkbd_ops = {\n    .init = vinput_vkbd_init,\n    .send = vinput_vkbd_send,\n    .read = vinput_vkbd_read,\n};\n\nstatic struct vinput_device vkbd_dev = {\n    .name = VINPUT_KBD,\n    .ops = &vkbd_ops,\n};\n\nstatic int __init vkbd_init(void)\n{\n    int i;\n\n    for (i = 0; i < KEY_MAX; i++)\n        vkeymap[i] = i;\n    return vinput_register(&vkbd_dev);\n}\n\nstatic void __exit vkbd_end(void)\n{\n    vinput_unregister(&vkbd_dev);\n}\n\nmodule_init(vkbd_init);\nmodule_exit(vkbd_end);\n\nMODULE_LICENSE(\"GPL\");\nMODULE_DESCRIPTION(\"Emulate keyboard input events through /dev/vinput\");\n"
  },
  {
    "path": "html.cfg",
    "content": "\\Preamble{xhtml}\n\n\\Configure{tableofcontents*}{chapter,section,subsection}\n\n\\Css{html {\n    width: 100vw;\n    overflow-x: hidden;\n}}\n\n\\Css{@font-face {\n  font-family: Manrope;\n  src: url(Manrope_variable.ttf);\n}}\n\n\\Css{body {\n    max-width: 55rem;\n    box-sizing: border-box;\n    padding: 1rem;\n    margin: 0 auto;\n    overflow-x: hidden;\n    background-color: \\#F4ECD8;\n    color: \\#5B464B;\n    line-height: 1.5;\n}}\n\n\\Css{a {\ncolor: \\#0060DF;\n}}\n\n\\Css{p, a {\nfont-size: 1.2rem;\nfont-family: Manrope;\n}}\n\n\\Css{p + pre {\nfont-size: 1.1em;\n}}\n\n\\Css{div.author {\n    white-space: normal;\n}}\n\n\\Css{img.math {\n    height: 1rem;\n    vertical-align: top;\n}}\n\n\\Css{pre.fancyvrb, {\n    white-space: pre;\n}}\n\n\\Css{figure, .fancyvrb, .verbatim {\n    margin-inline: 0;\n    overflow-x: auto;\n}}\n\n\\Css{.ecrm-0500 {\n    font-size: 70\\%;\n    font-style: italic;\n    color: gray;\n    width: 1.5rem;\n    display: inline-block;\n    -webkit-user-select: none;\n    -moz-user-select: none;\n    -o-user-select: none;\n    user-select: none;\n}}\n\n\\Css{.flushright:first-child {\n    position:absolute;\n    top: 10px;\n    right: 50px;\n}}\n\n\\Css{.right {\n    text-align: right;\n}}\n\n\\AtBeginDocument{%\n\\Configure{@HEAD}{\\HCode{\n    <script async defer src=\"https://buttons.github.io/buttons.js\"></script>\n    <div class=\"right\">\n        <a class=\"github-button\" href=\"https://github.com/sysprog21/lkmpg\" data-size=\"large\" aria-label=\"View on GitHub\">View on GitHub</a>\n        <a class=\"github-button\" href=\"https://github.com/sysprog21/lkmpg/releases/download/latest/lkmpg.pdf\" data-icon=\"octicon-download\" data-size=\"large\" aria-label=\"Download PDF document\">Download PDF document</a>\n        <br><br>\n    </div>\n    \\Hnewline}}\n}\n\n\\begin{document}\n\\EndPreamble\n"
  },
  {
    "path": "lib/codeblock.tex",
    "content": "\\newminted[code]{c}{frame=single,\n  framesep=2mm,\n  baselinestretch=1,\n  fontsize=\\footnotesize,\n  breaklines,\n  breakafter=d,\n  linenos\n}\n\n\\usemintedstyle{vs}\n\n\\NewDocumentCommand{\\samplec}{oom}{%\n  \\IfNoValueTF{#1}%\n  {%\n    \\inputminted[frame=single, framesep=2mm, baselinestretch=1, fontsize=\\footnotesize, breaklines, breakafter=d, linenos]{c}{#3}%\n  }%\n  {%\n    \\IfNoValueTF{#2}%\n    {%\n      \\inputminted[frame=single, framesep=2mm, baselinestretch=1, fontsize=\\footnotesize, breaklines, breakafter=d, firstline=#1, linenos]{c}{#3}%\n    }%\n    {%\n      \\inputminted[frame=single, framesep=2mm, baselinestretch=1, fontsize=\\footnotesize, breaklines, breakafter=d, firstline=#1, lastline=#2, linenos]{c}{#3}%\n    }%\n  }%\n}\n\n\\newminted[codebash]{bash}{frame=single,\n  framesep=2mm,\n  baselinestretch=1.2,\n  numbersep=8pt,\n  breaklines,\n  linenos\n}\n\n\\newmintinline[sh]{bash}{}\n\\newmintinline[cpp]{c}{}\n"
  },
  {
    "path": "lib/kernelsrc.tex",
    "content": "\\newcommand*{\\src}[2][]{\\href{https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/#2}%\n                             {\\ifthenelse{\\equal{#1}{}}{#2}{#1}}}\n"
  },
  {
    "path": "lkmpg.tex",
    "content": "\\documentclass[10pt, oneside]{book}\n\\usepackage[Bjornstrup]{fncychap}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{graphicx}\n\\usepackage{fancyhdr}\n\\usepackage{xparse}\n\\usepackage{ifthen}\n\\usepackage{pdfpages}\n\n% tikz settings\n\\usepackage{tikz}\n\\usetikzlibrary{shapes.geometric, arrows, shadows, decorations.text}\n\\tikzstyle{startstop} = [rectangle, rounded corners, minimum width=3cm, minimum height=1cm,text centered, draw=black, fill=red!30, drop shadow]\n\\tikzstyle{io} = [trapezium, trapezium left angle=70, trapezium right angle=110, minimum width=3cm, minimum height=1cm, text centered, draw=black, fill=blue!30]\n\\tikzstyle{process} = [rectangle, minimum width=3cm, minimum height=1cm, text centered, text width=3cm, draw=black, fill=orange!30]\n\\tikzstyle{decision} = [diamond, minimum width=1cm, minimum height=1cm, text centered, draw=black, fill=green!30]\n\\tikzstyle{arrow} = [thick,->,>=stealth]\n\\tikzstyle{line} = [draw, -latex']\n\n% packages for code\n\\usepackage{verbatim}\n\\usepackage{minted}\n\n% citation\n\\usepackage{cite}\n\\usepackage[colorlinks,citecolor=green]{hyperref}\n\\usepackage{cleveref}\n\n\\usepackage{xcolor}\n\\hypersetup{\n  colorlinks,\n  linkcolor = {red!50!black},\n  citecolor = {blue!50!black},\n  urlcolor = {blue!80!black}\n}\n\n\\input{lib/codeblock}\n\\input{lib/kernelsrc}\n\n% FIXME: classify with chapters instead of sections\n\\renewcommand{\\thesection}{\\arabic{section}}\n\n\\author{Peter Jay Salzman, Michael Burian, Ori Pomerantz, Bob Mottram, Jim Huang}\n\\date{\\today}\n\\title{The Linux Kernel Module Programming Guide}\n\\begin{document}\n\n\\maketitle\n\\ifdefined\\HCode\n\\includegraphics{assets/cover-with-names.png}\n% turn off TOC\n\\else\n\\pagestyle{empty}\n\\begin{tikzpicture}[remember picture, overlay]\n  \\node at (current page.center) {\\includegraphics[width=\\paperwidth, height=\\paperheight]{assets/cover.png}}; \\\\\n  \\node at (11, -9.5) {\\Large \\textbf{Peter Jay Salzman, Michael Burian,}}; \\\\\n  \\node at (11, -10.5) {\\Large \\textbf{Ori Pomerantz, Bob Mottram,}}; \\\\\n  \\node at (11, -11.5) {\\Large \\textbf{Jim Huang}};\n\\end{tikzpicture}\n\\tableofcontents\n\\fi\n\n\\section{Introduction}\n\\label{sec:introduction}\nThe Linux Kernel Module Programming Guide is a free book; you may reproduce or modify it under the terms of the \\href{https://opensource.org/licenses/OSL-3.0}{Open Software License}, version 3.0.\n\nThis book is distributed in the hope that it would be useful, but without any warranty,\nwithout even the implied warranty of merchantability or fitness for a particular purpose.\n\nThe author encourages wide distribution of this book for personal or commercial use,\nprovided the above copyright notice remains intact and the method adheres to the provisions of the \\href{https://opensource.org/licenses/OSL-3.0}{Open Software License}.\nIn summary, you may copy and distribute this book free of charge or for a profit.\nNo explicit permission is required from the author for reproduction of this book in any medium, physical or electronic.\n\nDerivative works and translations of this document must be placed under the Open Software License, and the original copyright notice must remain intact.\nIf you have contributed new material to this book, you must make the material and source code available for your revisions.\nPlease make revisions and updates available directly to the document maintainer, Jim Huang <jserv@ccns.ncku.edu.tw>.\nThis will allow for the merging of updates and provide consistent revisions to the Linux community.\n\nIf you publish or distribute this book commercially, donations, royalties,\nor printed copies are greatly appreciated by the author and the \\href{https://tldp.org/}{Linux Documentation Project} (LDP).\nContributing in this way shows your support for free software and the LDP.\nIf you have questions or comments, please contact the address above.\n\n\\subsection{Authorship}\n\\label{sec:authorship}\n\nThe Linux Kernel Module Programming Guide was initially authored by Ori Pomerantz for Linux v2.2.\nAs the Linux kernel evolved, Ori's availability to maintain the document diminished.\nConsequently, Peter Jay Salzman assumed the role of maintainer and updated the guide for Linux v2.4.\nSimilar constraints arose for Peter when tracking developments in Linux v2.6,\nleading to Michael Burian joining as a co-maintainer to bring the guide up to speed with Linux v2.6.\nBob Mottram contributed to the guide by updating examples for Linux v3.8 and later.\nJim Huang then undertook the task of updating the guide for recent Linux versions (v5.0 and beyond),\nalong with revising the LaTeX document.\nThe guide continues to be maintained for compatibility with modern kernels (v6.x series) while ensuring examples work with older LTS kernels.\n\n\\subsection{Acknowledgements}\n\\label{sec:acknowledgements}\n\nThe following people have contributed corrections or good suggestions:\n\n\\begin{flushleft}\n\\input{contrib}\n\\end{flushleft}\n\n\\subsection{What Is A Kernel Module?}\n\\label{sec:kernelmod}\n\nInvolvement in the development of Linux kernel modules requires a foundation in the C programming language and a track record of creating conventional programs intended for process execution.\nThis pursuit delves into a domain where an unregulated pointer, if disregarded,\nmay potentially trigger the total elimination of an entire filesystem,\nresulting in a scenario that necessitates a complete system reboot.\n\nA Linux kernel module is precisely defined as a code segment capable of dynamic loading and unloading within the kernel as needed.\nThese modules enhance kernel capabilities without necessitating a system reboot.\nA notable example is seen in the device driver module, which facilitates kernel interaction with hardware components linked to the system.\nIn the absence of modules, the prevailing approach leans toward monolithic kernels,\nrequiring direct integration of new functionalities into the kernel image.\nThis approach leads to larger kernels and necessitates kernel rebuilding and subsequent system rebooting when new functionalities are desired.\n\n\\subsection{Kernel module package}\n\\label{sec:packages}\n\nLinux distributions provide the commands \\sh|modprobe|, \\sh|insmod| and \\sh|depmod| within a package.\n\nOn Ubuntu/Debian GNU/Linux:\n\\begin{codebash}\nsudo apt-get install build-essential kmod\n\\end{codebash}\n\nOn Arch Linux:\n\\begin{codebash}\nsudo pacman -S gcc kmod\n\\end{codebash}\n\n\\subsection{What Modules are in my Kernel?}\n\\label{sec:modutils}\n\nTo discover what modules are already loaded within your current kernel, use the command \\sh|lsmod|.\n\\begin{codebash}\nlsmod\n\\end{codebash}\n\nModules are stored within the file \\verb|/proc/modules|, so you can also see them with:\n\\begin{codebash}\ncat /proc/modules\n\\end{codebash}\n\nThis can be a long list, and you might prefer to search for something particular.\nTo search for the \\verb|fat| module:\n\\begin{codebash}\nlsmod | grep fat\n\\end{codebash}\n\n\\subsection{Is there a need to download and compile the kernel?}\n\\label{sec:buildkernel}\nTo effectively follow this guide, there is no obligatory requirement for performing such actions.\nNonetheless, a prudent approach involves executing the examples within a test distribution on a virtual machine,\nthus mitigating any potential risk of disrupting the system.\n\n\\subsection{Before We Begin}\n\\label{sec:preparation}\nBefore delving into code, certain matters require attention.\nVariances exist among individuals' systems, and distinct personal approaches are evident.\nThe achievement of successful compilation and loading of the inaugural ``hello world'' program may,\nat times, present challenges.\nIt is reassuring to note that overcoming the initial obstacle on the first attempt paves the way for subsequent endeavors to proceed seamlessly.\n\n\\begin{enumerate}\n  \\item Modversioning.\n        A module compiled for one kernel will not load if a different kernel is booted,\n        unless \\cpp|CONFIG_MODVERSIONS| is enabled in the kernel.\n        Module versioning will be discussed later in this guide.\n        Until module versioning is covered, the examples in this guide may not work correctly if running a kernel with modversioning turned on.\n        However, most stock Linux distribution kernels come with modversioning enabled.\n        If difficulties arise when loading the modules due to versioning errors, consider compiling a kernel with modversioning turned off.\n\n  \\item Using the X Window System.\n        It is highly recommended to extract, compile, and load all the examples discussed in this guide from a console.\n        Working on these tasks within the X Window System is discouraged.\n\n        Modules cannot directly print to the screen like \\cpp|printf()| can,\n        but they can log information and warnings to the kernel's log ring buffer.\n        This output is \\emph{not} automatically displayed on any console or terminal.\n        To view kernel module messages, you must use \\sh|dmesg| to read the kernel log ring buffer,\n        or check the systemd journal with \\sh|journalctl -k| for kernel messages.\n        Refer to \\Cref{sec:helloworld} for more information.\n        The terminal or environment from which you load the module does not affect where the output goes—it always goes to the kernel log.\n  \\item SecureBoot.\n        Numerous modern computers arrive pre-configured with UEFI SecureBoot enabled—an essential security standard ensuring booting exclusively through trusted software endorsed by the original equipment manufacturer.\n        Certain Linux distributions even ship with the default Linux kernel configured to support SecureBoot.\n        In these cases, the kernel module necessitates a signed security key.\n\n        Failing that, an attempt to insert your first ``hello world'' module would result in the message: ``\\emph{ERROR: could not insert module}''.\n        If this message ``\\emph{Lockdown: insmod: unsigned module loading is restricted;\n        see man kernel lockdown.7}'' appears in the \\sh|dmesg| output,\n        the simplest approach involves disabling UEFI SecureBoot from the boot menu of your PC or laptop,\n        allowing the successful insertion of the ``hello world'' module.\n        Naturally, an alternative involves undergoing intricate procedures such as generating keys, system key installation,\n        and module signing to achieve functionality.\n        However, this intricate process is less appropriate for beginners. If interested,\n        more detailed steps for \\href{https://wiki.debian.org/SecureBoot}{SecureBoot} can be explored and followed.\n\\end{enumerate}\n\n\\section{Headers}\n\\label{sec:headers}\nBefore building anything, it is necessary to install the header files for the kernel.\n\nOn Ubuntu/Debian GNU/Linux:\n\\begin{codebash}\nsudo apt-get update\napt-cache search linux-headers-`uname -r`\n\\end{codebash}\n\nThe following command provides information about the available kernel header files.\nThen, for example:\n\\begin{codebash}\nsudo apt-get install linux-headers-`uname -r`\n\\end{codebash}\n\nOn Arch Linux:\n\\begin{codebash}\nsudo pacman -S linux-headers\n\\end{codebash}\n\nOn Fedora:\n\\begin{codebash}\nsudo dnf install kernel-devel kernel-headers\n\\end{codebash}\n\n\\section{Examples}\n\\label{sec:examples}\nAll the examples from this document are available within the \\verb|examples| subdirectory.\n\nShould compile errors occur, it may be due to a more recent kernel version being in use,\nor there might be a need to install the corresponding kernel header files.\n\n\\section{Hello World}\n\\label{sec:helloworld}\n\\subsection{The Simplest Module}\n\\label{sec:org2d3e245}\nMost individuals beginning their programming journey typically start with some variant of a \\emph{hello world} example.\nIt is unclear what the outcomes are for those who deviate from this tradition, but it seems prudent to adhere to it.\nThe learning process will begin with a series of hello world programs that illustrate various fundamental aspects of writing a kernel module.\n\nPresented next is the simplest possible module.\n\nMake a test directory:\n\\begin{codebash}\nmkdir -p ~/develop/kernel/hello-1\ncd ~/develop/kernel/hello-1\n\\end{codebash}\n\nPaste this into your favorite editor and save it as \\verb|hello-1.c|:\n\n\\samplec{examples/hello-1.c}\n\nNow you will need a \\verb|Makefile|. If you copy and paste this, change the indentation to use \\textit{tabs}, not spaces.\n\n\\begin{code}\nobj-m += hello-1.o\n\nPWD := $(CURDIR)\n\nall:\n\t$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules\n\nclean:\n\t$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean\n\\end{code}\n\nIn \\verb|Makefile|, \\verb|$(CURDIR)| can be set to the absolute pathname of the current working directory (after all \\verb|-C| options are processed, if any).\nSee more about \\verb|CURDIR| in \\href{https://www.gnu.org/software/make/manual/make.html}{GNU make manual}.\n\nAnd finally, just run \\verb|make| directly.\n\n\\begin{codebash}\nmake\n\\end{codebash}\n\nIf there is no \\verb|PWD := $(CURDIR)| statement in the Makefile, then it may not compile correctly with \\verb|sudo make|.\nThis is because some environment variables are specified by the security policy and cannot be inherited.\nThe default security policy is \\verb|sudoers|.\nIn the \\verb|sudoers| security policy, \\verb|env_reset| is enabled by default, which restricts environment variables.\nSpecifically, path variables are not retained from the user environment;\nthey are set to default values (for more information, see: \\href{https://www.sudo.ws/docs/man/sudoers.man/}{sudoers manual}).\nYou can see the environment variable settings by:\n\n\\begin{verbatim}\n$ sudo -s\n# sudo -V\n\\end{verbatim}\n\nHere is a simple Makefile as an example to demonstrate the problem mentioned above.\n\n\\begin{code}\nall:\n\techo $(PWD)\n\\end{code}\n\nThen, we can use the \\verb|-p| flag to print out the environment variable values from the Makefile.\n\n\\begin{verbatim}\n$ make -p | grep PWD\nPWD = /home/ubuntu/temp\nOLDPWD = /home/ubuntu\n\techo $(PWD)\n\\end{verbatim}\n\nThe \\verb|PWD| variable will not be inherited with \\verb|sudo|.\n\n\\begin{verbatim}\n$ sudo make -p | grep PWD\n\techo $(PWD)\n\\end{verbatim}\n\nHowever, there are three ways to solve this problem.\n\n\\begin{enumerate}\n  \\item {\n  You can use the \\verb|-E| flag to temporarily preserve them.\n\n  \\begin{codebash}\n    $ sudo -E make -p | grep PWD\n    PWD = /home/ubuntu/temp\n    OLDPWD = /home/ubuntu\n    echo $(PWD)\n  \\end{codebash}\n  }\n\n  \\item {\n  You can disable \\verb|env_reset| by editing \\verb|/etc/sudoers| as root using \\verb|visudo|.\n\n  \\begin{code}\n  ## sudoers file.\n  ##\n  ...\n  Defaults env_reset\n  ## Change env_reset to !env_reset in previous line to keep all environment variables\n  \\end{code}\n\n  Then execute \\verb|env| and \\verb|sudo env| individually.\n\n  \\begin{codebash}\n    # disable the env_reset\n    echo \"user:\" > non-env_reset.log; env >> non-env_reset.log\n    echo \"root:\" >> non-env_reset.log; sudo env >> non-env_reset.log\n    # enable the env_reset\n    echo \"user:\" > env_reset.log; env >> env_reset.log\n    echo \"root:\" >> env_reset.log; sudo env >> env_reset.log\n  \\end{codebash}\n\n  You can view and compare these logs to find differences between \\verb|env_reset| and \\verb|!env_reset|.\n  }\n\n  \\item {You can preserve environment variables by appending them to \\verb|env_keep| in \\verb|/etc/sudoers|.\n\n  \\begin{code}\n  Defaults env_keep += \"PWD\"\n  \\end{code}\n\n  After applying the above change, you can check the environment variable settings by:\n\n  \\begin{verbatim}\n    $ sudo -s\n    # sudo -V\n  \\end{verbatim}\n  }\n\\end{enumerate}\n\nIf all goes smoothly you should then find that you have a compiled \\verb|hello-1.ko| module.\nYou can find info on it with the command:\n\\begin{codebash}\nmodinfo hello-1.ko\n\\end{codebash}\n\nAt this point the command:\n\\begin{codebash}\nlsmod | grep hello\n\\end{codebash}\n\nshould return nothing.\nYou can try loading your new module with:\n\\begin{codebash}\nsudo insmod hello-1.ko\n\\end{codebash}\n\nThe dash character will get converted to an underscore, so when you again try:\n\\begin{codebash}\nlsmod | grep hello\n\\end{codebash}\n\nYou should now see your loaded module. It can be removed again with:\n\\begin{codebash}\nsudo rmmod hello_1\n\\end{codebash}\n\nNotice that the dash was replaced by an underscore.\nTo see the module's output messages, use \\sh|dmesg| to view the kernel log ring buffer:\n\\begin{codebash}\nsudo dmesg | tail -10\n\\end{codebash}\n\nYou should see messages like ``Hello world 1.'' and ``Goodbye world 1.'' from your module.\nAlternatively, you can check the systemd journal for kernel messages:\n\\begin{codebash}\njournalctl --since \"1 hour ago\" | grep kernel\n\\end{codebash}\n\nYou now know the basics of creating, compiling, installing and removing modules.\nNow for more of a description of how this module works.\n\nKernel modules must have at least two functions: a \"start\" (initialization) function called \\cpp|init_module()| which is called when the module is \\sh|insmod|ed into the kernel,\nand an \"end\" (cleanup) function called \\cpp|cleanup_module()| which is called just before it is removed from the kernel.\nActually, things have changed starting with kernel 2.3.13.\n% TODO: adjust the section anchor\nYou can now use whatever name you like for the start and end functions of a module,\nand you will learn how to do this in \\Cref{sec:hello_n_goodbye}.\nIn fact, the new method is the preferred method.\nThe old \\cpp|init_module()| and \\cpp|cleanup_module()| have been deprecated for x86 systems with indirect branch tracking (IBT) enabled starting from \\href{https://github.com/torvalds/linux/commit/4fab2d76}{commit 4fab2d76} in kernel 6.15, causing build failures.\nHowever, many existing examples still use these names for their start and end functions.\n\nTypically, \\cpp|init_module()| either registers a handler for something with the kernel, \nor it replaces one of the kernel functions with its own code (usually code to do something and then call the original function).\nThe \\cpp|cleanup_module()| function is supposed to undo whatever \\cpp|init_module()| did, so the module can be unloaded safely.\n\nLastly, every kernel module needs to include \\verb|<linux/module.h>|.\n% TODO: adjust the section anchor\nWe needed to include \\verb|<linux/printk.h>| only for the macro expansion for the \\cpp|pr_alert()| log level, which you'll learn about in \\Cref{sec:printk}.\n\n\\begin{enumerate}\n  \\item A point about coding style.\n        Another thing that may not be immediately obvious to anyone getting started with kernel programming is that indentation within your code should use \\textbf{tabs} and \\textbf{not spaces}.\n        It is one of the coding conventions of the kernel.\n        You may not like it, but you will need to get used to it if you ever submit a patch upstream.\n\n  \\item Introducing print macros.\n  \\label{sec:printk}\n        In the beginning there was \\cpp|printk|, usually followed by a priority such as \\cpp|KERN_INFO| or \\cpp|KERN_DEBUG|.\n        More recently, this can also be expressed in abbreviated form using a set of print macros, such as \\cpp|pr_info| and \\cpp|pr_debug|.\n        This just saves some mindless keyboard bashing and looks a bit neater.\n        They can be found within \\src{include/linux/printk.h}.\n        Take time to read through the available priority macros.\n\n        \\textbf{Important:} These functions write to the kernel log ring buffer, \\emph{not} directly to any terminal or console.\n        To view the output from your kernel modules, you must use \\sh|dmesg| or \\sh|journalctl -k|.\n\n  \\item About Compiling.\n        Kernel modules need to be compiled a bit differently from regular userspace apps.\n        Former kernel versions required us to care much about these settings, which are usually stored in Makefiles.\n        Although hierarchically organized, many redundant settings accumulated in sublevel Makefiles and made them large and rather difficult to maintain.\n        Fortunately, there is a new way of doing these things, called kbuild, and the build process for external loadable modules is now fully integrated into the standard kernel build mechanism.\n        To learn more about how to compile modules which are not part of the official kernel (such as all the examples you will find in this guide), see file \\src{Documentation/kbuild/modules.rst}.\n\n        Additional details about Makefiles for kernel modules are available in \\src{Documentation/kbuild/makefiles.rst}.\n        Be sure to read this and the related files before starting to hack Makefiles. It will probably save you lots of work.\n\n\\begin{quote}\nHere is another exercise for the reader.\nSee that comment above the return statement in \\cpp|init_module()|?\nChange the return value to something negative, recompile and load the module again.\nWhat happens?\n\\end{quote}\n\\end{enumerate}\n\n\\subsection{Hello and Goodbye}\n\\label{sec:hello_n_goodbye}\nIn early kernel versions you had to use the \\cpp|init_module| and \\cpp|cleanup_module| functions, as in the first hello world example,\nbut these days you can name those anything you want by using the \\cpp|module_init| and \\cpp|module_exit| macros.\nThese macros are defined in \\src{include/linux/module.h}.\nThe only requirement is that your init and cleanup functions must be defined before calling those macros, otherwise you will get compilation errors.\nHere is an example of this technique:\n\n\\samplec{examples/hello-2.c}\n\nSo now we have two real kernel modules under our belt. Adding another module is as simple as this:\n\n\\begin{code}\nobj-m += hello-1.o\nobj-m += hello-2.o\n\nPWD := $(CURDIR)\n\nall:\n\t$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules\n\nclean:\n\t$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean\n\\end{code}\n\nNow have a look at \\src{drivers/char/Makefile} for a real world example.\nAs you can see, some things got hardwired into the kernel (\\verb|obj-y|) but where have all those \\verb|obj-m| gone?\nThose familiar with shell scripts will easily be able to spot them.\nFor those who are not, the \\verb|obj-$(CONFIG_FOO)| entries you see everywhere expand into \\verb|obj-y| or \\verb|obj-m|,\ndepending on whether the \\verb|CONFIG_FOO| variable has been set to \\verb|y| or \\verb|m|.\nWhile we are at it, those were exactly the kind of variables that you have set in the \\verb|.config| file in the top-level directory of the Linux kernel source tree,\nthe last time you ran \\sh|make menuconfig| or something similar.\n\n\\subsection{The \\_\\_init and \\_\\_exit Macros}\n\\label{sec:init_n_exit}\nThe \\cpp|__init| macro causes the init function to be discarded and its memory freed once the init function finishes for built-in drivers.\nFor loadable modules, \\cpp|__init| still places the function into an init-only section, \\cpp|do_free_init| may still be observable during module loading even without \\cpp|__init|.\nIf you think about when the init function is invoked, this makes perfect sense.\n\nThere is also an \\cpp|__initdata| which works similarly to \\cpp|__init| but for init variables rather than functions.\n\nThe \\cpp|__exit| macro causes the omission of the function when the module is built into the kernel, and like \\cpp|__init|, has no effect for loadable modules.\nAgain, if you consider when the cleanup function runs, this makes complete sense; built-in drivers do not need a cleanup function, while loadable modules do.\n\nThese macros are defined in \\src{include/linux/init.h} and serve to free up kernel memory.\nWhen you boot your kernel and see something like Freeing unused kernel memory: 236k freed, this is precisely what the kernel is freeing.\n\n\\samplec{examples/hello-3.c}\n\n\\subsection{Licensing and Module Documentation}\n\\label{sec:modlicense}\nHonestly, who loads or even cares about proprietary modules?\nIf you do then you might have seen something like this:\n\\begin{verbatim}\n$ sudo insmod xxxxxx.ko\nloading out-of-tree module taints kernel.\nmodule license 'unspecified' taints kernel.\n\\end{verbatim}\n\nYou can use a few macros to indicate the license for your module.\nSome examples are \"GPL\", \"GPL v2\", \"GPL and additional rights\", \"Dual BSD/GPL\", \"Dual MIT/GPL\", \"Dual MPL/GPL\" and \"Proprietary\".\nThey are defined within \\src{include/linux/module.h}.\n\nTo reference what license you are using, a macro is available called \\cpp|MODULE_LICENSE|.\nThis and a few other macros describing the module are illustrated in the example below.\n\n\\samplec{examples/hello-4.c}\n\n\\subsection{Passing Command Line Arguments to a Module}\n\\label{sec:modparam}\nModules can take command line arguments, but not with the argc/argv you might be used to.\n\nTo allow arguments to be passed to your module, declare the variables that will take the values of the command line arguments as global and then use the \\cpp|module_param()| macro (defined in \\src{include/linux/moduleparam.h}) to set the mechanism up.\nAt runtime, \\sh|insmod| will fill the variables with any command line arguments that are given, like \\sh|insmod mymodule.ko myvariable=5|.\nThe variable declarations and macros should be placed at the beginning of the module for clarity.\nThe example code should clear up my admittedly lousy explanation.\n\nThe \\cpp|module_param()| macro takes 3 arguments: the name of the variable, its type and permissions for the corresponding file in sysfs.\nInteger types can be signed as usual or unsigned. If you would like to use arrays of integers or strings,\nsee \\cpp|module_param_array()| and \\cpp|module_param_string()|.\n\n\\begin{code}\nint myint = 3;\nmodule_param(myint, int, 0);\n\\end{code}\n\nArrays are supported too, but things are a bit different now than they were in the olden days.\nTo keep track of the number of parameters, you need to pass a pointer to a count variable as the third parameter.\nAt your option, you could also ignore the count and pass \\cpp|NULL| instead.\nWe show both possibilities here:\n\n\\begin{code}\nint myintarray[2];\nmodule_param_array(myintarray, int, NULL, 0); /* not interested in count */\n\nshort myshortarray[4];\nint count;\nmodule_param_array(myshortarray, short, &count, 0); /* put count into \"count\" variable */\n\\end{code}\n\nA good use for this is to have the module variable's default values set, like a port or IO address.\nIf the variables contain the default values, then perform autodetection (explained elsewhere).\nOtherwise, keep the current value.\nThis will be made clear later on.\n\nLastly, there is a macro function, \\cpp|MODULE_PARM_DESC()|, that is used to document arguments that the module can take.\nIt takes two parameters: a variable name and a free form string describing that variable.\n\n\\samplec{examples/hello-5.c}\n\nIt is recommended to experiment with the following code:\n\\begin{verbatim}\n$ sudo insmod hello-5.ko mystring=\"bebop\" myintarray=-1\n$ sudo dmesg -t | tail -7\nmyshort is a short integer: 1\nmyint is an integer: 420\nmylong is a long integer: 9999\nmystring is a string: bebop\nmyintarray[0] = -1\nmyintarray[1] = 420\ngot 1 arguments for myintarray.\n\n$ sudo rmmod hello-5\n$ sudo dmesg -t | tail -1\nGoodbye, world 5\n\n$ sudo insmod hello-5.ko mystring=\"supercalifragilisticexpialidocious\" myintarray=-1,-1\n$ sudo dmesg -t | tail -7\nmyshort is a short integer: 1\nmyint is an integer: 420\nmylong is a long integer: 9999\nmystring is a string: supercalifragilisticexpialidocious\nmyintarray[0] = -1\nmyintarray[1] = -1\ngot 2 arguments for myintarray.\n\n$ sudo rmmod hello_5\n$ sudo dmesg -t | tail -1\nGoodbye, world 5\n\n$ sudo insmod hello-5.ko mylong=hello\ninsmod: ERROR: could not insert module hello-5.ko: Invalid parameters\n\\end{verbatim}\n\n\\subsection{Modules Spanning Multiple Files}\n\\label{sec:modfiles}\nSometimes it makes sense to divide a kernel module between several source files.\n\nHere is an example of such a kernel module.\n\\samplec{examples/start.c}\n\nThe next file:\n\\samplec{examples/stop.c}\n\nAnd finally, the makefile:\n\n\\begin{code}\nobj-m += hello-1.o\nobj-m += hello-2.o\nobj-m += hello-3.o\nobj-m += hello-4.o\nobj-m += hello-5.o\nobj-m += startstop.o\nstartstop-objs := start.o stop.o\n\nPWD := $(CURDIR)\n\nall:\n\t$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules\n\nclean:\n\t$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean\n\\end{code}\n\nThis is the complete makefile for all the examples we have seen so far.\nThe first five lines are nothing special, but for the last example we will need two lines.\nFirst we invent an object name for our combined module, second we tell \\sh|make| what object files are part of that module.\n\n\\subsection{Building modules for a precompiled kernel}\n\\label{sec:precompiled}\n% TODO: Recent Linux kernel images shipped with distributions should already have sufficient debugging features enabled for LKMPG.\nObviously, we strongly suggest you to recompile your kernel, so that you can enable a number of useful debugging features,\nsuch as forced module unloading (\\cpp|MODULE_FORCE_UNLOAD|): when this option is enabled,\nyou can force the kernel to unload a module even when it believes it is unsafe, via a \\sh|sudo rmmod -f module| command.\nThis option can save you a lot of time and a number of reboots during the development of a module.\nIf you do not want to recompile your kernel then you should consider running the examples within a test distribution on a virtual machine.\nIf you mess anything up then you can easily reboot or restore the virtual machine (VM).\n\nThere are a number of cases in which you may want to load your module into a precompiled running kernel,\nsuch as the ones shipped with common Linux distributions, or a kernel you have compiled in the past.\nIn certain circumstances you could require to compile and insert a module into a running kernel which you are not allowed to recompile,\nor on a machine that you prefer not to reboot.\nIf you can't think of a case that will force you to use modules for a precompiled kernel you might want to skip this and treat the rest of this chapter as a big footnote.\n\nNow, if you just install a kernel source tree, use it to compile your kernel module and you try to insert your module into the kernel,\nin most cases you would obtain an error as follows:\n\n\\begin{verbatim}\ninsmod: ERROR: could not insert module poet.ko: Invalid module format\n\\end{verbatim}\n\nLess cryptic information is logged to the systemd journal:\n\n\\begin{verbatim}\nkernel: poet: disagrees about version of symbol module_layout\n\\end{verbatim}\n\nIn other words, your kernel refuses to accept your module because version strings (more precisely, \\textit{version magic}, see \\src{include/linux/vermagic.h}) do not match.\nIncidentally, version magic strings are stored in the module object in the form of a static string, starting with \\cpp|vermagic:|.\nVersion data are inserted in your module when it is linked against the \\verb|kernel/module.o| file.\nTo inspect version magics and other strings stored in a given module, issue the command \\sh|modinfo module.ko|:\n\n\\begin{verbatim}\n$ modinfo hello-4.ko\ndescription:    A sample driver\nauthor:         LKMPG\nlicense:        GPL\nsrcversion:     B2AA7FBFCC2C39AED665382\ndepends:\nretpoline:      Y\nname:           hello_4\nvermagic:       5.4.0-70-generic SMP mod_unload modversions\n\\end{verbatim}\n\nTo overcome this problem we could resort to the \\verb|--force-vermagic| option, but this solution is potentially unsafe, and unquestionably unacceptable in production modules.\nConsequently, we want to compile our module in an environment which was identical to the one in which our precompiled kernel was built.\nHow to do this, is the subject of the remainder of this chapter.\n\nFirst of all, make sure that a kernel source tree is available, having exactly the same version as your current kernel.\nThen, find the configuration file which was used to compile your precompiled kernel.\nUsually, this is available in your current \\verb|boot| directory, under a name like \\verb|config-5.14.x|.\nYou may just want to copy it to your kernel source tree: \\sh|cp /boot/config-`uname -r` .config|.\n\nLet's focus again on the previous error message: a closer look at the version magic strings suggests that, even with two configuration files which are exactly the same, a slight difference in the version magic could be possible, and it is sufficient to prevent insertion of the module into the kernel.\nThat slight difference, namely the custom string which appears in the module's version magic and not in the kernel's one, is due to a modification with respect to the original, in the makefile that some distributions include.\nThen, examine your \\verb|Makefile|, and make sure that the specified version information matches exactly the one used for your current kernel.\nFor example, your makefile could start as follows:\n\n\\begin{verbatim}\nVERSION = 5\nPATCHLEVEL = 14\nSUBLEVEL = 0\nEXTRAVERSION = -rc2\n\\end{verbatim}\n\nIn this case, you need to restore the value of symbol \\textbf{EXTRAVERSION} to \\textbf{-rc2}.\nWe suggest keeping a backup copy of the makefile used to compile your kernel available in \\verb|/lib/modules/5.14.0-rc2/build|.\nA simple command as follows should suffice.\n\\begin{codebash}\ncp /lib/modules/`uname -r`/build/Makefile linux-`uname -r`\n\\end{codebash}\nHere \\sh|linux-`uname -r`| is the Linux kernel source you are attempting to build.\n\nNow, please run \\sh|make| to update configuration and version headers and objects:\n\n\\begin{verbatim}\n$ make\n  SYNC    include/config/auto.conf.cmd\n  HOSTCC  scripts/basic/fixdep\n  HOSTCC  scripts/kconfig/conf.o\n  HOSTCC  scripts/kconfig/confdata.o\n  HOSTCC  scripts/kconfig/expr.o\n  LEX     scripts/kconfig/lexer.lex.c\n  YACC    scripts/kconfig/parser.tab.[ch]\n  HOSTCC  scripts/kconfig/preprocess.o\n  HOSTCC  scripts/kconfig/symbol.o\n  HOSTCC  scripts/kconfig/util.o\n  HOSTCC  scripts/kconfig/lexer.lex.o\n  HOSTCC  scripts/kconfig/parser.tab.o\n  HOSTLD  scripts/kconfig/conf\n\\end{verbatim}\n\nIf you do not desire to actually compile the kernel, you can interrupt the build process (CTRL-C) just after the SPLIT line, because at that time, the files you need are ready.\nNow you can turn back to the directory of your module and compile it: It will be built exactly according to your current kernel settings, and it will load into it without any errors.\n\n\\section{Preliminaries}\n\\subsection{How modules begin and end}\n\\label{sec:module_init_exit}\nA typical program starts with a \\cpp|main()| function, executes a series of instructions,\nand terminates after completing these instructions.\nKernel modules, however, follow a different pattern.\nA module always begins with either the \\cpp|init_module| function or a function designated by the \\cpp|module_init| call.\nThis function acts as the module's entry point,\ninforming the kernel of the module's functionalities and preparing the kernel to utilize the module's functions when necessary.\nAfter performing these tasks, the entry function returns, and the module remains inactive until the kernel requires its code.\n\nAll modules conclude by invoking either \\cpp|cleanup_module| or a function specified through the \\cpp|module_exit| call.\nThis serves as the module's exit function, reversing the actions of the entry function by unregistering the previously registered functionalities.\n\nIt is mandatory for every module to have both an entry and an exit function.\nWhile there are multiple methods to define these functions, the terms ``entry function'' and ``exit function'' are generally used.\nHowever, they may occasionally be referred to as \\cpp|init_module| and \\cpp|cleanup_module|,\nwhich are understood to mean the same.\n\n\\subsection{Functions available to modules}\n\\label{sec:avail_func}\nProgrammers use functions they do not define all the time.\nA prime example of this is \\cpp|printf()|.\nYou use these library functions which are provided by the standard C library, libc.\nThe definitions for these functions do not actually enter your program until the linking stage, which ensures that the code (for \\cpp|printf()| for example) is available, and fixes the call instruction to point to that code.\n\nKernel modules are different here, too. In the hello world example, you might have noticed that we used a function, \\cpp|pr_info()| but did not include a standard I/O library.\nThat is because modules are object files whose symbols get resolved upon running \\sh|insmod| or \\sh|modprobe|.\nThe definition for the symbols comes from the kernel itself; the only external functions you can use are the ones provided by the kernel.\nIf you're curious about what symbols have been exported by your kernel, take a look at \\verb|/proc/kallsyms|.\n\nOne point to keep in mind is the difference between library functions and system calls. Library functions are higher level, run completely in user space and provide a more convenient interface for the programmer to the functions that do the real work --- system calls.\nSystem calls run in kernel mode on the user's behalf and are provided by the kernel itself.\nThe library function \\cpp|printf()| may look like a very general printing function, but all it really does is format the data into strings and write the string data using the low-level system call \\cpp|write()|, which then sends the data to standard output.\n\nWould you like to see what system calls are made by \\cpp|printf()|?\nIt is easy!\nCompile the following program:\n\n\\begin{code}\n#include <stdio.h>\n\nint main(void)\n{\n    printf(\"hello\");\n    return 0;\n}\n\\end{code}\n\nwith \\sh|gcc -Wall -o hello hello.c|.\nRun the executable with \\sh|strace ./hello|.\nAre you impressed?\nEvery line you see corresponds to a system call.\n\\href{https://strace.io/}{strace} is a handy program that gives you details about what system calls a program is making, including which call is made, what its arguments are and what it returns.\nIt is an invaluable tool for figuring out things like what files a program is trying to access.\nTowards the end, you will see a line which looks like \\cpp|write(1, \"hello\", 5hello)|.\nThere it is.\nThe face behind the \\cpp|printf()| mask.\nYou may not be familiar with write, since most people use library functions for file I/O (like \\cpp|fopen|, \\cpp|fputs|, \\cpp|fclose|).\nIf that is the case, try looking at man 2 write.\nThe 2nd man section is devoted to system calls (like \\cpp|kill()| and \\cpp|read()|).\nThe 3rd man section is devoted to library calls, which you would probably be more familiar with (like \\cpp|cosh()| and \\cpp|random()|).\n\nYou can even write modules to replace the kernel's system calls, which we will do shortly.\nCrackers often make use of this sort of thing for backdoors or trojans, but you can write your own modules to do more benign things, like have the kernel log a message whenever someone attempts to delete a file on your system.\n\n\\subsection{User Space vs Kernel Space}\n\\label{sec:user_kernl_space}\nThe kernel primarily manages access to resources, be it a video card, hard drive, or memory.\nPrograms frequently vie for the same resources.\nFor instance, as a document is saved, updatedb might commence updating the locate database.\nSessions in editors like vim and processes like updatedb can simultaneously utilize the hard drive.\nThe kernel's role is to maintain order, ensuring that users do not access resources indiscriminately.\n\nTo manage this, CPUs operate in different modes, each offering varying levels of system control.\nThe Intel 80386 architecture, for example, featured four such modes, known as rings.\nUnix, however, utilizes only two of these rings: the highest ring (ring 0, also known as ``supervisor mode'',\nwhere all actions are permissible) and the lowest ring, referred to as ``user mode''.\n\nRecall the discussion about library functions vs system calls.\nTypically, you use a library function in user mode.\nThe library function calls one or more system calls, and these system calls execute on the library function's behalf, but do so in supervisor mode since they are part of the kernel itself.\nOnce the system call completes its task, it returns and execution gets transferred back to user mode.\n\n\\subsection{Name Space}\n\\label{sec:namespace}\nWhen you write a small C program, you use variables which are convenient and make sense to the reader.\nIf, on the other hand, you are writing routines which will be part of a bigger problem, any global variables you have are part of a community of other peoples' global variables; some of the variable names can clash.\nWhen a program has lots of global variables which aren't meaningful enough to be distinguished, you get namespace pollution.\nIn large projects, effort must be made to remember reserved names, and to find ways to develop a scheme for naming unique variable names and symbols.\n\nWhen writing kernel code, even the smallest module will be linked against the entire kernel, so this is definitely an issue.\nThe best way to deal with this is to declare all your variables as static and to use a well-defined prefix for your symbols.\nBy convention, all kernel prefixes are lowercase. If you do not want to declare everything as static, another option is to declare a symbol table and register it with the kernel.\nWe will get to this later.\n\nThe file \\verb|/proc/kallsyms| holds all the symbols that the kernel knows about and which are therefore accessible to your modules since they share the kernel's codespace.\n\n\\subsection{Code space}\n\\label{sec:codespace}\nMemory management is a very complicated subject and the majority of O'Reilly's \\href{https://www.oreilly.com/library/view/understanding-the-linux/0596005652/}{Understanding The Linux Kernel} exclusively covers memory management!\nWe are not setting out to be experts on memory management, but we do need to know a couple of facts to even begin worrying about writing real modules.\n\nIf you have not thought about what a segfault really means, you may be surprised to hear that pointers do not actually point to memory locations.\nNot real ones, anyway.\nWhen a process is created, the kernel sets aside a portion of real physical memory and hands it to the process to use for its executing code, variables, stack, heap and other things which a computer scientist would know about.\nThis memory begins with 0x00000000 and extends up to whatever it needs to be.\nSince the memory space for any two processes does not overlap, every process that can access a memory address, say 0xbffff978, would be accessing a different location in real physical memory!\nThe processes would be accessing an index named 0xbffff978 which points to some kind of offset into the region of memory set aside for that particular process.\nFor the most part, a process like our Hello, World program cannot access the space of another process, although there are ways which we will talk about later.\n\nThe kernel has its own space of memory as well. Since a module is code which can be dynamically inserted and removed in the kernel (as opposed to a semi-autonomous object), it shares the kernel's codespace rather than having its own.\nTherefore, if your module segfaults, the kernel segfaults.\nAnd if you start writing over data because of an off-by-one error, then you're trampling on kernel data (or code).\nThis is even worse than it sounds, so try your best to be careful.\n\nIt should be noted that the aforementioned discussion applies to any operating system utilizing a monolithic kernel.\nThis concept differs slightly from \\emph{``building all your modules into the kernel''},\nalthough the underlying principle is similar.\nIn contrast, there are microkernels, where modules are allocated their own code space.\nTwo notable examples of microkernels include the \\href{https://www.gnu.org/software/hurd/}{GNU Hurd} and the \\href{https://fuchsia.dev/fuchsia-src/concepts/kernel}{Zircon kernel} of Google's Fuchsia.\n\n\\subsection{Device Drivers}\n\\label{sec:device_drivers}\nOne class of module is the device driver, which provides functionality for hardware like a serial port.\nOn Unix, each piece of hardware is represented by a file located in \\verb|/dev| named a device file which provides the means to communicate with the hardware.\nThe device driver provides the communication on behalf of a user program.\n% FIXME: use popular device for example\nSo the es1370.ko sound card device driver might connect the \\verb|/dev/sound| device file to the Ensoniq ES1370 sound card.\nA userspace program like mp3blaster can use \\verb|/dev/sound| without ever knowing what kind of sound card is installed.\n\nLet's look at some device files.\nHere are device files which represent the first three partitions on the primary SCSI storage devices:\n\n\\begin{verbatim}\n$ ls -l /dev/sda[1-3]\nbrw-rw----  1 root  disk  8, 1 Apr  9  2025 /dev/sda1\nbrw-rw----  1 root  disk  8, 2 Apr  9  2025 /dev/sda2\nbrw-rw----  1 root  disk  8, 3 Apr  9  2025 /dev/sda3\n\\end{verbatim}\n\nNotice the column of numbers separated by a comma.\nThe first number is called the device's major number.\nThe second number is the minor number.\nThe major number tells you which driver is used to access the hardware.\nEach driver is assigned a unique major number; all device files with the same major number are controlled by the same driver.\nAll the above major numbers are 8, because they're all controlled by the same driver.\n\nThe minor number is used by the driver to distinguish between the various hardware it controls.\nReturning to the example above, although all three devices are handled by the same driver they have unique minor numbers because the driver sees them as being different pieces of hardware.\n\nDevices are divided into two types: character devices and block devices.\nThe difference is that block devices have a buffer for requests, so they can choose the best order in which to respond to the requests.\nThis is important in the case of storage devices, where it is faster to read or write sectors which are close to each other, rather than those which are further apart.\nAnother difference is that block devices can only accept input and return output in blocks (whose size can vary according to the device), whereas character devices are allowed to use as many or as few bytes as they like.\nMost devices in the world are character, because they don't need this type of buffering, and they don't operate with a fixed block size.\nYou can tell whether a device file is for a block device or a character device by looking at the first character in the output of \\sh|ls -l|.\nIf it is `b' then it is a block device, and if it is `c' then it is a character device.\nThe devices you see above are block devices. Here are some character devices (the serial ports):\n\n\\begin{verbatim}\ncrw-rw----  1 root  dial 4, 64 Feb 18 23:34 /dev/ttyS0\ncrw-r-----  1 root  dial 4, 65 Nov 17 10:26 /dev/ttyS1\ncrw-rw----  1 root  dial 4, 66 Jul  5  2000 /dev/ttyS2\ncrw-rw----  1 root  dial 4, 67 Jul  5  2000 /dev/ttyS3\n\\end{verbatim}\n\nIf you want to see which major numbers have been assigned, you can look at \\src{Documentation/admin-guide/devices.txt}.\n\nWhen the system was installed, all of those device files were created by the \\sh|mknod| command.\nTo create a new char device named \\verb|coffee| with major/minor number 12 and 2, simply do \\sh|mknod /dev/coffee c 12 2|.\nYou do not have to put your device files into \\verb|/dev|, but it is done by convention.\nLinus put his device files in \\verb|/dev|, and so should you.\nHowever, when creating a device file for testing purposes, it is probably OK to place it in your working directory where you compile the kernel module.\nJust be sure to put it in the right place when you're done writing the device driver.\n\nA few final points, although implicit in the previous discussion, are worth stating explicitly for clarity.\nWhen a device file is accessed, the kernel utilizes the file's major number to identify the appropriate driver for handling the access.\nThis indicates that the kernel does not necessarily rely on or need to be aware of the minor number.\nIt is the driver that concerns itself with the minor number, using it to differentiate between various pieces of hardware.\n\nIt is important to note that when referring to \\emph{``hardware''},\nthe term is used in a slightly more abstract sense than just a physical PCI card that can be held in hand.\nConsider the following two device files:\n\n\\begin{verbatim}\n$ ls -l /dev/sda /dev/sdb\nbrw-rw---- 1 root disk 8,  0 Jan  3 09:02 /dev/sda\nbrw-rw---- 1 root disk 8, 16 Jan  3 09:02 /dev/sdb\n\\end{verbatim}\n\nBy now you can look at these two device files and know instantly that they are block devices and are handled by same driver (block major 8).\nSometimes two device files with the same major but different minor number can actually represent the same piece of physical hardware.\nSo just be aware that the word ``hardware'' in our discussion can mean something very abstract.\n\n\\section{Character Device drivers}\n\\label{sec:chardev}\n\\subsection{The file\\_operations Structure}\n\\label{sec:file_operations}\nThe \\cpp|file_operations| structure is defined in \\src{include/linux/fs.h}, and holds pointers to functions defined by the driver that perform various operations on the device.\nEach field of the structure corresponds to the address of some function defined by the driver to handle a requested operation.\n\nFor example, every character driver needs to define a function that reads from the device.\nThe \\cpp|file_operations| structure holds the address of the module's function that performs that operation.\nHere is what the definition looks like for kernel 5.4 and later versions:\n\n\\begin{code}\nstruct file_operations {\n    struct module *owner;\n    loff_t (*llseek) (struct file *, loff_t, int);\n    ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);\n    ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);\n    ssize_t (*read_iter) (struct kiocb *, struct iov_iter *);\n    ssize_t (*write_iter) (struct kiocb *, struct iov_iter *);\n    int (*iopoll)(struct kiocb *kiocb, bool spin);\n    int (*iterate) (struct file *, struct dir_context *);\n    int (*iterate_shared) (struct file *, struct dir_context *);\n    __poll_t (*poll) (struct file *, struct poll_table_struct *);\n    long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);\n    long (*compat_ioctl) (struct file *, unsigned int, unsigned long);\n    int (*mmap) (struct file *, struct vm_area_struct *);\n    unsigned long mmap_supported_flags;\n    int (*open) (struct inode *, struct file *);\n    int (*flush) (struct file *, fl_owner_t id);\n    int (*release) (struct inode *, struct file *);\n    int (*fsync) (struct file *, loff_t, loff_t, int datasync);\n    int (*fasync) (int, struct file *, int);\n    int (*lock) (struct file *, int, struct file_lock *);\n    ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);\n    unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);\n    int (*check_flags)(int);\n    int (*flock) (struct file *, int, struct file_lock *);\n    ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);\n    ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int);\n    int (*setlease)(struct file *, long, struct file_lock **, void **);\n    long (*fallocate)(struct file *file, int mode, loff_t offset,\n        loff_t len);\n    void (*show_fdinfo)(struct seq_file *m, struct file *f);\n    ssize_t (*copy_file_range)(struct file *, loff_t, struct file *,\n        loff_t, size_t, unsigned int);\n    loff_t (*remap_file_range)(struct file *file_in, loff_t pos_in,\n             struct file *file_out, loff_t pos_out,\n             loff_t len, unsigned int remap_flags);\n    int (*fadvise)(struct file *, loff_t, loff_t, int);\n} __randomize_layout;\n\\end{code}\n\nSome operations are not implemented by a driver.\nFor example, a driver that handles a video card will not need to read from a directory structure.\nThe corresponding entries in the \\cpp|file_operations| structure should be set to \\cpp|NULL|.\n\\footnote{\nAs of Linux kernel 6.12, several member fields have been added, removed, or had their prototypes changed.\nFor example, additions include \\texttt{fop\\_flags}, \\texttt{splice\\_eof}, and \\texttt{uring\\_cmd};\nremovals include \\texttt{iterate} and \\texttt{sendpage}; and the prototype for \\texttt{iopoll} was modified.\n}\n\nThere is a gcc extension that makes assigning to this structure more convenient.\nYou will see it in modern drivers, and may catch you by surprise.\nThis is what the new way of assigning to the structure looks like:\n\n\\begin{code}\nstruct file_operations fops = {\n\tread: device_read,\n\twrite: device_write,\n\topen: device_open,\n\trelease: device_release\n};\n\\end{code}\n\nHowever, there is also a C99 way of assigning to elements of a structure, \\href{https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html}{designated initializers}, and this is definitely preferred over using the GNU extension.\nYou should use this syntax in case someone wants to port your driver.\nIt will help with compatibility:\n\n\\begin{code}\nstruct file_operations fops = {\n\t.read = device_read,\n\t.write = device_write,\n\t.open = device_open,\n\t.release = device_release\n};\n\\end{code}\n\nThe meaning is clear, and you should be aware that any member of the structure which you do not explicitly assign will be initialized to \\cpp|NULL| by gcc.\n\nAn instance of \\cpp|struct file_operations| containing pointers to functions that are used to implement \\cpp|read|, \\cpp|write|, \\cpp|open|, \\ldots{} system calls is commonly named \\cpp|fops|.\n\nSince Linux v3.14, the read, write and seek operations are guaranteed for thread-safe by using the \\cpp|f_pos| specific lock, which makes the file position update to become the mutual exclusion.\nSo, we can safely implement those operations without unnecessary locking.\n\nAdditionally, since Linux v5.6, the \\cpp|proc_ops| structure was introduced to replace the use of the \\cpp|file_operations| structure when registering proc handlers.\nSee more information in the \\Cref{sec:proc_ops}.\n\n\\subsection{The file structure}\n\\label{sec:file_struct}\n\nEach device is represented in the kernel by a file structure, which is defined in \\src{include/linux/fs.h}.\nBe aware that a file is a kernel level structure and never appears in a user space program.\nIt is not the same thing as a \\cpp|FILE|, which is defined by glibc and would never appear in a kernel space function.\nAlso, its name is a bit misleading; it represents an abstract open `file', not a file on a disk, which is represented by a structure named \\cpp|inode|.\n\nAn instance of struct file is commonly named \\cpp|filp|.\nYou'll also see it referred to as a struct file object.\nResist the temptation.\n\nGo ahead and look at the definition of file.\nMost of the entries you see, like struct dentry, are not used by device drivers, and you can ignore them.\nThis is because drivers do not fill file directly; they only use structures contained in file which are created elsewhere.\n\n\\subsection{Registering A Device}\n\\label{sec:register_device}\nAs discussed earlier, char devices are accessed through device files, usually located in \\verb|/dev|.\nThis is by convention. When writing a driver, it is OK to put the device file in your current directory.\nJust make sure you place it in \\verb|/dev| for a production driver.\nThe major number tells you which driver handles which device file.\nThe minor number is used only by the driver itself to differentiate which device it is operating on, just in case the driver handles more than one device.\n\nAdding a driver to your system means registering it with the kernel.\nThis is synonymous with assigning it a major number during the module's initialization.\nYou do this by using the \\cpp|register_chrdev| function, defined by \\src{include/linux/fs.h}.\n\n\\begin{code}\nint register_chrdev(unsigned int major, const char *name, struct file_operations *fops);\n\\end{code}\n\nWhere \\cpp|unsigned int major| is the major number you want to request, \\cpp|const char *name| is the name of the device as it will appear in \\verb|/proc/devices| and \\cpp|struct file_operations *fops| is a pointer to the \\cpp|file_operations| table for your driver.\nA negative return value means the registration failed. Note that we didn't pass the minor number to \\cpp|register_chrdev|.\nThat is because the kernel doesn't care about the minor number; only our driver uses it.\n\nNow the question is, how do you get a major number without hijacking one that's already in use?\nThe easiest way would be to look through \\src{Documentation/admin-guide/devices.txt} and pick an unused one.\nThat is a bad way of doing things because you will never be sure if the number you picked will be assigned later.\nThe answer is that you can ask the kernel to assign you a dynamic major number.\n\nIf you pass a major number of 0 to \\cpp|register_chrdev|, the return value will be the dynamically allocated major number.\nThe downside is that you can not make a device file in advance, since you do not know what the major number will be.\nThere are a couple of ways to do this.\nFirst, the driver itself can print the newly assigned number and we can make the device file by hand.\nSecond, the newly registered device will have an entry in \\verb|/proc/devices|, and we can either make the device file by hand or write a shell script to read the file in and make the device file.\nThe third method is that we can have our driver make the device file using the \\cpp|device_create| function after a successful registration and \\cpp|device_destroy| during the call to \\cpp|cleanup_module|.\n\nHowever, \\cpp|register_chrdev()| would occupy a range of minor numbers associated with the given major.\nThe recommended way to reduce waste for char device registration is using cdev interface.\n\nThe newer interface completes the char device registration in two distinct steps.\nFirst, we should register a range of device numbers, which can be completed with \\cpp|register_chrdev_region| or \\cpp|alloc_chrdev_region|.\n\n\\begin{code}\nint register_chrdev_region(dev_t from, unsigned count, const char *name);\nint alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name);\n\\end{code}\n\nThe choice between two different functions depends on whether you know the major numbers for your device.\nUsing \\cpp|register_chrdev_region| if you know the device major number and \\cpp|alloc_chrdev_region| if you would like to allocate a dynamically-allocated major number.\n\nSecond, we should initialize the data structure \\cpp|struct cdev| for our char device and associate it with the device numbers.\nTo initialize the \\cpp|struct cdev|, we can achieve by the similar sequence of the following codes.\n\n\\begin{code}\nstruct cdev *my_dev = cdev_alloc();\nmy_cdev->ops = &my_fops;\n\\end{code}\n\nHowever, the common usage pattern will embed the \\cpp|struct cdev| within a device-specific structure of your own.\nIn this case, we'll need \\cpp|cdev_init| for the initialization.\n\n\\begin{code}\nvoid cdev_init(struct cdev *cdev, const struct file_operations *fops);\n\\end{code}\n\nOnce we finish the initialization, we can add the char device to the system by using the \\cpp|cdev_add|.\n\n\\begin{code}\nint cdev_add(struct cdev *p, dev_t dev, unsigned count);\n\\end{code}\n\nTo find an example using the interface, you can see \\verb|ioctl.c| described in \\Cref{sec:device_files}.\n\n\\subsection{Unregistering A Device}\n\\label{sec:unregister_device}\nWe can not allow the kernel module to be \\sh|rmmod|'ed whenever root feels like it.\nIf the device file is opened by a process and then we remove the kernel module, using the file would cause a call to the memory location where the appropriate function (read/write) used to be.\nIf we are lucky, no other code was loaded there, and we'll get an ugly error message.\nIf we are unlucky, another kernel module was loaded into the same location, which means a jump into the middle of another function within the kernel.\nThe results of this would be impossible to predict, but they can not be very positive.\n\nNormally, when you do not want to allow something, you return an error code (a negative number) from the function which is supposed to do it.\nWith \\cpp|cleanup_module| that's impossible because it is a void function.\nHowever, there is a counter which keeps track of how many processes are using your module.\nYou can see what its value is by looking at the 3rd field with the command \\sh|cat /proc/modules| or \\sh|lsmod|.\nIf this number isn't zero, \\sh|rmmod| will fail.\nNote that you do not have to check the counter within \\cpp|cleanup_module| because the check will be performed for you by the system call \\cpp|sys_delete_module|, defined in \\src{include/linux/syscalls.h}.\nYou should not use this counter directly, but there are functions defined in \\src{include/linux/module.h} which let you display this counter:\n\n\\begin{itemize}\n  \\item \\cpp|module_refcount(THIS_MODULE)|: Return the value of reference count of current module.\n\\end{itemize}\n\nNote: The use of \\cpp|try_module_get(THIS_MODULE)| and \\cpp|module_put(THIS_MODULE)| within a module's own code is considered unsafe and should be avoided.\nThe kernel automatically manages the reference count when file operations are in progress,\nso manual reference counting is unnecessary and can lead to race conditions.\nFor a deeper understanding of when and how to properly use module reference counting,\nsee \\url{https://stackoverflow.com/questions/1741415/linux-kernel-modules-when-to-use-try-module-get-module-put}.\n\n\\subsection{chardev.c}\n\\label{sec:chardev_c}\nThe next code sample creates a char driver named \\verb|chardev|.\nYou can verify it has been registered by checking:\n\n\\begin{codebash}\ncat /proc/devices\n\\end{codebash}\n\nThis will show the device's major number.\nTo actually use the device, you need to read from \\verb|/dev/chardev| (or open the file with a program) and the driver will put the number of times the device file has been read from into the file.\nWe do not support writing to the file (like \\sh|echo \"hi\" > /dev/chardev|),\nbut catch these attempts and tell the user that the operation is not supported.\nDo not worry if you do not see what we do with the data we read into the buffer; we do not do much with it.\nWe simply read in the data and print a message acknowledging that we received it.\n\nIn a multi-threaded environment, without any protection, concurrent access to the same memory may lead to race conditions and will not preserve performance.\nIn the kernel module, this problem may happen due to multiple instances accessing the shared resources.\nTherefore, a solution is to enforce exclusive access.\nWe use atomic Compare-And-Swap (CAS) to maintain the states, \\cpp|CDEV_NOT_USED| and \\cpp|CDEV_EXCLUSIVE_OPEN|, to determine whether the file is currently opened by someone or not.\nCAS compares the contents of a memory location with the expected value and, only if they are the same, modifies the contents of that memory location to the desired value.\nSee more concurrency details in the \\Cref{sec:synchronization}.\n\n\\samplec{examples/chardev.c}\n\n\\subsection{Writing Modules for Multiple Kernel Versions}\n\\label{sec:modules_for_versions}\nThe system calls, which are the major interface the kernel shows to the processes, generally stay the same across versions.\nA new system call may be added, but usually the old ones will behave exactly like they used to.\nThis is necessary for backward compatibility -- a new kernel version is not supposed to break regular processes.\nIn most cases, the device files will also remain the same. On the other hand, the internal interfaces within the kernel can and do change between versions.\n\nThere are differences between different kernel versions, and if you want to support multiple kernel versions, you will find yourself having to code conditional compilation directives.\nThe way to do this is to compare the macro \\cpp|LINUX_VERSION_CODE| to the macro \\cpp|KERNEL_VERSION|.\nIn version \\verb|a.b.c| of the kernel, the value of this macro would be \\(2^{16}a+2^{8}b+c\\).\n\n\\section{The /proc Filesystem}\n\\label{sec:procfs}\nIn Linux, there is an additional mechanism for the kernel and kernel modules to send information to processes --- the \\verb|/proc| filesystem.\nOriginally designed to allow easy access to information about processes (hence the name), it is now used by every bit of the kernel which has something interesting to report, such as \\verb|/proc/modules| which provides the list of modules and \\verb|/proc/meminfo| which gathers memory usage statistics.\n\nThe method to use the proc filesystem is very similar to the one used with device drivers --- a structure is created with all the information needed for the \\verb|/proc| file, including pointers to any handler functions (in our case there is only one, the one called when somebody attempts to read from the \\verb|/proc| file).\nThen, \\cpp|init_module| registers the structure with the kernel and \\cpp|cleanup_module| unregisters it.\n\nNormal filesystems are located on a disk, rather than just in memory (which is where \\verb|/proc| is), and in that case the index-node (inode for short) number is a pointer to a disk location where the file's inode is located.\nThe inode contains information about the file, for example the file's permissions, together with a pointer to the disk location or locations where the file's data can be found.\n\nBecause we do not get called when the file is opened or closed, there is nowhere for us to put \\cpp|try_module_get| and \\cpp|module_put| in this module, and if the file is opened and then the module is removed, there is no way to avoid the consequences.\nThe kernel's automatic reference counting for file operations helps prevent module removal while files are in use,\nbut \\verb|/proc| files require careful handling due to their different lifecycle.\n\nHere is a simple example showing how to use a \\verb|/proc| file.\nThis is the HelloWorld for the \\verb|/proc| filesystem.\nThere are three parts: create the file \\verb|/proc/helloworld| in the function \\cpp|init_module|, return a value (and a buffer) when the file \\verb|/proc/helloworld| is read in the callback function \\cpp|procfile_read|, and delete the file \\verb|/proc/helloworld| in the function \\cpp|cleanup_module|.\n\nThe \\verb|/proc/helloworld| is created when the module is loaded with the function \\cpp|proc_create|.\nThe return value is a pointer to \\cpp|struct proc_dir_entry|, and it will be used to configure the file \\verb|/proc/helloworld| (for example, the owner of this file).\nA null return value means that the creation has failed.\n\nEvery time the file \\verb|/proc/helloworld| is read, the function \\cpp|procfile_read| is called.\nTwo parameters of this function are very important: the buffer (the second parameter) and the offset (the fourth one).\nThe content of the buffer will be returned to the application which read it (for example the \\sh|cat| command).\nThe offset is the current position in the file.\nIf the return value of the function is not null, then this function is called again.\nSo be careful with this function, if it never returns zero, the read function is called endlessly.\n\n\\begin{verbatim}\n$ cat /proc/helloworld\nHelloWorld!\n\\end{verbatim}\n\n\\samplec{examples/procfs1.c}\n\n\\subsection{The proc\\_ops Structure}\n\\label{sec:proc_ops}\nThe \\cpp|proc_ops| structure is defined in \\src{include/linux/proc\\_fs.h} in Linux v5.6+.\nIn older kernels, it used \\cpp|file_operations| for custom hooks in \\verb|/proc| filesystem, but it contains some members that are unnecessary in VFS, and every time VFS expands \\cpp|file_operations| set, \\verb|/proc| code comes bloated.\nOn the other hand, not only the space, but also some operations were saved by this structure to improve its performance.\nFor example, the file which never disappears in \\verb|/proc| can set the \\cpp|proc_flag| as \\cpp|PROC_ENTRY_PERMANENT| to save 2 atomic ops, 1 allocation, 1 free in per open/read/close sequence.\n\n\\subsection{Read and Write a /proc File}\n\\label{sec:read_write_procfs}\nWe have seen a very simple example for a \\verb|/proc| file where we only read the file \\verb|/proc/helloworld|.\nIt is also possible to write in a \\verb|/proc| file.\nIt works the same way as read, a function is called when the \\verb|/proc| file is written.\nBut there is a little difference with read, data comes from user, so you have to import data from user space to kernel space (with \\cpp|copy_from_user| or \\cpp|get_user|)\n\nThe reason for \\cpp|copy_from_user| or \\cpp|get_user| is that Linux memory (on Intel architecture, it may be different under some other processors) is segmented.\nThis means that a pointer, by itself, does not reference a unique location in memory, only a location in a memory segment, and you need to know which memory segment it is to be able to use it.\nThere is one memory segment for the kernel, and one for each of the processes.\n\nThe only memory segment accessible to a process is its own, so when writing regular programs to run as processes, there is no need to worry about segments.\nWhen you write a kernel module, normally you want to access the kernel memory segment, which is handled automatically by the system.\nHowever, when the content of a memory buffer needs to be passed between the currently running process and the kernel, the kernel function receives a pointer to the memory buffer which is in the process segment.\nThe \\cpp|put_user| and \\cpp|get_user| macros allow you to access that memory.\nThese functions handle only one character, you can handle several characters with \\cpp|copy_to_user| and \\cpp|copy_from_user|.\nAs the buffer (in read or write function) is in kernel space, for write function you need to import data because it comes from user space, but not for the read function because data is already in kernel space.\n\n\\samplec{examples/procfs2.c}\n\n\\subsection{Manage /proc file with standard filesystem}\n\\label{sec:manage_procfs}\nWe have seen how to read and write a \\verb|/proc| file with the \\verb|/proc| interface.\nBut it is also possible to manage \\verb|/proc| file with inodes.\nThe main concern is to use advanced functions, like permissions.\n\nIn Linux, there is a standard mechanism for filesystem registration.\nSince every filesystem has to have its own functions to handle inode and file operations, there is a special structure to hold pointers to all those functions, \\cpp|struct inode_operations|, which includes a pointer to \\cpp|struct proc_ops|.\n\nThe difference between file and inode operations is that file operations deal with the file itself whereas inode operations deal with ways of referencing the file, such as creating links to it.\n\nIn \\verb|/proc|, whenever we register a new file, we're allowed to specify which \\cpp|struct inode_operations| will be used to access to it.\nThis is the mechanism we use, a \\cpp|struct inode_operations| which includes a pointer to a \\cpp|struct proc_ops| which includes pointers to our \\cpp|procfs_read| and \\cpp|procfs_write| functions.\n\nAnother interesting point here is the \\cpp|module_permission| function.\nThis function is called whenever a process tries to do something with the \\verb|/proc| file, and it can decide whether to allow access or not.\nRight now it is only based on the operation and the uid of the current user (as available in current, a pointer to a structure which includes information on the currently running process), but it could be based on anything we like, such as what other processes are doing with the same file, the time of day, or the last input we received.\n\nIt is important to note that the standard roles of read and write are reversed in the kernel.\nRead functions are used for output, whereas write functions are used for input.\nThe reason for that is that read and write refer to the user's point of view --- if a process reads something from the kernel, then the kernel needs to output it, and if a process writes something to the kernel, then the kernel receives it as input.\n\n\\samplec{examples/procfs3.c}\n\nStill hungry for procfs examples?\nWell, first of all keep in mind, there are rumors around, claiming that procfs is on its way out, consider using \\verb|sysfs| instead.\nConsider using this mechanism, in case you want to document something kernel related yourself.\n\n\\subsection{Manage /proc file with seq\\_file}\n\\label{sec:manage_procfs_with_seq_file}\nAs we have seen, writing a \\verb|/proc| file may be quite ``complex''.\nSo to help people writing \\verb|/proc| file, there is an API named \\cpp|seq_file| that helps formatting a \\verb|/proc| file for output.\nIt is based on sequence, which is composed of 3 functions: \\cpp|start()|, \\cpp|next()|, and \\cpp|stop()|.\nThe \\cpp|seq_file| API starts a sequence when a user reads the \\verb|/proc| file.\n\nA sequence begins with the call of the function \\cpp|start()|.\nIf the return is a non \\cpp|NULL| value, the function \\cpp|next()| is called; otherwise, the \\cpp|stop()| function is called directly.\nThis function is an iterator, the goal is to go through all the data.\nEach time \\cpp|next()| is called, the function \\cpp|show()| is also called.\nIt writes data values in the buffer read by the user.\nThe function \\cpp|next()| is called until it returns \\cpp|NULL|.\nThe sequence ends when \\cpp|next()| returns \\cpp|NULL|, then the function \\cpp|stop()| is called.\n\nBE CAREFUL: when a sequence is finished, another one starts.\nThat means that at the end of function \\cpp|stop()|, the function \\cpp|start()| is called again.\nThis loop finishes when the function \\cpp|start()| returns \\cpp|NULL|.\nYou can see a scheme of this in the \\Cref{img:seqfile}.\n\n\\begin{figure}[h]\n  \\center\n  \\begin{tikzpicture}[node distance=2cm, thick]\n    \\node (start) [startstop] {start() treatment};\n    \\node (branch1) [decision, below of=start, yshift=-1cm] {return is NULL?};\n    \\node (next) [process, below of=branch1, yshift=-1cm] {next() treatment};\n    \\node (branch2) [decision, below of=next, yshift=-1cm] {return is NULL?};\n    \\node (stop) [startstop, below of=branch2, yshift=-1cm] {stop() treatment};\n\n    \\draw [->] (start) -- (branch1);\n    \\draw [->] (branch1.east) to [out=135, in=-135, bend left=45] node [right] {Yes} (stop.east);\n    \\draw [->] (branch1) -- node[left=2em, anchor=south] {No} (next);\n    \\draw [->] (next) -- (branch2);\n    \\draw [->] (branch2.west) to [out=135, in=-135, bend left=45] node [left] {No} (next.west);\n    \\draw [->] (branch2) -- node[left=2em, anchor=south] {Yes} (stop);\n    \\draw [->] (stop.west) to [out=135, in=-135] node [left] {} (start.west);\n  \\end{tikzpicture}\n  \\caption{How seq\\_file works}\n  \\label{img:seqfile}\n\\end{figure}\n\nThe \\cpp|seq_file| provides basic functions for \\cpp|proc_ops|, such as \\cpp|seq_read|, \\cpp|seq_lseek|, and some others.\nBut nothing to write in the \\verb|/proc| file.\nOf course, you can still use the same way as in the previous example.\n\n\\samplec{examples/procfs4.c}\n\nIf you want more information, you can read this web page:\n\n\\begin{itemize}\n  \\item \\url{https://lwn.net/Articles/22355/}\n  \\item \\url{https://kernelnewbies.org/Documents/SeqFileHowTo}\n\\end{itemize}\n\nYou can also read the code of \\src{fs/seq\\_file.c} in the Linux kernel.\n\n\\section{sysfs: Interacting with your module}\n\\label{sec:sysfs}\n\\emph{sysfs} allows you to interact with the running kernel from userspace by reading or setting variables inside of modules.\nThis can be useful for debugging purposes, or just as an interface for applications or scripts.\nYou can find sysfs directories and files under the \\verb|/sys| directory on your system.\n\n\\begin{codebash}\nls -l /sys\n\\end{codebash}\n\nAttributes can be exported for kobjects in the form of regular files in the filesystem.\nSysfs forwards file I/O operations to methods defined for the attributes, providing a means to read and write kernel attributes.\n\nA simple attribute definition:\n\n\\begin{code}\nstruct attribute {\n    char *name;\n    struct module *owner;\n    umode_t mode;\n};\n\nint sysfs_create_file(struct kobject * kobj, const struct attribute * attr);\nvoid sysfs_remove_file(struct kobject * kobj, const struct attribute * attr);\n\\end{code}\n\nFor example, the driver model defines \\cpp|struct device_attribute| like:\n\n\\begin{code}\nstruct device_attribute {\n    struct attribute attr;\n    ssize_t (*show)(struct device *dev, struct device_attribute *attr,\n                    char *buf);\n    ssize_t (*store)(struct device *dev, struct device_attribute *attr,\n                    const char *buf, size_t count);\n};\n\nint device_create_file(struct device *, const struct device_attribute *);\nvoid device_remove_file(struct device *, const struct device_attribute *);\n\\end{code}\n\nTo read or write attributes, the \\cpp|show()| or \\cpp|store()| method must be specified when declaring the attribute.\nFor the common cases \\src{include/linux/sysfs.h} provides convenience macros (\\cpp|__ATTR|, \\cpp|__ATTR_RO|, \\cpp|__ATTR_WO|, etc.) to make defining attributes easier as well as making code more concise and readable.\n\nAn example of a hello world module which includes the creation of a variable accessible via sysfs is given below.\n\n\\samplec{examples/hello-sysfs.c}\n\nMake and install the module:\n\n\\begin{codebash}\nmake\nsudo insmod hello-sysfs.ko\n\\end{codebash}\n\nCheck that it exists:\n\n\\begin{codebash}\nlsmod | grep hello_sysfs\n\\end{codebash}\n\nWhat is the current value of \\cpp|myvariable| ?\n\n\\begin{codebash}\ncat /sys/kernel/mymodule/myvariable\n\\end{codebash}\n\nSet the value of \\cpp|myvariable| and check that it changed.\n\n\\begin{codebash}\necho \"32\" | sudo tee /sys/kernel/mymodule/myvariable\ncat /sys/kernel/mymodule/myvariable\n\\end{codebash}\n\nFinally, remove the test module:\n\n\\begin{codebash}\nsudo rmmod hello_sysfs\n\\end{codebash}\n\nIn the above case, we use a simple kobject to create a directory under sysfs, and communicate with its attributes.\nSince Linux v2.6.0, the \\cpp|kobject| structure made its appearance.\nIt was initially meant as a simple way of unifying kernel code which manages reference counted objects.\nAfter a bit of mission creep, it is now the glue that holds much of the device model and its sysfs interface together.\nFor more information about kobject and sysfs, see \\src{Documentation/driver-api/driver-model/driver.rst} and \\url{https://lwn.net/Articles/51437/}.\n\n\\section{Talking To Device Files}\n\\label{sec:device_files}\nDevice files are supposed to represent physical devices.\nMost physical devices are used for output as well as input, so there has to be some mechanism for device drivers in the kernel to get the output to send to the device from processes.\nThis is done by opening the device file for output and writing to it, just like writing to a file.\nIn the following example, this is implemented by \\cpp|device_write|.\n\nThis is not always enough.\nImagine you had a serial port connected to a modem (even if you have an internal modem, it is still implemented from the CPU's perspective as a serial port connected to a modem, so you don't have to tax your imagination too hard).\nThe natural thing to do would be to use the device file to write things to the modem (either modem commands or data to be sent through the phone line) and read things from the modem (either responses for commands or the data received through the phone line).\nHowever, this leaves open the question of what to do when you need to talk to the serial port itself, for example to configure the rate at which data is sent and received.\n\nThe answer in Unix is to use a special function called \\cpp|ioctl| (short for Input Output ConTroL).\nEvery device can have its own \\cpp|ioctl| commands, which can be read ioctl's (to send information from a process to the kernel), write ioctl's (to return information to a process), both or neither.\nNotice here the roles of read and write are reversed again, so in ioctl's read is to send information to the kernel and write is to receive information from the kernel.\n\nThe ioctl function is called with three parameters: the file descriptor of the appropriate device file, the ioctl number, and a parameter, which is of type long so you can use a cast to use it to pass anything.\nYou will not be able to pass a structure this way, but you will be able to pass a pointer to the structure.\nHere is an example:\n\n\\samplec{examples/ioctl.c}\n\nYou can see there is an argument called \\cpp|cmd| in \\cpp|test_ioctl_ioctl()| function.\nIt is the ioctl number.\nThe ioctl number encodes the major device number, the type of the ioctl, the command, and the type of the parameter.\nThis ioctl number is usually created by a macro call (\\cpp|_IO|, \\cpp|_IOR|, \\cpp|_IOW| or \\cpp|_IOWR| --- depending on the type) in a header file.\nThis header file should then be included both by the programs which will use ioctl (so they can generate the appropriate ioctl's) and by the kernel module (so it can understand it).\nIn the example below, the header file is \\verb|chardev.h| and the program which uses it is \\verb|userspace_ioctl.c|.\n\nIf you want to use ioctls in your own kernel modules, it is best to receive an official ioctl assignment, so if you accidentally get somebody else's ioctls, or if they get yours, you'll know something is wrong.\nFor more information, consult the kernel source tree at \\src{Documentation/userspace-api/ioctl/ioctl-number.rst}.\n\nAlso, we need to be careful that concurrent access to the shared resources will lead to the race condition.\nThe solution is using atomic Compare-And-Swap (CAS), which we mentioned at \\Cref{sec:chardev_c}, to enforce the exclusive access.\n\n\\samplec{examples/chardev2.c}\n\n\\samplec{examples/chardev.h}\n\n\\samplec{examples/other/userspace_ioctl.c}\n\n\\section{System Calls}\n\\label{sec:syscall}\nSo far, the only thing we've done was to use well defined kernel mechanisms to register \\verb|/proc| files and device handlers.\nThis is fine if you want to do something the kernel programmers thought you'd want, such as write a device driver.\nBut what if you want to do something unusual, to change the behavior of the system in some way?\nThen, you are mostly on your own.\n\nNotice that this example has been unavailable since Linux v6.9.\nSpecifically, after this \\href{https://github.com/torvalds/linux/commit/1e3ad78334a69b36e107232e337f9d693dcc9df2#diff-4a16bf89a09b4f49669a30d54540f0b936ea0224dc6ee9edfa7700deb16c3e11R52}{commit}, due to the system call table changing the implementation from an indirect function call table to a switch statement for security issues, such as Branch History Injection (BHI) attack.\nSee more information \\href{https://bugs.launchpad.net/ubuntu/+source/linux/+bug/2060909}{here}.\n\nShould one choose not to use a virtual machine, kernel programming can become risky.\nFor example, while writing the code below, the \\cpp|open()| system call was inadvertently disrupted.\nThis resulted in an inability to open any files, run programs, or shut down the system, necessitating a restart of the virtual machine.\nFortunately, no critical files were lost in this instance.\nHowever, if such modifications were made on a live, mission-critical system, the consequences could be severe.\nTo mitigate the risk of file loss, even in a test environment, it is advised to execute \\sh|sync| right before using \\sh|insmod| and \\sh|rmmod|.\n\nForget about \\verb|/proc| files, forget about device files.\nThey are just minor details.\nMinutiae in the vast expanse of the universe.\nThe real process to kernel communication mechanism, the one used by all processes, is \\emph{system calls}.\nWhen a process requests a service from the kernel (such as opening a file, forking to a new process, or requesting more memory), this is the mechanism used.\nIf you want to change the behaviour of the kernel in interesting ways, this is the place to do it.\nBy the way, if you want to see which system calls a program uses, run \\sh|strace <arguments>|.\n\nIn general, a process is not supposed to be able to access the kernel.\nIt can not access kernel memory and it can't call kernel functions.\nThe hardware of the CPU enforces this (that is the reason why it is called ``protected mode'' or ``page protection'').\n\nSystem calls are an exception to this general rule.\nWhat happens is that the process fills the registers with the appropriate values and then calls a special instruction which jumps to a previously defined location in the kernel (of course, that location is readable by user processes, it is not writable by them).\nUnder Intel CPUs, this is done by means of interrupt 0x80. The hardware knows that once you jump to this location, you are no longer running in restricted user mode, but as the operating system kernel --- and therefore you're allowed to do whatever you want.\n\n% FIXME: recent kernel changes the system call entries\nThe location in the kernel a process can jump to is called \\verb|system_call|.\nThe procedure at that location checks the system call number, which tells the kernel what service the process requested.\nThen, it looks at the table of system calls (\\cpp|sys_call_table|) to see the address of the kernel function to call.\nThen it calls the function, and after it returns, does a few system checks and then return back to the process (or to a different process, if the process time ran out).\nIf you want to read this code, it is at the source file \\verb|arch/$(architecture)/kernel/entry.S|, after the line \\cpp|ENTRY(system_call)|.\n\nSo, if we want to change the way a certain system call works, what we need to do is to write our own function to implement it (usually by adding a bit of our own code, and then calling the original function) and then change the pointer at \\cpp|sys_call_table| to point to our function.\nBecause we might be removed later and we don't want to leave the system in an unstable state, it's important for \\cpp|cleanup_module| to restore the table to its original state.\n\nTo modify the content of \\cpp|sys_call_table|, we need to consider the control register.\nA control register is a processor register that changes or controls the general behavior of the CPU.\nFor x86 architecture, the \\verb|cr0| register has various control flags that modify the basic operation of the processor.\nThe \\verb|WP| flag in \\verb|cr0| stands for write protection.\nOnce the \\verb|WP| flag is set, the processor disallows further write attempts to the read-only sections.\nTherefore, we must disable the \\verb|WP| flag before modifying \\cpp|sys_call_table|.\nSince Linux v5.3, the \\cpp|write_cr0| function cannot be used because of the sensitive \\verb|cr0| bits pinned by the security issue, the attacker may write into CPU control registers to disable CPU protections like write protection.\nAs a result, we have to provide the custom assembly routine to bypass it.\n\nHowever, \\cpp|sys_call_table| symbol is unexported to prevent misuse.\nBut there have few ways to get the symbol, manual symbol lookup and \\cpp|kallsyms_lookup_name|.\nHere we use both depend on the kernel version.\n\nBecause of the \\textit{control-flow integrity}, which is a technique to prevent the redirect execution code from the attacker, for making sure that the indirect calls go to the expected addresses and the return addresses are not changed.\nSince Linux v5.7, the kernel patched the series of \\textit{control-flow enforcement} (CET) for x86,\nand some configurations of GCC, like GCC versions 9 and 10 in Ubuntu Linux,\nwill add with CET (the \\verb|-fcf-protection| option) in the kernel by default.\nUsing that GCC to compile the kernel with retpoline off may result in CET being enabled in the kernel.\nYou can use the following command to check out the \\verb|-fcf-protection| option is enabled or not:\n\\begin{verbatim}\n$ gcc -v -Q -O2 --help=target | grep protection\nUsing built-in specs.\nCOLLECT_GCC=gcc\nCOLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper\n...\ngcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)\nCOLLECT_GCC_OPTIONS='-v' '-Q' '-O2' '--help=target' '-mtune=generic' '-march=x86-64'\n /usr/lib/gcc/x86_64-linux-gnu/9/cc1 -v ... -fcf-protection ...\n GNU C17 (Ubuntu 9.3.0-17ubuntu1~20.04) version 9.3.0 (x86_64-linux-gnu)\n...\n\\end{verbatim}\nBut CET should not be enabled in the kernel, it may break the Kprobes and bpf.\nConsequently, CET is disabled since v5.11.\nTo guarantee the manual symbol lookup worked, we only use up to v5.4.\n\nUnfortunately, since Linux v5.7 \\cpp|kallsyms_lookup_name| is also unexported, it needs certain trick to get the address of \\cpp|kallsyms_lookup_name|.\nIf \\cpp|CONFIG_KPROBES| is enabled, we can facilitate the retrieval of function addresses by means of Kprobes to dynamically break into the specific kernel routine.\nKprobes inserts a breakpoint at the entry of function by replacing the first bytes of the probed instruction.\nWhen a CPU hits the breakpoint, registers are stored, and the control will pass to Kprobes.\nIt passes the addresses of the saved registers and the Kprobe struct to the handler you defined, then executes it.\nKprobes can be registered by symbol name or address.\nWithin the symbol name, the address will be handled by the kernel.\n\nOtherwise, specify the address of \\cpp|sys_call_table| from \\verb|/proc/kallsyms| and \\verb|/boot/System.map| into \\cpp|sym| parameter.\nFollowing is the sample usage for \\verb|/proc/kallsyms|:\n\\begin{verbatim}\n$ sudo grep sys_call_table /proc/kallsyms\nffffffff82000280 R x32_sys_call_table\nffffffff820013a0 R sys_call_table\nffffffff820023e0 R ia32_sys_call_table\n$ sudo insmod syscall-steal.ko sym=0xffffffff820013a0\n\\end{verbatim}\n\nUsing the address from \\verb|/boot/System.map|, be careful about \\verb|KASLR| (Kernel Address Space Layout Randomization).\n\\verb|KASLR| may randomize the address of kernel code and data at every boot time, such as the static address listed in \\verb|/boot/System.map| will offset by some entropy.\nThe purpose of \\verb|KASLR| is to protect the kernel space from the attacker.\nWithout \\verb|KASLR|, the attacker may find the target address in the fixed address easily.\nThen the attacker can use return-oriented programming to insert some malicious codes to execute or receive the target data by a tampered pointer.\n\\verb|KASLR| mitigates these kinds of attacks because the attacker cannot immediately know the target address, but a brute-force attack can still work.\nIf the address of a symbol in \\verb|/proc/kallsyms| is different from the address in \\verb|/boot/System.map|, \\verb|KASLR| is enabled with the kernel, which your system running on.\n\\begin{verbatim}\n$ grep GRUB_CMDLINE_LINUX_DEFAULT /etc/default/grub\nGRUB_CMDLINE_LINUX_DEFAULT=\"quiet splash\"\n$ sudo grep sys_call_table /boot/System.map-$(uname -r)\nffffffff82000300 R sys_call_table\n$ sudo grep sys_call_table /proc/kallsyms\nffffffff820013a0 R sys_call_table\n# Reboot\n$ sudo grep sys_call_table /boot/System.map-$(uname -r)\nffffffff82000300 R sys_call_table\n$ sudo grep sys_call_table /proc/kallsyms\nffffffff86400300 R sys_call_table\n\\end{verbatim}\nIf \\verb|KASLR| is enabled, we have to take care of the address from \\verb|/proc/kallsyms| each time we reboot the machine.\nIn order to use the address from \\verb|/boot/System.map|, make sure that \\verb|KASLR| is disabled.\nYou can add the \\verb|nokaslr| for disabling \\verb|KASLR| in next booting time:\n\\begin{verbatim}\n$ grep GRUB_CMDLINE_LINUX_DEFAULT /etc/default/grub\nGRUB_CMDLINE_LINUX_DEFAULT=\"quiet splash\"\n$ sudo perl -i -pe 'm/quiet/ and s//quiet nokaslr/' /etc/default/grub\n$ grep quiet /etc/default/grub\nGRUB_CMDLINE_LINUX_DEFAULT=\"quiet nokaslr splash\"\n$ sudo update-grub\n\\end{verbatim}\n\nFor more information, check out the following:\n\n\\begin{itemize}\n  \\item \\href{https://lwn.net/Articles/804849/}{Cook: Security things in Linux v5.3}\n  \\item \\href{https://lwn.net/Articles/12211/}{Unexporting the system call table}\n  \\item \\href{https://lwn.net/Articles/810077/}{Control-flow integrity for the kernel}\n  \\item \\href{https://lwn.net/Articles/813350/}{Unexporting kallsyms\\_lookup\\_name()}\n  \\item \\href{https://www.kernel.org/doc/Documentation/kprobes.txt}{Kernel Probes (Kprobes)}\n  \\item \\href{https://lwn.net/Articles/569635/}{Kernel address space layout randomization}\n\\end{itemize}\n\nThe source code here is an example of such a kernel module.\nWe want to ``spy'' on a certain user, and to \\cpp|pr_info()| a message whenever that user opens a file.\nTowards this end, we replace the system call to open a file with our own function, called \\cpp|our_sys_openat|.\nThis function checks the uid (user's id) of the current process, and if it is equal to the uid we spy on, it calls \\cpp|pr_info()| to display the name of the file to be opened.\nThen, either way, it calls the original \\cpp|openat()| function with the same parameters, to actually open the file.\n\nThe \\cpp|init_module| function replaces the appropriate location in \\cpp|sys_call_table| and keeps the original pointer in a variable.\nThe \\cpp|cleanup_module| function uses that variable to restore everything back to normal.\nThis approach is dangerous, because of the possibility of two kernel modules changing the same system call.\nImagine we have two kernel modules, A and B. A's openat system call will be \\cpp|A_openat| and B's will be \\cpp|B_openat|.\nNow, when A is inserted into the kernel, the system call is replaced with \\cpp|A_openat|, which will call the original \\cpp|sys_openat| when it is done.\nNext, B is inserted into the kernel, which replaces the system call with \\cpp|B_openat|, which will call what it thinks is the original system call, \\cpp|A_openat|, when it's done.\n\nNow, if B is removed first, everything will be well --- it will simply restore the system call to \\cpp|A_openat|, which calls the original.\nHowever, if A is removed and then B is removed, the system will crash.\nA's removal will restore the system call to the original, \\cpp|sys_openat|, cutting B out of the loop.\nThen, when B is removed, it will restore the system call to what it thinks is the original, \\cpp|A_openat|, which is no longer in memory.\nAt first glance, it appears we could solve this particular problem by checking if the system call is equal to our open function and if so not changing it at all (so that B won't change the system call when it is removed), but that will cause an even worse problem.\nWhen A is removed, it sees that the system call was changed to \\cpp|B_openat| so that it is no longer pointing to \\cpp|A_openat|, so it will not restore it to \\cpp|sys_openat| before it is removed from memory.\nUnfortunately, \\cpp|B_openat| will still try to call \\cpp|A_openat| which is no longer there, so that even without removing B the system would crash.\n\nFor x86 architecture, the system call table cannot be used to invoke a system call after commit\n\\href{https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=1e3ad78334a69b36e107232e337f9d693dcc9df2}{1e3ad78} since v6.9.\nThis commit has been backported to long term stable kernels, like v5.15.154+, v6.1.85+, v6.6.26+ and v6.8.5+, see this \\href{https://stackoverflow.com/a/78607015}{answer} for more details.\nIn this case, thanks to Kprobes, a hook can be used instead on the system call entry to intercept the system call.\n\nNote that all the related problems make syscall stealing unfeasible for production use.\nIn order to keep people from doing potentially harmful things \\cpp|sys_call_table| is no longer exported.\nThis means, if you want to do something more than a mere dry run of this example, you will have to patch your current kernel in order to have \\cpp|sys_call_table| exported.\n\n\\samplec{examples/syscall-steal.c}\n\n\\section{Blocking Processes and threads}\n\\label{sec:blocking_process_thread}\n\\subsection{Sleep}\n\\label{sec:sleep}\nWhat do you do when somebody asks you for something you can not do right away?\nIf you are a human being and you are bothered by a human being, the only thing you can say is: \"\\emph{Not right now, I'm busy. Go away!}\".\nBut if you are a kernel module and you are bothered by a process, you have another possibility.\nYou can put the process to sleep until you can service it.\nAfter all, processes are being put to sleep by the kernel and woken up all the time (that is the way multiple processes appear to run on the same time on a single CPU).\n\nThis kernel module is an example of this.\nThe file (called \\verb|/proc/sleep|) can only be opened by a single process at a time.\nIf the file is already open, the kernel module calls \\cpp|wait_event_interruptible|.\nThe easiest way to keep a file open is to open it with:\n\n\\begin{codebash}\ntail -f\n\\end{codebash}\n\nThis function changes the status of the task (a task is the kernel data structure which holds information about a process and the system call it is in,\nif any) to \\cpp|TASK_INTERRUPTIBLE|, which means that the task will not run until it is woken up somehow, and adds it to WaitQ, the queue of tasks waiting to access the file.\nThen, the function calls the scheduler to context switch to a different process, one which has some use for the CPU.\n\nWhen a process is done with the file, it closes it, and \\cpp|module_close| is called.\nThat function wakes up all the processes in the queue (there's no mechanism to only wake up one of them).\nIt then returns and the process which just closed the file can continue to run.\nIn time, the scheduler decides that that process has had enough and gives control of the CPU to another process.\nEventually, one of the processes which was in the queue will be given control of the CPU by the scheduler.\nIt starts at the point right after the call to \\cpp|wait_event_interruptible|.\n\nThis means that the process is still in kernel mode - as far as the process is concerned, it issued the open system call and the system call has not returned yet.\nThe process does not know somebody else used the CPU for most of the time between the moment it issued the call and the moment it returned.\n\nIt can then proceed to set a global variable to tell all the other processes that the file is still open and go on with its life.\nWhen the other processes get a piece of the CPU, they'll see that global variable and go back to sleep.\n\nSo we will use \\sh|tail -f| to keep the file open in the background, and attempt to access it with another background process.\nThis way, we don't need to switch to another terminal window or virtual terminal to run the second process.\nAs soon as the first background process is killed with kill \\%1 , the second is woken up, is able to access the file and finally terminates.\n\nTo make our life more interesting, \\cpp|module_close| does not have a monopoly on waking up the processes which wait to access the file.\nA signal, such as \\emph{Ctrl +c} (\\textbf{SIGINT}) can also wake up a process. This is because we used \\cpp|wait_event_interruptible|.\nWe could have used \\cpp|wait_event| instead, but that would have resulted in extremely angry users whose \\emph{Ctrl+c}'s are ignored.\n\nIn that case, we want to return with \\cpp|-EINTR| immediately. This is important so users can, for example, kill the process before it receives the file.\n\nThere is one more point to remember. Some times processes don't want to sleep, they want either to get what they want immediately, or to be told it cannot be done.\nSuch processes use the \\cpp|O_NONBLOCK| flag when opening the file.\nThe kernel is supposed to respond by returning with the error code \\cpp|-EAGAIN| from operations which would otherwise block, such as opening the file in this example. The program \\sh|cat_nonblock|, available in the \\verb|examples/other| directory, can be used to open a file with \\cpp|O_NONBLOCK|.\n\n\\begin{verbatim}\n$ sudo insmod sleep.ko\n$ cat_nonblock /proc/sleep\nLast input:\n$ tail -f /proc/sleep &\nLast input:\nLast input:\nLast input:\nLast input:\nLast input:\nLast input:\nLast input:\ntail: /proc/sleep: file truncated\n[1] 6540\n$ cat_nonblock /proc/sleep\nOpen would block\n$ kill %1\n[1]+  Terminated              tail -f /proc/sleep\n$ cat_nonblock /proc/sleep\nLast input:\n$\n\\end{verbatim}\n\n\\samplec{examples/sleep.c}\n\n\\samplec{examples/other/cat_nonblock.c}\n\n\\subsection{Completions}\n\\label{sec:completion}\nSometimes one thing should happen before another within a module having multiple threads.\nRather than using \\sh|/bin/sleep| commands, the kernel has another way to do this which allows timeouts or interrupts to also happen.\n\nCompletions as code synchronization mechanism have three main parts, initialization of struct completion synchronization object, the waiting or barrier part through \\cpp|wait_for_completion()|, and the signalling side through a call to \\cpp|complete()|.\n\nIn the subsequent example, two threads are initiated: crank and flywheel.\nIt is imperative that the crank thread starts before the flywheel thread.\nA completion state is established for each of these threads, with a distinct completion defined for both the crank and flywheel threads.\nAt the exit point of each thread the respective completion state is updated, and \\cpp|wait_for_completion| is used by the flywheel thread to ensure that it does not begin prematurely.\nThe crank thread uses the \\cpp|complete_all()| function to update the completion, which lets the flywheel thread continue.\n\nSo even though \\cpp|flywheel_thread| is started first you should notice when you load this module and run \\sh|dmesg|, that turning the crank always happens first because the flywheel thread waits for the crank thread to complete.\n\nThere are other variations of the \\cpp|wait_for_completion| function, which include timeouts or being interrupted, but this basic mechanism is enough for many common situations without adding a lot of complexity.\n\n\\samplec{examples/completions.c}\n\n\\section{Synchronization}\n\\label{sec:synchronization}\nIf processes running on different CPUs or in different threads try to access the same memory, then it is possible that strange things can happen or your system can lock up.\nTo avoid this, various types of mutual exclusion kernel functions are available.\nThese indicate if a section of code is \"locked\" or \"unlocked\" so that simultaneous attempts to run it can not happen.\n\\subsection{Mutex}\n\\label{sec:mutex}\nYou can use kernel mutexes (mutual exclusions) in much the same manner that you might deploy them in userland.\nThis may be all that is needed to avoid collisions in most cases.\n\nMutexes in the Linux kernel enforce strict ownership: only the task that successfully acquired the mutex can release (or unlock) it.\nAttempting to release a mutex held by another task or releasing an unheld mutex multiple times by the same task typically leads to errors or undefined behavior.\nIf a task tries to lock a mutex it already holds, it may be blocked or sleep, where the task waits for itself to release the lock.\n\nBefore use, a mutex must be initialized through specific APIs (such as \\cpp|mutex_init| or by using the \\cpp|DEFINE_MUTEX| macro for compile-time initialization).\nAnd it is prohibited to directly modify the internal structure of a mutex using a memory manipulation function like \\cpp|memset|.\n\n\\samplec{examples/example_mutex.c}\n\nThe various suffixes appended to mutex functions in the Linux kernel primarily dictate how a task waiting to acquire a lock will behave,\nparticularly concerning its interruptibility.\n\nWhen a task calls \\cpp|mutex_lock()|, and if the mutex is currently unavailable,\nthe task enters a sleep state until it can successfully obtain the lock.\nDuring this period, the task cannot be interrupted.\nIn contrast, functions with the \\cpp|_interruptible| suffix, such as \\cpp|mutex_lock_interruptible()|,\nbehave similarly to \\cpp|mutex_lock()| but allow the waiting process to be interrupted by signals.\nIf a task receives a signal (like a termination signal) while waiting for the lock,\nit will exit the waiting state and return an error code (\\cpp|-EINTR|).\nThis is useful for applications that need to handle external events even while waiting for a lock.\n\nBeyond these fundamental locking behaviors, other mutex functions offer specialized capabilities.\nFunctions like \\cpp|mutex_lock_nested| and \\cpp|mutex_lock_interruptible_nested()| incorporate the \\cpp|__nested()| functionality,\nproviding support for nested locking.\nThis prior locking mechanism aids in managing lock acquisition and preventing deadlocks,\noften employing a subclass parameter for more precise deadlock detection.\nThe latter variant combines nested locking with the ability for the waiting process to be interrupted by signals.\nAnother function is \\cpp|mutex_trylock()|, which attempts to acquire the mutex without blocking.\nIt returns 1 if the lock is successfully acquired and 0 if the mutex is already held by another task.\n\nDespite the fact that \\cpp|mutex_trylock| does not sleep,\nit is still generally not safe for use in interrupt context because its implementation isn't atomic.\nIf an interrupt occurs between checking the lock's availability and its acquisition,\nthis can lead to race conditions and potential data corruption.\n\n\\subsection{Spinlocks}\n\\label{sec:spinlock}\nAs the name suggests, spinlocks lock up the CPU that the code is running on, taking 100\\% of its resources.\nBecause of this you should only use the spinlock mechanism around code which is likely to take no more than a few milliseconds to run and so will not noticeably slow anything down from the user's point of view.\n\nThe example here is \\verb|\"irq safe\"| in that if interrupts happen during the lock then they will not be forgotten and will activate when the unlock happens, using the \\cpp|flags| variable to retain their state.\n\n\\samplec{examples/example_spinlock.c}\n\nTaking 100\\% of a CPU's resources comes with greater responsibility.\nSituations where the kernel code monopolizes a CPU are called \\textbf{atomic contexts}.\nHolding a spinlock is one of those situations.\nSleeping in atomic contexts may leave the system hanging, as the occupied CPU devotes 100\\% of its resources doing nothing but sleeping.\nIn some worse cases the system may crash.\nThus, sleeping in atomic contexts is considered a bug in the kernel.\nThey are sometimes called ``sleep-in-atomic-context'' in some materials.\n\nNote that sleeping here is not limited to calling the sleep functions explicitly.\nIf subsequent function calls eventually invoke a function that sleeps, it is also considered sleeping.\nThus, it is important to pay attention to functions being used in atomic context.\nThere's no documentation recording all such functions, but code comments may help.\nSometimes you may find comments in kernel source code stating that a function ``may sleep'', ``might sleep'', or more explicitly ``the caller should not hold a spinlock''.\nThose comments are hints that a function may implicitly sleep and must not be called in atomic contexts.\n\nNow, let's differentiate between a few types of spinlock functions in the Linux kernel: \\cpp|spin_lock()|, \\cpp|spin_lock_irq()|, \\cpp|spin_lock_irqsave()|, and \\cpp|spin_lock_bh()|.\n\n\\cpp|spin_lock()| does not allow the CPU to sleep while waiting for the lock, which makes it suitable for most use cases where the critical section is short.\nHowever, this is problematic for real-time Linux because spinlocks in this configuration behave as sleeping locks.\nThis can prevent other tasks from running and cause the system to become unresponsive.\nTo address this in real-time Linux environments, a \\cpp|raw_spin_lock()| is used, which behaves similarly to a \\cpp|spin_lock()| but without causing the system to sleep.\n\nOn the other hand, \\cpp|spin_lock_irq()| disables interrupts while holding the lock, but it does not save the interrupt state.\nThis means that if an interrupt occurs while the lock is held, the interrupt state could be lost.\nIn contrast, \\cpp|spin_lock_irqsave()| disables interrupts and also saves the interrupt state, ensuring that interrupts are restored to their previous state when the lock is released.\nThis makes \\cpp|spin_lock_irqsave()| a safer option in scenarios where preserving the interrupt state is crucial.\n\nNext, \\cpp|spin_lock_bh()| disables \\textbf{softirqs} (software interrupts) but allows hardware interrupts to continue.\nUnlike \\cpp|spin_lock_irq()| and \\cpp|spin_lock_irqsave()|, which disable both hardware and software interrupts, \\cpp|spin_lock_bh()| is useful when hardware interrupts need to remain active.\n\nFor more information about spinlock usage and lock types, see the following resources:\n\\begin{itemize}\n  \\item \\href{https://www.kernel.org/doc/Documentation/locking/spinlocks.txt}{Lesson 1: Spin locks}\n  \\item \\href{https://docs.kernel.org/locking/locktypes.html}{Lock types and their rules}\n\\end{itemize}\n\n\\subsection{Read and write locks}\n\\label{sec:rwlock}\nRead and write locks are specialised kinds of spinlocks so that you can exclusively read from something or write to something.\nLike the earlier spinlocks example, the one below shows an \"irq safe\" situation in which if other functions were triggered from irqs which might also read and write to whatever you are concerned with then they would not disrupt the logic.\nAs before it is a good idea to keep anything done within the lock as short as possible so that it does not hang up the system and cause users to start revolting against the tyranny of your module.\n\n\\samplec{examples/example_rwlock.c}\n\nOf course, if you know for sure that there are no functions triggered by irqs which could possibly interfere with your logic then you can use the simpler \\cpp|read_lock(&myrwlock)| and \\cpp|read_unlock(&myrwlock)| or the corresponding write functions.\n\\subsection{Atomic operations}\n\\label{sec:atomics}\nIf you are doing simple arithmetic: adding, subtracting or bitwise operations, then there is another way in the multi-CPU and multi-hyperthreaded world to stop other parts of the system from messing with your mojo.\nBy using atomic operations you can be confident that your addition, subtraction or bit flip did actually happen and was not overwritten by some other shenanigans.\nAn example is shown below.\n\n\\samplec{examples/example_atomic.c}\n\nBefore the C11 standard adopted the built-in atomic types, the kernel already provided a small set of atomic types by using a bunch of tricky architecture-specific codes.\nImplementing the atomic types by C11 atomics may allow the kernel to throw away the architecture-specific codes and make the kernel code be more friendly to the people who understand the standard.\nBut there are some problems, such as the memory model of the kernel doesn't match the model formed by the C11 atomics.\nFor further details, see:\n\\begin{itemize}\n  \\item \\href{https://www.kernel.org/doc/Documentation/atomic_t.txt}{kernel documentation of atomic types}\n  \\item \\href{https://lwn.net/Articles/691128/}{Time to move to C11 atomics?}\n  \\item \\href{https://lwn.net/Articles/698315/}{Atomic usage patterns in the kernel}\n\\end{itemize}\n\n% FIXME: we should rewrite this section\n\\section{Replacing Print Macros}\n\\label{sec:print_macros}\n\\subsection{Replacement}\n% FIXME: cross-reference\nIn \\Cref{sec:preparation}, it was noted that the X Window System and kernel module programming are not conducive to integration.\nThis remains valid during the development of kernel modules.\nHowever, in practical scenarios, the necessity emerges to relay messages to the tty (teletype) originating the module load command.\n\nThe term ``tty'' originates from \\emph{teletype}, which initially referred to a combined keyboard-printer for Unix system communication.\nToday, it signifies a text stream abstraction employed by Unix programs, encompassing physical terminals,\nxterms in X displays, and network connections like SSH.\n\nTo achieve this, the ``current'' pointer is leveraged to access the active task's tty structure.\nWithin this structure lies a pointer to a string write function, facilitating the string's transmission to the tty.\n\n\\samplec{examples/print_string.c}\n\n\\subsection{Flashing keyboard LEDs}\n\\label{sec:flash_kb_led}\nIn certain conditions, you may desire a simpler and more direct way to communicate to the external world.\nFlashing keyboard LEDs can be such a solution: It is an immediate way to attract attention or to display a status condition.\nKeyboard LEDs are present on every hardware, they are always visible, they do not need any setup, and their use is rather simple and non-intrusive, compared to writing to a tty or a file.\n\nFrom v4.14 to v4.15, the timer API made a series of changes to improve memory safety.\nA buffer overflow in the area of a \\cpp|timer_list| structure may be able to overwrite the \\cpp|function| and \\cpp|data| fields, providing the attacker with a way to use return-oriented programming (ROP) to call arbitrary functions within the kernel.\nAlso, the function prototype of the callback, containing an \\cpp|unsigned long| argument, will prevent the compiler from performing type checking.\nFurthermore, the function prototype with \\cpp|unsigned long| argument may be an obstacle to the forward-edge protection of \\textit{control-flow integrity}.\nThus, it is better to use a unique prototype to separate from the cluster that takes an \\cpp|unsigned long| argument.\nThe timer callback should be passed a pointer to the \\cpp|timer_list| structure rather than an \\cpp|unsigned long| argument.\nThen, it wraps all the information the callback needs, including the \\cpp|timer_list| structure, into a larger structure, and it can use the \\cpp|container_of| macro instead of the \\cpp|unsigned long| value.\nFor more information, see: \\href{https://lwn.net/Articles/735887/}{Improving the kernel timers API}.\n\nBefore Linux v4.14, \\cpp|setup_timer| was used to initialize the timer and the \\cpp|timer_list| structure looked like:\n\\begin{code}\nstruct timer_list {\n    unsigned long expires;\n    void (*function)(unsigned long);\n    unsigned long data;\n    u32 flags;\n    /* ... */\n};\n\nvoid setup_timer(struct timer_list *timer, void (*callback)(unsigned long),\n                 unsigned long data);\n\\end{code}\n\nSince Linux v4.14, \\cpp|timer_setup| is adopted and the kernel step by step converting to \\cpp|timer_setup| from \\cpp|setup_timer|.\nOne of the reasons why the API was changed is that it needed to coexist with the old version of the interface.\nMoreover, the \\cpp|timer_setup| was implemented by \\cpp|setup_timer| at first.\n\\begin{code}\nvoid timer_setup(struct timer_list *timer,\n                 void (*callback)(struct timer_list *), unsigned int flags);\n\\end{code}\n\nThe \\cpp|setup_timer| was then removed since v4.15.\nAs a result, the \\cpp|timer_list| structure had changed to the following.\n\\begin{code}\nstruct timer_list {\n    unsigned long expires;\n    void (*function)(struct timer_list *);\n    u32 flags;\n    /* ... */\n};\n\\end{code}\n\nThe following source code illustrates a minimal kernel module which, when loaded, starts blinking the keyboard LEDs until it is unloaded.\n\n\\samplec{examples/kbleds.c}\n\nIf none of the examples in this chapter fit your debugging needs, there might yet be some other tricks to try.\nEver wondered what \\cpp|CONFIG_LL_DEBUG| in \\sh|make menuconfig| is good for?\nIf you activate that you get low level access to the serial port.\nWhile this might not sound very powerful by itself, you can patch \\src{kernel/printk.c} or any other essential syscall to print ASCII characters, thus making it possible to trace virtually everything what your code does over a serial line.\nIf you find yourself porting the kernel to some new and former unsupported architecture, this is usually amongst the first things that should be implemented.\nLogging over a netconsole might also be worth a try.\n\nWhile you have seen lots of stuff that can be used to aid debugging here, there are some things to be aware of. Debugging is almost always intrusive.\nAdding debug code can change the situation enough to make the bug seem to disappear.\nThus, you should keep debug code to a minimum and make sure it does not show up in production code.\n\n\\section{GPIO}\n\\label{sec:gpio}\n\\subsection{GPIO}\n\\label{sec:gpio_introduction}\nGeneral Purpose Input/Output (GPIO) appears on the development board as pins.\nIt acts as a bridge for communication between the development board and external devices.\nYou can think of it like a switch: users can turn it on or off (Input), and the development board can also turn it on or off (Output).\n\nTo implement a GPIO device driver, you use the \\cpp|gpio_request()| function to enable a specific GPIO pin.\nAfter successfully enabling it, you can check that the pin is being used by looking at /sys/kernel/debug/gpio.\n\n\\begin{codebash}\ncat /sys/kernel/debug/gpio\n\\end{codebash}\n\nThere are other ways to register GPIOs.\nFor example, you can use \\cpp|gpio_request_one()| to register a GPIO while setting its direction (input or output) and initial state at the same time.\nYou can also use \\cpp|gpio_request_array()| to register multiple GPIOs at once. However, note that \\cpp|gpio_request_array()| has been removed since Linux v6.10.\n\nWhen using GPIO, you must set it as either output with \\cpp|gpio_direction_output()| or input with \\cpp|gpio_direction_input()|.\n\n\\begin{itemize}\n  \\item when the GPIO is set as output, you can use \\cpp|gpio_set_value()| to choose to set it to high voltage or low voltage.\n  \\item when the GPIO is set as input, you can use \\cpp|gpio_get_value()| to read whether the voltage is high or low.\n\\end{itemize}\n\n\\subsection{Control the LED's on/off state}\n\\label{sec:gpio_led}\nIn \\Cref{sec:device_files}, we learned how to communicate with device files.\nTherefore, we will further use device files to control the LED on and off.\n\nIn the implementation, a pull-down resistor is used.\nThe anode of the LED is connected to GPIO4, and the cathode is connected to GND.\nFor more details about the Raspberry Pi pin assignments, refer to \\href{https://pinout.xyz/}{Raspberry Pi Pinout}.\nThe materials used include a Raspberry Pi 5, an LED, jumper wires, and a 220$\\Omega$ resistor.\n\n\\samplec{examples/led.c}\n\nMake and install the module:\n\\begin{codebash}\nmake\nsudo insmod led.ko\n\\end{codebash}\n\nSwitch on the LED:\n\\begin{codebash}\necho \"1\" | sudo tee /dev/gpio_led\n\\end{codebash}\n\nSwitch off the LED:\n\\begin{codebash}\necho \"0\" | sudo tee /dev/gpio_led\n\\end{codebash}\n\nFinally, remove the module:\n\\begin{codebash}\nsudo rmmod led\n\\end{codebash}\n\n\\subsection{DHT11 sensor}\n\\label{sec:gpio_dht11}\nThe DHT11 sensor is a well-known entry-level sensor commonly used to measure humidity and temperature.\nIn this subsection, we will use GPIO to communicate through a single data line.\nThe DHT11 communication protocol can be referred to in the \\href{https://www.mouser.com/datasheet/2/758/DHT11-Technical-Data-Sheet-Translated-Version-1143054.pdf?srsltid=AfmBOoppls-QTd864640bVtbK90sWBsFzJ_7SgjOD2EpwuLLGUSTyYnv}{datasheet}.\n\nIn the implementation, the data pin of the DHT11 sensor is connected to GPIO4 on the Raspberry Pi.\nThe sensor's VCC and GND pins are connected to 3.3V and GND, respectively.\nFor more details about the Raspberry Pi pin assignments, refer to \\href{https://pinout.xyz/}{Raspberry Pi Pinout}.\nThe materials used include a Raspberry Pi 5, a DHT11 sensor, and jumper wires.\n\n\\samplec{examples/dht11.c}\nMake and install the module:\n\\begin{codebash}\nmake\nsudo insmod dht11.ko\n\\end{codebash}\n\nCheck the Output of the DHT11 Sensor:\n\\begin{codebash}\nsudo cat /dev/dht11\n\\end{codebash}\n\nExpected Output:\n\\begin{verbatim}\n$ sudo cat /dev/dht11\nHumidity: 61%\nTemperature: 30°C\n\\end{verbatim}\n\nFinally, remove the module:\n\\begin{codebash}\nsudo rmmod dht11\n\\end{codebash}\n\n\\section{Scheduling Tasks}\n\\label{sec:scheduling_tasks}\nThere are two main ways of running tasks: tasklets and work queues.\nTasklets are a quick and easy way of scheduling a single function to be run.\nFor example, when triggered from an interrupt,\nwhereas work queues are more complicated but also better suited to running multiple things in a sequence.\n\nIt is possible that in future tasklets may be replaced by \\textit{threaded IRQs}.\nHowever, discussion about that has been ongoing since 2007 (\\href{https://lwn.net/Articles/239633}{Eliminating tasklets} and \\href{https://lwn.net/Articles/960041/}{The end of tasklets}),\nso expecting immediate changes would be unwise.\nSee the \\Cref{sec:irq} for alternatives that avoid the tasklet debate.\n\n\\subsection{Tasklets}\n\\label{sec:tasklet}\nHere is an example tasklet module.\nThe \\cpp|tasklet_fn| function runs for a few seconds.\nIn the meantime, execution of the \\cpp|example_tasklet_init| function may continue to the exit point,\ndepending on whether it is interrupted by \\textbf{softirq}.\n\n\\samplec{examples/example_tasklet.c}\n\nSo with this example loaded \\sh|dmesg| should show:\n\n\\begin{verbatim}\ntasklet example init\nExample tasklet starts\nExample tasklet init continues...\nExample tasklet ends\n\\end{verbatim}\nAlthough tasklet is easy to use, it comes with several drawbacks, and developers have been discussing their removal from the Linux kernel.\nThe tasklet callback runs in atomic context, inside a software interrupt, meaning that it cannot sleep or access user-space data, so not all work can be done in a tasklet handler.\nAlso, the kernel only allows one instance of any given tasklet to be running at any given time; multiple different tasklet callbacks can run in parallel.\n\nIn recent kernels, tasklets can be replaced by workqueues, timers, or threaded interrupts.\n\\footnote{\nThe goal of threaded interrupts is to push more of the work to separate threads,\nso that the minimum needed for acknowledging an interrupt is reduced,\nand therefore the time spent handling the interrupt (where it can't handle any other interrupts at the same time) is reduced.\nSee \\url{https://lwn.net/Articles/302043/}.\n}\nWhile the removal of tasklets remains a longer-term goal, the current kernel contains more than a hundred uses of tasklets.\nNow developers are proceeding with the API changes and the macro \\cpp|DECLARE_TASKLET_OLD| exists for compatibility.\nFor further information, see \\url{https://lwn.net/Articles/830964/}.\n\n\\subsection{Work queues}\n\\label{sec:workqueue}\nTo add a task to the scheduler we can use a workqueue.\nThe kernel then uses the Completely Fair Scheduler (CFS) to execute work within the queue.\n\n\\samplec{examples/sched.c}\n\n\\section{Interrupt Handlers}\n\\label{sec:interrupt_handler}\n\\subsection{Interrupt Handlers}\n\\label{sec:irq}\nExcept for the last chapter, everything we did in the kernel so far we have done as a response to a process asking for it, either by dealing with a special file, sending an \\cpp|ioctl()|, or issuing a system call.\nBut the job of the kernel is not just to respond to process requests.\nAnother job, which is every bit as important, is to speak to the hardware connected to the machine.\n\nThere are two types of interaction between the CPU and the rest of the computer's hardware.\nThe first type is when the CPU gives orders to the hardware, the other is when the hardware needs to tell the CPU something.\nThe second, called interrupts, is much harder to implement because it has to be dealt with when convenient for the hardware, not the CPU.\nHardware devices typically have a very small amount of RAM, and if you do not read their information when available, it is lost.\n\nUnder Linux, hardware interrupts are called IRQs (Interrupt ReQuests).\nThere are two types of IRQs, short and long.\nA short IRQ is one which is expected to take a very short period of time, during which the rest of the machine will be blocked and no other interrupts will be handled.\nA long IRQ is one which can take longer, and during which other interrupts may occur (but not interrupts from the same device).\nIf at all possible, it is better to declare an interrupt handler to be long.\n\nWhen the CPU receives an interrupt, it stops whatever it is doing (unless it is processing a more important interrupt, in which case it will deal with this one only when the more important one is done),\nsaves certain parameters on the stack and calls the interrupt handler.\nThis means that certain things are not allowed in the interrupt handler itself, because the system is in an unknown state.\n% TODO: add some diagrams\nLinux kernel solves the problem by splitting interrupt handling into two parts.\nThe first part executes right away and masks the interrupt line.\nHardware interrupts must be handled quickly, and that is why we need the second part to handle the heavy work deferred from an interrupt handler.\nHistorically, BH (Linux naming for \\textit{Bottom Halves}) statistically book-keeps the deferred functions.\n\\textbf{Softirq} and its higher level abstraction, \\textbf{Tasklet}, replace BH since Linux 2.3.\n\nThe way to implement this is to call \\cpp|request_irq()| to get your interrupt handler called when the relevant IRQ is received.\n\nIn practice IRQ handling can be a bit more complex.\nHardware is often designed in a way that chains two interrupt controllers, so that all the IRQs from interrupt controller B are cascaded to a certain IRQ from interrupt controller A.\nOf course, that requires that the kernel finds out which IRQ it really was afterwards and that adds overhead. Other architectures offer some special, very low overhead, so called \"fast IRQ\" or FIQs.\nTo take advantage of them requires handlers to be written in assembly language, so they do not really fit into the kernel.\nThey can be made to work similar to the others, but after that procedure, they are no longer any faster than \"common\" IRQs.\nSMP enabled kernels running on systems with more than one processor need to solve another truckload of problems.\nIt is not enough to know if a certain IRQs has happened, it's also important to know what CPU(s) it was for.\nPeople still interested in more details, might want to refer to \"APIC\" now.\n\nThis function receives the IRQ number, the name of the function, flags, a name for \\verb|/proc/interrupts| and a parameter to be passed to the interrupt handler.\nUsually there is a certain number of IRQs available.\nHow many IRQs there are is hardware-dependent.\n\nThe flags can be used to specify behaviors of the IRQ.\nFor example, use \\cpp|IRQF_SHARED| to indicate you are willing to share the IRQ with other interrupt handlers (usually because a number of hardware devices sit on the same IRQ); use the \\cpp|IRQF_ONESHOT| to indicate that the IRQ is not reenabled after the handler finished.\nIt should be noted that in some materials, you may encounter another set of IRQ flags named with the \\cpp|SA| prefix.\nFor example, the \\cpp|SA_SHIRQ| and the \\cpp|SA_INTERRUPT|.\nThose are the IRQ flags in the older kernels.\nThey have been removed completely.\nToday only the \\cpp|IRQF| flags are in use.\nThis function will only succeed if there is not already a handler on this IRQ, or if you are both willing to share.\n\n\\subsection{Detecting button presses}\n\\label{sec:detect_button}\nMany popular single board computers, such as Raspberry Pi or Beagleboards, have a bunch of GPIO pins.\nAttaching buttons to those and then having a button press do something is a classic case in which you might need to use interrupts,\nso that instead of having the CPU waste time and battery power polling for a change in input state, it is better for the input to trigger the CPU to then run a particular handling function.\n\nHere is an example where buttons are connected to GPIO numbers 17 and 18 and an LED is connected to GPIO 4.\nYou can change those numbers to whatever is appropriate for your board.\n\n\\samplec{examples/intrpt.c}\n\n\\subsection{Bottom Half}\n\\label{sec:bottom_half}\nSuppose you want to do a bunch of stuff inside of an interrupt routine.\nA common way to avoid blocking the interrupt for a significant duration\nis to defer the time-consuming part to a workqueue.\nThis pushes the bulk of the work off into the scheduler.\nThis approach helps speed up the interrupt handling process itself,\nallowing the system to respond to the next hardware interrupt more quickly.\n\nKernel developers generally discourage using tasklets due to their design limitations,\nsuch as memory management issues and unpredictable latencies.\nInstead, they recommend more robust mechanisms like workqueues or \\textbf{softirqs}.\nTo address tasklet shortcomings, Linux contributors introduced the BH workqueue,\nactivated with the \\cpp|WQ_BH| flag.\nThis workqueue retains critical features,\nsuch as execution in atomic (\\textbf{softirq}) context on the same CPU and the inability to sleep.\n\nThe example below extends the previous code to include an additional task executed in process context when an interrupt is triggered.\n\\samplec{examples/bottomhalf.c}\n\n\\subsection{Threaded IRQ}\n\\label{sec:threaded_irq}\nThreaded IRQ is a mechanism to organize both top-half and bottom-half of an IRQ at once.\nA threaded IRQ splits the one handler in \\cpp|request_irq()| into two: one for the top-half, the other for the bottom-half.\nThe \\cpp|request_threaded_irq()| is the function for using threaded IRQs.\nTwo handlers are registered at once in the \\cpp|request_threaded_irq()|.\n\nThose two handlers run in different context.\nThe top-half handler runs in interrupt context.\nIt's the equivalence of the handler passed to the \\cpp|request_irq()|.\nThe bottom-half handler on the other hand runs in its own thread.\nThis thread is created on registration of a threaded IRQ.\nIts sole purpose is to run this bottom-half handler.\nThis is where a threaded IRQ is ``threaded''.\nIf \\cpp|IRQ_WAKE_THREAD| is returned by the top-half handler, that bottom-half serving thread will wake up.\nThe thread then runs the bottom-half handler.\n\nHere is an example of how to do the same thing as before, with top and bottom halves, but using threads.\n\n\\samplec{examples/bh_threaded.c}\n\nA threaded IRQ is registered using \\cpp|request_threaded_irq()|.\nThis function only takes one additional parameter than the \\cpp|request_irq()| -- the bottom-half handling function that runs in its own thread.\nIn this example it is the \\cpp|button_bottom_half()|.\nUsage of other parameters are the same as \\cpp|request_irq()|.\n\nPresence of both handlers is not mandatory.\nIf either of them is not needed, pass the \\cpp|NULL| instead.\nA \\cpp|NULL| top-half handler implies that no action is taken except to wake up the bottom-half serving thread, which runs the bottom-half handler.\nSimilarly, a \\cpp|NULL| bottom-half handler effectively acts as if \\cpp|request_irq()| were used.\nIn fact, this is how \\cpp|request_irq()| is implemented.\n\nNote that passing \\cpp|NULL| to both handlers is considered an error and will make registration fail.\n\n\\section{Virtual Input Device Driver}\n\\label{sec:vinput}\nThe input device driver is a module that provides a way to communicate with the interaction device via the event.\nFor example, the keyboard can send the press or release event to tell the kernel what we want to do.\nThe input device driver will allocate a new input structure with \\cpp|input_allocate_device()| and sets up input bitfields, device id, version, etc.\nAfter that, registers it by calling \\cpp|input_register_device()|.\n\nHere is an example, vinput,\nIt is an API to allow easy development of virtual input drivers.\nThe driver needs to export a \\cpp|vinput_device()| that contains the virtual device name and \\cpp|vinput_ops| structure that describes:\n\n\\begin{itemize}\n  \\item the init function: \\cpp|init()|\n  \\item the input event injection function: \\cpp|send()|\n  \\item the readback function: \\cpp|read()|\n\\end{itemize}\n\nThen using \\cpp|vinput_register_device()| and \\cpp|vinput_unregister_device()| will add a new device to the list of support virtual input devices.\n\n\\begin{code}\nint init(struct vinput *);\n\\end{code}\n\nThis function is passed a \\cpp|struct vinput| already initialized with an allocated \\cpp|struct input_dev|.\nThe \\cpp|init()| function is responsible for initializing the capabilities of the input device and register it.\n\n\\begin{code}\nint send(struct vinput *, char *, int);\n\\end{code}\n\nThis function will receive a user string to interpret and inject the event using the \\cpp|input_report_XXXX| or \\cpp|input_event| call.\nThe string is already copied from user.\n\n\\begin{code}\nint read(struct vinput *, char *, int);\n\\end{code}\n\nThis function is used for debugging and should fill the buffer parameter with the last event sent in the virtual input device format.\nThe buffer will then be copied to user.\n\nvinput devices are created and destroyed using sysfs.\nAnd, event injection is done through a \\verb|/dev| node.\nThe device name will be used by the userland to export a new virtual input device.\n\nThe \\cpp|class_attribute| structure is similar to other attribute types we talked about in \\Cref{sec:sysfs}:\n\n\\begin{code}\nstruct class_attribute {\n    struct attribute attr;\n    ssize_t (*show)(struct class *class, struct class_attribute *attr,\n                    char *buf);\n    ssize_t (*store)(struct class *class, struct class_attribute *attr,\n                    const char *buf, size_t count);\n};\n\\end{code}\n\nIn \\verb|vinput.c|, the macro \\cpp|CLASS_ATTR_WO(export/unexport)| defined in \\src{include/linux/device.h} (in this case, \\verb|device.h| is included in \\src{include/linux/input.h}) will generate the \\cpp|class_attribute| structures which are named \\verb|class_attr_export/unexport|.\nThen, put them into \\cpp|vinput_class_attrs| array and the macro \\cpp|ATTRIBUTE_GROUPS(vinput_class)| will generate the \\cpp|struct attribute_group vinput_class_group| that should be assigned in \\cpp|vinput_class|.\nFinally, call \\cpp|class_register(&vinput_class)| to create attributes in sysfs.\n\nTo create a \\verb|vinputX| sysfs entry and \\verb|/dev| node.\n\n\\begin{codebash}\necho \"vkbd\" | sudo tee /sys/class/vinput/export\n\\end{codebash}\n\nTo unexport the device, just echo its id in unexport:\n\n\\begin{codebash}\necho \"0\" | sudo tee /sys/class/vinput/unexport\n\\end{codebash}\n\n\\samplec{examples/vinput.h}\n\\samplec{examples/vinput.c}\n\nHere the virtual keyboard is one of example to use vinput.\nIt supports all \\cpp|KEY_MAX| keycodes.\nThe injection format is the \\cpp|KEY_CODE| such as defined in \\src{include/linux/input.h}.\nA positive value means \\cpp|KEY_PRESS| while a negative value is a \\cpp|KEY_RELEASE|.\nThe keyboard supports repetition when the key stays pressed for too long.\nThe following demonstrates how simulation work.\n\nSimulate a key press on \"g\" (\\cpp|KEY_G| = 34):\n\n\\begin{codebash}\necho \"+34\" | sudo tee /dev/vinput0\n\\end{codebash}\n\nSimulate a key release on \"g\" (\\cpp|KEY_G| = 34):\n\n\\begin{codebash}\necho \"-34\" | sudo tee /dev/vinput0\n\\end{codebash}\n\n\\samplec{examples/vkbd.c}\n\n% TODO: Add vts.c and vmouse.c example\n\n\\section{Standardizing the interfaces: The Device Model}\n\\label{sec:device_model}\nUp to this point we have seen all kinds of modules doing all kinds of things, but there was no consistency in their interfaces with the rest of the kernel.\nTo impose some consistency such that there is at minimum a standardized way to start, suspend and resume a device model was added.\nAn example is shown below, and you can use this as a template to add your own suspend, resume or other interface functions.\n\n\\samplec{examples/devicemodel.c}\n\n\\section{Device Tree}\n\\label{sec:device_tree}\n\\subsection{Introduction to Device Tree}\n\\label{sec:dt_intro}\nDevice Tree is a data structure that describes hardware components in a system, particularly in embedded systems and ARM-based platforms.\nInstead of hard-coding hardware details in the kernel source, Device Tree provides a separate, human-readable description that the kernel can parse at boot time.\nThis separation allows the same kernel binary to support multiple hardware platforms,\nmaking development and maintenance significantly easier.\n\nDevice Tree files (with \\verb|.dts| extension for source files and \\verb|.dtb| for compiled binary files) use a hierarchical structure similar to a filesystem to represent the hardware topology.\nEach hardware component is represented as a node with properties that describe its characteristics,\nsuch as memory addresses, interrupt numbers, and device-specific parameters.\n\n\\subsection{Device Tree and Kernel Modules}\n\\label{sec:dt_modules}\nWhile Device Tree is primarily used during kernel initialization, kernel modules can also interact with Device Tree nodes through the platform device framework.\nWhen the kernel parses the Device Tree at boot, it creates platform devices for nodes that have compatible strings.\nKernel modules can then register platform drivers that match these compatible strings, allowing them to be automatically probed when the corresponding hardware is detected.\n\nThe key concepts for Device Tree interaction in kernel modules include:\n\\begin{itemize}\n  \\item \\textbf{Compatible strings}: Unique identifiers that match Device Tree nodes to their drivers\n  \\item \\textbf{Property reading}: Functions to extract configuration data from Device Tree nodes\n  \\item \\textbf{Platform driver framework}: Infrastructure for binding drivers to devices described in Device Tree\n  \\item \\textbf{Device-specific data}: Custom properties that can be defined for specific hardware\n\\end{itemize}\n\n\\subsection{Example: Device Tree Module}\n\\label{sec:dt_example}\nThe following example demonstrates how a kernel module can interact with Device Tree nodes.\nThis module registers a platform driver that matches specific compatible strings and extracts properties from the matched Device Tree nodes.\n\n\\samplec{examples/devicetree.c}\n\n\\subsection{Device Tree Source Example}\n\\label{sec:dt_source}\nTo use the above module, you would need a Device Tree entry like this:\n\n\\begin{code}\n/* Example device tree fragment */\nlkmpg_device@0 {\n    compatible = \"lkmpg,example-device\";\n    reg = <0x40000000 0x1000>;\n    label = \"LKMPG Test Device\";\n    lkmpg,custom-value = <100>;\n    lkmpg,has-clock;\n};\n\\end{code}\n\nThe properties in this Device Tree node would be read by the module's probe function when the device is matched.\nThe \\verb|compatible| property is used to match the device with the driver, while other properties provide device-specific configuration.\n\n\\subsection{Testing Device Tree Modules}\n\\label{sec:dt_testing}\nTesting Device Tree modules can be done in several ways:\n\n\\begin{enumerate}\n  \\item \\textbf{Using Device Tree overlays}: On systems that support it (like Raspberry Pi), you can load Device Tree overlays at runtime to add new devices without rebooting.\n\n  \\item \\textbf{Modifying the main Device Tree}: Add your device nodes to the system's main Device Tree source file and recompile it.\n\n  \\item \\textbf{Using QEMU}: For development and testing, QEMU can emulate systems with custom Device Trees, allowing you to test your modules without physical hardware.\n\\end{enumerate}\n\nTo check if your device was properly detected, you can examine the sysfs filesystem:\n\n\\begin{codebash}\n# List all platform devices\nls /sys/bus/platform/devices/\n\n# Check device tree nodes\nls /proc/device-tree/\n\\end{codebash}\n\n\\subsection{Common Device Tree Functions}\n\\label{sec:dt_functions}\nHere are some commonly used Device Tree functions in kernel modules:\n\n\\begin{itemize}\n  \\item \\cpp|of_property_read_string()| - Read a string property\n  \\item \\cpp|of_property_read_u32()| - Read a 32-bit integer property\n  \\item \\cpp|of_property_read_bool()| - Check if a boolean property exists\n  \\item \\cpp|of_find_property()| - Find a property by name\n  \\item \\cpp|of_get_property()| - Get a property's raw value\n  \\item \\cpp|of_match_device()| - Match a device against a match table\n  \\item \\cpp|of_parse_phandle()| - Parse a phandle reference to another node\n\\end{itemize}\n\nThese functions provide a robust interface for extracting configuration data from Device Tree nodes,\nallowing modules to be highly configurable without code changes.\n\n\\section{Optimizations}\n\\label{sec:optimization}\n\\subsection{Likely and Unlikely conditions}\n\\label{sec:likely_unlikely}\nSometimes you might want your code to run as quickly as possible, especially if it is handling an interrupt or doing something which might cause noticeable latency.\nIf your code contains boolean conditions and if you know that the conditions are almost always likely to evaluate as either \\cpp|true| or \\cpp|false|,\nthen you can allow the compiler to optimize for this using the \\cpp|likely| and \\cpp|unlikely| macros.\nFor example, when allocating memory you are almost always expecting this to succeed.\n\n\\begin{code}\nbvl = bvec_alloc(gfp_mask, nr_iovecs, &idx);\nif (unlikely(!bvl)) {\n    mempool_free(bio, bio_pool);\n    bio = NULL;\n    goto out;\n}\n\\end{code}\n\nWhen the \\cpp|unlikely| macro is used, the compiler alters its machine instruction output, so that it continues along the false branch and only jumps if the condition is true.\nThat avoids flushing the processor pipeline.\nThe opposite happens if you use the \\cpp|likely| macro.\n\n\\subsection{Static keys}\n\\label{sec:static_keys}\nStatic keys allow us to enable or disable kernel code paths based on the runtime state of a key.\nTheir APIs have been available since 2010 (most architectures are already supported) and use self-modifying code to eliminate the overhead of cache and branch prediction.\nThe most typical use case of static keys is for performance-sensitive kernel code, such as tracepoints, context switching, networking, etc. These hot paths of the kernel often contain branches and can be optimized easily using this technique.\nBefore we can use static keys in the kernel, we need to make sure that gcc supports \\cpp|asm goto| inline assembly, and the following kernel configurations are set:\n\n\\begin{code}\nCONFIG_JUMP_LABEL=y\nCONFIG_HAVE_ARCH_JUMP_LABEL=y\nCONFIG_HAVE_ARCH_JUMP_LABEL_RELATIVE=y\n\\end{code}\n\nTo declare a static key, we need to define a global variable using the \\cpp|DEFINE_STATIC_KEY_FALSE| or \\cpp|DEFINE_STATIC_KEY_TRUE| macro defined in \\src{include/linux/jump\\_label.h}.\nThis macro initializes the key with the given initial value, which is either false or true, respectively. For example, to declare a static key with an initial value of false, we can use the following code:\n\n\\begin{code}\nDEFINE_STATIC_KEY_FALSE(fkey);\n\\end{code}\n\nOnce the static key has been declared, we need to add branching code to the module that uses the static key.\nFor example, the code includes a fastpath, where a no-op instruction will be generated at compile time as the key is initialized to false and the branch is unlikely to be taken.\n\n\\begin{code}\npr_info(\"fastpath 1\\n\");\nif (static_branch_unlikely(&fkey))\n    pr_alert(\"do unlikely thing\\n\");\npr_info(\"fastpath 2\\n\");\n\\end{code}\n\nIf the key is enabled at runtime by calling \\cpp|static_branch_enable(&fkey)|, the fastpath will be patched with an unconditional jump instruction to the slowpath code \\cpp|pr_alert|, so the branch will always be taken until the key is disabled again.\n\nThe following kernel module derived from \\verb|chardev.c|, demonstrates how the static key works.\n\n\\samplec{examples/static_key.c}\n\nTo check the state of the static key, we can use the \\verb|/dev/key_state| interface.\n\n\\begin{codebash}\ncat /dev/key_state\n\\end{codebash}\n\nThis will display the current state of the key, which is disabled by default.\n\nTo change the state of the static key, we can perform a write operation on the file:\n\n\\begin{codebash}\necho enable > /dev/key_state\n\\end{codebash}\n\nThis will enable the static key, causing the code path to switch from the fastpath to the slowpath.\n\nIn some cases, the key is enabled or disabled at initialization and never changed, we can declare a static key as read-only, which means that it can only be toggled in the module init function. To declare a read-only static key, we can use the \\cpp|DEFINE_STATIC_KEY_FALSE_RO| or \\cpp|DEFINE_STATIC_KEY_TRUE_RO| macro instead. Attempts to change the key at runtime will result in a page fault.\nFor more information, see \\href{https://www.kernel.org/doc/Documentation/static-keys.txt}{Static keys}\n\n\\section{Common Pitfalls}\n\\label{sec:pitfall}\n\n\\subsection{Using standard libraries}\n\\label{sec:using_stdlib}\nYou can not do that.\nIn a kernel module, you can only use kernel functions which are the functions you can see in \\verb|/proc/kallsyms|.\n\n\\subsection{Disabling interrupts}\n\\label{sec:disabling_interrupts}\nYou might need to do this for a short time and that is OK, but if you do not enable them afterwards, your system will be stuck and you will have to power it off.\n\n\\section{Where To Go From Here?}\n\\label{sec:where_to_go}\nFor those deeply interested in kernel programming,\n\\href{https://kernelnewbies.org}{kernelnewbies.org} and the \\src{Documentation} subdirectory within the kernel source code are highly recommended.\nAlthough the latter may not always be straightforward, it serves as a valuable initial step for further exploration.\nEchoing Linus Torvalds' perspective, the most effective method to understand the kernel is through personal examination of the source code.\n\nContributions to this guide are welcome, especially if there are any significant inaccuracies identified.\nTo contribute or report an issue, please initiate an issue at \\url{https://github.com/sysprog21/lkmpg}.\nPull requests are greatly appreciated.\n\nHappy hacking!\n\\end{document}\n"
  },
  {
    "path": "scripts/Contributors",
    "content": "Amit Dhingra,<mechanicalamit@gmail.com>\nAndrew Kreimer,<algonell@gmail.com>\nAndrew Lin,<35786166+classAndrew@users.noreply.github.com>\nAndy Shevchenko,<andriy.shevchenko@linux.intel.com>\nArush Sharma,<46960231+arushsharma24@users.noreply.github.com>\nAykhan Hagverdili,<aykhanhagverdili@gmail.com>\nBenno Bielmeier,<32938211+bbenno@users.noreply.github.com>\nBob Lee,<defru04002@gmail.com>\nBrad Baker,<brad@brdbkr.com>\nChe-Chia Chang,<vivahavey@gmail.com>\nCheng-Shian Yeh,<yehchanshen@gmail.com>\nCheng-Yang Chou,<yphbchou0911@gmail.com>\nChih-En Lin,<shiyn.lin@gmail.com>,<0086d026@email.ntou.edu.tw>,<66012716+linD026@users.noreply.github.com>\nChih-Hsuan Yang,<zxc25077667@gmail.com>\nChih-Yu Chen,<34228283+chihyu1206@users.noreply.github.com>\nChing-Hua (Vivian) Lin,<jkrvivian@gmail.com>\nChin Yik Ming,<yikming2222@gmail.com>\nChung-Han Tsai,<jeremy90307@gmail.com>\ncvvletter,<cvvletter@pm.me>\nCyril Brulebois,<cyril@debamax.com>\nDaniele Paolo Scarpazza,<>\nDavid Porter,<>\ndemonsome,<horseradish1208@gmail.com>\nDimo Velev,<>\nEkang Monyet,<ekangmonyet@posteo.net>\nEthan Chan,<F04066028@gs.ncku.edu.tw>\nFrancois Audeon,<>\nGilad Reti,<gilad.reti@gmail.com>\nHao.Dong,<hao.dong.nj@outlook.com>\nheartofrain,<heartofrain@outlook.com>\nHorst Schirmeier,<>\nHsin-Hsiang Peng,<hsinspeng@gmail.com>\nHung-Jen Pao,<ginn0122@gmail.com>\nIgnacio Martin,<>\nI-Hsin Cheng,<richard120310@gmail.com>\nIntegral,<integral@member.fsf.org>\nIûnn Kiàn-îng,<black.yangcr@gmail.com>\nJian-Xing Wu,<fdgkhdkgh@gmail.com>\nJimmy Ma,<jimmatw@gmail.com>\nJohan Calle,<43998967+jcallemc@users.noreply.github.com>\nkeytouch,<qsytech@126.com>\nKohei Otsuka,<13173186+rjhcnf@users.noreply.github.com>\nKuan-Wei Chiu,<visitorckw@gmail.com>\nmanbing,<manbing3@gmail.com>\nMarconi Jiang,<marconi1964@yahoo.com>\nmengxinayan,<31788564+mengxinayan@users.noreply.github.com>\nMeng-Zong Tsai,<hwahwa649@gmail.com>,<58484289+fennecJ@users.noreply.github.com>\nPeter Lin,<peterlin@qilai.dev>,<lyctw.ee@gmail.com>,<peterlin.tw@protonmail.com>\nRoman Lakeev,<>\nSam Erickson,<samuelerickson977@gmail.com>\nShao-Tse Hung,<ccs100203@gmail.com>\nShih-Sheng Yang,<james1qaz2wsx12qw@gmail.com>\nStacy Prowell,<sprowell@gmail.com>\nSteven Lung,<1030steven@gmail.com>\nTristan Lelong,<tristan.lelong@blunderer.org>\nTse-Wei Lin,<20110901eric@outlook.com>\nTucker Polomik,<tucker.polomik@inficon.com>\nTyler Fanelli,<tfanelli@redhat.com>\nVxTeemo,<tcccvvv123@gmail.com>\nWei-Hsin Yeh,<weihsinyeh168@gmail.com>,<90430653+weihsinyeh@users.noreply.github.com>\nWei-Lun Tsai,<alan23273850@gmail.com>\nXatierlike Lee,<xatierlike@gmail.com>\nYan-Jie Chan,<51120603+jouae@users.noreply.github.com>\nYen-Yu Chen,<matt162162162@gmail.com>,<69316865+YLowy@users.noreply.github.com>\nYin-Chiuan Chen,<leovincentseles@gmail.com>\nYi-Wei Lin,<s921975628@gmail.com>\nYo-Jung Lin,<0xff07@gmail.com>,<leo.lin@canonical.com>\nYu-Chun Lin,<eleanor15x@gmail.com>\nYu-Hsiang Tseng,<asas1asas200@gmail.com>\nYYGO,<srayuws@users.noreply.github.com>\n"
  },
  {
    "path": "scripts/Exclude",
    "content": "Jim Huang,              One of main author\n"
  },
  {
    "path": "scripts/Include",
    "content": "Daniele Paolo Scarpazza,<>\nDavid Porter,<>\nDimo Velev,<>\nFrancois Audeon,<>\nHorst Schirmeier,<>\nIgnacio Martin,<>\nRoman Lakeev,<>\nTristan Lelong,<tristan.lelong@blunderer.org>\n"
  },
  {
    "path": "scripts/list-contributors.sh",
    "content": "#!/usr/bin/env bash\nFORMAT=\"%aN,<%aE>\"                   #Set git output format in \"Name,<Email>\" //Capital in aN and aE means replace str based on .mailmap\nTARGET=(examples lkmpg.tex)          #Target files we want to trace\nDIR=`git rev-parse --show-toplevel`  #Get root dir of the repo\nTARGET=(\"${TARGET[@]/#/$DIR/}\")      #Concat $DIR BEFORE ALL elements in array TARGET\n\n#The str in each line should be Username,<useremail>\nfunction gen-raw-list()\n{\n    git log --pretty=\"$FORMAT\" ${TARGET[@]} | sort -u\n}\n\nfunction parse-list()\n{\n    > Contributors  # Clear contributors' list (Overwrite with null)\n    while read -r line; do\n        User=`echo \"$line\" | awk -F \",\" '{print $1}'`   \n        if [[ `grep -w \"$User\" Exclude` ]]; then\n            echo \"[skip] $User\"\n            continue;\n        fi\n        echo \"[Add] $User\"\n        MainMail=`echo \"$line\" | awk -F \"[<*>]\" '{print $2}'`\n        Emails=(`cat $DIR/.mailmap | grep -w \"$User\" | awk -F \"[<*>]\" '{print $4}' | sort -u`)\n        for Email in ${Emails[@]}; do\n            if [[ \"$Email\" != \"$MainMail\" ]]; then\n                line=\"$line,<$Email>\";\n            fi\n        done\n        echo \"$line\" >> Contributors\n    done <<< $(gen-raw-list)\n    cat Include >> Contributors\n}\n\nfunction sort-list()\n{\n    if [[ `git diff Contributors` ]]; then\n        sort -f -o Contributors{,}\n        git add $DIR/scripts/Contributors\n    fi\n}\n\n#For all lines before endline, print \"name, % <email>\"\n#For endline print \"name. % <email>\"\nfunction gen-tex-file()\n{\n    cat Contributors | awk -F \",\" \\\n    '   BEGIN{k=0}{name[k]=$1;email[k++]=$2}\n        END{\n           for(i=0;i<k;i++){\n               name[i]=(i<k-1)?name[i]\",\":name[i]\".\";\n               printf(\"%-30s %% %s\\n\",name[i],email[i]);\n               }\n           }\n    '\n}\n\nparse-list\nsort-list\ngen-tex-file > $DIR/contrib.tex"
  }
]