├── .github └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── btrfs.c ├── btrfs.go ├── btrfs.h ├── cmd └── btrfs-test │ └── main.go ├── doc.go ├── go.mod ├── go.sum ├── hack └── Dockerfile.compilation-test ├── helpers.go ├── info.go └── ioctl.go /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | 11 | build: 12 | name: Btrfs CI 13 | runs-on: ubuntu-22.04 14 | timeout-minutes: 5 15 | steps: 16 | 17 | - name: Set up Go 18 | uses: actions/setup-go@v3 19 | with: 20 | go-version: 1.19.x 21 | id: go 22 | 23 | - name: Setup environment 24 | shell: bash 25 | run: | 26 | echo "GOPATH=${{ github.workspace }}" >> $GITHUB_ENV 27 | echo "${{ github.workspace }}/bin" >> $GITHUB_PATH 28 | 29 | - name: Check out code 30 | uses: actions/checkout@v3 31 | with: 32 | path: src/github.com/containerd/btrfs 33 | fetch-depth: 25 34 | 35 | - name: Project checks 36 | uses: containerd/project-checks@v1 37 | with: 38 | working-directory: src/github.com/containerd/btrfs 39 | 40 | - name: Build 41 | working-directory: src/github.com/containerd/btrfs 42 | run: | 43 | make vet binaries 44 | 45 | - name: Build with an old version of kernel headers 46 | working-directory: src/github.com/containerd/btrfs 47 | run: | 48 | DOCKER_BUILDKIT=1 docker build -f hack/Dockerfile.compilation-test . 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | bin/ 6 | 7 | # Folders 8 | _obj 9 | _test 10 | 11 | # Architecture specific extensions/prefixes 12 | *.[568vq] 13 | [568vq].out 14 | 15 | *.cgo1.go 16 | *.cgo2.c 17 | _cgo_defun.c 18 | _cgo_gotypes.go 19 | _cgo_export.* 20 | 21 | _testmain.go 22 | 23 | *.exe 24 | *.test 25 | *.prof 26 | 27 | # Support running go modules in vendor mode for local development 28 | /vendor/ 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Copyright The containerd Authors. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | .PHONY: clean binaries generate lint vet test 17 | all: vet lint test binaries 18 | 19 | binaries: bin/btrfs-test 20 | 21 | vet: 22 | go vet ./... 23 | 24 | lint: 25 | golint ./... 26 | 27 | test: 28 | go test -v ./... 29 | 30 | bin/%: ./cmd/% *.go 31 | go build -o ./$@ ./$< 32 | 33 | clean: 34 | rm -rf bin/* 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-btrfs 2 | 3 | [![PkgGoDev](https://pkg.go.dev/badge/github.com/containerd/btrfs)](https://pkg.go.dev/github.com/containerd/btrfs) 4 | [![Build Status](https://github.com/containerd/btrfs/workflows/CI/badge.svg)](https://github.com/containerd/btrfs/actions?query=workflow%3ACI) 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/containerd/btrfs)](https://goreportcard.com/report/github.com/containerd/btrfs) 6 | 7 | Native Go bindings for btrfs. 8 | 9 | # Status 10 | 11 | These are in the early stages. We will try to maintain stability, but please 12 | vendor if you are relying on these directly. 13 | 14 | # Dependencies 15 | 16 | ## v2.x 17 | 18 | Headers from kernel 4.12 or newer. 19 | The package name is `linux-libc-dev` on Debian/Ubuntu, `kernel-headers` on Fedora and RHEL-like distros. 20 | 21 | The headers are only required on compilation time, not on run time. 22 | 23 | ## v1.x 24 | 25 | libbtrfs headers. 26 | The package name is `libbtrfs-dev` on Debian/Ubuntu, `btrfs-progs-devel` on Fedora and CentOS 7. 27 | The package is not available for Rocky Linux and AlmaLinux. 28 | 29 | # Contribute 30 | 31 | This package may not cover all the use cases for btrfs. If something you need 32 | is missing, please don't hesitate to submit a PR. 33 | 34 | Note that due to struct alignment issues, this isn't yet fully native. 35 | Preferably, this could be resolved, so contributions in this direction are 36 | greatly appreciated. 37 | 38 | ## Applying License Header to New Files 39 | 40 | If you submit a contribution that adds a new file, please add the license 41 | header. You can do so manually or use the `ltag` tool: 42 | 43 | 44 | ```console 45 | $ go get github.com/kunalkushwaha/ltag 46 | $ ltag -t ./license-templates 47 | ``` 48 | 49 | The above will add the appropriate licenses to Go files. New templates will 50 | need to be added if other kinds of files are added. Please consult the 51 | documentation at https://github.com/kunalkushwaha/ltag 52 | 53 | ## Project details 54 | 55 | btrfs is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE). 56 | As a containerd sub-project, you will find the: 57 | * [Project governance](https://github.com/containerd/project/blob/main/GOVERNANCE.md), 58 | * [Maintainers](https://github.com/containerd/project/blob/main/MAINTAINERS), 59 | * and [Contributing guidelines](https://github.com/containerd/project/blob/main/CONTRIBUTING.md) 60 | 61 | information in our [`containerd/project`](https://github.com/containerd/project) repository. 62 | -------------------------------------------------------------------------------- /btrfs.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright The containerd Authors 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | #include 18 | #include "btrfs.h" 19 | 20 | void unpack_root_item(struct gosafe_btrfs_root_item* dst, struct btrfs_root_item* src) { 21 | memcpy(dst->uuid, src->uuid, BTRFS_UUID_SIZE); 22 | memcpy(dst->parent_uuid, src->parent_uuid, BTRFS_UUID_SIZE); 23 | memcpy(dst->received_uuid, src->received_uuid, BTRFS_UUID_SIZE); 24 | dst->generation = src->generation; 25 | dst->otransid = src->otransid; 26 | dst->flags = src->flags; 27 | } 28 | 29 | /* unpack_root_ref(struct gosafe_btrfs_root_ref* dst, struct btrfs_root_ref* src) { */ 30 | -------------------------------------------------------------------------------- /btrfs.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright The containerd Authors. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package btrfs 18 | 19 | /* 20 | #include 21 | #include "btrfs.h" 22 | 23 | static char* get_name_btrfs_ioctl_vol_args_v2(struct btrfs_ioctl_vol_args_v2* btrfs_struct) { 24 | return btrfs_struct->name; 25 | } 26 | */ 27 | import "C" 28 | 29 | import ( 30 | "errors" 31 | "fmt" 32 | "os" 33 | "path/filepath" 34 | "sort" 35 | "syscall" 36 | "unsafe" 37 | ) 38 | 39 | // maxByteSliceSize is the smallest size that Go supports on various platforms. 40 | // On mipsle, 1<<31-1 overflows the address space. 41 | const maxByteSliceSize = 1 << 30 42 | 43 | // IsSubvolume returns nil if the path is a valid subvolume. An error is 44 | // returned if the path does not exist or the path is not a valid subvolume. 45 | func IsSubvolume(path string) error { 46 | fi, err := os.Lstat(path) 47 | if err != nil { 48 | return err 49 | } 50 | 51 | if err := isFileInfoSubvol(fi); err != nil { 52 | return err 53 | } 54 | 55 | var statfs syscall.Statfs_t 56 | if err := syscall.Statfs(path, &statfs); err != nil { 57 | return err 58 | } 59 | 60 | return isStatfsSubvol(&statfs) 61 | } 62 | 63 | // SubvolID returns the subvolume ID for the provided path 64 | func SubvolID(path string) (uint64, error) { 65 | fp, err := openSubvolDir(path) 66 | if err != nil { 67 | return 0, err 68 | } 69 | defer fp.Close() 70 | 71 | return subvolID(fp.Fd()) 72 | } 73 | 74 | // SubvolInfo returns information about the subvolume at the provided path. 75 | func SubvolInfo(path string) (info Info, err error) { 76 | path, err = filepath.EvalSymlinks(path) 77 | if err != nil { 78 | return info, err 79 | } 80 | 81 | fp, err := openSubvolDir(path) 82 | if err != nil { 83 | return info, err 84 | } 85 | defer fp.Close() 86 | 87 | id, err := subvolID(fp.Fd()) 88 | if err != nil { 89 | return info, err 90 | } 91 | 92 | subvolsByID, err := subvolMap(path) 93 | if err != nil { 94 | return info, err 95 | } 96 | 97 | if info, ok := subvolsByID[id]; ok { 98 | return *info, nil 99 | } 100 | 101 | return info, fmt.Errorf("%q not found", path) 102 | } 103 | 104 | func subvolMap(path string) (map[uint64]*Info, error) { 105 | fp, err := openSubvolDir(path) 106 | if err != nil { 107 | return nil, err 108 | } 109 | defer fp.Close() 110 | 111 | var args C.struct_btrfs_ioctl_search_args 112 | 113 | args.key.tree_id = C.BTRFS_ROOT_TREE_OBJECTID 114 | args.key.min_type = C.BTRFS_ROOT_ITEM_KEY 115 | args.key.max_type = C.BTRFS_ROOT_BACKREF_KEY 116 | args.key.min_objectid = C.BTRFS_FS_TREE_OBJECTID 117 | args.key.max_objectid = C.BTRFS_LAST_FREE_OBJECTID 118 | args.key.max_offset = ^C.__u64(0) 119 | args.key.max_transid = ^C.__u64(0) 120 | 121 | subvolsByID := make(map[uint64]*Info) 122 | 123 | for { 124 | args.key.nr_items = 4096 125 | if err := ioctl(fp.Fd(), C.BTRFS_IOC_TREE_SEARCH, uintptr(unsafe.Pointer(&args))); err != nil { 126 | return nil, err 127 | } 128 | 129 | if args.key.nr_items == 0 { 130 | break 131 | } 132 | 133 | var ( 134 | sh C.struct_btrfs_ioctl_search_header 135 | shSize = unsafe.Sizeof(sh) 136 | buf = (*[maxByteSliceSize]byte)(unsafe.Pointer(&args.buf[0]))[:C.BTRFS_SEARCH_ARGS_BUFSIZE] 137 | ) 138 | 139 | for i := 0; i < int(args.key.nr_items); i++ { 140 | sh = (*(*C.struct_btrfs_ioctl_search_header)(unsafe.Pointer(&buf[0]))) 141 | buf = buf[shSize:] 142 | 143 | info := subvolsByID[uint64(sh.objectid)] 144 | if info == nil { 145 | info = &Info{} 146 | } 147 | info.ID = uint64(sh.objectid) 148 | 149 | if sh._type == C.BTRFS_ROOT_BACKREF_KEY { 150 | rr := (*(*C.struct_btrfs_root_ref)(unsafe.Pointer(&buf[0]))) 151 | 152 | // This branch processes the backrefs from the root object. We 153 | // get an entry of the objectid, with name, but the parent is 154 | // the offset. 155 | 156 | nname := le16ToNative(rr.name_len) 157 | name := string(buf[C.sizeof_struct_btrfs_root_ref : C.sizeof_struct_btrfs_root_ref+uintptr(nname)]) 158 | 159 | info.ID = uint64(sh.objectid) 160 | info.ParentID = uint64(sh.offset) 161 | info.Name = name 162 | info.DirID = le64ToNative(rr.dirid) 163 | 164 | subvolsByID[uint64(sh.objectid)] = info 165 | } else if sh._type == C.BTRFS_ROOT_ITEM_KEY && 166 | (sh.objectid >= C.BTRFS_ROOT_ITEM_KEY || 167 | sh.objectid == C.BTRFS_FS_TREE_OBJECTID) { 168 | 169 | var ( 170 | ri = (*C.struct_btrfs_root_item)(unsafe.Pointer(&buf[0])) 171 | gri C.struct_gosafe_btrfs_root_item 172 | ) 173 | 174 | C.unpack_root_item(&gri, ri) 175 | 176 | if gri.flags&C.BTRFS_ROOT_SUBVOL_RDONLY != 0 { 177 | info.Readonly = true 178 | } 179 | 180 | // in this case, the offset is the actual offset. 181 | info.Offset = uint64(sh.offset) 182 | 183 | info.UUID = uuidString(&gri.uuid) 184 | info.ParentUUID = uuidString(&gri.parent_uuid) 185 | info.ReceivedUUID = uuidString(&gri.received_uuid) 186 | 187 | info.Generation = le64ToNative(gri.generation) 188 | info.OriginalGeneration = le64ToNative(gri.otransid) 189 | 190 | subvolsByID[uint64(sh.objectid)] = info 191 | } 192 | 193 | args.key.min_objectid = sh.objectid 194 | args.key.min_offset = sh.offset 195 | args.key.min_type = sh._type // this is very questionable. 196 | 197 | buf = buf[sh.len:] 198 | } 199 | 200 | args.key.min_offset++ 201 | if args.key.min_offset == 0 { 202 | args.key.min_type++ 203 | } else { 204 | continue 205 | } 206 | 207 | if args.key.min_type > C.BTRFS_ROOT_BACKREF_KEY { 208 | args.key.min_type = C.BTRFS_ROOT_ITEM_KEY 209 | args.key.min_objectid++ 210 | } else { 211 | continue 212 | } 213 | 214 | if args.key.min_objectid > args.key.max_objectid { 215 | break 216 | } 217 | } 218 | 219 | mnt, err := findMountPoint(path) 220 | if err != nil { 221 | return nil, err 222 | } 223 | 224 | for _, sv := range subvolsByID { 225 | path := sv.Name 226 | parentID := sv.ParentID 227 | 228 | for parentID != 0 { 229 | parent, ok := subvolsByID[parentID] 230 | if !ok { 231 | break 232 | } 233 | 234 | parentID = parent.ParentID 235 | path = filepath.Join(parent.Name, path) 236 | } 237 | 238 | sv.Path = filepath.Join(mnt, path) 239 | } 240 | return subvolsByID, nil 241 | } 242 | 243 | // SubvolList will return the information for all subvolumes corresponding to 244 | // the provided path. 245 | func SubvolList(path string) ([]Info, error) { 246 | subvolsByID, err := subvolMap(path) 247 | if err != nil { 248 | return nil, err 249 | } 250 | 251 | subvols := make([]Info, 0, len(subvolsByID)) 252 | for _, sv := range subvolsByID { 253 | subvols = append(subvols, *sv) 254 | } 255 | 256 | sort.Sort(infosByID(subvols)) 257 | 258 | return subvols, nil 259 | } 260 | 261 | // SubvolCreate creates a subvolume at the provided path. 262 | func SubvolCreate(path string) error { 263 | dir, name := filepath.Split(path) 264 | 265 | fp, err := os.Open(dir) 266 | if err != nil { 267 | return err 268 | } 269 | defer fp.Close() 270 | 271 | var args C.struct_btrfs_ioctl_vol_args 272 | args.fd = C.__s64(fp.Fd()) 273 | 274 | if len(name) > C.BTRFS_PATH_NAME_MAX { 275 | return fmt.Errorf("%q too long for subvolume", name) 276 | } 277 | nameptr := (*[maxByteSliceSize]byte)(unsafe.Pointer(&args.name[0]))[:C.BTRFS_PATH_NAME_MAX:C.BTRFS_PATH_NAME_MAX] 278 | copy(nameptr[:C.BTRFS_PATH_NAME_MAX], []byte(name)) 279 | 280 | if err := ioctl(fp.Fd(), C.BTRFS_IOC_SUBVOL_CREATE, uintptr(unsafe.Pointer(&args))); err != nil { 281 | return fmt.Errorf("btrfs subvolume create failed: %w", err) 282 | } 283 | 284 | return nil 285 | } 286 | 287 | // SubvolSnapshot creates a snapshot in dst from src. If readonly is true, the 288 | // snapshot will be readonly. 289 | func SubvolSnapshot(dst, src string, readonly bool) error { 290 | dstdir, dstname := filepath.Split(dst) 291 | 292 | dstfp, err := openSubvolDir(dstdir) 293 | if err != nil { 294 | return fmt.Errorf("opening snapshot destination subvolume failed: %w", err) 295 | } 296 | defer dstfp.Close() 297 | 298 | srcfp, err := openSubvolDir(src) 299 | if err != nil { 300 | return fmt.Errorf("opening snapshot source subvolume failed: %w", err) 301 | } 302 | defer srcfp.Close() 303 | 304 | // dstdir is the ioctl arg, wile srcdir gets set on the args 305 | var args C.struct_btrfs_ioctl_vol_args_v2 306 | args.fd = C.__s64(srcfp.Fd()) 307 | name := C.get_name_btrfs_ioctl_vol_args_v2(&args) 308 | 309 | if len(dstname) > C.BTRFS_SUBVOL_NAME_MAX { 310 | return fmt.Errorf("%q too long for subvolume", dstname) 311 | } 312 | 313 | nameptr := (*[maxByteSliceSize]byte)(unsafe.Pointer(name))[:C.BTRFS_SUBVOL_NAME_MAX:C.BTRFS_SUBVOL_NAME_MAX] 314 | copy(nameptr[:C.BTRFS_SUBVOL_NAME_MAX], []byte(dstname)) 315 | 316 | if readonly { 317 | args.flags |= C.BTRFS_SUBVOL_RDONLY 318 | } 319 | 320 | if err := ioctl(dstfp.Fd(), C.BTRFS_IOC_SNAP_CREATE_V2, uintptr(unsafe.Pointer(&args))); err != nil { 321 | return fmt.Errorf("snapshot create failed: %w", err) 322 | } 323 | 324 | return nil 325 | } 326 | 327 | // SubvolDelete deletes the subvolumes under the given path. 328 | func SubvolDelete(path string) error { 329 | dir, name := filepath.Split(path) 330 | fp, err := openSubvolDir(dir) 331 | if err != nil { 332 | return fmt.Errorf("failed opening %v: %w", path, err) 333 | } 334 | defer fp.Close() 335 | 336 | // remove child subvolumes 337 | if err := filepath.Walk(path, func(p string, fi os.FileInfo, err error) error { 338 | if err != nil { 339 | if os.IsNotExist(err) || p == path { 340 | return nil 341 | } 342 | 343 | return fmt.Errorf("failed walking subvolume %v: %w", p, err) 344 | } 345 | 346 | if !fi.IsDir() { 347 | return nil // just ignore it! 348 | } 349 | 350 | if p == path { 351 | return nil 352 | } 353 | 354 | if err := isFileInfoSubvol(fi); err != nil { 355 | return nil 356 | } 357 | 358 | if err := SubvolDelete(p); err != nil { 359 | return fmt.Errorf("recursive delete of %v failed: %w", p, err) 360 | } 361 | 362 | return filepath.SkipDir // children get walked by call above. 363 | }); err != nil { 364 | return err 365 | } 366 | 367 | var args C.struct_btrfs_ioctl_vol_args 368 | if len(name) > C.BTRFS_SUBVOL_NAME_MAX { 369 | return fmt.Errorf("%q too long for subvolume", name) 370 | } 371 | 372 | nameptr := (*[maxByteSliceSize]byte)(unsafe.Pointer(&args.name[0]))[:C.BTRFS_SUBVOL_NAME_MAX:C.BTRFS_SUBVOL_NAME_MAX] 373 | copy(nameptr[:C.BTRFS_SUBVOL_NAME_MAX], []byte(name)) 374 | 375 | if err := ioctl(fp.Fd(), C.BTRFS_IOC_SNAP_DESTROY, uintptr(unsafe.Pointer(&args))); err != nil { 376 | return fmt.Errorf("failed removing subvolume %v: %w", path, err) 377 | } 378 | 379 | return nil 380 | } 381 | 382 | func openSubvolDir(path string) (*os.File, error) { 383 | fp, err := os.Open(path) 384 | if err != nil { 385 | return nil, fmt.Errorf("opening %v as subvolume failed: %w", path, err) 386 | } 387 | 388 | return fp, nil 389 | } 390 | 391 | func isStatfsSubvol(statfs *syscall.Statfs_t) error { 392 | if int64(statfs.Type) != int64(C.BTRFS_SUPER_MAGIC) { 393 | return fmt.Errorf("not a btrfs filesystem") 394 | } 395 | 396 | return nil 397 | } 398 | 399 | func isFileInfoSubvol(fi os.FileInfo) error { 400 | if !fi.IsDir() { 401 | return errors.New("must be a directory") 402 | } 403 | 404 | stat := fi.Sys().(*syscall.Stat_t) 405 | 406 | if stat.Ino != C.BTRFS_FIRST_FREE_OBJECTID { 407 | return fmt.Errorf("incorrect inode type") 408 | } 409 | 410 | return nil 411 | } 412 | -------------------------------------------------------------------------------- /btrfs.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright The containerd Authors 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | #include 18 | #if LINUX_VERSION_CODE < KERNEL_VERSION(4,12,0) 19 | #warning "Headers from kernel >= 4.12 are required on compilation time (not on run time)" 20 | #endif 21 | #include 22 | #include 23 | 24 | // unfortunately, we need to define "alignment safe" C structs to populate for 25 | // packed structs that aren't handled by cgo. Fields will be added here, as 26 | // needed. 27 | 28 | struct gosafe_btrfs_root_item { 29 | __u8 uuid[BTRFS_UUID_SIZE]; 30 | __u8 parent_uuid[BTRFS_UUID_SIZE]; 31 | __u8 received_uuid[BTRFS_UUID_SIZE]; 32 | 33 | __le64 generation; 34 | __le64 otransid; 35 | __le64 flags; 36 | }; 37 | 38 | void unpack_root_item(struct gosafe_btrfs_root_item* dst, struct btrfs_root_item* src); 39 | /* void unpack_root_ref(struct gosafe_btrfs_root_ref* dst, struct btrfs_root_ref* src); */ 40 | -------------------------------------------------------------------------------- /cmd/btrfs-test/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright The containerd Authors. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "flag" 21 | "fmt" 22 | "log" 23 | "os" 24 | "text/tabwriter" 25 | 26 | "github.com/containerd/btrfs/v2" 27 | ) 28 | 29 | var ( 30 | readonly bool 31 | ) 32 | 33 | func init() { 34 | flag.BoolVar(&readonly, "readonly", false, "readonly snapshot") 35 | } 36 | 37 | func main() { 38 | flag.Parse() 39 | 40 | switch os.Args[1] { 41 | case "create": 42 | if err := btrfs.SubvolCreate(os.Args[2]); err != nil { 43 | log.Fatalln(err) 44 | } 45 | case "snapshot": 46 | if err := btrfs.SubvolSnapshot(os.Args[3], os.Args[2], readonly); err != nil { 47 | log.Fatalln(err) 48 | } 49 | case "delete": 50 | if err := btrfs.SubvolDelete(os.Args[2]); err != nil { 51 | log.Fatalln(err) 52 | } 53 | case "list": 54 | infos, err := btrfs.SubvolList(os.Args[2]) 55 | if err != nil { 56 | log.Fatalln(err) 57 | } 58 | tw := tabwriter.NewWriter(os.Stdout, 0, 8, 4, '\t', 0) 59 | 60 | fmt.Fprintf(tw, "ID\tParent\tTopLevel\tGen\tOGen\tUUID\tParentUUID\tPath\n") 61 | 62 | for _, subvol := range infos { 63 | fmt.Fprintf(tw, "%d\t%d\t%d\t%d\t%d\t%s\t%s\t%s\n", 64 | subvol.ID, subvol.ParentID, subvol.TopLevelID, 65 | subvol.Generation, subvol.OriginalGeneration, subvol.UUID, subvol.ParentUUID, 66 | subvol.Path) 67 | 68 | } 69 | 70 | tw.Flush() 71 | case "show": 72 | info, err := btrfs.SubvolInfo(os.Args[2]) 73 | if err != nil { 74 | log.Fatalln(err) 75 | } 76 | 77 | fmt.Printf("%#v\n", info) 78 | default: 79 | log.Fatal("unknown command", os.Args[1]) 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright The containerd Authors. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | // Package btrfs provides bindings for working with btrfs partitions from Go. 18 | package btrfs 19 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/containerd/btrfs/v2 2 | 3 | go 1.19 4 | 5 | require golang.org/x/sys v0.5.0 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= 2 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 3 | -------------------------------------------------------------------------------- /hack/Dockerfile.compilation-test: -------------------------------------------------------------------------------- 1 | # Dockerfile for testing compilation with an old version of the kernel headers. 2 | 3 | ARG GOLANG_VERSION=1.19 4 | # LINUX_VERSION must be >= 4.12 (https://github.com/torvalds/linux/commit/fcc8487d477a3452a1d0ccbdd4c5e0e1e3cb8bed) 5 | ARG LINUX_VERSION=4.12 6 | 7 | FROM golang:${GOLANG_VERSION} 8 | ARG LINUX_VERSION 9 | RUN curl -sSL -O "https://mirrors.edge.kernel.org/pub/linux/kernel/v$(echo ${LINUX_VERSION} | cut -d. -f1).x/linux-${LINUX_VERSION}.tar.gz" 10 | RUN tar Cxzf / "linux-${LINUX_VERSION}.tar.gz" && \ 11 | cd "/linux-${LINUX_VERSION}" && \ 12 | make headers_install INSTALL_HDR_PATH=/usr2 && \ 13 | for f in /usr2/include/*; do rm -rf "/usr/include/$(basename ${f})"; done && \ 14 | cp -a /usr2/include /usr 15 | 16 | COPY . /go/src/github.com/containerd/btrfs 17 | WORKDIR /go/src/github.com/containerd/btrfs 18 | RUN make binaries 19 | -------------------------------------------------------------------------------- /helpers.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright The containerd Authors. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package btrfs 18 | 19 | /* 20 | #include "btrfs.h" 21 | */ 22 | import "C" 23 | 24 | import ( 25 | "bufio" 26 | "bytes" 27 | "encoding/binary" 28 | "fmt" 29 | "os" 30 | "strings" 31 | "unsafe" 32 | 33 | "golang.org/x/sys/cpu" 34 | ) 35 | 36 | func subvolID(fd uintptr) (uint64, error) { 37 | var args C.struct_btrfs_ioctl_ino_lookup_args 38 | args.objectid = C.BTRFS_FIRST_FREE_OBJECTID 39 | 40 | if err := ioctl(fd, C.BTRFS_IOC_INO_LOOKUP, uintptr(unsafe.Pointer(&args))); err != nil { 41 | return 0, err 42 | } 43 | 44 | return uint64(args.treeid), nil 45 | } 46 | 47 | var ( 48 | zeroArray = [16]byte{} 49 | zeros = zeroArray[:] 50 | ) 51 | 52 | func uuidString(uuid *[C.BTRFS_UUID_SIZE]C.__u8) string { 53 | b := (*[maxByteSliceSize]byte)(unsafe.Pointer(uuid))[:C.BTRFS_UUID_SIZE] 54 | 55 | if bytes.Equal(b, zeros) { 56 | return "" 57 | } 58 | 59 | return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:4+2], b[6:6+2], b[8:8+2], b[10:16]) 60 | } 61 | 62 | func le16ToNative(le16 C.__le16) uint16 { 63 | if cpu.IsBigEndian { 64 | b := make([]byte, 2) 65 | binary.LittleEndian.PutUint16(b, uint16(le16)) 66 | return binary.BigEndian.Uint16(b) 67 | } 68 | return uint16(le16) 69 | } 70 | 71 | func le64ToNative(le64 C.__le64) uint64 { 72 | if cpu.IsBigEndian { 73 | b := make([]byte, 8) 74 | binary.LittleEndian.PutUint64(b, uint64(le64)) 75 | return binary.BigEndian.Uint64(b) 76 | } 77 | return uint64(le64) 78 | } 79 | 80 | func findMountPoint(path string) (string, error) { 81 | fp, err := os.Open("/proc/self/mounts") 82 | if err != nil { 83 | return "", err 84 | } 85 | defer fp.Close() 86 | 87 | const ( 88 | deviceIdx = 0 89 | pathIdx = 1 90 | typeIdx = 2 91 | options = 3 92 | ) 93 | 94 | var ( 95 | mount string 96 | scanner = bufio.NewScanner(fp) 97 | ) 98 | 99 | for scanner.Scan() { 100 | fields := strings.Fields(scanner.Text()) 101 | if fields[typeIdx] != "btrfs" { 102 | continue // skip non-btrfs 103 | } 104 | 105 | if strings.HasPrefix(path, fields[pathIdx]) { 106 | mount = fields[pathIdx] 107 | } 108 | } 109 | 110 | if scanner.Err() != nil { 111 | return "", scanner.Err() 112 | } 113 | 114 | if mount == "" { 115 | return "", fmt.Errorf("mount point of %v not found", path) 116 | } 117 | 118 | return mount, nil 119 | } 120 | -------------------------------------------------------------------------------- /info.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright The containerd Authors. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package btrfs 18 | 19 | // Info describes metadata about a btrfs subvolume. 20 | type Info struct { 21 | ID uint64 // subvolume id 22 | ParentID uint64 // aka ref_tree 23 | TopLevelID uint64 // not actually clear what this is, not set for now. 24 | Offset uint64 // key offset for root 25 | DirID uint64 26 | 27 | Generation uint64 28 | OriginalGeneration uint64 29 | 30 | UUID string 31 | ParentUUID string 32 | ReceivedUUID string 33 | 34 | Name string 35 | Path string // absolute path of subvolume 36 | Root string // path of root mount point 37 | 38 | Readonly bool // true if the snaps hot is readonly, extracted from flags 39 | } 40 | 41 | type infosByID []Info 42 | 43 | func (b infosByID) Len() int { return len(b) } 44 | func (b infosByID) Less(i, j int) bool { return b[i].ID < b[j].ID } 45 | func (b infosByID) Swap(i, j int) { b[i], b[j] = b[j], b[i] } 46 | -------------------------------------------------------------------------------- /ioctl.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright The containerd Authors. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package btrfs 18 | 19 | import "syscall" 20 | 21 | func ioctl(fd, request, args uintptr) error { 22 | _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, fd, request, args) 23 | if errno != 0 { 24 | return errno 25 | } 26 | return nil 27 | } 28 | --------------------------------------------------------------------------------