daemon/graphdriver/aufs/aufs.go
9a9dc5ba
 // +build linux
 
b8b509e1
 /*
 
 aufs driver directory structure
 
9a9dc5ba
   .
   ├── layers // Metadata of layers
   │   ├── 1
   │   ├── 2
   │   └── 3
   ├── diff  // Content of the layer
   │   ├── 1  // Contains layers that need to be mounted for the id
   │   ├── 2
   │   └── 3
   └── mnt    // Mount points for the rw layers to be mounted
       ├── 1
       ├── 2
       └── 3
b8b509e1
 
 */
 
699a1074
 package aufs
 
 import (
043a5761
 	"bufio"
699a1074
 	"fmt"
aa2cc187
 	"io"
281abd2c
 	"io/ioutil"
699a1074
 	"os"
 	"os/exec"
 	"path"
65d79e3e
 	"path/filepath"
043a5761
 	"strings"
5fe26ee4
 	"sync"
0e539fec
 	"time"
e8a87120
 
b3ee9ac7
 	"github.com/docker/docker/daemon/graphdriver"
30d5a42c
 	"github.com/docker/docker/pkg/archive"
1cb17f03
 	"github.com/docker/docker/pkg/chrootarchive"
7a7357da
 	"github.com/docker/docker/pkg/containerfs"
e2b8933d
 	"github.com/docker/docker/pkg/directory"
442b4562
 	"github.com/docker/docker/pkg/idtools"
fc1cf191
 	"github.com/docker/docker/pkg/locker"
b3ee9ac7
 	mountpk "github.com/docker/docker/pkg/mount"
54dcbab2
 	"github.com/docker/docker/pkg/system"
2a71f28a
 	rsystem "github.com/opencontainers/runc/libcontainer/system"
abbbf914
 	"github.com/opencontainers/selinux/go-selinux/label"
d42dbdd3
 	"github.com/pkg/errors"
1009e6a4
 	"github.com/sirupsen/logrus"
069fdc8a
 	"github.com/vbatts/tar-split/tar/storage"
 	"golang.org/x/sys/unix"
699a1074
 )
 
9e28c3e3
 var (
55885daa
 	// ErrAufsNotSupported is returned if aufs is not supported by the host.
9e28c3e3
 	ErrAufsNotSupported = fmt.Errorf("AUFS was not found in /proc/filesystems")
2a71f28a
 	// ErrAufsNested means aufs cannot be used bc we are in a user namespace
1fc0acc9
 	ErrAufsNested = fmt.Errorf("AUFS cannot be used in non-init user namespace")
 	backingFs     = "<unknown>"
281abd2c
 
 	enableDirpermLock sync.Once
 	enableDirperm     bool
9e28c3e3
 )
 
752bfba2
 func init() {
 	graphdriver.Register("aufs", Init)
 }
 
55885daa
 // Driver contains information about the filesystem mounted.
51a972f3
 type Driver struct {
824c24e6
 	sync.Mutex
65d79e3e
 	root          string
 	uidMaps       []idtools.IDMap
 	gidMaps       []idtools.IDMap
5b6b8df0
 	ctr           *graphdriver.RefCounter
65d79e3e
 	pathCacheLock sync.Mutex
 	pathCache     map[string]string
362369b4
 	naiveDiff     graphdriver.DiffDriver
fc1cf191
 	locker        *locker.Locker
699a1074
 }
 
55885daa
 // Init returns a new AUFS driver.
ff42748b
 // An error is returned if AUFS is not supported.
