github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/pkg/rtc/rtc.go (about)

     1  // Copyright 2021 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package rtc
     6  
     7  import (
     8  	"errors"
     9  	"os"
    10  )
    11  
    12  type RTC struct {
    13  	file *os.File
    14  	syscalls
    15  }
    16  
    17  // OpenRTC opens an RTC. It will typically only work on Linux, but since it
    18  // uses a file API, it will be tried on all systems. Perhaps at some future
    19  // time, other kernels will implement this API.
    20  func OpenRTC() (*RTC, error) {
    21  	devs := []string{
    22  		"/dev/rtc",
    23  		"/dev/rtc0",
    24  		"/dev/misc/rtc0",
    25  	}
    26  
    27  	// This logic seems a bit odd, but here is the problem:
    28  	// an error that is NOT IsNotExist may indicate some
    29  	// deeper RTC problem, and should probably halt further efforts.
    30  	// If all opens fail, and we drop out of the loop, then there is
    31  	// no device.
    32  	for _, dev := range devs {
    33  		f, err := os.Open(dev)
    34  		if err == nil {
    35  			return &RTC{f, realSyscalls{}}, err
    36  		}
    37  		if !os.IsNotExist(err) {
    38  			return nil, err
    39  		}
    40  	}
    41  
    42  	return nil, errors.New("no RTC device found")
    43  }
    44  
    45  // Close closes the RTC
    46  func (r *RTC) Close() error {
    47  	return r.file.Close()
    48  }