File: fileutil_linux.go

package info (click to toggle)
golang-github-cznic-fileutil 0.0~git20150708.0.1c9c88f-4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 392 kB
  • sloc: makefile: 21
file content (98 lines) | stat: -rw-r--r-- 2,281 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Copyright (c) 2014 The fileutil Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build !arm

package fileutil

import (
	"bytes"
	"io"
	"io/ioutil"
	"os"
	"strconv"
	"syscall"
)

const hasPunchHole = true

func n(s []byte) byte {
	for i, c := range s {
		if c < '0' || c > '9' {
			s = s[:i]
			break
		}
	}
	v, _ := strconv.Atoi(string(s))
	return byte(v)
}

func init() {
	b, err := ioutil.ReadFile("/proc/sys/kernel/osrelease")
	if err != nil {
		panic(err)
	}

	tokens := bytes.Split(b, []byte("."))
	if len(tokens) > 3 {
		tokens = tokens[:3]
	}
	switch len(tokens) {
	case 3:
		// Supported since kernel 2.6.38
		if bytes.Compare([]byte{n(tokens[0]), n(tokens[1]), n(tokens[2])}, []byte{2, 6, 38}) < 0 {
			puncher = func(*os.File, int64, int64) error { return nil }
		}
	case 2:
		if bytes.Compare([]byte{n(tokens[0]), n(tokens[1])}, []byte{2, 7}) < 0 {
			puncher = func(*os.File, int64, int64) error { return nil }
		}
	default:
		puncher = func(*os.File, int64, int64) error { return nil }
	}
}

var puncher = func(f *os.File, off, len int64) error {
	const (
		/*
			/usr/include/linux$ grep FL_ falloc.h
		*/
		_FALLOC_FL_KEEP_SIZE  = 0x01 // default is extend size
		_FALLOC_FL_PUNCH_HOLE = 0x02 // de-allocates range
	)

	_, _, errno := syscall.Syscall6(
		syscall.SYS_FALLOCATE,
		uintptr(f.Fd()),
		uintptr(_FALLOC_FL_KEEP_SIZE|_FALLOC_FL_PUNCH_HOLE),
		uintptr(off),
		uintptr(len),
		0, 0)
	if errno != 0 {
		return os.NewSyscallError("SYS_FALLOCATE", errno)
	}
	return nil
}

// PunchHole deallocates space inside a file in the byte range starting at
// offset and continuing for len bytes. No-op for kernels < 2.6.38 (or < 2.7).
func PunchHole(f *os.File, off, len int64) error {
	return puncher(f, off, len)
}

// Fadvise predeclares an access pattern for file data.  See also 'man 2
// posix_fadvise'.
func Fadvise(f *os.File, off, len int64, advice FadviseAdvice) error {
	_, _, errno := syscall.Syscall6(
		syscall.SYS_FADVISE64,
		uintptr(f.Fd()),
		uintptr(off),
		uintptr(len),
		uintptr(advice),
		0, 0)
	return os.NewSyscallError("SYS_FADVISE64", errno)
}

// IsEOF reports whether err is an EOF condition.
func IsEOF(err error) bool { return err == io.EOF }