442b4562
 func Init(root string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
48b1dd00
 
752bfba2
 	// Try to load the aufs kernel module
043a5761
 	if err := supportsAufs(); err != nil {
4bdb8c03
 		return nil, graphdriver.ErrNotSupported
752bfba2
 	}
e8a87120
 
f9c8fa30
 	// Perform feature detection on /var/lib/docker/aufs if it's an existing directory.
 	// This covers situations where /var/lib/docker/aufs is a mount, and on a different
 	// filesystem than /var/lib/docker.
 	// If the path does not exist, fall back to using /var/lib/docker for feature detection.
 	testdir := root
 	if _, err := os.Stat(testdir); os.IsNotExist(err) {
 		testdir = filepath.Dir(testdir)
 	}
 
 	fsMagic, err := graphdriver.GetFSMagic(testdir)
48b1dd00
 	if err != nil {
 		return nil, err
 	}
 	if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
 		backingFs = fsName
e8a87120
 	}
 
1fc0acc9
 	switch fsMagic {
5e85ec82
 	case graphdriver.FsMagicAufs, graphdriver.FsMagicBtrfs, graphdriver.FsMagicEcryptfs:
1fc0acc9
 		logrus.Errorf("AUFS is not supported over %s", backingFs)
 		return nil, graphdriver.ErrIncompatibleFS
e8a87120
 	}
 
b8b509e1
 	paths := []string{
 		"mnt",
 		"diff",
 		"layers",
 	}
 
5fe26ee4
 	a := &Driver{
65d79e3e
 		root:      root,
 		uidMaps:   uidMaps,
 		gidMaps:   gidMaps,
 		pathCache: make(map[string]string),
5b6b8df0
 		ctr:       graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicAufs)),
fc1cf191
 		locker:    locker.New(),
5fe26ee4
 	}
 
442b4562
 	rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
 	if err != nil {
 		return nil, err
 	}
516010e9
 	// Create the root aufs driver dir
38b3af56
 	if err := idtools.MkdirAllAndChown(root, 0700, idtools.IDPair{UID: rootUID, GID: rootGID}); err != nil {
b8b509e1
 		return nil, err
 	}
 
930a756a
 	if err := mountpk.MakePrivate(root); err != nil {
3609b051
 		return nil, err
 	}
 
a83a7693
 	// Populate the dir structure
b8b509e1
 	for _, p := range paths {
38b3af56
 		if err := idtools.MkdirAllAndChown(path.Join(root, p), 0700, idtools.IDPair{UID: rootUID, GID: rootGID}); err != nil {
b8b509e1
 			return nil, err
 		}
 	}
0a98025d
 	logger := logrus.WithFields(logrus.Fields{
 		"module": "graphdriver",
 		"driver": "aufs",
 	})
362369b4
 
276b4460
 	for _, path := range []string{"mnt", "diff"} {
 		p := filepath.Join(root, path)
0a98025d
 		entries, err := ioutil.ReadDir(p)
276b4460
 		if err != nil {
0a98025d
 			logger.WithError(err).WithField("dir", p).Error("error reading dir entries")
276b4460
 			continue
 		}
0a98025d
 		for _, entry := range entries {
 			if !entry.IsDir() {
 				continue
 			}
 			if strings.HasSuffix(entry.Name(), "-removing") {
 				logger.WithField("dir", entry.Name()).Debug("Cleaning up stale layer dir")
 				if err := system.EnsureRemoveAll(filepath.Join(p, entry.Name())); err != nil {
 					logger.WithField("dir", entry.Name()).WithError(err).Error("Error removing stale layer dir")
276b4460
 				}
 			}
 		}
 	}
 
362369b4
 	a.naiveDiff = graphdriver.NewNaiveDiffDriver(a, uidMaps, gidMaps)
5fe26ee4
 	return a, nil
699a1074
 }
 
043a5761
 // Return a nil error if the kernel supports aufs
 // We cannot modprobe because inside dind modprobe fails
 // to run
 func supportsAufs() error {
7b2d59b9
 	// We can try to modprobe aufs first before looking at
 	// proc/filesystems for when aufs is supported
 	exec.Command("modprobe", "aufs").Run()
 
2a71f28a
 	if rsystem.RunningInUserNS() {
 		return ErrAufsNested
 	}
 
043a5761
 	f, err := os.Open("/proc/filesystems")
 	if err != nil {
 		return err
 	}
 	defer f.Close()
 
 	s := bufio.NewScanner(f)
 	for s.Scan() {
 		if strings.Contains(s.Text(), "aufs") {
 			return nil
 		}
 	}
9e28c3e3
 	return ErrAufsNotSupported
043a5761
 }
 
