github.com/shaardie/u-root@v4.0.1-0.20190127173353-f24a1c26aa2e+incompatible/pkg/loop/loop.go (about)

     1  // Copyright 2018 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 loop provides an interface to interacting with Linux loop devices.
     6  //
     7  // A loop device exposes a regular file as if it were a block device.
     8  package loop
     9  
    10  import (
    11  	"github.com/u-root/u-root/pkg/mount"
    12  	"golang.org/x/sys/unix"
    13  )
    14  
    15  // Loop represents a regular file exposed as a loop block device.
    16  //
    17  // Loop implements mount.Mount.
    18  type Loop struct {
    19  	// Dev is the loop device path.
    20  	Dev string
    21  
    22  	// Source is the regular file to use as a block device.
    23  	Source string
    24  
    25  	// Dir is the directory to mount the block device on.
    26  	Dir string
    27  
    28  	// FSType is the file system to use when mounting the block device.
    29  	FSType string
    30  
    31  	// Flags are flags to pass to mount(2).
    32  	Flags uintptr
    33  
    34  	// Data is the data to pass to mount(2).
    35  	Data string
    36  
    37  	// Mounted indicates whether the device has been mounted.
    38  	Mounted bool
    39  }
    40  
    41  // New initializes a Loop struct and allocates a loodevice to it.
    42  //
    43  // source is the file to use as a loop block device. target is the directory
    44  // the device should be mounted on.
    45  func New(source, target, fstype string, flags uintptr, data string) (mount.Mounter, error) {
    46  	devicename, err := FindDevice()
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  	if err := SetFile(devicename, source); err != nil {
    51  		return nil, err
    52  	}
    53  	return &Loop{
    54  		Dev:    devicename,
    55  		Dir:    target,
    56  		Source: source,
    57  		FSType: fstype,
    58  		Flags:  flags,
    59  		Data:   data,
    60  	}, nil
    61  }
    62  
    63  // Mount mounts the provided source file, with type fstype, and flags and data options
    64  // (which are usually 0 and ""), using the allocated loop device.
    65  func (l *Loop) Mount() error {
    66  	if err := unix.Mount(l.Dev, l.Dir, l.FSType, l.Flags, l.Data); err != nil {
    67  		return err
    68  	}
    69  	l.Mounted = true
    70  	return nil
    71  }