├── debian ├── compat ├── source │ └── format ├── hd-idle.logrotate ├── rules ├── hd-idle.service ├── copyright ├── control ├── hd-idle.init ├── hd-idle.default ├── hd-idle.8 └── changelog ├── vendor ├── modules.txt └── github.com │ └── benmcclelland │ └── sgio │ ├── .gitignore │ ├── parse.go │ ├── README.md │ ├── LICENSE │ ├── sg.go │ └── asc.go ├── go.mod ├── go.sum ├── .gitignore ├── main_test.go ├── Makefile ├── io ├── disk.go └── disk_test.go ├── sgio ├── common.go ├── scsi.go ├── type_test.go ├── type.go └── ata.go ├── diskstats ├── snapshot.go └── snapshot_test.go ├── main.go ├── hdidle.go ├── README.md └── LICENSE /debian/compat: -------------------------------------------------------------------------------- 1 | 9 2 | -------------------------------------------------------------------------------- /debian/source/format: -------------------------------------------------------------------------------- 1 | 3.0 (native) 2 | -------------------------------------------------------------------------------- /debian/hd-idle.logrotate: -------------------------------------------------------------------------------- 1 | /var/log/hd-idle.log { 2 | missingok 3 | notifempty 4 | compress 5 | delaycompress 6 | } 7 | -------------------------------------------------------------------------------- /vendor/modules.txt: -------------------------------------------------------------------------------- 1 | # github.com/benmcclelland/sgio v0.0.0-20180629175614-f710aebf64c1 2 | ## explicit 3 | github.com/benmcclelland/sgio 4 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/adelolmo/hd-idle 2 | 3 | go 1.16 4 | 5 | require github.com/benmcclelland/sgio v0.0.0-20180629175614-f710aebf64c1 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/benmcclelland/sgio v0.0.0-20180629175614-f710aebf64c1 h1:f1AIRyf6d21xBd1DirrIa6fk41O3LB0WvVuVqhPN4co= 2 | github.com/benmcclelland/sgio v0.0.0-20180629175614-f710aebf64c1/go.mod h1:WdrapyVn/Aduwwf/OMW6sEtk9+7BSoMst1kGrx4E4xE= 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .run 3 | *.iml 4 | hd-idle 5 | build 6 | obj* 7 | debian/hd-idle 8 | debian/debhelper-build-stamp 9 | debian/*.debhelper 10 | debian/files 11 | debian/hd-idle.debhelper.log 12 | debian/hd-idle.substvars 13 | release 14 | pkg 15 | -------------------------------------------------------------------------------- /debian/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | export DH_VERBOSE=1 3 | export DEB_BUILD_MAINT_OPTIONS = hardening=+all 4 | 5 | %: 6 | dh $@ 7 | 8 | override_dh_auto_build: 9 | 10 | override_dh_auto_install: 11 | install -d $(CURDIR)/debian/hd-idle 12 | make install DESTDIR=$(CURDIR)/debian/hd-idle ARCH=$(DEB_HOST_ARCH) 13 | 14 | override_dh_strip: 15 | -------------------------------------------------------------------------------- /debian/hd-idle.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=hd-idle - spin down idle hard disks 3 | Documentation=man:hd-idle(8) 4 | After=suspend.target hibernate.target hybrid-sleep.target suspend-then-hibernate.target 5 | 6 | [Service] 7 | Type=simple 8 | EnvironmentFile=/etc/default/hd-idle 9 | ExecStart=/usr/sbin/hd-idle $HD_IDLE_OPTS 10 | Restart=always 11 | 12 | [Install] 13 | WantedBy=multi-user.target 14 | -------------------------------------------------------------------------------- /vendor/github.com/benmcclelland/sgio/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | -------------------------------------------------------------------------------- /debian/copyright: -------------------------------------------------------------------------------- 1 | Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ 2 | Upstream-Name: hd-idle 3 | Source: https://github.com/adelolmo/hd-idle 4 | 5 | Files: * 6 | Copyright: 2018 Andoni del Olmo 7 | Author: Andoni del Olmo 8 | License: GPL-3 9 | 10 | Files: debian/hd-idle.8 debian/hd-idle.default debian/control 11 | Copyright: 2007 Christian Mueller 12 | License: GPL-3 13 | -------------------------------------------------------------------------------- /vendor/github.com/benmcclelland/sgio/parse.go: -------------------------------------------------------------------------------- 1 | package sgio 2 | 3 | import ( 4 | "bytes" 5 | "encoding/hex" 6 | ) 7 | 8 | func stringify(a, b byte) string { 9 | return dumpHex(append([]byte{a}, b)) 10 | } 11 | 12 | func dumpHex(data []byte) string { 13 | var buf bytes.Buffer 14 | var tmp [3]byte 15 | for i := range data { 16 | hex.Encode(tmp[:], data[i:i+1]) 17 | tmp[2] = ' ' 18 | _, err := buf.Write(tmp[:3]) 19 | if err != nil { 20 | return "" 21 | } 22 | } 23 | return buf.String() 24 | } 25 | -------------------------------------------------------------------------------- /vendor/github.com/benmcclelland/sgio/README.md: -------------------------------------------------------------------------------- 1 | # sgio 2 | golang library for issuing SCSI commands with SG_IO ioctl 3 | 4 | [![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/benmcclelland/sgio) 5 | 6 | See TestUnitReady() for example function using SG_IO 7 | 8 | example: 9 | ``` 10 | f, err := OpenScsiDevice("/dev/sg0") 11 | if err != nil { 12 | log.Fatalln(err) 13 | } 14 | defer f.Close() 15 | ``` 16 | Fill out SgIoHdr for SCSI command 17 | ``` 18 | ioHdr := &SgIoHdr{...} 19 | err := SgioSyscall(f, ioHdr) 20 | if err != nil { 21 | log.Fatalln(err) 22 | } 23 | 24 | err = CheckSense(ioHdr, &senseBuf) 25 | if err != nil { 26 | log.Fatalln(err) 27 | } 28 | ``` -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | ) 7 | 8 | func TestIntervalWithZeroSecondsIdle(t *testing.T) { 9 | confs := []DeviceConf{{ 10 | Name: "test", 11 | GivenName: "test", 12 | Idle: 0, 13 | CommandType: "ata", 14 | }} 15 | interval := poolInterval(confs) 16 | if interval != defaultIdleTime/10 { 17 | t.Fatalf("interval should be the default. it was %d", interval) 18 | } 19 | } 20 | 21 | func TestIntervalWith300SecondsIdle(t *testing.T) { 22 | confs := []DeviceConf{{ 23 | Name: "test", 24 | GivenName: "test", 25 | Idle: 300 * time.Second, 26 | CommandType: "ata", 27 | }} 28 | interval := poolInterval(confs) 29 | if interval != 30*time.Second { 30 | t.Fatalf("interval should be the 30s. it was %v", interval) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /debian/control: -------------------------------------------------------------------------------- 1 | Source: hd-idle 2 | Section: admin 3 | Priority: optional 4 | Maintainer: Andoni del Olmo 5 | Build-Depends: debhelper (>=9), golang-go:native (>= 1.3.3), dh-golang 6 | Standards-Version: 4.3.0 7 | Vcs-Browser: https://github.com/adelolmo/hd-idle 8 | Vcs-Git: https://github.com/adelolmo/hd-idle.git 9 | Homepage: https://github.com/adelolmo/hd-idle 10 | 11 | Package: hd-idle 12 | Architecture: any 13 | Description: Spin down idle hard disks 14 | hd-idle is a utility program for spinning-down external disks after a period 15 | of idle time. Since most external IDE disk enclosures don't support setting 16 | the IDE idle timer, a program like hd-idle is required to spin down idle disks 17 | automatically. 18 | . 19 | A word of caution: hard disks don't like spinning up too often. Laptop disks 20 | are more robust in this respect than desktop disks but if you set your disks 21 | to spin down after a few seconds you may damage the disk over time due to the 22 | stress the spin-up causes on the spindle motor and bearings. It seems that 23 | manufacturers recommend a minimum idle time of 3-5 minutes, the default in 24 | hd-idle is 10 minutes. 25 | -------------------------------------------------------------------------------- /vendor/github.com/benmcclelland/sgio/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Ben McClelland 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | MAKEFLAGS += --silent 2 | 3 | TARGET = hd-idle 4 | PLATFORM := $(shell uname -m) 5 | 6 | ARCH := 7 | ifeq ($(PLATFORM),x86_64) 8 | ARCH = amd64 9 | endif 10 | ifeq ($(PLATFORM),aarch64) 11 | ARCH = arm64 12 | endif 13 | ifeq ($(PLATFORM),armv7l) 14 | ARCH = armhf 15 | endif 16 | GOARCH := 17 | ifeq ($(ARCH),amd64) 18 | GOARCH = amd64 19 | endif 20 | ifeq ($(ARCH),i386) 21 | GOARCH = 386 22 | endif 23 | ifeq ($(ARCH),arm64) 24 | GOARCH = arm64 25 | endif 26 | ifeq ($(ARCH),armhf) 27 | GOARCH = arm 28 | endif 29 | 30 | ifeq ($(GOARCH),) 31 | $(error Invalid ARCH: $(ARCH)) 32 | endif 33 | 34 | ifdef DESTDIR 35 | # dh_auto_install (Debian) sets this variable 36 | TARGET_DIR = $(DESTDIR)/usr 37 | else 38 | TARGET_DIR ?= /usr/local 39 | endif 40 | 41 | all: $(TARGET) 42 | 43 | distclean: clean 44 | 45 | clean: 46 | rm -f $(TARGET) 47 | 48 | install: $(TARGET) 49 | install -Dm755 $(TARGET) $(TARGET_DIR)/sbin/$(TARGET) 50 | install -Dm755 debian/$(TARGET).8 $(TARGET_DIR)/share/man/man8/$(TARGET).8 51 | 52 | uninstall: 53 | rm -f $(TARGET_DIR)/sbin/$(TARGET) 54 | 55 | $(TARGET): 56 | GOOS=linux GOARCH=$(GOARCH) go build 57 | 58 | test: 59 | go test ./... -race -cover 60 | -------------------------------------------------------------------------------- /debian/hd-idle.init: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | 4 | ### BEGIN INIT INFO 5 | # Provides: hd-idle 6 | # Required-Start: $local_fs 7 | # Required-Stop: $local_fs 8 | # Default-Start: 2 3 4 5 9 | # Default-Stop: 0 1 6 10 | # Short-Description: Start hd-idle daemon 11 | # Description: Start hd-idle daemon (spin down idle hard disks) 12 | ### END INIT INFO 13 | 14 | PATH=/sbin:/bin:/usr/sbin:/usr/bin 15 | 16 | DAEMON=/usr/sbin/hd-idle 17 | 18 | [ -r /etc/default/hd-idle ] && . /etc/default/hd-idle 19 | 20 | # See if the daemon is there 21 | test -x $DAEMON || exit 0 22 | 23 | . /lib/lsb/init-functions 24 | 25 | case "$1" in 26 | start) 27 | log_daemon_msg "Starting the hd-idle daemon" "hd-idle" 28 | 29 | start-stop-daemon --start --quiet --oknodo --background --exec $DAEMON -- $HD_IDLE_OPTS 30 | 31 | log_end_msg $? 32 | ;; 33 | 34 | stop) 35 | log_daemon_msg "Stopping the hd-idle daemon" "hd-idle" 36 | start-stop-daemon --stop --quiet --oknodo --exec $DAEMON 37 | log_end_msg $? 38 | ;; 39 | 40 | restart|force-reload) 41 | $0 stop && sleep 2 && $0 start 42 | ;; 43 | status) 44 | status_of_proc $DAEMON hd-idle && exit 0 || exit $? 45 | ;; 46 | *) 47 | echo "Usage: /etc/init.d/hd-idle start/stop/restart/force-reload" 48 | exit 1 49 | ;; 50 | esac 51 | -------------------------------------------------------------------------------- /io/disk.go: -------------------------------------------------------------------------------- 1 | // hd-idle - spin down idle hard disks 2 | // Copyright (C) 2018 Andoni del Olmo 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | package io 18 | 19 | import ( 20 | "fmt" 21 | "os" 22 | "path/filepath" 23 | "strconv" 24 | "strings" 25 | ) 26 | 27 | func RealPath(path string) (string, error) { 28 | if path[0] != '/' { 29 | return path, nil 30 | } 31 | if !strings.Contains(path, "by-") { 32 | return filepath.Base(path), nil 33 | } 34 | s, err := os.Readlink(path) 35 | if err == nil { 36 | device := filepath.Base(s) 37 | /* remove partition numbers, if any */ 38 | for { 39 | i := device[len(device)-1:] 40 | _, err := strconv.Atoi(i) 41 | if err != nil { 42 | break 43 | } 44 | device = device[:len(device)-1] 45 | } 46 | return device, nil 47 | } 48 | 49 | return "", fmt.Errorf("cannot find device for %s", path) 50 | } 51 | -------------------------------------------------------------------------------- /sgio/common.go: -------------------------------------------------------------------------------- 1 | // hd-idle - spin down idle hard disks 2 | // Copyright (C) 2018 Andoni del Olmo 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | package sgio 18 | 19 | import ( 20 | "fmt" 21 | "github.com/benmcclelland/sgio" 22 | "os" 23 | "syscall" 24 | "unsafe" 25 | ) 26 | 27 | const SgDxferNone = -1 28 | 29 | func openDevice(fname string) (*os.File, error) { 30 | f, err := os.OpenFile(fname, os.O_RDONLY, 0) 31 | if err != nil { 32 | return nil, err 33 | } 34 | var version uint32 35 | if (ioctl(f.Fd(), sgio.SG_GET_VERSION_NUM, uintptr(unsafe.Pointer(&version))) != nil) || (version < 30000) { 36 | return nil, fmt.Errorf("device does not appear to be an sg device") 37 | } 38 | return f, nil 39 | } 40 | 41 | func ioctl(fd, cmd, ptr uintptr) error { 42 | _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, cmd, ptr) 43 | if err != 0 { 44 | return err 45 | } 46 | return nil 47 | } 48 | -------------------------------------------------------------------------------- /sgio/scsi.go: -------------------------------------------------------------------------------- 1 | // hd-idle - spin down idle hard disks 2 | // Copyright (C) 2018 Andoni del Olmo 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | package sgio 18 | 19 | import ( 20 | "fmt" 21 | "github.com/benmcclelland/sgio" 22 | ) 23 | 24 | // https://en.wikipedia.org/wiki/SCSI_command 25 | const startStopUnit = 0x1b 26 | 27 | func StartStopScsiDevice(device string, powerCondition uint8) error { 28 | f, err := openDevice(device) 29 | if err != nil { 30 | return err 31 | } 32 | 33 | senseBuf := make([]byte, sgio.SENSE_BUF_LEN) 34 | //See https://www.seagate.com/files/staticfiles/support/docs/manual/Interface%20manuals/100293068j.pdf - 3.49 START STOP UNIT command 35 | inqCmdBlk := []uint8{ 36 | startStopUnit, 37 | 0, //Reserved (7 bit) + IMMED 38 | 0, //Reserved (8 bit) 39 | 0, //Reserved (4 bit) + POWER CONDITION MODIFER 40 | powerCondition << 4, //POWER CONDITION + Reserved (1 bit) + NO_ FLUSH + LOEJ + LOEJ 41 | 0} //CONTROL 42 | ioHdr := &sgio.SgIoHdr{ 43 | InterfaceID: 'S', 44 | DxferDirection: SgDxferNone, 45 | Cmdp: &inqCmdBlk[0], 46 | CmdLen: uint8(len(inqCmdBlk)), 47 | Sbp: &senseBuf[0], 48 | MxSbLen: sgio.SENSE_BUF_LEN, 49 | } 50 | 51 | if err := sgio.SgioSyscall(f, ioHdr); err != nil { 52 | return err 53 | } 54 | 55 | if err := sgio.CheckSense(ioHdr, &senseBuf); err != nil { 56 | return err 57 | } 58 | 59 | if err := f.Close(); err != nil { 60 | return fmt.Errorf("cannot close file %s. Error: %s", device, err) 61 | } 62 | return nil 63 | } 64 | -------------------------------------------------------------------------------- /sgio/type_test.go: -------------------------------------------------------------------------------- 1 | package sgio 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "path/filepath" 7 | "strings" 8 | "testing" 9 | ) 10 | 11 | const ( 12 | tmpDir = "/tmp/hd-idle/ata" 13 | ) 14 | 15 | func TestAtaDevice_deviceType(t *testing.T) { 16 | type fields struct { 17 | device string 18 | debug bool 19 | fsRoot string 20 | idVendor, idProduct, bcdDevice string 21 | } 22 | tests := []struct { 23 | name string 24 | fields fields 25 | want int 26 | }{ 27 | { 28 | name: "find jmicron controller", 29 | fields: fields{ 30 | device: "/dev/sde", 31 | debug: true, 32 | fsRoot: filepath.Join(tmpDir, "sys", "block"), 33 | idVendor: "152d", 34 | idProduct: "2339", 35 | bcdDevice: "100", 36 | }, 37 | want: Jmicron, 38 | }, 39 | { 40 | name: "unknown device", 41 | fields: fields{ 42 | device: "/dev/sde", 43 | debug: true, 44 | fsRoot: filepath.Join(tmpDir, "sys", "block"), 45 | idVendor: "1058", 46 | idProduct: "25a3", 47 | bcdDevice: "1021", 48 | }, 49 | want: Unknown, 50 | }, 51 | } 52 | for _, tt := range tests { 53 | t.Run(tt.name, func(t *testing.T) { 54 | ad := AtaDevice{ 55 | device: tt.fields.device, 56 | debug: tt.fields.debug, 57 | fsRoot: tt.fields.fsRoot, 58 | } 59 | 60 | err := os.RemoveAll(tmpDir) 61 | if err != nil { 62 | log.Fatal(err) 63 | } 64 | infoDir := filepath.Join(tmpDir, "/sys/devices/pci0000:00/0000:00:15.0/usb2/2-2/2-2.3/2-2.3.2") 65 | diskname := strings.Split(tt.fields.device, "/")[2] 66 | deviceRoot := infoDir + "/2-2.3.2:1.0/host5/target5:0:0/5:0:0:0/block/" + diskname 67 | _ = os.MkdirAll(deviceRoot, 0755) 68 | _ = os.WriteFile(filepath.Join(infoDir, "idVendor"), []byte(tt.fields.idVendor), 0666) 69 | _ = os.WriteFile(filepath.Join(infoDir, "idProduct"), []byte(tt.fields.idProduct), 0666) 70 | _ = os.WriteFile(filepath.Join(infoDir, "bcdDevice"), []byte(tt.fields.bcdDevice), 0666) 71 | _ = os.MkdirAll(filepath.Join(tmpDir, "/sys/block"), 0755) 72 | if err = os.Symlink(deviceRoot, filepath.Join(tmpDir, "/sys/block", diskname)); err != nil { 73 | log.Fatal(err) 74 | } 75 | if got := ad.deviceType(); got != tt.want { 76 | t.Errorf("deviceType() = %v, want %v", got, tt.want) 77 | } 78 | }) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /io/disk_test.go: -------------------------------------------------------------------------------- 1 | // hd-idle - spin down idle hard disks 2 | // Copyright (C) 2018 Andoni del Olmo 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | package io 18 | 19 | import ( 20 | "fmt" 21 | "os" 22 | "testing" 23 | ) 24 | 25 | func TestRealPath(t *testing.T) { 26 | 27 | type args struct { 28 | path string 29 | } 30 | tests := []struct { 31 | name string 32 | args args 33 | want string 34 | symlinkTarget string 35 | expectError bool 36 | }{ 37 | { 38 | name: "only device name", 39 | args: args{path: "sda"}, 40 | want: "sda", 41 | }, 42 | { 43 | name: "full device path", 44 | args: args{path: "/tmp/dev/sda"}, 45 | want: "sda", 46 | }, 47 | { 48 | name: "wrong symlink by id", 49 | args: args{path: "/tmp/dev/disk/by-id/ata-SAMSUNG_HD103SJ"}, 50 | want: "", 51 | expectError: true, 52 | }, 53 | { 54 | name: "symlink by id", 55 | args: args{path: "/tmp/dev/disk/by-id/ata-SAMSUNG_HD103SJ"}, 56 | want: "sdc", 57 | symlinkTarget: "/tmp/dev/sdc", 58 | }, 59 | { 60 | name: "symlink to partition by id", 61 | args: args{path: "/tmp/dev/disk/by-label/disk2"}, 62 | want: "sdc", 63 | symlinkTarget: "/tmp/dev/sdc1", 64 | }, 65 | } 66 | for _, tt := range tests { 67 | err := os.RemoveAll("/tmp/dev") 68 | if err != nil { 69 | panic(err) 70 | } 71 | err = os.MkdirAll("/tmp/dev/disk/by-id", os.ModePerm) 72 | if err != nil { 73 | panic("cannot create tmp dir") 74 | } 75 | err = os.MkdirAll("/tmp/dev/disk/by-label", os.ModePerm) 76 | if err != nil { 77 | panic("cannot create tmp dir") 78 | } 79 | t.Run(tt.name, func(t *testing.T) { 80 | if len(tt.want) > 0 { 81 | disk := fmt.Sprintf("/tmp/dev/%s", tt.want) 82 | _, err := os.Create(disk) 83 | if err != nil { 84 | panic(err) 85 | } 86 | if len(tt.symlinkTarget) > 0 { 87 | err = os.Symlink(tt.symlinkTarget, tt.args.path) 88 | if err != nil { 89 | panic(err) 90 | } 91 | } 92 | } 93 | got, err := RealPath(tt.args.path) 94 | 95 | if err != nil && tt.expectError == false { 96 | panic(err) 97 | } 98 | if got != tt.want { 99 | t.Errorf("RealPath() = %v, want %v", got, tt.want) 100 | } 101 | }) 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /debian/hd-idle.default: -------------------------------------------------------------------------------- 1 | # defaults file for hd-idle 2 | 3 | # start hd-idle automatically? 4 | START_HD_IDLE=false 5 | 6 | # hd-idle command line options 7 | # Options are: 8 | # -a Set device name of disks for subsequent idle-time 9 | # parameters (-i). This parameter is optional in the 10 | # sense that there's a default entry for all disks 11 | # which are not named otherwise by using this 12 | # parameter. This can also be a symlink 13 | # (e.g. /dev/disk/by-uuid/...) 14 | # -i Idle time in seconds. 15 | # -c Api call to stop the device. Possible values are "scsi" 16 | # (default value) and "ata". 17 | # -p 18 | # Power condition to send with the issued SCSI START STOP UNIT command. Possible values 19 | # are `0-15` (inclusive). The default value of `0` works fine for disks accessible via the 20 | # SCSI layer (USB, IEEE1394, ...), but it will *NOT* work as intended with real SCSI / SAS disks. 21 | # A stopped SAS disk will not start up automatically on access, but requires a startup command for reactivation. 22 | # Useful values for SAS disks are `2` for idle and `3` for standby. 23 | # -s symlink_policy Set the policy to resolve symlinks for devices. 24 | # If set to "0", symlinks are resolve only on start. 25 | # If set to "1", symlinks are also resolved on runtime 26 | # until success. By default symlinks are only resolve on start. 27 | # If the symlink doesn't resolve to a device, the default 28 | # configuration will be applied. 29 | # -l Name of logfile (written only after a disk has spun 30 | # up). Please note that this option might cause the 31 | # disk which holds the logfile to spin up just because 32 | # another disk had some activity. This option should 33 | # not be used on systems with more than one disk 34 | # except for tuning purposes. On single-disk systems, 35 | # this option should not cause any additional spinups. 36 | # 37 | # -I 38 | # Ignore spin down detection. Will trigger the spin down command even if hd-idle considers 39 | # the disk to be spun down already. This is useful if the drive is spinning because of 40 | # undetected activities (e.g SMART calls). 41 | # Options not exactly useful here: 42 | # -t Spin-down the specified disk immediately and exit. 43 | # -d Debug mode. It will print debugging info to 44 | # stdout/stderr (/var/log/syslog if started as with systemctl) 45 | # -h Print usage information. 46 | #HD_IDLE_OPTS="-i 180 -l /var/log/hd-idle.log" 47 | -------------------------------------------------------------------------------- /sgio/type.go: -------------------------------------------------------------------------------- 1 | // hd-idle - spin down idle hard disks 2 | // Copyright (C) 2023 Andoni del Olmo 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | package sgio 18 | 19 | import ( 20 | "fmt" 21 | "os" 22 | "path/filepath" 23 | "strings" 24 | ) 25 | 26 | const ( 27 | Jmicron = iota 28 | Unknown = iota 29 | 30 | sysblock = "/sys/block" 31 | 32 | jmicron = "152d" 33 | ) 34 | 35 | type AtaDevice struct { 36 | device string 37 | debug bool 38 | fsRoot string 39 | } 40 | 41 | func NewAtaDevice(device string, debug bool) AtaDevice { 42 | return AtaDevice{ 43 | device: device, 44 | debug: debug, 45 | fsRoot: sysblock, 46 | } 47 | } 48 | 49 | type apt struct { 50 | idVendor, idProduct, bcdDevice string 51 | } 52 | 53 | func (a apt) isJmicron() bool { 54 | if a.idVendor != jmicron { 55 | return false 56 | } 57 | switch a.idProduct { 58 | case "2329", "2336", "2338", "2339": 59 | return true 60 | } 61 | return false 62 | } 63 | 64 | func (ad AtaDevice) deviceType() int { 65 | a, err := ad.identifyDevice(ad.device) 66 | if err != nil { 67 | if ad.debug { 68 | fmt.Println("APT: Unsupported device") 69 | } 70 | return Unknown 71 | } 72 | if a.isJmicron() { 73 | if ad.debug { 74 | fmt.Println("APT: Found supported device jmicron") 75 | } 76 | return Jmicron 77 | } 78 | 79 | if ad.debug { 80 | fmt.Println("APT: Unsupported device") 81 | } 82 | return Unknown 83 | } 84 | 85 | func (ad AtaDevice) identifyDevice(device string) (apt, error) { 86 | diskname := strings.Split(device, "/")[2] 87 | sysblockdisk := filepath.Join(ad.fsRoot, diskname) 88 | idVendor, err := findSystemFile(sysblockdisk, "idVendor") 89 | if err != nil { 90 | return apt{}, err 91 | } 92 | idProduct, err := findSystemFile(sysblockdisk, "idProduct") 93 | if err != nil { 94 | return apt{}, err 95 | } 96 | bcdDevice, err := findSystemFile(sysblockdisk, "bcdDevice") 97 | if err != nil { 98 | return apt{}, err 99 | } 100 | if ad.debug { 101 | fmt.Printf("APT: USB ID = 0x%s:0x%s (0x%3s)\n", idVendor, idProduct, bcdDevice) 102 | } 103 | return apt{ 104 | idVendor: idVendor, 105 | idProduct: idProduct, 106 | bcdDevice: bcdDevice, 107 | }, 108 | nil 109 | } 110 | 111 | func findSystemFile(systemRoot, filename string) (string, error) { 112 | _, err := os.ReadFile(filepath.Join(systemRoot, filename)) 113 | relativeDir := "" 114 | var content []byte 115 | 116 | depth := 0 117 | for depth < 20 { 118 | if err == nil { 119 | return strings.TrimSpace(string(content)), nil 120 | } 121 | relativeDir += "/.." 122 | content, err = os.ReadFile(systemRoot + relativeDir + "/" + filename) 123 | depth++ 124 | } 125 | 126 | return "", fmt.Errorf("device not found") 127 | } 128 | -------------------------------------------------------------------------------- /sgio/ata.go: -------------------------------------------------------------------------------- 1 | // hd-idle - spin down idle hard disks 2 | // Copyright (C) 2018 Andoni del Olmo 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | package sgio 18 | 19 | import ( 20 | "fmt" 21 | "github.com/benmcclelland/sgio" 22 | "os" 23 | ) 24 | 25 | const ( 26 | sgAta16 = 0x85 // ATA PASS-THROUGH(16) 27 | sgAta12 = 0xa1 // ATA PASS-THROUGH (12) 28 | 29 | sgAtaProtoNonData = 3 << 1 30 | ataUsingLba = 1 << 6 31 | 32 | ataOpStandbyNow1 = 0xe0 // https://wiki.osdev.org/ATA/ATAPI_Power_Management 33 | ataOpStandbyNow2 = 0x94 // Retired in ATA4. Did not coexist with ATAPI. 34 | ) 35 | 36 | func StopAtaDevice(device string, debug bool) error { 37 | f, err := openDevice(device) 38 | if err != nil { 39 | return err 40 | } 41 | 42 | switch NewAtaDevice(device, debug).deviceType() { 43 | case Jmicron: 44 | if err = sendSgio(f, jmicronGetRegisters(), debug); err != nil { 45 | return err 46 | } 47 | if debug { 48 | fmt.Println(" issuing standby command") 49 | } 50 | if err = sendSgio(f, jmicronStandby(), debug); err != nil { 51 | return err 52 | } 53 | return nil 54 | default: 55 | if debug { 56 | fmt.Println(" issuing standby command") 57 | } 58 | if err = sendAtaCommand(f, ataOpStandbyNow1, debug); err != nil { 59 | if err = sendAtaCommand(f, ataOpStandbyNow2, debug); err != nil { 60 | return err 61 | } 62 | } 63 | } 64 | 65 | if err := f.Close(); err != nil { 66 | return fmt.Errorf("cannot close file %s. Error: %s", device, err) 67 | } 68 | return nil 69 | } 70 | 71 | func jmicronGetRegisters() []uint8 { 72 | cbd := []uint8{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} // len 12 73 | cbd[0] = 0xdf 74 | cbd[1] = 0x10 // read 75 | cbd[4] = 0x01 76 | cbd[6] = 0x72 77 | cbd[7] = 0x0f 78 | cbd[11] = 0xfd 79 | return cbd 80 | } 81 | 82 | func jmicronStandby() []uint8 { 83 | cbd := []uint8{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} // len 12 84 | cbd[0] = 0xdf 85 | cbd[1] = 0x10 86 | cbd[10] = 0xa0 // device port. either 0xa0 or 0xb0 87 | cbd[11] = ataOpStandbyNow1 88 | return cbd 89 | } 90 | 91 | func sendAtaCommand(f *os.File, command uint8, debug bool) error { 92 | cbd := []uint8{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} // len 16 93 | cbd[0] = sgAta16 94 | cbd[1] = sgAtaProtoNonData 95 | cbd[13] = ataUsingLba 96 | cbd[14] = command 97 | return sendSgio(f, cbd, debug) 98 | } 99 | 100 | func sendSgio(f *os.File, inqCmdBlk []uint8, debug bool) error { 101 | senseBuf := make([]byte, sgio.SENSE_BUF_LEN) 102 | ioHdr := &sgio.SgIoHdr{ 103 | InterfaceID: 'S', // 0 4 104 | DxferDirection: SgDxferNone, // 4 4 105 | CmdLen: uint8(len(inqCmdBlk)), // 8 1 106 | MxSbLen: sgio.SENSE_BUF_LEN, // 9 1 107 | Cmdp: &inqCmdBlk[0], // 24 8 108 | Sbp: &senseBuf[0], // 32 8 109 | Timeout: 0, // 40 4 110 | } 111 | 112 | if debug { 113 | dumpBytes(inqCmdBlk) 114 | } 115 | 116 | if err := sgio.SgioSyscall(f, ioHdr); err != nil { 117 | return err 118 | } 119 | 120 | if err := sgio.CheckSense(ioHdr, &senseBuf); err != nil { 121 | return err 122 | } 123 | return nil 124 | } 125 | 126 | func dumpBytes(p []uint8) { 127 | fmt.Print("outgoing cdb: ") 128 | for i := range p { 129 | fmt.Printf("%02x ", p[i]) 130 | } 131 | fmt.Print("\n") 132 | } 133 | -------------------------------------------------------------------------------- /vendor/github.com/benmcclelland/sgio/sg.go: -------------------------------------------------------------------------------- 1 | package sgio 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "os" 7 | "syscall" 8 | "unsafe" 9 | ) 10 | 11 | const ( 12 | SG_GET_VERSION_NUM = 0x2282 13 | SG_IO = 0x2285 14 | SG_INFO_OK_MASK = 0x1 15 | SG_INFO_OK = 0x0 16 | SG_DXFER_TO_DEV = -2 17 | SG_DXFER_FROM_DEV = -3 18 | SG_DXFER_TO_FROM_DEV = -4 19 | INQ_CMD_CODE = 0x12 20 | INQ_REPLY_LEN = 96 21 | SENSE_BUF_LEN = 32 22 | TIMEOUT_20_SECS = 20000 23 | ) 24 | 25 | // pahole for sg_io_hdr_t on amd64 26 | /* 27 | * struct sg_io_hdr { 28 | * int interface_id; // 0 4 29 | * int dxfer_direction; // 4 4 30 | * unsigned char cmd_len; // 8 1 31 | * unsigned char mx_sb_len; // 9 1 32 | * short unsigned int iovec_count; // 10 2 33 | * unsigned int dxfer_len; // 12 4 34 | * void * dxferp; // 16 8 35 | * unsigned char * cmdp; // 24 8 36 | * unsigned char * sbp; // 32 8 37 | * unsigned int timeout; // 40 4 38 | * unsigned int flags; // 44 4 39 | * int pack_id; // 48 4 40 | * 41 | * // XXX 4 bytes hole, try to pack 42 | * 43 | * void * usr_ptr; // 56 8 44 | * // --- cacheline 1 boundary (64 bytes) --- 45 | * unsigned char status; // 64 1 46 | * unsigned char masked_status; // 65 1 47 | * unsigned char msg_status; // 66 1 48 | * unsigned char sb_len_wr; // 67 1 49 | * short unsigned int host_status; // 68 2 50 | * short unsigned int driver_status; // 70 2 51 | * int resid; // 72 4 52 | * unsigned int duration; // 76 4 53 | * unsigned int info; // 80 4 54 | * 55 | * // size: 88, cachelines: 2, members: 22 56 | * // sum members: 80, holes: 1, sum holes: 4 57 | * // padding: 4 58 | * // last cacheline: 24 bytes 59 | * }; 60 | */ 61 | 62 | // SgIoHdr is our version of sg_io_hdr_t that gets passed to the SG_IO ioctl 63 | type SgIoHdr struct { 64 | InterfaceID int32 65 | DxferDirection int32 66 | CmdLen uint8 67 | MxSbLen uint8 68 | IovecCount uint16 69 | DxferLen uint32 70 | Dxferp *byte 71 | Cmdp *uint8 72 | Sbp *byte 73 | Timeout uint32 74 | Flags uint32 75 | PackID int32 76 | pad0 [4]byte 77 | UsrPtr *byte 78 | Status uint8 79 | MaskedStatus uint8 80 | MsgStatus uint8 81 | SbLenWr uint8 82 | HostStatus uint16 83 | DriverStatus uint16 84 | Resid int32 85 | Duration uint32 86 | Info uint32 87 | } 88 | 89 | func TestUnitReady(f *os.File) error { 90 | senseBuf := make([]byte, SENSE_BUF_LEN) 91 | inqCmdBlk := []uint8{0, 0, 0, 0, 0, 0} 92 | ioHdr := &SgIoHdr{ 93 | InterfaceID: int32('S'), 94 | CmdLen: uint8(len(inqCmdBlk)), 95 | MxSbLen: SENSE_BUF_LEN, 96 | DxferDirection: SG_DXFER_FROM_DEV, 97 | Cmdp: &inqCmdBlk[0], 98 | Sbp: &senseBuf[0], 99 | Timeout: TIMEOUT_20_SECS, 100 | } 101 | 102 | err := SgioSyscall(f, ioHdr) 103 | if err != nil { 104 | return err 105 | } 106 | 107 | err = CheckSense(ioHdr, &senseBuf) 108 | if err != nil { 109 | return err 110 | } 111 | 112 | return nil 113 | } 114 | 115 | func CheckSense(i *SgIoHdr, s *[]byte) error { 116 | var b bytes.Buffer 117 | if (i.Info & SG_INFO_OK_MASK) != SG_INFO_OK { 118 | _, err := b.WriteString( 119 | fmt.Sprintf("SCSI response not ok\n"+ 120 | "SCSI status: %v host status: %v driver status: %v", 121 | i.Status, i.HostStatus, i.DriverStatus)) 122 | if err != nil { 123 | return err 124 | } 125 | if i.SbLenWr > 0 { 126 | _, err := b.WriteString( 127 | fmt.Sprintf("\nSENSE:\n%v\n%v", 128 | dumpHex(*s), GetErrString((*s)[12], (*s)[13]))) 129 | if err != nil { 130 | return err 131 | } 132 | } 133 | return fmt.Errorf(b.String()) 134 | } 135 | return nil 136 | } 137 | 138 | func SgioSyscall(f *os.File, i *SgIoHdr) error { 139 | return ioctl(f.Fd(), SG_IO, uintptr(unsafe.Pointer(i))) 140 | } 141 | 142 | func ioctl(fd, cmd, ptr uintptr) error { 143 | _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, cmd, ptr) 144 | if err != 0 { 145 | return err 146 | } 147 | return nil 148 | } 149 | 150 | func OpenScsiDevice(fname string) (*os.File, error) { 151 | f, err := os.OpenFile(fname, os.O_RDWR, 0) 152 | if err != nil { 153 | return nil, err 154 | } 155 | var version uint32 156 | if (ioctl(f.Fd(), SG_GET_VERSION_NUM, uintptr(unsafe.Pointer(&version))) != nil) || (version < 30000) { 157 | return nil, fmt.Errorf("device does not appear to be an sg device") 158 | } 159 | return f, nil 160 | } 161 | -------------------------------------------------------------------------------- /debian/hd-idle.8: -------------------------------------------------------------------------------- 1 | .\" Hey, EMACS: -*- nroff -*- 2 | .\" First parameter, NAME, should be all caps 3 | .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection 4 | .\" other parameters are allowed: see man(7), man(1) 5 | .TH HD-IDLE 8 "September 8, 2019" 6 | .\" Please adjust this date whenever revising the manpage. 7 | .\" 8 | .\" Some roff macros, for reference: 9 | .\" .nh disable hyphenation 10 | .\" .hy enable hyphenation 11 | .\" .ad l left justify 12 | .\" .ad b justify to both left and right margins 13 | .\" .nf disable filling 14 | .\" .fi enable filling 15 | .\" .br insert line break 16 | .\" .sp insert n+1 empty lines 17 | .\" for manpage-specific macros, see man(7) 18 | .SH NAME 19 | hd-idle \- spin down idle hard disks 20 | .SH SYNOPSIS 21 | .B hd-idle 22 | .RI [ options ] 23 | .P 24 | .SH DESCRIPTION 25 | hd-idle is a utility program for spinning down external disks after a period 26 | of idle time. Since most external IDE disk enclosures don't support setting 27 | the IDE idle timer, a program like hd-idle is required to spin down idle 28 | disks automatically. 29 | .P 30 | A word of caution: hard disks don't like spinning up too often. Laptop disks 31 | are more robust in this respect than desktop disks but if you set your disks 32 | to spin down after a few seconds you may damage the disk over time due to the 33 | stress the spin-up causes on the spindle motor and bearings. It seems that 34 | manufacturers recommend a minimum idle time of 3-5 minutes, the default in 35 | hd-idle is 10 minutes. 36 | .SH OPTIONS 37 | .TP 38 | .B \-a name 39 | Set device name of disks for subsequent idle-time parameters 40 | .B (-i). 41 | This parameter is optional in the sense that there's a default entry for 42 | all disks which are not named otherwise by using this parameter. This can 43 | also be a symlink (e.g. /dev/disk/by-uuid/...) 44 | .TP 45 | .B \-i idle_time 46 | Idle time in seconds for the currently named disk(s) (-a ) or for 47 | all disks. 48 | Setting this value to "0" will never spin down the disk(s). 49 | .TP 50 | .B \-c command_type 51 | Api call to stop the device. Possible values are "scsi" (default value) 52 | and "ata". 53 | .TP 54 | .B \-p power_condition 55 | Power condition to send with the issued SCSI START STOP UNIT command. 56 | Possible values are "0-15" (inclusive). The default value of "0" works fine 57 | for disks accessible via the SCSI layer (USB, IEEE1394, ...), but it will 58 | *NOT* work as intended with real SCSI / SAS disks. A stopped SAS disk will 59 | not start up automatically on access, but requires a startup command for 60 | reactivation. Useful values for SAS disks are "2" for idle and "3" for standby. 61 | .TP 62 | .B \-s symlink_policy 63 | Set the policy to resolve symlinks for devices. If set to "0", symlinks 64 | are resolve only on start. If set to "1", symlinks are also resolved on 65 | runtime until success. By default symlinks are only resolve on start. 66 | If the symlink doesn't resolve to a device, the default configuration 67 | will be applied. 68 | .TP 69 | .B \-l logfile 70 | Name of logfile (written only after a disk has spun up). Please note that 71 | this option might cause the disk which holds the logfile to spin up just 72 | because another disk had some activity. This option should not be used on 73 | systems with more than one disk except for tuning purposes. On single-disk 74 | systems, this option should not cause any additional spinups. 75 | .TP 76 | .B \-t disk 77 | Spin-down the specified disk immediately and exit. It can be used in combination 78 | with 79 | .B \-c 80 | to specify the command type. 81 | .TP 82 | .B \-d 83 | Debug mode. It will print debugging info to stdout/stderr (/var/log/syslog 84 | if started as with systemctl) 85 | .TP 86 | .B \-h 87 | Print usage information. 88 | .SH "DISK SELECTION" 89 | The parameter 90 | .B \-a 91 | can be used to set a filter on the disk's device name (omit /dev/) for 92 | subsequent idle-time settings. The default is all disks: 93 | .P 94 | .TP 95 | .B \1) 96 | A 97 | .B \-i 98 | option before the first 99 | .B \-a 100 | option will set the default idle time. 101 | .TP 102 | .B \2) 103 | In order to disable spin-down of disks per default, and then re-enable 104 | spin-down on selected disks, set the default idle time to 0. 105 | .SH EXAMPLE 106 | hd-idle -i 0 -a sda -i 300 -a sdb -i 1200 107 | .P 108 | This example sets the default idle time to 0 (meaning hd-idle will never 109 | try to spin down a disk) and default "scsi" api command, then sets explicit 110 | idle times for disks which have the string "sda" or "sdb" in their device name. 111 | .SH EXAMPLE 112 | hd-idle -i 0 -c ata -a sda -i 300 -a sdb -i 1200 -c scsi 113 | .P 114 | This example sets the default idle time to 0 (meaning hd-idle will never 115 | try to spin down a disk) and default "ata" api command, then sets explicit 116 | idle times for disks which have the string "sda" or "sdb" in their device name 117 | and sets "sdb" to use "ata" api command. 118 | .P 119 | The option -c allows to set the api call that sends the spindown command. 120 | Possible values are "scsi" (the default value) or "ata". 121 | .SH AUTHOR 122 | hd-idle was written by Andoni del Olmo based on Chistian Mueller's work. 123 | .PP 124 | This manual page was written by Christian Mueller , for the Debian 125 | project (and may be used by others). 126 | .PP 127 | Modified by Andoni del Olmo . 128 | -------------------------------------------------------------------------------- /diskstats/snapshot.go: -------------------------------------------------------------------------------- 1 | // hd-idle - spin down idle hard disks 2 | // Copyright (C) 2018 Andoni del Olmo 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | package diskstats 18 | 19 | import ( 20 | "bufio" 21 | "errors" 22 | "fmt" 23 | "io" 24 | "log" 25 | "os" 26 | "regexp" 27 | "strconv" 28 | "strings" 29 | ) 30 | 31 | /* 32 | https://www.kernel.org/doc/Documentation/ABI/testing/procfs-diskstats 33 | 34 | The /proc/diskstats file displays the I/O statistics 35 | of block devices. Each line contains the following 14 36 | fields: 37 | 38 | 1 - major number 39 | 2 - minor mumber 40 | 3 - device name 41 | 4 - reads completed successfully 42 | 5 - reads merged 43 | 6 - sectors read 44 | 7 - time spent reading (ms) 45 | 8 - writes completed 46 | 9 - writes merged 47 | 10 - sectors written 48 | 11 - time spent writing (ms) 49 | 12 - I/Os currently in progress 50 | 13 - time spent doing I/Os (ms) 51 | 14 - weighted time spent doing I/Os (ms) 52 | 53 | Kernel 4.18+ appends four more fields for discard 54 | tracking putting the total at 18: 55 | 56 | 15 - discards completed successfully 57 | 16 - discards merged 58 | 17 - sectors discarded 59 | 18 - time spent discarding 60 | 61 | Kernel 5.5+ appends two more fields for flush requests: 62 | 63 | 19 - flush requests completed successfully 64 | 20 - time spent flushing 65 | 66 | For more details refer to Documentation/admin-guide/iostats.rst 67 | */ 68 | 69 | const ( 70 | deviceNameCol = 2 // field 3 - device name 71 | readsCol = 5 // field 6 - sectors read 72 | writesCol = 9 // field 10 - sectors written 73 | ) 74 | 75 | type DeviceType int 76 | 77 | const ( 78 | Unknown DeviceType = iota 79 | Disk 80 | Partition 81 | DeviceMapper 82 | ) 83 | 84 | type ReadWriteStats struct { 85 | Name string 86 | Type DeviceType 87 | Reads uint64 88 | Writes uint64 89 | } 90 | 91 | var scsiDiskRegex *regexp.Regexp 92 | var scsiPartitionRegex *regexp.Regexp 93 | var deviceMapperRegex *regexp.Regexp 94 | 95 | type diskHolderGetterFunc func(string, string) (string, error) 96 | 97 | func init() { 98 | scsiDiskRegex = regexp.MustCompile("sd[a-z]+$") 99 | scsiPartitionRegex = regexp.MustCompile("sd[a-z]+[0-9]+$") 100 | deviceMapperRegex = regexp.MustCompile("dm-.*$") 101 | } 102 | 103 | func Snapshot() []ReadWriteStats { 104 | f, err := os.Open("/proc/diskstats") 105 | if err != nil { 106 | log.Fatal(err) 107 | } 108 | defer f.Close() 109 | 110 | return readSnapshot(f, getDiskHolder) 111 | } 112 | 113 | func readSnapshot(r io.Reader, holderGetter diskHolderGetterFunc) []ReadWriteStats { 114 | diskStatsMap := make(map[string]ReadWriteStats) 115 | partitionStatsMap := make(map[string]ReadWriteStats) 116 | deviceMapperHolderMap := make(map[string]string) 117 | 118 | scanner := bufio.NewScanner(r) 119 | for scanner.Scan() { 120 | diskStats, err := statsForDisk(scanner.Text()) 121 | if err != nil { 122 | continue 123 | } 124 | 125 | if diskStats.Type == Disk { 126 | diskStatsMap[diskStats.Name] = *diskStats 127 | 128 | if dmName, err := holderGetter(diskStats.Name, "/sys/class/block/%s/holders/"); err == nil && dmName != "" { 129 | deviceMapperHolderMap[dmName] = diskStats.Name 130 | } 131 | } else { 132 | partitionStatsMap[diskStats.Name] = *diskStats 133 | } 134 | } 135 | 136 | if err := scanner.Err(); err != nil { 137 | log.Fatal(err) 138 | } 139 | for _, partitionStats := range partitionStatsMap { 140 | 141 | var diskName string 142 | var ok bool 143 | 144 | switch partitionStats.Type { 145 | case Partition: 146 | diskName = strings.TrimRight(partitionStats.Name,"0123456789") 147 | case DeviceMapper: 148 | if diskName, ok = deviceMapperHolderMap[partitionStats.Name]; !ok { 149 | continue 150 | } 151 | default: 152 | continue 153 | } 154 | 155 | var diskStats ReadWriteStats 156 | if diskStats, ok = diskStatsMap[diskName]; !ok { 157 | continue 158 | } 159 | if diskStats.Type == Disk { 160 | // replace disk statistics by partition or holder stats 161 | diskStats.Type = partitionStats.Type 162 | diskStats.Writes = partitionStats.Writes 163 | diskStats.Reads = partitionStats.Reads 164 | } else { 165 | // otherwise, accumulate stats of all partitions and holder if any 166 | diskStats.Writes += partitionStats.Writes 167 | diskStats.Reads += partitionStats.Reads 168 | } 169 | diskStatsMap[diskName] = diskStats 170 | } 171 | 172 | return toSlice(diskStatsMap) 173 | } 174 | 175 | func getDiskHolder(diskName, pathFormat string) (string, error) { 176 | /* This returns only the first holder. In practice when using LUKS, there is only one holder */ 177 | 178 | holdersDir := fmt.Sprintf(pathFormat, diskName) 179 | if _, err := os.Stat(holdersDir); os.IsNotExist(err) { 180 | return "", err 181 | } 182 | 183 | files, err := os.ReadDir(holdersDir) 184 | if err != nil { 185 | return "", err 186 | } 187 | for _, file := range files { 188 | return file.Name(), nil 189 | } 190 | return "", nil 191 | } 192 | 193 | func statsForDisk(rawStats string) (*ReadWriteStats, error) { 194 | reader := strings.NewReader(rawStats) 195 | scanner := bufio.NewScanner(reader) 196 | for scanner.Scan() { 197 | cols := strings.Fields(scanner.Text()) 198 | 199 | name := cols[deviceNameCol] 200 | deviceType := Unknown 201 | reads, _ := strconv.ParseUint(cols[readsCol], 10, 64) 202 | writes, _ := strconv.ParseUint(cols[writesCol], 10, 64) 203 | 204 | 205 | if scsiDiskRegex.MatchString(name) { 206 | deviceType = Disk 207 | } else if scsiPartitionRegex.MatchString(name) { 208 | deviceType = Partition 209 | } else if deviceMapperRegex.MatchString(name) { 210 | deviceType = DeviceMapper 211 | } else { 212 | continue 213 | } 214 | 215 | stats := &ReadWriteStats{ 216 | Name: name, 217 | Type: deviceType, 218 | Reads: reads, 219 | Writes: writes, 220 | } 221 | return stats, nil 222 | } 223 | 224 | if err := scanner.Err(); err != nil { 225 | return nil, err 226 | } 227 | return nil, errors.New("cannot read disk stats") 228 | } 229 | 230 | func toSlice(rws map[string]ReadWriteStats) []ReadWriteStats { 231 | var snapshot []ReadWriteStats 232 | for _, r := range rws { 233 | snapshot = append(snapshot, r) 234 | } 235 | return snapshot 236 | } 237 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // hd-idle - spin down idle hard disks 2 | // Copyright (C) 2018 Andoni del Olmo 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | package main 18 | 19 | import ( 20 | "fmt" 21 | "github.com/adelolmo/hd-idle/io" 22 | "os" 23 | "strconv" 24 | "time" 25 | ) 26 | 27 | const ( 28 | defaultIdleTime = 600 * time.Second 29 | symlinkResolveOnce = 0 30 | symlinkResolveRetry = 1 31 | ) 32 | 33 | func main() { 34 | 35 | if os.Getenv("START_HD_IDLE") == "false" { 36 | fmt.Println("START_HD_IDLE=false exiting now.") 37 | os.Exit(0) 38 | } 39 | 40 | singleDiskMode := false 41 | var disk string 42 | defaultConf := DefaultConf{ 43 | Idle: defaultIdleTime, 44 | CommandType: SCSI, 45 | PowerCondition: 0, 46 | Debug: false, 47 | SymlinkPolicy: 0, 48 | } 49 | var config = &Config{ 50 | Devices: []DeviceConf{}, 51 | Defaults: defaultConf, 52 | NameMap: map[string]string{}, 53 | } 54 | var deviceConf *DeviceConf 55 | 56 | if len(os.Args) == 0 { 57 | usage() 58 | os.Exit(1) 59 | } 60 | 61 | for index, arg := range os.Args[1:] { 62 | switch arg { 63 | case "-t": 64 | var err error 65 | disk, err = argument(index) 66 | if err != nil { 67 | fmt.Println("Missing disk argument after -t. Must be a device (e.g. -t sda).") 68 | os.Exit(1) 69 | } 70 | singleDiskMode = true 71 | 72 | case "-s": 73 | s, err := argument(index) 74 | if err != nil { 75 | fmt.Println("Missing symlink_policy. Must be 0 or 1.") 76 | os.Exit(1) 77 | } 78 | switch s { 79 | case "0": 80 | config.Defaults.SymlinkPolicy = symlinkResolveOnce 81 | case "1": 82 | config.Defaults.SymlinkPolicy = symlinkResolveRetry 83 | default: 84 | fmt.Printf("Wrong symlink_policy -s %s. Must be 0 or 1.\n", s) 85 | os.Exit(1) 86 | } 87 | 88 | case "-a": 89 | if deviceConf != nil { 90 | config.Devices = append(config.Devices, *deviceConf) 91 | } 92 | 93 | name, err := argument(index) 94 | if err != nil { 95 | fmt.Println("Missing disk argument after -a. Must be a device (e.g. -a sda).") 96 | os.Exit(1) 97 | } 98 | 99 | deviceRealPath, err := io.RealPath(name) 100 | if err != nil { 101 | deviceRealPath = "" 102 | fmt.Printf("Unable to resolve symlink: %s\n", name) 103 | } 104 | deviceConf = &DeviceConf{ 105 | Name: deviceRealPath, 106 | GivenName: name, 107 | Idle: config.Defaults.Idle, 108 | CommandType: config.Defaults.CommandType, 109 | PowerCondition: config.Defaults.PowerCondition, 110 | } 111 | config.NameMap[deviceRealPath] = name 112 | 113 | case "-i": 114 | s, err := argument(index) 115 | if err != nil { 116 | fmt.Println("Missing idle_time after -i. Must be a number.") 117 | os.Exit(1) 118 | } 119 | idle, err := strconv.Atoi(s) 120 | if err != nil { 121 | fmt.Printf("Wrong idle_time -i %d. Must be a number.", idle) 122 | os.Exit(1) 123 | } 124 | if deviceConf == nil { 125 | config.Defaults.Idle = time.Duration(idle) * time.Second 126 | break 127 | } 128 | deviceConf.Idle = time.Duration(idle) * time.Second 129 | 130 | case "-I": 131 | config.Defaults.IgnoreSpinDownDetection = true 132 | 133 | case "-c": 134 | command, err := argument(index) 135 | if err != nil { 136 | fmt.Println("Missing command_type after -c. Must be one of: scsi, ata.") 137 | os.Exit(1) 138 | } 139 | switch command { 140 | case SCSI, ATA: 141 | if deviceConf == nil { 142 | config.Defaults.CommandType = command 143 | break 144 | } 145 | deviceConf.CommandType = command 146 | default: 147 | fmt.Printf("Wrong command_type -c %s. Must be one of: scsi, ata.", command) 148 | os.Exit(1) 149 | } 150 | 151 | case "-p": 152 | s, err := argument(index) 153 | if err != nil { 154 | fmt.Println("Missing power condition after -p. Must be a number from 0-15.") 155 | os.Exit(1) 156 | } 157 | powerCondition, err := strconv.ParseUint(s, 0, 4) 158 | if err != nil { 159 | fmt.Printf("Invalid power condition %s: %s", s, err.Error()) 160 | os.Exit(1) 161 | } 162 | if deviceConf == nil { 163 | config.Defaults.PowerCondition = uint8(powerCondition) 164 | break 165 | } 166 | deviceConf.PowerCondition = uint8(powerCondition) 167 | 168 | case "-l": 169 | logfile, err := argument(index) 170 | if err != nil { 171 | fmt.Println("Missing logfile after -l.") 172 | os.Exit(1) 173 | } 174 | config.Defaults.LogFile = logfile 175 | 176 | case "-d": 177 | config.Defaults.Debug = true 178 | 179 | case "-h": 180 | usage() 181 | os.Exit(0) 182 | } 183 | } 184 | 185 | if singleDiskMode { 186 | if err := spindownDisk( 187 | disk, 188 | config.Defaults.CommandType, 189 | config.Defaults.PowerCondition, 190 | config.Defaults.Debug, 191 | ); err != nil { 192 | fmt.Println(err.Error()) 193 | os.Exit(1) 194 | } 195 | os.Exit(0) 196 | } 197 | 198 | if deviceConf != nil { 199 | config.Devices = append(config.Devices, *deviceConf) 200 | } 201 | fmt.Println(config.String()) 202 | 203 | interval := poolInterval(config.Devices) 204 | config.SkewTime = interval * 3 205 | for { 206 | ObserveDiskActivity(config) 207 | time.Sleep(interval) 208 | } 209 | } 210 | 211 | func argument(index int) (string, error) { 212 | argIndex := index + 2 213 | if argIndex >= len(os.Args) { 214 | return "", fmt.Errorf("option requires argument") 215 | } 216 | arg := os.Args[argIndex] 217 | if arg[:1] == "-" { 218 | return "", fmt.Errorf("option requires argument") 219 | } 220 | return arg, nil 221 | } 222 | 223 | func usage() { 224 | fmt.Println("usage: hd-idle [-t ] [-s ] [-a ] [-i ] " + 225 | "[-c ] [-p power_condition] [-l ] [-d] [-I] [-h]") 226 | } 227 | 228 | func poolInterval(deviceConfs []DeviceConf) time.Duration { 229 | if len(deviceConfs) == 0 { 230 | return defaultIdleTime / 10 231 | } 232 | 233 | interval := defaultIdleTime 234 | for _, dev := range deviceConfs { 235 | if dev.Idle == 0 { 236 | continue 237 | } 238 | if dev.Idle < interval { 239 | interval = dev.Idle 240 | } 241 | } 242 | 243 | sleepTime := interval / 10 244 | if sleepTime == 0 { 245 | return time.Second 246 | } 247 | return sleepTime 248 | } 249 | -------------------------------------------------------------------------------- /diskstats/snapshot_test.go: -------------------------------------------------------------------------------- 1 | // hd-idle - spin down idle hard disks 2 | // Copyright (C) 2018 Andoni del Olmo 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | package diskstats 18 | 19 | import ( 20 | "os" 21 | "path/filepath" 22 | "sort" 23 | "strings" 24 | "testing" 25 | ) 26 | 27 | func mockGetDiskHolder(diskName, format string) (string, error) { 28 | if diskName == "sdf" { 29 | return "dm-4", nil 30 | } 31 | return "", nil 32 | } 33 | 34 | func TestTakeSnapshot(t *testing.T) { 35 | s := ` 7 0 loop0 0 0 0 0 0 0 0 0 0 0 0 36 | 7 1 loop1 0 0 0 0 0 0 0 0 0 0 0 37 | 7 2 loop2 0 0 0 0 0 0 0 0 0 0 0 38 | 7 3 loop3 0 0 0 0 0 0 0 0 0 0 0 39 | 7 4 loop4 0 0 0 0 0 0 0 0 0 0 0 40 | 7 5 loop5 0 0 0 0 0 0 0 0 0 0 0 41 | 7 6 loop6 0 0 0 0 0 0 0 0 0 0 0 42 | 7 7 loop7 0 0 0 0 0 0 0 0 0 0 0 43 | 179 0 mmcblk0 133145 53235 6878634 3020910 1544414 1254150 48441345 240124500 0 13439150 243142800 44 | 179 1 mmcblk0p1 80 40 1760 210 1 0 1 0 0 140 210 45 | 179 2 mmcblk0p2 132931 53195 6874482 3020440 1544413 1254150 48441344 240124500 0 13439000 243278260 46 | 8 0 sda 321553 158156 37537568 5961590 50820 94361 10439592 26691430 0 3357150 32650910 47 | 8 1 sda1 321454 158156 37536344 5725790 50820 94361 10439592 26691430 0 3121370 32415240 48 | 8 32 sdc 52147 2738 6494584 913050 28092 1251 6370936 8938800 0 506360 9852970 49 | 8 33 sdc1 52087 2738 6493672 905390 28092 1251 6370936 8938800 0 498700 9892750 50 | 8 16 sdb 5650742 34516 727476416 92732820 1728864 35618 404215912 705303450 0 22944140 798112260 51 | 8 17 sdb1 5650643 34516 727475192 92673920 1728864 35618 404215912 705303450 0 22893010 798071230 52 | 8 16 sdd 982501 110903 37074938 9468348 60870 112203 15682640 17081448 0 2086868 26550788 53 | 8 17 sdd1 369 0 39960 1288 0 0 0 0 0 792 1288 54 | 8 18 sdd2 443 0 53496 1224 0 0 0 0 0 1204 1224 55 | 8 19 sdd3 52 0 2632 76 0 0 0 0 0 76 76 56 | 8 21 sdd5 76541 1090 22221672 979636 8845 2335 8316352 14986056 0 470364 15965544 57 | 8 22 sdd6 904573 109813 14736818 8485644 51818 109868 7366288 2094080 0 1642436 10580612 58 | 8 22 sdd11 904573 109813 1 8485644 51818 109868 1 2094080 0 1642436 10580612 59 | 8 32 sde 2891 192 57743 13523 1085550 14035 982686648 9819204 0 5102050 10209416 0 0 0 0 12140 376689 60 | 8 34 sdf 207814 251309 3670180 1378314 38505 27680 21787544 926421 0 552176 2325026 0 0 0 0 272 20290 61 | 253 4 dm-4 25371 0 206376 195492 1330 0 10640 657392 0 19480 852884 0 0 0 0 0 0 62 | 65 160 sdaa 157371 937 11375913 1617587 8304860 2117223236 17004224768 98631435 0 49649267 100249022 0 0 0 0 0 0 63 | 65 161 sdaa1 157257 937 11371536 1617417 8304860 2117223236 17004224768 98631435 0 49649104 100248853 0 0 0 0 0 0 64 | 65 176 sdab 54244 803 1223811 596585 368 9 3008 1051 0 342387 597828 0 0 0 0 8 191` 65 | 66 | stats := readSnapshot(strings.NewReader(s), mockGetDiskHolder) 67 | sort.Slice(stats, func(i, j int) bool { 68 | return stats[i].Name < stats[j].Name 69 | }) 70 | 71 | expected := []ReadWriteStats{ 72 | {Name: "sda", Type: Partition, Reads: 37536344, Writes: 10439592}, 73 | {Name: "sdaa", Type: Partition, Reads: 11371536, Writes: 17004224768}, 74 | {Name: "sdab", Type: Disk, Reads: 1223811, Writes: 3008}, 75 | {Name: "sdb", Type: Partition, Reads: 727475192, Writes: 404215912}, 76 | {Name: "sdc", Type: Partition, Reads: 6493672, Writes: 6370936}, 77 | {Name: "sdd", Type: Partition, Reads: 37054579, Writes: 15682641}, 78 | {Name: "sde", Type: Disk, Reads: 57743, Writes: 982686648}, 79 | {Name: "sdf", Type: DeviceMapper, Reads: 206376, Writes: 10640}, 80 | } 81 | 82 | if len(expected) != len(stats) { 83 | t.Fatalf("Expected %d disks but found %d", len(expected), len(stats)) 84 | } 85 | for i := 0; i < len(expected); i++ { 86 | exp := expected[i] 87 | act := stats[i] 88 | 89 | if exp != act { 90 | t.Fatalf("Expected %v but found %v", exp, act) 91 | } 92 | } 93 | } 94 | 95 | func TestGetDiskHolder(t *testing.T) { 96 | type wantParams struct { 97 | name string 98 | errorMessage string 99 | } 100 | tests := []struct { 101 | name string 102 | diskName string 103 | holderPath string 104 | want wantParams 105 | }{ 106 | { 107 | name: "disk not found", 108 | diskName: "sda", 109 | holderPath: "", 110 | want: wantParams{ 111 | name: "", 112 | errorMessage: "stat /tmp/sys/class/block/sda/holders/: no such file or directory", 113 | }, 114 | }, { 115 | name: "disk found", 116 | diskName: "sda", 117 | holderPath: "/tmp/sys/class/block/sda/holders/dm-0", 118 | want: wantParams{ 119 | name: "dm-0", 120 | errorMessage: "", 121 | }, 122 | }, 123 | } 124 | for _, test := range tests { 125 | err := os.RemoveAll("/tmp/sys") 126 | if err != nil { 127 | panic(err) 128 | } 129 | t.Run(test.name, func(t *testing.T) { 130 | if len(test.holderPath) > 0 { 131 | if err := os.MkdirAll(filepath.Dir(test.holderPath), 0770); err != nil { 132 | panic(err) 133 | } 134 | _, err := os.Create(test.holderPath) 135 | if err != nil { 136 | panic(err) 137 | } 138 | } 139 | got, err := getDiskHolder(test.diskName, "/tmp/sys/class/block/%s/holders/") 140 | 141 | if len(test.want.errorMessage) > 0 && 142 | test.want.errorMessage != err.Error() { 143 | 144 | t.Fatalf("Expected %v but found %v", test.want.errorMessage, err.Error()) 145 | } 146 | 147 | if test.want.name != got { 148 | t.Fatalf("Expected %v but found %v", test.want.name, got) 149 | } 150 | 151 | }) 152 | } 153 | } 154 | 155 | func TestStatsForDisk(t *testing.T) { 156 | type wantParams struct { 157 | name string 158 | deviceType DeviceType 159 | errorMessage string 160 | } 161 | tests := []struct { 162 | name string 163 | line string 164 | want wantParams 165 | }{ 166 | { 167 | name: "disk type", 168 | line: "8 0 sda 321553 158156 37537568 5961590 50820 94361 10439592 26691430 0 3357150 32650910", 169 | want: wantParams{ 170 | name: "sda", 171 | deviceType: Disk, 172 | }, 173 | }, 174 | { 175 | name: "partition type", 176 | line: "8 17 sdd1 369 0 39960 1288 0 0 0 0 0 792 1288", 177 | want: wantParams{ 178 | name: "sdd1", 179 | deviceType: Partition, 180 | }, 181 | }, 182 | { 183 | name: "device mapper type", 184 | line: "253 4 dm-4 25371 0 206376 195492 1330 0 10640 657392 0 19480 852884 0 0 0 0 0 0", 185 | want: wantParams{ 186 | name: "dm-4", 187 | deviceType: DeviceMapper, 188 | }, 189 | }, 190 | { 191 | name: "unknown type", 192 | line: "7 1 loop1 0 0 0 0 0 0 0 0 0 0 0", 193 | want: wantParams{ 194 | errorMessage: "cannot read disk stats", 195 | }, 196 | }, 197 | } 198 | for _, test := range tests { 199 | t.Run(test.name, func(t *testing.T) { 200 | got, gotError := statsForDisk(test.line) 201 | 202 | if test.want.errorMessage != "" && test.want.errorMessage != gotError.Error() { 203 | t.Fatalf("Expected %v but found %v", test.want.errorMessage, gotError.Error()) 204 | } 205 | if gotError != nil { 206 | return 207 | } 208 | 209 | if test.want.name != got.Name { 210 | t.Fatalf("Expected %v but found %v", test.want.name, got.Name) 211 | } 212 | 213 | if test.want.deviceType != got.Type { 214 | t.Fatalf("Expected %v but found %v", test.want.deviceType, got.Type) 215 | } 216 | }) 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /debian/changelog: -------------------------------------------------------------------------------- 1 | hd-idle (1.21) unstable; urgency=medium 2 | 3 | [ Gray Xu ] 4 | * Use GivenName instead of Name in the log 5 | 6 | [ Andoni del Olmo ] 7 | * Support Jmicron USB Bridge Controller for ATA command 8 | 9 | -- Andoni del Olmo Sun, 22 Oct 2023 09:55:29 +0200 10 | 11 | hd-idle (1.20) unstable; urgency=medium 12 | 13 | * Fix force hd-idle into background in init script 14 | * Fix missing man page 15 | 16 | -- Andoni del Olmo Fri, 17 Feb 2023 16:54:38 +0100 17 | 18 | hd-idle (1.19) unstable; urgency=medium 19 | 20 | [ Benjamin Engele ] 21 | * Support more than 26 disks. 22 | 23 | [ Paul Webster ] 24 | * Use explicit uint64 25 | 26 | [ Benjamin Engele ] 27 | * Use standby instead of stop command. 28 | * Support configuring power condition. 29 | * Add and describe -p parameter usage. 30 | * Adjusted documentation of power condition. 31 | 32 | [ Martin Oemus ] 33 | * fixed poolInterval calculation when using idle intervals of 0 34 | 35 | [ Andoni del Olmo ] 36 | * fixed Use UNIX time to calculate skew interval 37 | 38 | -- Andoni del Olmo Thu, 09 Feb 2023 11:55:12 +0100 39 | 40 | hd-idle (1.18) unstable; urgency=medium 41 | 42 | * fix cross platform compilation 43 | * simplify package generation in rules file 44 | * Complete the list of targets for the service restart 45 | 46 | -- Andoni del Olmo Wed, 17 Aug 2022 13:02:42 +0200 47 | 48 | hd-idle (1.17) unstable; urgency=medium 49 | 50 | [ Alexander Raab ] 51 | * Readme cosmetics 52 | 53 | [ Andoni del Olmo ] 54 | * restart service after suspend 55 | * go mod tidy 56 | * Update readme with instructions to build with golang 17 or higher 57 | * Add Makefile 58 | * build debian package compiling with Makefile 59 | * document usage of LUKS encrypted devices 60 | * Redo explanation of how the log file works. Thanks to rabelux. 61 | * restart service after hibernate 62 | 63 | [ Sylvain Pasche ] 64 | * Get statistics from device mapper devices 65 | 66 | [ Andoni del Olmo ] 67 | * use /sys/class/block/%s/holders for holderGetter + add test 68 | * add test for statsForDisk 69 | 70 | -- Andoni del Olmo Thu, 28 Jul 2022 18:12:46 +0200 71 | 72 | hd-idle (1.16) unstable; urgency=medium 73 | 74 | [ Maximilian Bichel ] 75 | * Update help and man page to inform that "i" parameter with value zero never spins down disks. 76 | 77 | [ Zhenyu Wu ] 78 | * Try both ATA standby commands before fail. 79 | 80 | -- Andoni del Olmo Sun, 05 Sep 2021 19:45:17 +0200 81 | 82 | hd-idle (1.15) unstable; urgency=medium 83 | 84 | * Handle disks with no partitions. 85 | Encrypted disks do not have any partitions. In this case, the disk level activity has to be taken into 86 | consideration. 87 | 88 | -- Andoni del Olmo Mon, 05 Apr 2021 09:39:11 +0200 89 | 90 | hd-idle (1.14) unstable; urgency=medium 91 | 92 | * Add logrotate for log file /var/log/hd-idle.log 93 | * Use partitions read/write to calculate disk activity: 94 | It changes the method to calculate disk activity. Now the disk activity is calculated by watching read/write 95 | changes on partition level instead of disk level. 96 | 97 | -- Andoni del Olmo Sun, 28 Mar 2021 14:34:51 +0200 98 | 99 | hd-idle (1.13) unstable; urgency=medium 100 | 101 | * Fix crash when required arguments are not given. Now it will fail 102 | gracefully when required arguments are missing. 103 | * Add SystemV init script. 104 | 105 | -- Andoni del Olmo Thu, 04 Mar 2021 20:33:26 +0100 106 | 107 | hd-idle (1.12) unstable; urgency=medium 108 | 109 | * Fix inconsistent spin down log. The release v1.11 changed the log output on spin down to 110 | "/dev/sda spindown". Now is back to the format "sda spindown". 111 | * Fix typo in help -h flag. This bug prevented showing the help on cli. 112 | 113 | -- Andoni del Olmo Sat, 05 Dec 2020 15:43:05 +0100 114 | 115 | hd-idle (1.11) unstable; urgency=medium 116 | 117 | * Ignore sense response data for ata command to prevent error on arm64. 118 | * Allow set command type in combination with -t option. 119 | * Remove go-co-op dependency. 120 | * Clean control and man page. 121 | * Add copyright. 122 | * Update readme. No need for GOPATH anymore. 123 | 124 | -- Andoni del Olmo Sat, 31 Oct 2020 21:43:04 +0100 125 | 126 | hd-idle (1.10) unstable; urgency=medium 127 | 128 | * Check sectors read/write to determine disk activity 129 | * Package. Move debian files to debian dir 130 | * Package. Simplify rules and delete config handle system 131 | * Update readme. Explain logs 132 | * Update readme. Entry to response not ok error 133 | 134 | -- Andoni del Olmo Sun, 09 Aug 2020 10:26:32 +0200 135 | 136 | hd-idle (1.9) unstable; urgency=medium 137 | 138 | * Improve log on start up and ATA error reporting. 139 | 140 | -- Andoni del Olmo Wed, 11 Mar 2020 10:25:00 +0200 141 | 142 | hd-idle (1.8) unstable; urgency=medium 143 | 144 | * Allow usage of symlinks that point to partitions. Like: by-label, by-partlabel, 145 | by-partuuid and by-uuid. 146 | * Improve error handling when spin down fails. 147 | 148 | -- Andoni del Olmo Wed, 23 Oct 2019 21:15:00 +0200 149 | 150 | hd-idle (1.7) unstable; urgency=medium 151 | 152 | * Change package section to admin and priority to optional. 153 | * Fix man page format error. 154 | * Move man page to section 8 (System administration commands and daemons). 155 | * Sign package. 156 | 157 | -- Andoni del Olmo Sun, 8 Sep 2019 08:47:00 +0200 158 | 159 | hd-idle (1.6) unstable; urgency=low 160 | 161 | * The parameter "-s" allows to resolve symlinks for disk names also in runtime. 162 | It is disable by default, because resolving symlinks causes an overhead. 163 | That means that disk symlinks only get resolved on start up by default. 164 | If the parameter "-s" is set to 1, disk symlinks will be also resolve during 165 | execution until the symlink is resolved. 166 | 167 | -- Andoni del Olmo Wed, 28 Aug 2019 19:33:00 +0100 168 | 169 | hd-idle (1.5) unstable; urgency=low 170 | 171 | * Monitor the skew between monitoring cycles, on discovery of clock skew 172 | reset the drive spin_down status to "spun up" and reset the time to current 173 | in order to capture potential high loading or (more likely) recovery from 174 | suspend or sleep 175 | 176 | -- Andoni del Olmo Sat, 13 Aug 2019 21:15:00 +0100 177 | 178 | hd-idle (1.4) unstable; urgency=low 179 | 180 | * The parameter "-a" now also supports symlinks for disk names. Thus, disks 181 | can be specified using something like /dev/disk/by-uuid/... Use "-d" to 182 | verify that the resulting disk name is what you want. 183 | 184 | Please note that disk names are resolved to device nodes at startup. Also, 185 | since many entries in /dev/disk/by-xxx are actually partitions, partition 186 | numbers are automatically removed from the resulting device node. 187 | 188 | * Simply log spinup. 189 | 190 | -- Andoni del Olmo Sat, 5 Jan 2019 18:42:00 +0100 191 | 192 | hd-idle (1.3) unstable; urgency=low 193 | 194 | * Set sleep time to 1/10th of the shortest idle time. 195 | 196 | -- Andoni del Olmo Fri, 5 Oct 2018 20:47:10 +0100 197 | 198 | hd-idle (1.2) unstable; urgency=low 199 | 200 | * Persist user's config across package upgrades. 201 | 202 | -- Andoni del Olmo Mon, 17 Sep 2018 22:03:10 +0100 203 | 204 | hd-idle (1.1) unstable; urgency=low 205 | 206 | * Add missing feature to spin-down the specified disk immediately. 207 | 208 | -- Andoni del Olmo Sun, 16 Sep 2018 18:13:10 +0100 209 | 210 | hd-idle (1.0) unstable; urgency=low 211 | 212 | * Add "ata" api call to stop devices on top of the original functionality. 213 | 214 | -- Andoni del Olmo Sun, 16 Sep 2018 10:01:10 +0100 215 | -------------------------------------------------------------------------------- /hdidle.go: -------------------------------------------------------------------------------- 1 | // hd-idle - spin down idle hard disks 2 | // Copyright (C) 2018 Andoni del Olmo 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | package main 18 | 19 | import ( 20 | "fmt" 21 | "github.com/adelolmo/hd-idle/diskstats" 22 | "github.com/adelolmo/hd-idle/io" 23 | "github.com/adelolmo/hd-idle/sgio" 24 | "log" 25 | "math" 26 | "os" 27 | "time" 28 | ) 29 | 30 | const ( 31 | SCSI = "scsi" 32 | ATA = "ata" 33 | dateFormat = "2006-01-02T15:04:05" 34 | ) 35 | 36 | type DefaultConf struct { 37 | Idle time.Duration 38 | CommandType string 39 | PowerCondition uint8 40 | Debug bool 41 | LogFile string 42 | SymlinkPolicy int 43 | IgnoreSpinDownDetection bool 44 | } 45 | 46 | type DeviceConf struct { 47 | Name string 48 | GivenName string 49 | Idle time.Duration 50 | CommandType string 51 | PowerCondition uint8 52 | } 53 | 54 | type Config struct { 55 | Devices []DeviceConf 56 | Defaults DefaultConf 57 | SkewTime time.Duration 58 | NameMap map[string]string 59 | } 60 | 61 | func (c *Config) resolveDeviceGivenName(name string) string { 62 | if givenName, ok := c.NameMap[name]; ok { 63 | return givenName 64 | } 65 | return name 66 | } 67 | 68 | type DiskStats struct { 69 | Name string 70 | GivenName string 71 | IdleTime time.Duration 72 | CommandType string 73 | PowerCondition uint8 74 | Reads uint64 75 | Writes uint64 76 | SpinDownAt time.Time 77 | SpinUpAt time.Time 78 | LastIoAt time.Time 79 | LastSpunDownAt time.Time 80 | SpunDown bool 81 | } 82 | 83 | var previousSnapshots []DiskStats 84 | var now = time.Now() 85 | var lastNow = time.Now() 86 | 87 | func ObserveDiskActivity(config *Config) { 88 | actualSnapshot := diskstats.Snapshot() 89 | 90 | now = time.Now() 91 | resolveSymlinks(config) 92 | for _, stats := range actualSnapshot { 93 | d := &DiskStats{ 94 | Name: stats.Name, 95 | Reads: stats.Reads, 96 | Writes: stats.Writes, 97 | } 98 | updateState(*d, config) 99 | } 100 | lastNow = now 101 | } 102 | 103 | func resolveSymlinks(config *Config) { 104 | if config.Defaults.SymlinkPolicy == 0 { 105 | return 106 | } 107 | for i := range config.Devices { 108 | device := config.Devices[i] 109 | if len(device.Name) == 0 { 110 | realPath, err := io.RealPath(device.GivenName) 111 | if err == nil { 112 | config.Devices[i].Name = realPath 113 | logToFile(config.Defaults.LogFile, 114 | fmt.Sprintf("symlink %s resolved to %s", device.GivenName, realPath)) 115 | } 116 | if err != nil && config.Defaults.Debug { 117 | fmt.Printf("Cannot resolve sysmlink %s\n", device.GivenName) 118 | } 119 | } 120 | } 121 | } 122 | 123 | func updateState(tmp DiskStats, config *Config) { 124 | dsi := previousDiskStatsIndex(tmp.Name) 125 | if dsi < 0 { 126 | previousSnapshots = append(previousSnapshots, initDevice(tmp, config)) 127 | return 128 | } 129 | 130 | intervalDurationInSeconds := now.Unix() - lastNow.Unix() 131 | if intervalDurationInSeconds > config.SkewTime.Milliseconds()/1000 { 132 | /* we slept too long, assume a suspend event and disks may be spun up */ 133 | /* reset spin status and timers */ 134 | previousSnapshots[dsi].SpinUpAt = now 135 | previousSnapshots[dsi].LastIoAt = now 136 | previousSnapshots[dsi].SpunDown = false 137 | logSpinupAfterSleep(previousSnapshots[dsi].Name, config.Defaults.LogFile) 138 | } 139 | 140 | ds := previousSnapshots[dsi] 141 | if ds.Writes == tmp.Writes && ds.Reads == tmp.Reads { 142 | if !ds.SpunDown || config.Defaults.IgnoreSpinDownDetection { 143 | 144 | idleDuration := now.Sub(ds.LastIoAt) 145 | timeSinceLastSpunDown := now.Sub(ds.LastSpunDownAt) 146 | 147 | if ds.IdleTime != 0 && idleDuration > ds.IdleTime && timeSinceLastSpunDown > ds.IdleTime { 148 | if ds.SpunDown && config.Defaults.IgnoreSpinDownDetection { 149 | fmt.Printf("%s spindown (ignoring prior spin down state)\n", 150 | config.resolveDeviceGivenName(ds.Name)) 151 | } else { 152 | fmt.Printf("%s spindown\n", 153 | config.resolveDeviceGivenName(ds.Name)) 154 | } 155 | device := fmt.Sprintf("/dev/%s", ds.Name) 156 | if err := spindownDisk(device, ds.CommandType, ds.PowerCondition, config.Defaults.Debug); err != nil { 157 | fmt.Println(err.Error()) 158 | } 159 | previousSnapshots[dsi].LastSpunDownAt = now 160 | previousSnapshots[dsi].SpinDownAt = now 161 | previousSnapshots[dsi].SpunDown = true 162 | } 163 | } 164 | 165 | } else { 166 | /* disk had some activity */ 167 | if ds.SpunDown { 168 | /* disk was spun down, thus it has just spun up */ 169 | fmt.Printf("%s spinup\n", config.resolveDeviceGivenName(ds.Name)) 170 | logSpinup(ds, config.Defaults.LogFile, config.resolveDeviceGivenName(ds.Name)) 171 | previousSnapshots[dsi].SpinUpAt = now 172 | } 173 | previousSnapshots[dsi].Reads = tmp.Reads 174 | previousSnapshots[dsi].Writes = tmp.Writes 175 | previousSnapshots[dsi].LastIoAt = now 176 | previousSnapshots[dsi].SpunDown = false 177 | } 178 | 179 | if config.Defaults.Debug { 180 | ds = previousSnapshots[dsi] 181 | idleDuration := now.Sub(ds.LastIoAt) 182 | fmt.Printf("disk=%s command=%s spunDown=%t "+ 183 | "reads=%d writes=%d idleTime=%v idleDuration=%v "+ 184 | "spindown=%s spinup=%s lastIO=%s lastSpunDown=%s \n", 185 | ds.Name, ds.CommandType, ds.SpunDown, 186 | ds.Reads, ds.Writes, ds.IdleTime.Seconds(), math.RoundToEven(idleDuration.Seconds()), 187 | ds.SpinDownAt.Format(dateFormat), ds.SpinUpAt.Format(dateFormat), ds.LastIoAt.Format(dateFormat), 188 | ds.LastSpunDownAt.Format(dateFormat)) 189 | } 190 | } 191 | 192 | func previousDiskStatsIndex(diskName string) int { 193 | for i, stats := range previousSnapshots { 194 | if stats.Name == diskName { 195 | return i 196 | } 197 | } 198 | return -1 199 | } 200 | 201 | func initDevice(stats DiskStats, config *Config) DiskStats { 202 | idle := config.Defaults.Idle 203 | command := config.Defaults.CommandType 204 | powerCondition := config.Defaults.PowerCondition 205 | deviceConf := deviceConfig(stats.Name, config) 206 | if deviceConf != nil { 207 | idle = deviceConf.Idle 208 | command = deviceConf.CommandType 209 | powerCondition = deviceConf.PowerCondition 210 | } 211 | 212 | return DiskStats{ 213 | Name: stats.Name, 214 | LastIoAt: time.Now(), 215 | SpinUpAt: time.Now(), 216 | SpunDown: false, 217 | Writes: stats.Writes, 218 | Reads: stats.Reads, 219 | IdleTime: idle, 220 | CommandType: command, 221 | PowerCondition: powerCondition, 222 | } 223 | } 224 | 225 | func deviceConfig(diskName string, config *Config) *DeviceConf { 226 | for _, device := range config.Devices { 227 | if device.Name == diskName { 228 | return &device 229 | } 230 | } 231 | return &DeviceConf{ 232 | Name: diskName, 233 | CommandType: config.Defaults.CommandType, 234 | PowerCondition: config.Defaults.PowerCondition, 235 | Idle: config.Defaults.Idle, 236 | } 237 | } 238 | 239 | func spindownDisk(device, command string, powerCondition uint8, debug bool) error { 240 | switch command { 241 | case SCSI: 242 | if err := sgio.StartStopScsiDevice(device, powerCondition); err != nil { 243 | return fmt.Errorf("cannot spindown scsi disk %s:\n%s\n", device, err.Error()) 244 | } 245 | return nil 246 | case ATA: 247 | if err := sgio.StopAtaDevice(device, debug); err != nil { 248 | return fmt.Errorf("cannot spindown ata disk %s:\n%s\n", device, err.Error()) 249 | } 250 | return nil 251 | } 252 | return nil 253 | } 254 | 255 | func logSpinup(ds DiskStats, file, givenName string) { 256 | now := time.Now() 257 | text := fmt.Sprintf("date: %s, time: %s, disk: %s, running: %d, stopped: %d", 258 | now.Format("2006-01-02"), now.Format("15:04:05"), givenName, 259 | int(ds.SpinDownAt.Sub(ds.SpinUpAt).Seconds()), int(now.Sub(ds.SpinDownAt).Seconds())) 260 | logToFile(file, text) 261 | } 262 | 263 | func logSpinupAfterSleep(name, file string) { 264 | text := fmt.Sprintf("date: %s, time: %s, disk: %s, assuming disk spun up after long sleep", 265 | now.Format("2006-01-02"), now.Format("15:04:05"), name) 266 | logToFile(file, text) 267 | } 268 | 269 | func logToFile(file, text string) { 270 | if len(file) == 0 { 271 | return 272 | } 273 | 274 | cacheFile, err := os.OpenFile(file, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) 275 | if err != nil { 276 | log.Fatalf("Cannot open file %s. Error: %s", file, err) 277 | } 278 | if _, err = cacheFile.WriteString(text + "\n"); err != nil { 279 | log.Fatalf("Cannot write into file %s. Error: %s", file, err) 280 | } 281 | err = cacheFile.Close() 282 | if err != nil { 283 | log.Fatalf("Cannot close file %s. Error: %s", file, err) 284 | } 285 | } 286 | 287 | func (c *Config) String() string { 288 | var devices string 289 | for _, device := range c.Devices { 290 | devices += "{" + device.String() + "}" 291 | } 292 | return fmt.Sprintf("symlinkPolicy=%d, defaultIdle=%v, defaultCommand=%s, defaultPowerCondition=%v, debug=%t, logFile=%s, devices=%s, ignoreSpinDownDetection=%t", 293 | c.Defaults.SymlinkPolicy, c.Defaults.Idle.Seconds(), c.Defaults.CommandType, c.Defaults.PowerCondition, c.Defaults.Debug, c.Defaults.LogFile, devices, c.Defaults.IgnoreSpinDownDetection) 294 | } 295 | 296 | func (dc *DeviceConf) String() string { 297 | return fmt.Sprintf("name=%s, givenName=%s, idle=%v, commandType=%s, powerCondition=%v", 298 | dc.Name, dc.GivenName, dc.Idle.Seconds(), dc.CommandType, dc.PowerCondition) 299 | } 300 | -------------------------------------------------------------------------------- /vendor/github.com/benmcclelland/sgio/asc.go: -------------------------------------------------------------------------------- 1 | package sgio 2 | 3 | var errmap map[string]string 4 | 5 | func GetErrString(a, b byte) string { 6 | return errmap[stringify(a, b)] 7 | } 8 | 9 | func init() { 10 | errmap = make(map[string]string) 11 | errmap[stringify(0x00, 0x00)] = "NO ADDITIONAL SENSE INFORMATION" 12 | errmap[stringify(0x00, 0x01)] = "FILEMARK DETECTED" 13 | errmap[stringify(0x00, 0x02)] = "END-OF-PARTITION/MEDIUM DETECTED" 14 | errmap[stringify(0x00, 0x03)] = "SETMARK DETECTED" 15 | errmap[stringify(0x00, 0x04)] = "BEGINNING-OF-PARTITION/MEDIUM DETECTED" 16 | errmap[stringify(0x00, 0x05)] = "END-OF-DATA DETECTED" 17 | errmap[stringify(0x00, 0x06)] = "I/O PROCESS TERMINATED" 18 | errmap[stringify(0x00, 0x11)] = "AUDIO PLAY OPERATION IN PROGRESS" 19 | errmap[stringify(0x00, 0x12)] = "AUDIO PLAY OPERATION PAUSED" 20 | errmap[stringify(0x00, 0x13)] = "AUDIO PLAY OPERATION SUCCESSFULLY COMPLETED" 21 | errmap[stringify(0x00, 0x14)] = "AUDIO PLAY OPERATION STOPPED DUE TO ERROR" 22 | errmap[stringify(0x00, 0x15)] = "NO CURRENT AUDIO STATUS TO RETURN" 23 | errmap[stringify(0x01, 0x00)] = "NO INDEX/SECTOR SIGNAL" 24 | errmap[stringify(0x02, 0x00)] = "NO SEEK COMPLETE" 25 | errmap[stringify(0x03, 0x00)] = "PERIPHERAL DEVICE WRITE FAULT" 26 | errmap[stringify(0x03, 0x01)] = "NO WRITE CURRENT" 27 | errmap[stringify(0x03, 0x02)] = "EXCESSIVE WRITE ERRORS" 28 | errmap[stringify(0x04, 0x00)] = "LOGICAL UNIT NOT READY, CAUSE NOT REPORTABLE" 29 | errmap[stringify(0x04, 0x01)] = "LOGICAL UNIT IS IN PROCESS OF BECOMING READY" 30 | errmap[stringify(0x04, 0x02)] = "LOGICAL UNIT NOT READY, INITIALIZING COMMAND REQUIRED" 31 | errmap[stringify(0x04, 0x03)] = "LOGICAL UNIT NOT READY, MANUAL INTERVENTION REQUIRED" 32 | errmap[stringify(0x04, 0x04)] = "LOGICAL UNIT NOT READY, FORMAT IN PROGRESS" 33 | errmap[stringify(0x05, 0x00)] = "LOGICAL UNIT DOES NOT RESPOND TO SELECTION" 34 | errmap[stringify(0x06, 0x00)] = "REFERENCE POSITION FOUND" 35 | errmap[stringify(0x07, 0x00)] = "MULTIPLE PERIPHERAL DEVICES SELECTED" 36 | errmap[stringify(0x08, 0x00)] = "LOGICAL UNIT COMMUNICATION FAILURE" 37 | errmap[stringify(0x08, 0x01)] = "LOGICAL UNIT COMMUNICATION TIME-OUT" 38 | errmap[stringify(0x08, 0x02)] = "LOGICAL UNIT COMMUNICATION PARITY ERROR" 39 | errmap[stringify(0x09, 0x00)] = "TRACK FOLLOWING ERROR" 40 | errmap[stringify(0x09, 0x01)] = "TRA CKING SERVO FAILURE" 41 | errmap[stringify(0x09, 0x02)] = "FOC US SERVO FAILURE" 42 | errmap[stringify(0x09, 0x03)] = "SPI NDLE SERVO FAILURE" 43 | errmap[stringify(0x0A, 0x00)] = "ERROR LOG OVERFLOW" 44 | errmap[stringify(0x0B, 0x00)] = "" 45 | errmap[stringify(0x0C, 0x00)] = "WRITE ERROR" 46 | errmap[stringify(0x0C, 0x01)] = "WRITE ERROR RECOVERED WITH AUTO REALLOCATION" 47 | errmap[stringify(0x0C, 0x02)] = "WRITE ERROR - AUTO REALLOCATION FAILED" 48 | errmap[stringify(0x0D, 0x00)] = "" 49 | errmap[stringify(0x0E, 0x00)] = "" 50 | errmap[stringify(0x0F, 0x00)] = "" 51 | errmap[stringify(0x10, 0x00)] = "ID CRC OR ECC ERROR" 52 | errmap[stringify(0x11, 0x00)] = "UNRECOVERED READ ERROR" 53 | errmap[stringify(0x11, 0x01)] = "READ RETRIES EXHAUSTED" 54 | errmap[stringify(0x11, 0x02)] = "ERROR TOO LONG TO CORRECT" 55 | errmap[stringify(0x11, 0x03)] = "MULTIPLE READ ERRORS" 56 | errmap[stringify(0x11, 0x04)] = "UNRECOVERED READ ERROR - AUTO REALLOCATE FAILED" 57 | errmap[stringify(0x11, 0x05)] = "L-EC UNCORRECTABLE ERROR" 58 | errmap[stringify(0x11, 0x06)] = "CIRC UNRECOVERED ERROR" 59 | errmap[stringify(0x11, 0x07)] = "DATA RESYCHRONIZATION ERROR" 60 | errmap[stringify(0x11, 0x08)] = "INCOMPLETE BLOCK READ" 61 | errmap[stringify(0x11, 0x09)] = "NO GAP FOUND" 62 | errmap[stringify(0x11, 0x0A)] = "MISCORRECTED ERROR" 63 | errmap[stringify(0x11, 0x0B)] = "UNRECOVERED READ ERROR - RECOMMEND REASSIGNMENT" 64 | errmap[stringify(0x11, 0x0C)] = "UNRECOVERED READ ERROR - RECOMMEND REWRITE THE DATA" 65 | errmap[stringify(0x12, 0x00)] = "ADDRESS MARK NOT FOUND FOR ID FIELD" 66 | errmap[stringify(0x13, 0x00)] = "ADDRESS MARK NOT FOUND FOR DATA FIELD" 67 | errmap[stringify(0x14, 0x00)] = "RECORDED ENTITY NOT FOUND" 68 | errmap[stringify(0x14, 0x01)] = "RECORD NOT FOUND" 69 | errmap[stringify(0x14, 0x02)] = "FILEMARK OR SETMARK NOT FOUND" 70 | errmap[stringify(0x14, 0x03)] = "END-OF-DATA NOT FOUND" 71 | errmap[stringify(0x14, 0x04)] = "BLOCK SEQUENCE ERROR" 72 | errmap[stringify(0x15, 0x00)] = "RANDOM POSITIONING ERROR" 73 | errmap[stringify(0x15, 0x01)] = "MECHANICAL POSITIONING ERROR" 74 | errmap[stringify(0x15, 0x02)] = "POSITIONING ERROR DETECTED BY READ OF MEDIUM" 75 | errmap[stringify(0x16, 0x00)] = "DATA SYNCHRONIZATION MARK ERROR" 76 | errmap[stringify(0x17, 0x00)] = "RECOVERED DATA WITH NO ERROR CORRECTION APPLIED" 77 | errmap[stringify(0x17, 0x01)] = "RECOVERED DATA WITH RETRIES" 78 | errmap[stringify(0x17, 0x02)] = "RECOVERED DATA WITH POSITIVE HEAD OFFSET" 79 | errmap[stringify(0x17, 0x03)] = "RECOVERED DATA WITH NEGATIVE HEAD OFFSET" 80 | errmap[stringify(0x17, 0x04)] = "RECOVERED DATA WITH RETRIES AND/OR CIRC APPLIED" 81 | errmap[stringify(0x17, 0x05)] = "RECOVERED DATA USING PREVIOUS SECTOR ID" 82 | errmap[stringify(0x17, 0x06)] = "RECOVERED DATA WITHOUT ECC - DATA AUTO-REALLOCATED" 83 | errmap[stringify(0x17, 0x07)] = "RECOVERED DATA WITHOUT ECC - RECOMMEND REASSIGNMENT" 84 | errmap[stringify(0x17, 0x08)] = "RECOVERED DATA WITHOUT ECC - RECOMMEND REWRITE" 85 | errmap[stringify(0x18, 0x00)] = "RECOVERED DATA WITH ERROR CORRECTION APPLIED" 86 | errmap[stringify(0x18, 0x01)] = "RECOVERED DATA WITH ERROR CORRECTION & RETRIES APPLIED" 87 | errmap[stringify(0x18, 0x02)] = "RECOVERED DATA - DATA AUTO-REALLOCATED" 88 | errmap[stringify(0x18, 0x03)] = "RECOVERED DATA WITH CIRC" 89 | errmap[stringify(0x18, 0x04)] = "RECOVERED DATA WITH LEC" 90 | errmap[stringify(0x18, 0x05)] = "RECOVERED DATA - RECOMMEND REASSIGNMENT" 91 | errmap[stringify(0x18, 0x06)] = "RECOVERED DATA - RECOMMEND REWRITE" 92 | errmap[stringify(0x19, 0x00)] = "DEFECT LIST ERROR" 93 | errmap[stringify(0x19, 0x01)] = "DEFECT LIST NOT AVAILABLE" 94 | errmap[stringify(0x19, 0x02)] = "DEFECT LIST ERROR IN PRIMARY LIST" 95 | errmap[stringify(0x19, 0x03)] = "DEFECT LIST ERROR IN GROWN LIST" 96 | errmap[stringify(0x1A, 0x00)] = "PARAMETER LIST LENGTH ERROR" 97 | errmap[stringify(0x1B, 0x00)] = "SYNCHRONOUS DATA TRANSFER ERROR" 98 | errmap[stringify(0x1C, 0x00)] = "DEFECT LIST NOT FOUND" 99 | errmap[stringify(0x1C, 0x01)] = "PRIMARY DEFECT LIST NOT FOUND" 100 | errmap[stringify(0x1C, 0x02)] = "GROWN DEFECT LIST NOT FOUND" 101 | errmap[stringify(0x1D, 0x00)] = "MISCOMPARE DURING VERIFY OPERATION" 102 | errmap[stringify(0x1E, 0x00)] = "RECOVERED ID WITH ECC" 103 | errmap[stringify(0x1F, 0x00)] = "" 104 | errmap[stringify(0x20, 0x00)] = "INVALID COMMAND OPERATION CODE" 105 | errmap[stringify(0x21, 0x00)] = "LOGICAL BLOCK ADDRESS OUT OF RANGE" 106 | errmap[stringify(0x21, 0x01)] = "INVALID ELEMENT ADDRESS" 107 | errmap[stringify(0x22, 0x00)] = "ILLEGAL FUNCTION (SHOULD USE 20 00, 24 00, OR 26 00)" 108 | errmap[stringify(0x23, 0x00)] = "" 109 | errmap[stringify(0x24, 0x00)] = "INVALID FIELD IN CDB" 110 | errmap[stringify(0x25, 0x00)] = "LOGICAL UNIT NOT SUPPORTED" 111 | errmap[stringify(0x26, 0x00)] = "INVALID FIELD IN PARAMETER LIST" 112 | errmap[stringify(0x26, 0x01)] = "PARAMETER NOT SUPPORTED" 113 | errmap[stringify(0x26, 0x02)] = "PARAMETER VALUE INVALID" 114 | errmap[stringify(0x26, 0x03)] = "THRESHOLD PARAMETERS NOT SUPPORTED" 115 | errmap[stringify(0x27, 0x00)] = "WRITE PROTECTED" 116 | errmap[stringify(0x28, 0x00)] = "NOT READY TO READY TRANSITION(MEDIUM MAY HAVE CHANGED)" 117 | errmap[stringify(0x28, 0x01)] = "IMPORT OR EXPORT ELEMENT ACCESSED" 118 | errmap[stringify(0x29, 0x00)] = "POWER ON, RESET, OR BUS DEVICE RESET OCCURRED" 119 | errmap[stringify(0x2A, 0x00)] = "PARAMETERS CHANGED" 120 | errmap[stringify(0x2A, 0x01)] = "MODE PARAMETERS CHANGED" 121 | errmap[stringify(0x2A, 0x02)] = "LOG PARAMETERS CHANGED" 122 | errmap[stringify(0x2B, 0x00)] = "COPY CANNOT EXECUTE SINCE HOST CANNOT DISCONNECT" 123 | errmap[stringify(0x2C, 0x00)] = "COMMAND SEQUENCE ERROR" 124 | errmap[stringify(0x2C, 0x01)] = "TOO MANY WINDOWS SPECIFIED" 125 | errmap[stringify(0x2C, 0x02)] = "INVALID COMBINATION OF WINDOWS SPECIFIED" 126 | errmap[stringify(0x2D, 0x00)] = "OVERWRITE ERROR ON UPDATE IN PLACE" 127 | errmap[stringify(0x2E, 0x00)] = "" 128 | errmap[stringify(0x2F, 0x00)] = "COMMANDS CLEARED BY ANOTHER INITIATOR" 129 | errmap[stringify(0x30, 0x00)] = "INCOMPATIBLE MEDIUM INSTALLED" 130 | errmap[stringify(0x30, 0x01)] = "CANNOT READ MEDIUM - UNKNOWN FORMAT" 131 | errmap[stringify(0x30, 0x02)] = "CANNOT READ MEDIUM - INCOMPATIBLE FORMAT" 132 | errmap[stringify(0x30, 0x03)] = "CLEANING CARTRIDGE INSTALLED" 133 | errmap[stringify(0x31, 0x00)] = "MEDIUM FORMAT CORRUPTED" 134 | errmap[stringify(0x31, 0x01)] = "FORMAT COMMAND FAILED" 135 | errmap[stringify(0x32, 0x00)] = "NO DEFECT SPARE LOCATION AVAILABLE" 136 | errmap[stringify(0x32, 0x01)] = "DEFECT LIST UPDATE FAILURE" 137 | errmap[stringify(0x33, 0x00)] = "TAPE LENGTH ERROR" 138 | errmap[stringify(0x34, 0x00)] = "" 139 | errmap[stringify(0x35, 0x00)] = "" 140 | errmap[stringify(0x36, 0x00)] = "RIBBON, INK, OR TONER FAILURE" 141 | errmap[stringify(0x37, 0x00)] = "ROUNDED PARAMETER" 142 | errmap[stringify(0x38, 0x00)] = "" 143 | errmap[stringify(0x39, 0x00)] = "SAVING PARAMETERS NOT SUPPORTED" 144 | errmap[stringify(0x3A, 0x00)] = "MEDIUM NOT PRESENT" 145 | errmap[stringify(0x3B, 0x00)] = "SEQUENTIAL POSITIONING ERROR" 146 | errmap[stringify(0x3B, 0x01)] = "TAPE POSITION ERROR AT BEGINNING-OF-MEDIUM" 147 | errmap[stringify(0x3B, 0x02)] = "TAPE POSITION ERROR AT END-OF-MEDIUM" 148 | errmap[stringify(0x3B, 0x03)] = "TAPE OR ELECTRONIC VERTICAL FORMS UNIT NOT READY" 149 | errmap[stringify(0x3B, 0x04)] = "SLEW FAILURE" 150 | errmap[stringify(0x3B, 0x05)] = "PAPER JAM" 151 | errmap[stringify(0x3B, 0x06)] = "FAILED TO SENSE TOP-OF-FORM" 152 | errmap[stringify(0x3B, 0x07)] = "FAILED TO SENSE BOTTOM-OF-FORM" 153 | errmap[stringify(0x3B, 0x08)] = "REPOSITION ERROR" 154 | errmap[stringify(0x3B, 0x09)] = "READ PAST END OF MEDIUM" 155 | errmap[stringify(0x3B, 0x0A)] = "READ PAST BEGINNING OF MEDIUM" 156 | errmap[stringify(0x3B, 0x0B)] = "POSITION PAST END OF MEDIUM" 157 | errmap[stringify(0x3B, 0x0C)] = "POSITION PAST BEGINNING OF MEDIUM" 158 | errmap[stringify(0x3B, 0x0D)] = "MEDIUM DESTINATION ELEMENT FULL" 159 | errmap[stringify(0x3B, 0x0E)] = "MEDIUM SOURCE ELEMENT EMPTY" 160 | errmap[stringify(0x3C, 0x00)] = "" 161 | errmap[stringify(0x3D, 0x00)] = "INVALID BITS IN IDENTIFY MESSAGE" 162 | errmap[stringify(0x3E, 0x00)] = "LOGICAL UNIT HAS NOT SELF-CONFIGURED YET" 163 | errmap[stringify(0x3F, 0x00)] = "TARGET OPERATING CONDITIONS HAVE CHANGED" 164 | errmap[stringify(0x3F, 0x01)] = "MICROCODE HAS BEEN CHANGED" 165 | errmap[stringify(0x3F, 0x02)] = "CHANGED OPERATING DEFINITION" 166 | errmap[stringify(0x3F, 0x03)] = "INQUIRY DATA HAS CHANGED" 167 | errmap[stringify(0x40, 0x00)] = "RAM FAILURE (SHOULD USE 40 NN)" 168 | //errmap[stringify(0x40, 0xNN)] = "DIAGNOSTIC FAILURE ON COMPONENT NN (80H-FFH)" 169 | errmap[stringify(0x41, 0x00)] = "DATA PATH FAILURE (SHOULD USE 40 NN)" 170 | errmap[stringify(0x42, 0x00)] = "POWER-ON OR SELF-TEST FAILURE (SHOULD USE 40 NN)" 171 | errmap[stringify(0x43, 0x00)] = "MESSAGE ERROR" 172 | errmap[stringify(0x44, 0x00)] = "INTERNAL TARGET FAILURE" 173 | errmap[stringify(0x45, 0x00)] = "SELECT OR RESELECT FAILURE" 174 | errmap[stringify(0x46, 0x00)] = "UNSUCCESSFUL SOFT RESET" 175 | errmap[stringify(0x47, 0x00)] = "SCSI PARITY ERROR" 176 | errmap[stringify(0x48, 0x00)] = "INITIATOR DETECTED ERROR MESSAGE RECEIVED" 177 | errmap[stringify(0x49, 0x00)] = "INVALID MESSAGE ERROR" 178 | errmap[stringify(0x4A, 0x00)] = "COMMAND PHASE ERROR" 179 | errmap[stringify(0x4B, 0x00)] = "DATA PHASE ERROR" 180 | errmap[stringify(0x4C, 0x00)] = "LOGICAL UNIT FAILED SELF-CONFIGURATION" 181 | errmap[stringify(0x4D, 0x00)] = "" 182 | errmap[stringify(0x4E, 0x00)] = "OVERLAPPED COMMANDS ATTEMPTED" 183 | errmap[stringify(0x4F, 0x00)] = "" 184 | errmap[stringify(0x50, 0x00)] = "WRITE APPEND ERROR" 185 | errmap[stringify(0x50, 0x01)] = "WRITE APPEND POSITION ERROR" 186 | errmap[stringify(0x50, 0x02)] = "POSITION ERROR RELATED TO TIMING" 187 | errmap[stringify(0x51, 0x00)] = "ERASE FAILURE" 188 | errmap[stringify(0x52, 0x00)] = "CARTRIDGE FAULT" 189 | errmap[stringify(0x53, 0x00)] = "MEDIA LOAD OR EJECT FAILED" 190 | errmap[stringify(0x53, 0x01)] = "UNLOAD TAPE FAILURE" 191 | errmap[stringify(0x53, 0x02)] = "MEDIUM REMOVAL PREVENTED" 192 | errmap[stringify(0x54, 0x00)] = "SCSI TO HOST SYSTEM INTERFACE FAILURE" 193 | errmap[stringify(0x55, 0x00)] = "SYSTEM RESOURCE FAILURE" 194 | errmap[stringify(0x56, 0x00)] = "" 195 | errmap[stringify(0x57, 0x00)] = "UNABLE TO RECOVER TABLE-OF-CONTENTS" 196 | errmap[stringify(0x58, 0x00)] = "GENERATION DOES NOT EXIST" 197 | errmap[stringify(0x59, 0x00)] = "UPDATED BLOCK READ" 198 | errmap[stringify(0x5A, 0x00)] = "OPERATOR REQUEST OR STATE CHANGE INPUT (UNSPECIFIED)" 199 | errmap[stringify(0x5A, 0x01)] = "OPERATOR MEDIUM REMOVAL REQUEST" 200 | errmap[stringify(0x5A, 0x02)] = "OPERATOR SELECTED WRITE PROTECT" 201 | errmap[stringify(0x5A, 0x03)] = "OPERATOR SELECTED WRITE PERMIT" 202 | errmap[stringify(0x5B, 0x00)] = "LOG EXCEPTION" 203 | errmap[stringify(0x5B, 0x01)] = "THRESHOLD CONDITION MET" 204 | errmap[stringify(0x5B, 0x02)] = "LOG COUNTER AT MAXIMUM" 205 | errmap[stringify(0x5B, 0x03)] = "LOG LIST CODES EXHAUSTED" 206 | errmap[stringify(0x5C, 0x00)] = "RPL STATUS CHANGE" 207 | errmap[stringify(0x5C, 0x01)] = "SPINDLES SYNCHRONIZED" 208 | errmap[stringify(0x5C, 0x02)] = "SPINDLES NOT SYNCHRONIZED" 209 | errmap[stringify(0x5D, 0x00)] = "" 210 | errmap[stringify(0x5E, 0x00)] = "" 211 | errmap[stringify(0x5F, 0x00)] = "" 212 | errmap[stringify(0x60, 0x00)] = "LAMP FAILURE" 213 | errmap[stringify(0x61, 0x00)] = "VIDEO ACQUISITION ERROR" 214 | errmap[stringify(0x61, 0x01)] = "UNABLE TO ACQUIRE VIDEO" 215 | errmap[stringify(0x61, 0x02)] = "OUT OF FOCUS" 216 | errmap[stringify(0x62, 0x00)] = "SCAN HEAD POSITIONING ERROR" 217 | errmap[stringify(0x63, 0x00)] = "END OF USER AREA ENCOUNTERED ON THIS TRACK" 218 | errmap[stringify(0x64, 0x00)] = "ILLEGAL MODE FOR THIS TRACK" 219 | } 220 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hd-idle 2 | 3 | Reimplementation of _Christian Mueller's_ [hd-idle](http://hd-idle.sf.net) with some extra features. 4 | 5 | `hd-idle` is a utility program for spinning-down external disks after a period of idle time. 6 | Since most external IDE disk enclosures don't support setting the IDE idle timer, 7 | a program like `hd-idle` is required to spin down idle disks automatically. 8 | 9 | _Important note_: `hd-idle` is not compatible with the usage of disk monitoring tools like 10 | **smartmontools**. 11 | 12 | **Index** 13 | * [Extra features](#extra-features) 14 | * [Support ATA commands](#support-ata-commands) 15 | * [Monitor the skew between monitoring cycles](#monitor-the-skew-between-monitoring-cycles) 16 | * [Resolve symlinks in runtime](#resolve-symlinks-in-runtime) 17 | * [Log disk spin up](#log-disk-spin-up) 18 | * [Use disk partitions or device mapper to calculate activity](#use-disk-partitions-or-device-mapper-to-calculate-activity) 19 | * [Install](#Install) 20 | * [Precompiled binaries](#precompiled-binaries) 21 | * [Build from source](#build-from-source) 22 | * [Run hd-idle](#run-hd-idle) 23 | * [Configuration](#Configuration) 24 | * [Understand the logs](#understand-the-logs) 25 | * [Standard log](#standard-log) 26 | * [Log file](#log-file) 27 | * [Warning on spinning down disks](#warning-on-spinning-down-disks) 28 | * [Troubleshot](#Troubleshot) 29 | * [Disks won't spin down](#disks-wont-spin-down) 30 | * [LUKS support](#luks-support) 31 | * [SCSI response not ok](#scsi-response-not-ok) 32 | 33 | ## Extra features 34 | 35 | List of extra features compared to the original `hd-idle`: 36 | 37 | ### Support ATA commands 38 | 39 | The implementation of `hd-idle` written by _Christian Mueller_ relies on the `SCSI` api to work. 40 | When listing the drives by id, disks starting with `usb` stop using the original implementation, 41 | but disk starting with `ata` do not. 42 | 43 | $ ls /dev/disk/by-id/ 44 | 45 | ata-WDC_WD40EZRX- 46 | ata-WDC_WD50EZRX- 47 | usb-WD_My_Book_1140_ 48 | 49 | [hdparm](https://en.wikipedia.org/wiki/Hdparm) on the other hand always stops the drives without any problems. 50 | It uses `ATA` api calls to send disks to standby. `hd-idle` comes with `ATA` commands support to replicate `hdparm`'s api calls. 51 | 52 | ### Monitor the skew between monitoring cycles 53 | 54 | Identify if the sleep took longer than expected and reset the spun down flag if it waited too long for the main loop sleep. 55 | This should capture suspend events as well as excessive machine load. 56 | 57 | ### Resolve symlinks in runtime 58 | 59 | `hd-idle` can resolve disk symlinks also in runtime. Disks added after application's start won't be hidden. 60 | 61 | ### Log disk spin up 62 | 63 | Show in standard output when disks spin up. 64 | 65 | ### Use disk partitions or device mapper to calculate activity 66 | 67 | The disk activity is calculated by watching read/write changes on partition or device mapper level instead of disk level. 68 | This is required for kernels newer than 5.4 LTS, because disk monitoring tools change read/write values on disk level, 69 | although there's no real activity on the disk itself. 70 | When using LUKS, activity will happen on the device mapper device mapped to the corresponding disk. 71 | 72 | ## Install 73 | 74 | There are various ways of installing `hd-idle`: 75 | 76 | ### Precompiled binaries 77 | 78 | Precompiled binaries for released versions are available in the 79 | [*releases*](https://github.com/adelolmo/hd-idle/releases) section. 80 | 81 | ### Build from source 82 | 83 | To build `hd-idle` from the source code yourself you need to have a working 84 | Go environment with [version 1.16 or greater installed](http://golang.org/doc/install). 85 | 86 | Open a terminal and execute these commands: 87 | 88 | git clone https://github.com/adelolmo/hd-idle 89 | cd hd-idle 90 | make 91 | 92 | On Debian you can also build the package yourself using `dpkg-buildpackage`: 93 | 94 | git clone https://github.com/adelolmo/hd-idle.git 95 | cd hd-idle 96 | dpkg-buildpackage -a armhf -us -uc -b 97 | 98 | In the example above, the package is built for `armhf`, but you can build it also for the platforms `i386`, `amd64`, and `arm64` 99 | by substituting the parameter `-a`. 100 | 101 | Then install the package: 102 | 103 | # dpkg -i ../hd-idle*.deb 104 | 105 | ## Run hd-idle 106 | 107 | In order to run `hd-idle`, type: 108 | 109 | $ hd-idle 110 | 111 | This will start `hd-idle` with the default options, causing all `SCSI` 112 | (read: USB, Firewire, SCSI, ...) hard disks to spin down after 10 minutes of inactivity. 113 | 114 | If the Debian package was installed, after editing `/etc/default/hd-idle` and enabling it (`START_HD_IDLE=true`), 115 | run hd-idle with: 116 | 117 | # systemctl start hd-idle 118 | 119 | To enable `hd-idle` on reboot: 120 | 121 | # systemctl enable hd-idle 122 | 123 | Please note that `hd-idle` uses */proc/diskstats* to read disk statistics. If 124 | this file is not present, `hd-idle` won't work. 125 | 126 | In case of problems, use the debug option *-d* to get further information. 127 | 128 | ## Configuration 129 | 130 | Command line options: 131 | 132 | + -a *name* 133 | Set device name of disks for subsequent idle-time 134 | parameters *-i*. This parameter is optional in the 135 | sense that there's a default entry for all disks 136 | which are not named otherwise by using this 137 | parameter. This can also be a symlink 138 | (e.g. /dev/disk/by-uuid/...) 139 | 140 | + -i *idle_time* 141 | Idle time in seconds for the currently named disk(s) 142 | (-a *name*) or for all disks. 143 | Setting this value to `0` will never spin down the disk(s). 144 | 145 | + -c *command_type* 146 | Api call to stop the device. Possible values are `scsi` 147 | (default value) and `ata`. 148 | 149 | + -p *power_condition* 150 | Power condition to send with the issued SCSI START STOP UNIT command. Possible values 151 | are `0-15` (inclusive). The default value of `0` works fine for disks accessible via the 152 | SCSI layer (USB, IEEE1394, ...), but it will *NOT* work as intended with real SCSI / SAS disks. 153 | A stopped SAS disk will not start up automatically on access, but requires a startup command for reactivation. 154 | Useful values for SAS disks are `2` for idle and `3` for standby. 155 | 156 | + -s *symlink_policy* 157 | Set the policy to resolve symlinks for devices. If set 158 | to `0`, symlinks are resolved only on start. If set to `1`, 159 | symlinks are also resolved on runtime until success. 160 | By default symlinks are only resolved on start. If the 161 | symlink doesn't resolve to a device, the default 162 | configuration will be applied. 163 | 164 | + -l *logfile* 165 | Name of logfile (written only after a disk has spun 166 | up or down). Please note that this option might cause the 167 | disk which holds the logfile to spin up just because 168 | another disk had some activity. On single-disk systems, 169 | this option should not cause any additional spinups. 170 | On systems with more than one disk, the disk where the log 171 | is written will be spun up. On raspberry based systems the 172 | log should be written to the SD card. 173 | + -I 174 | Ignore spin down detection. Will trigger the spin down command even if hd-idle considers 175 | the disk to be spun down already. This is useful if the drive is spinning because of 176 | undetected activities (e.g SMART calls). 177 | 178 | Miscellaneous options: 179 | 180 | + -t *disk* 181 | Spin-down the specified disk immediately and exit. 182 | 183 | + -d 184 | Debug mode. It will print debugging info to 185 | stdout/stderr (/var/log/syslog if started with systemctl) 186 | 187 | + -h 188 | Print usage information. 189 | 190 | Regarding the parameter *-a*: 191 | 192 | The parameter *-a* can be used to set a filter on the disk's device name (omit /dev/) 193 | for subsequent idle-time settings. 194 | 195 | 1) 196 | A *-i* option before the first *-a* option will set the default idle time. 197 | 198 | 2) 199 | In order to disable spin-down of disks per default, and then re-enable 200 | spin-down on selected disks, set the default idle time to 0. 201 | 202 | Example: 203 | ``` 204 | hd-idle -i 0 -a sda -i 300 -a sdb -i 1200 205 | ``` 206 | This example sets the default idle time to 0 (meaning hd-idle will never 207 | try to spin down a disk) and the default api command to `scsi`, then sets explicit 208 | idle times for disks which have the string `sda` or `sdb` in their device name. 209 | 210 | 3) 211 | The option *-c* allows to set the api call that sends the spindown command. 212 | Possible values are `scsi` (the default value) or `ata`. 213 | 214 | Example: 215 | ``` 216 | hd-idle -i 0 -c ata -a sda -i 300 -a sdb -i 1200 -c scsi 217 | ``` 218 | This example sets the default idle time to 0 (meaning hd-idle will never 219 | try to spin down a disk) and the default api command to `ata`, then sets explicit 220 | idle times for disks which have the string `sda` or `sdb` in their device name 221 | and sets `sdb` to use `scsi` api command. 222 | 223 | ## Understand the logs 224 | 225 | By default `hd-idle` only logs to the standard output. You can find them in the syslog if the application starts via service. 226 | 227 | If you set the log file (`-l` flag) then the application writes extra details to it. (Check the [Configuration](#Configuration) section). 228 | 229 | ### Standard log 230 | 231 | The standard log output registers two kinds of events: 232 | 233 | * disk spin up 234 | * disk spin down 235 | 236 | ``` 237 | Aug 8 00:14:55 enterprise hd-idle[9958]: sda spindown 238 | Aug 8 00:14:55 enterprise hd-idle[9958]: sdb spindown 239 | Aug 8 00:14:56 enterprise hd-idle[9958]: sdc spindown 240 | Aug 8 00:17:55 enterprise hd-idle[9958]: sdb spinup 241 | Aug 8 00:28:55 enterprise hd-idle[9958]: sdb spindown 242 | ``` 243 | 244 | ### Log file 245 | 246 | You can enable the log file with the flag `-l` followed by the log path. (Check the [Configuration](#Configuration) section). 247 | 248 | This is the kind of entry shown in the log file: 249 | 250 | ``` 251 | date: 2020-07-30, time: 05:28:01, disk: sdc, running: 601, stopped: 76654 252 | ``` 253 | 254 | Explanation: 255 | * `date` and `time` when the disk spins up. 256 | * `disk` involved. 257 | * `running` seconds the device was running before it spun down the last time. 258 | * `stopped` seconds since last spin down. This is the time the disk was asleep before spinning up. 259 | 260 | **Important Note:** 261 | 262 | The log file is written after a full cycle of running-stopped-wakeup. 263 | 264 | A bit more on `running` explained with the above example: 265 | 266 | | timestamp |disk spin| event |new disk spin| running | stopped | 267 | |:-----------------:|:-------:|:-----------:|:-----------:|:------------------------:|:-------------------------------------------------------:| 268 | |2020-07-29 07:59:57| down |disk activity| up | ? | ? | 269 | |2020-07-29 08:09:58| up | go to sleep | down | - | - | 270 | |2020-07-30 05:28:01| down |disk activity| up |08:09:58 - 07:59:57 = 601s|2020-07-30 05:28:01 - 2020-07-29 08:09:58 = ~21h (76654s)| 271 | 272 | Explanation: 273 | 274 | At 07:59:57 the disk is on standby and hd-idle detects disk activity. 275 | 276 | At 08:09:58 the disk is active and hd-idle determines inactivity of the disk and spins it down. 277 | 278 | At 05:28:01 on the next day the disk is on standby and hd-idle detects disk activity. It writes on the log file 601s of previous disk spin up and ~21h of standby. 279 | 280 | 281 | ## Warning on spinning down disks 282 | 283 | A word of caution: hard disks don't like spinning up too often. Laptop disks 284 | are more robust in this respect than desktop disks but if you set your disks 285 | to spin down after a few seconds you may damage the disk over time due to the 286 | stress the spin-up causes on the spindle motor and bearings. It seems that 287 | manufacturers recommend a minimum idle time of 3-5 minutes, the default in 288 | `hd-idle` is 10 minutes. 289 | 290 | You have been warned... 291 | 292 | # Troubleshot 293 | 294 | This section covers some usual issues that users face while using `hd-idle`. 295 | 296 | ## Disks won't spin down 297 | 298 | Unfortunately, it's not possible to get `hd-idle` working alongside disk monitoring 299 | tools like _smartmontools_. You have to disable those tools in order to 300 | get `hd-idle` working. 301 | 302 | ## LUKS support 303 | 304 | Using encrypted disk or partitions with LUKS is supported by the use of symlinks. 305 | 306 | 1. Run the following command with you're disk mounted: 307 | `sudo lsblk /dev/sd* -o PATH,FSSIZE,LABEL,UUID,PARTLABEL,PARTUUID,MODEL,SIZE,SERIAL,TYPE,WWN` 308 | 309 | ``` 310 | PATH FSSIZE LABEL UUID PARTLABEL PARTUUID MODEL SIZE SERIAL TYPE WWN 311 | /dev/sde ST400 3.7T ZGY0LB disk 0x5000c500a3d1d419 312 | /dev/sde1 100e952e-0ffb-4b73-bb1a-8401d4fe56c0 dropbox 14a81aa8-c2c9-448e-967b-85d87dc9b488 1T part 0x5000c500a3d1d419 313 | /dev/sde1 100e952e-0ffb-4b73-bb1a-8401d4fe56c0 dropbox 14a81aa8-c2c9-448e-967b-85d87dc9b488 1T part 0x5000c500a3d1d419 314 | /dev/sde2 2.6T three 175e2227-d24f-4ad0-9e42-2ddb8846682d d2792423-3c07-44fe-ab6b-a1aca61c73a5 2.7T part 0x5000c500a3d1d419 315 | /dev/sde2 2.6T three 175e2227-d24f-4ad0-9e42-2ddb8846682d d2792423-3c07-44fe-ab6b-a1aca61c73a5 2.7T part 0x5000c500a3d1d419 316 | /dev/mapper/luks-100e952e-0ffb-4b73-bb1a-8401d4fe56c0 317 | 1007.8G dropbox 318 | 649dd15e-6750-472c-8185-4d76bffc2490 1024G crypt 319 | ``` 320 | 321 | You have to take symlinks that resolve to disk devices: `/dev/sd*`. 322 | 323 | In the example above `/dev/mapper/luks-100e952e-0ffb-4b73-bb1a-8401d4fe56c0` is the Path to the encrypted partition, 324 | which WWN is `0x5000c500a3d1d419`. 325 | 326 | 2. Run the following command to see which devices the system has identified using `by-id`: 327 | `sudo ls -lv /dev/disk/by-id/` 328 | 329 | Output: 330 | ``` 331 | lrwxrwxrwx 1 root root 9 Jul 18 15:56 ata-ST4000DM005-2DP166_ZGY0LBRB -> ../../sde 332 | lrwxrwxrwx 1 root root 10 Jul 18 16:01 ata-ST4000DM005-2DP166_ZGY0LBRB-part1 -> ../../sde1 333 | lrwxrwxrwx 1 root root 10 Jul 18 15:56 ata-ST4000DM005-2DP166_ZGY0LBRB-part2 -> ../../sde2 334 | lrwxrwxrwx 1 root root 9 Jul 18 15:56 wwn-0x5000c500a3d1d419 -> ../../sde 335 | lrwxrwxrwx 1 root root 10 Jul 18 16:01 wwn-0x5000c500a3d1d419-part1 -> ../../sde1 336 | lrwxrwxrwx 1 root root 10 Jul 18 15:56 wwn-0x5000c500a3d1d419-part2 -> ../../sde2 337 | ``` 338 | 339 | Here we see that we can either use `ata-ST4000DM005-2DP166_ZGY0LBRB` or `wwn-0x5000c500a3d1d419` as symlinks. 340 | 341 | 3. Edit `/etc/default/hd-idle` to use the symlink you prefer. 342 | In my case, I went with the symlink using WWN (unique storage identifier), yet I could have chosen MODEL (device identifier) instead. 343 | 344 | `HD_IDLE_OPTS='-i 0 -c ata -s 1 -l /var/log/hd-idle.log -a /dev/disk/by-id/wwn-0x5000c500a3d1d419 -i 600'` 345 | Or 346 | `HD_IDLE_OPTS='-i 0 -c ata -s 1 -l /var/log/hd-idle.log -a /dev/disk/by-id/ata-ST4000DM005-2DP166_ZGY0LBRB -i 600'` 347 | 348 | ## SCSI response not ok 349 | 350 | You can find information about the issue here: [SCSI-response-not-ok](https://github.com/adelolmo/hd-idle/wiki/SCSI-response-not-ok) 351 | 352 | ## License 353 | 354 | GNU General Public License v3.0, see [LICENSE](https://github.com/adelolmo/hd-idle/blob/master/LICENSE). 355 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------