2540765d
 func (a *Driver) rootPath() string {
08a27698
 	return a.root
b8b509e1
 }
 
2540765d
 func (*Driver) String() string {
b8b509e1
 	return "aufs"
 }
 
55885daa
 // Status returns current information about the filesystem such as root directory, number of directories mounted, etc.
2540765d
 func (a *Driver) Status() [][2]string {
5306053e
 	ids, _ := loadIds(path.Join(a.rootPath(), "layers"))
 	return [][2]string{
 		{"Root Dir", a.rootPath()},
48b1dd00
 		{"Backing Filesystem", backingFs},
5306053e
 		{"Dirs", fmt.Sprintf("%d", len(ids))},
d68d5f2e
 		{"Dirperm1 Supported", fmt.Sprintf("%v", useDirperm())},
5306053e
 	}
243843c0
 }
 
55885daa
 // GetMetadata not implemented
407a626b
 func (a *Driver) GetMetadata(id string) (map[string]string, error) {
 	return nil, nil
 }
 
29f07f85
 // Exists returns true if the given id is registered with
 // this driver
2540765d
 func (a *Driver) Exists(id string) bool {
5ee8e41e
 	if _, err := os.Lstat(path.Join(a.rootPath(), "layers", id)); err != nil {
a518b847
 		return false
 	}
 	return true
 }
 
ef5bfad3
 // CreateReadWrite creates a layer that is writable for use as a container
 // file system.
b937aa8e
 func (a *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
 	return a.Create(id, parent, opts)
ef5bfad3
 }
 
55885daa
 // Create three folders for each id
b8b509e1
 // mnt, layers, and diff
b937aa8e
 func (a *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error {
b16decfc
 
b937aa8e
 	if opts != nil && len(opts.StorageOpt) != 0 {
b16decfc
 		return fmt.Errorf("--storage-opt is not supported for aufs")
 	}
 
c2f77776
 	if err := a.createDirsFor(id); err != nil {
ed572b45
 		return err
 	}
b8b509e1
 	// Write the layers metadata
 	f, err := os.Create(path.Join(a.rootPath(), "layers", id))
 	if err != nil {
ed572b45
 		return err
 	}
b8b509e1
 	defer f.Close()
ed572b45
 
b8b509e1
 	if parent != "" {
362369b4
 		ids, err := getParentIDs(a.rootPath(), parent)
b8b509e1
 		if err != nil {
ed572b45
 			return err
 		}
 
c2f77776
 		if _, err := fmt.Fprintln(f, parent); err != nil {
ed188446
 			return err
 		}
b8b509e1
 		for _, i := range ids {
c2f77776
 			if _, err := fmt.Fprintln(f, i); err != nil {
ed188446
 				return err
 			}
b8b509e1
 		}
ed572b45
 	}
65d79e3e
 
ed572b45
 	return nil
 }
 
772f5495
 // createDirsFor creates two directories for the given id.
 // mnt and diff
51a972f3
 func (a *Driver) createDirsFor(id string) error {
b8b509e1
 	paths := []string{
 		"mnt",
 		"diff",
 	}
ed572b45
 
442b4562
 	rootUID, rootGID, err := idtools.GetRootUIDGID(a.uidMaps, a.gidMaps)
 	if err != nil {
 		return err
 	}
772f5495
 	// Directory permission is 0755.
 	// The path of directories are <aufs_root_path>/mnt/<image_id>
 	// and <aufs_root_path>/diff/<image_id>
b8b509e1
 	for _, p := range paths {
38b3af56
 		if err := idtools.MkdirAllAndChown(path.Join(a.rootPath(), p, id), 0755, idtools.IDPair{UID: rootUID, GID: rootGID}); err != nil {
b8b509e1
 			return err
 		}
ed572b45
 	}
b8b509e1
 	return nil
 }
ed572b45
 
55885daa
 // Remove will unmount and remove the given id.
51a972f3
 func (a *Driver) Remove(id string) error {
fc1cf191
 	a.locker.Lock(id)
 	defer a.locker.Unlock(id)
65d79e3e
 	a.pathCacheLock.Lock()
 	mountpoint, exists := a.pathCache[id]
 	a.pathCacheLock.Unlock()
 	if !exists {
 		mountpoint = a.getMountpoint(id)
ed572b45
 	}
0e539fec
 
d42dbdd3
 	logger := logrus.WithFields(logrus.Fields{
 		"module": "graphdriver",
 		"driver": "aufs",
 		"layer":  id,
 	})
 
0e539fec
 	var retries int
 	for {
 		mounted, err := a.mounted(mountpoint)
 		if err != nil {
d42dbdd3
 			if os.IsNotExist(err) {
 				break
 			}
0e539fec
 			return err
 		}
 		if !mounted {
 			break
 		}
 
d42dbdd3
 		err = a.unmount(mountpoint)
 		if err == nil {
 			break
 		}
 
 		if err != unix.EBUSY {
 			return errors.Wrapf(err, "aufs: unmount error: %s", mountpoint)
 		}
 		if retries >= 5 {
 			return errors.Wrapf(err, "aufs: unmount error after retries: %s", mountpoint)
0e539fec
 		}
d42dbdd3
 		// If unmount returns EBUSY, it could be a transient error. Sleep and retry.
 		retries++
 		logger.Warnf("unmount failed due to EBUSY: retry count: %d", retries)
 		time.Sleep(100 * time.Millisecond)
b8b509e1
 	}
 
276b4460
 	// Remove the layers file for the id
 	if err := os.Remove(path.Join(a.rootPath(), "layers", id)); err != nil && !os.IsNotExist(err) {
 		return errors.Wrapf(err, "error removing layers dir for %s", id)
65d79e3e
 	}
 
276b4460
 	if err := atomicRemove(a.getDiffPath(id)); err != nil {
 		return errors.Wrapf(err, "could not remove diff path for id %s", id)
b8b509e1
 	}
65d79e3e
 
276b4460
 	// Atomically remove each directory in turn by first moving it out of the
 	// way (so that docker doesn't find it anymore) before doing removal of
 	// the whole tree.
 	if err := atomicRemove(mountpoint); err != nil {
 		if errors.Cause(err) == unix.EBUSY {
 			logger.WithField("dir", mountpoint).WithError(err).Warn("error performing atomic remove due to EBUSY")
 		}
 		return errors.Wrapf(err, "could not remove mountpoint for id %s", id)
43899a77
 	}
65d79e3e
 
 	a.pathCacheLock.Lock()
 	delete(a.pathCache, id)
 	a.pathCacheLock.Unlock()
43899a77
 	return nil
ed572b45
 }
 
276b4460
 func atomicRemove(source string) error {
 	target := source + "-removing"
 
 	err := os.Rename(source, target)
 	switch {
 	case err == nil, os.IsNotExist(err):
 	case os.IsExist(err):
 		// Got error saying the target dir already exists, maybe the source doesn't exist due to a previous (failed) remove
 		if _, e := os.Stat(source); !os.IsNotExist(e) {
 			return errors.Wrapf(err, "target rename dir '%s' exists but should not, this needs to be manually cleaned up")
 		}
 	default:
 		return errors.Wrapf(err, "error preparing atomic delete")
 	}
 
 	return system.EnsureRemoveAll(target)
 }
 
55885daa
 // Get returns the rootfs path for the id.
4e959ef2
 // This will mount the dir at its given path
7a7357da
 func (a *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) {
fc1cf191
 	a.locker.Lock(id)
 	defer a.locker.Unlock(id)
55c91f2a
 	parents, err := a.getParentLayerPaths(id)
 	if err != nil && !os.IsNotExist(err) {
7a7357da
 		return nil, err
55c91f2a
 	}
 
65d79e3e
 	a.pathCacheLock.Lock()
 	m, exists := a.pathCache[id]
 	a.pathCacheLock.Unlock()
 
 	if !exists {
 		m = a.getDiffPath(id)
 		if len(parents) > 0 {
 			m = a.getMountpoint(id)
 		}
 	}
5b6b8df0
 	if count := a.ctr.Increment(m); count > 1 {
7a7357da
 		return containerfs.NewLocalContainerFS(m), nil
5b6b8df0
 	}
65d79e3e
 
b8b509e1
 	// If a dir does not have a parent ( no layers )do not try to mount
 	// just return the diff path to the data
55c91f2a
 	if len(parents) > 0 {
65d79e3e
 		if err := a.mount(id, m, mountLabel, parents); err != nil {
7a7357da
 			return nil, err
b8b509e1
 		}
 	}
65d79e3e
 
 	a.pathCacheLock.Lock()
 	a.pathCache[id] = m
 	a.pathCacheLock.Unlock()
7a7357da
 	return containerfs.NewLocalContainerFS(m), nil
b8b509e1
 }
 
55885daa
 // Put unmounts and updates list of active mounts.
00fd63e5
 func (a *Driver) Put(id string) error {
fc1cf191
 	a.locker.Lock(id)
 	defer a.locker.Unlock(id)
65d79e3e
 	a.pathCacheLock.Lock()
 	m, exists := a.pathCache[id]
 	if !exists {
 		m = a.getMountpoint(id)
 		a.pathCache[id] = m
20bb0655
 	}
65d79e3e
 	a.pathCacheLock.Unlock()
5b6b8df0
 	if count := a.ctr.Decrement(m); count > 0 {
 		return nil
 	}
65d79e3e
 
 	err := a.unmount(m)
 	if err != nil {
 		logrus.Debugf("Failed to unmount %s aufs: %v", id, err)
5fe26ee4
 	}
65d79e3e
 	return err
bcaf6c23
 }
 
362369b4
 // isParent returns if the passed in parent is the direct parent of the passed in layer
 func (a *Driver) isParent(id, parent string) bool {
 	parents, _ := getParentIDs(a.rootPath(), id)
 	if parent == "" && len(parents) > 0 {
 		return false
 	}
 	return !(len(parents) > 0 && parent != parents[0])
 }
 
dee6b481
 // Diff produces an archive of the changes between the specified
 // layer and its parent layer which may be "".
aa2cc187
 func (a *Driver) Diff(id, parent string) (io.ReadCloser, error) {
362369b4
 	if !a.isParent(id, parent) {
 		return a.naiveDiff.Diff(id, parent)
 	}
 
dee6b481
 	// AUFS doesn't need the parent layer to produce a diff.
111ab125
 	return archive.TarWithOptions(path.Join(a.rootPath(), "diff", id), &archive.TarOptions{
6d801a3c
 		Compression:     archive.Uncompressed,
2fb5d0c3
 		ExcludePatterns: []string{archive.WhiteoutMetaPrefix + "*", "!" + archive.WhiteoutOpaqueDir},
442b4562
 		UIDMaps:         a.uidMaps,
 		GIDMaps:         a.gidMaps,
5d972300
 	})
 }
 
58bec40d
 type fileGetNilCloser struct {
 	storage.FileGetter
 }
 
 func (f fileGetNilCloser) Close() error {
 	return nil
 }
 
 // DiffGetter returns a FileGetCloser that can read files from the directory that
 // contains files for the layer differences. Used for direct access for tar-split.
 func (a *Driver) DiffGetter(id string) (graphdriver.FileGetCloser, error) {
 	p := path.Join(a.rootPath(), "diff", id)
 	return fileGetNilCloser{storage.NewPathFileGetter(p)}, nil
0641429a
 }
 
aa2cc187
 func (a *Driver) applyDiff(id string, diff io.Reader) error {
98d09978
 	return chrootarchive.UntarUncompressed(diff, path.Join(a.rootPath(), "diff", id), &archive.TarOptions{
442b4562
 		UIDMaps: a.uidMaps,
 		GIDMaps: a.gidMaps,
98d09978
 	})
b8b509e1
 }
699a1074
 
dee6b481
 // DiffSize calculates the changes between the specified id
 // and its parent and returns the size in bytes of the changes
 // relative to its base filesystem directory.
35a22c9e
 func (a *Driver) DiffSize(id, parent string) (size int64, err error) {
362369b4
 	if !a.isParent(id, parent) {
 		return a.naiveDiff.DiffSize(id, parent)
 	}
dee6b481
 	// AUFS doesn't need the parent layer to calculate the diff size.
e2b8933d
 	return directory.Size(path.Join(a.rootPath(), "diff", id))
b8b509e1
 }
 
dee6b481
 // ApplyDiff extracts the changeset from the given diff into the
 // layer with the specified id and parent, returning the size of the
 // new layer in bytes.
aa2cc187
 func (a *Driver) ApplyDiff(id, parent string, diff io.Reader) (size int64, err error) {
362369b4
 	if !a.isParent(id, parent) {
 		return a.naiveDiff.ApplyDiff(id, parent, diff)
 	}
 
 	// AUFS doesn't need the parent id to apply the diff if it is the direct parent.
dee6b481
 	if err = a.applyDiff(id, diff); err != nil {
 		return
 	}
 
 	return a.DiffSize(id, parent)
 }
 
 // Changes produces a list of changes between the specified layer
 // and its parent layer. If parent is "", then all changes will be ADD changes.
 func (a *Driver) Changes(id, parent string) ([]archive.Change, error) {
362369b4
 	if !a.isParent(id, parent) {
 		return a.naiveDiff.Changes(id, parent)
 	}
 
dee6b481
 	// AUFS doesn't have snapshots, so we need to get changes from all parent
 	// layers.
ed188446
 	layers, err := a.getParentLayerPaths(id)
 	if err != nil {
 		return nil, err
 	}
 	return archive.Changes(layers, path.Join(a.rootPath(), "diff", id))
 }
 
51a972f3
 func (a *Driver) getParentLayerPaths(id string) ([]string, error) {
362369b4
 	parentIds, err := getParentIDs(a.rootPath(), id)
ed188446
 	if err != nil {
 		return nil, err
 	}
 	layers := make([]string, len(parentIds))
 
 	// Get the diff paths for all the parent ids
 	for i, p := range parentIds {
 		layers[i] = path.Join(a.rootPath(), "diff", p)
 	}
 	return layers, nil
b8b509e1
 }
 
65d79e3e
 func (a *Driver) mount(id string, target string, mountLabel string, layers []string) error {
824c24e6
 	a.Lock()
 	defer a.Unlock()
 
b8b509e1
 	// If the id is mounted or we get an error return
65d79e3e
 	if mounted, err := a.mounted(target); err != nil || mounted {
699a1074
 		return err
 	}
b8b509e1
 
65d79e3e
 	rw := a.getDiffPath(id)
b8b509e1
 
f0e6e135
 	if err := a.aufsMount(layers, rw, target, mountLabel); err != nil {
c0f78199
 		return fmt.Errorf("error creating aufs mount to %s: %v", target, err)
699a1074
 	}
 	return nil
 }
 
65d79e3e
 func (a *Driver) unmount(mountPath string) error {
824c24e6
 	a.Lock()
 	defer a.Unlock()
 
65d79e3e
 	if mounted, err := a.mounted(mountPath); err != nil || !mounted {
 		return err
 	}
b4a63139
 	return Unmount(mountPath)
699a1074
 }
 
65d79e3e
 func (a *Driver) mounted(mountpoint string) (bool, error) {
 	return graphdriver.Mounted(graphdriver.FsMagicAufs, mountpoint)
ed572b45
 }
 
55885daa
 // Cleanup aufs and unmount all mountpoints
51a972f3
 func (a *Driver) Cleanup() error {
65d79e3e
 	var dirs []string
 	if err := filepath.Walk(a.mntPath(), func(path string, info os.FileInfo, err error) error {
 		if err != nil {
 			return err
 		}
 		if !info.IsDir() {
 			return nil
 		}
 		dirs = append(dirs, path)
 		return nil
 	}); err != nil {
 		return err
 	}
 
 	for _, m := range dirs {
20bb0655
 		if err := a.unmount(m); err != nil {
af835956
 			logrus.Debugf("aufs error unmounting %s: %s", m, err)
ed572b45
 		}
 	}
3609b051
 	return mountpk.Unmount(a.root)
699a1074
 }
 
f0e6e135
 func (a *Driver) aufsMount(ro []string, rw, target, mountLabel string) (err error) {
6d34c50e
 	defer func() {
 		if err != nil {
 			Unmount(target)
 		}
 	}()
699a1074
 
6d97339c
 	// Mount options are clipped to page size(4096 bytes). If there are more
 	// layers then these are remounted individually using append.
 
281abd2c
 	offset := 54
 	if useDirperm() {
1a6bf824
 		offset += len(",dirperm1")
281abd2c
 	}
069fdc8a
 	b := make([]byte, unix.Getpagesize()-len(mountLabel)-offset) // room for xino & mountLabel
6d97339c
 	bp := copy(b, fmt.Sprintf("br:%s=rw", rw))
 
b6a268d9
 	index := 0
 	for ; index < len(ro); index++ {
 		layer := fmt.Sprintf(":%s=ro+wh", ro[index])
 		if bp+len(layer) > len(b) {
 			break
699a1074
 		}
b6a268d9
 		bp += copy(b[bp:], layer)
 	}
6d34c50e
 
b6a268d9
 	opts := "dio,xino=/dev/shm/aufs.xino"
 	if useDirperm() {
 		opts += ",dirperm1"
 	}
 	data := label.FormatMountLabel(fmt.Sprintf("%s,%s", string(b[:bp]), opts), mountLabel)
 	if err = mount("none", target, "aufs", 0, data); err != nil {
 		return
 	}
6d34c50e
 
b6a268d9
 	for ; index < len(ro); index++ {
 		layer := fmt.Sprintf(":%s=ro+wh", ro[index])
 		data := label.FormatMountLabel(fmt.Sprintf("append%s", layer), mountLabel)
069fdc8a
 		if err = mount("none", target, "aufs", unix.MS_REMOUNT, data); err != nil {
b6a268d9
 			return
6d97339c
 		}
6d34c50e
 	}
6d97339c
 
 	return
699a1074
 }
281abd2c
 
 // useDirperm checks dirperm1 mount option can be used with the current
 // version of aufs.
 func useDirperm() bool {
 	enableDirpermLock.Do(func() {
 		base, err := ioutil.TempDir("", "docker-aufs-base")
 		if err != nil {
d1306e63
 			logrus.Errorf("error checking dirperm1: %v", err)
281abd2c
 			return
 		}
 		defer os.RemoveAll(base)
 
 		union, err := ioutil.TempDir("", "docker-aufs-union")
 		if err != nil {
d1306e63
 			logrus.Errorf("error checking dirperm1: %v", err)
281abd2c
 			return
 		}
 		defer os.RemoveAll(union)
 
 		opts := fmt.Sprintf("br:%s,dirperm1,xino=/dev/shm/aufs.xino", base)
 		if err := mount("none", union, "aufs", 0, opts); err != nil {
 			return
 		}
 		enableDirperm = true
 		if err := Unmount(union); err != nil {
d1306e63
 			logrus.Errorf("error checking dirperm1: failed to unmount %v", err)
281abd2c
 		}
 	})
 	return enableDirperm
 }