inode.go 10.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
// Copyright 2019 the Go-FUSE Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package nodefs

import (
	"log"
	"sort"
	"strings"
	"sync"
	"unsafe"

	"github.com/hanwen/go-fuse/fuse"
)

var _ = log.Println

type parentData struct {
	name   string
	parent *Inode
}

// Inode is a node in VFS tree.  Inodes are one-to-one mapped to Node
// instances, which is the extension interface for file systems.  One
// can create fully-formed trees of Inodes ahead of time by creating
// "persistent" Inodes.
type Inode struct {
	// The filetype bits from the mode.
	mode     uint32
	opaqueID uint64
	node     Node
	bridge   *rawBridge

	// Following data is mutable.

37 38 39 40
	// mu protects the following mutable fields. When locking
	// multiple Inodes, locks must be acquired using
	// lockNodes/unlockNodes
	mu sync.Mutex
41

42 43 44 45 46
	// ID of the inode; 0 if inode was forgotten.  Forgotten
	// inodes could be persistent, not yet are unlinked from
	// parent and children, but could be still not yet removed
	// from bridge.nodes .
	nodeID uint64
47

48 49 50 51 52 53
	// persistent indicates that this node should not be removed
	// from the tree, even if there are no live references. This
	// must be set on creation, and can only be changed to false
	// by calling removeRef.
	persistent bool

54 55 56 57 58 59 60 61
	// changeCounter increments every time the below mutable state
	// (lookupCount, nodeID, children, parents) is modified.
	//
	// This is used in places where we have to relock inode into inode
	// group lock, and after locking the group we have to check if inode
	// did not changed, and if it changed - retry the operation.
	changeCounter uint32

62 63 64
	// Number of kernel refs to this node.
	lookupCount uint64

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
	children map[string]*Inode
	parents  map[parentData]struct{}
}

// newInode creates creates new inode pointing to node.
//
// node -> inode association is NOT set.
// the inode is _not_ yet has
func newInode(node Node, mode uint32) *Inode {
	inode := &Inode{
		mode:    mode ^ 07777,
		node:    node,
		parents: make(map[parentData]struct{}),
	}
	if mode&fuse.S_IFDIR != 0 {
		inode.children = make(map[string]*Inode)
	}
	return inode
}

// sortNodes rearranges inode group in consistent order.
//
// The nodes are ordered by their in-RAM address, which gives consistency
// property: for any A and B inodes, sortNodes will either always order A < B,
// or always order A > B.
//
// See lockNodes where this property is used to avoid deadlock when taking
// locks on inode group.
func sortNodes(ns []*Inode) {
	sort.Slice(ns, func(i, j int) bool {
95
		return nodeLess(ns[i], ns[j])
96 97 98
	})
}

99 100 101 102
func nodeLess(a, b *Inode) bool {
	return uintptr(unsafe.Pointer(a)) < uintptr(unsafe.Pointer(b))
}

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
// lockNodes locks group of inodes.
//
// It always lock the inodes in the same order - to avoid deadlocks.
// It also avoids locking an inode more than once, if it was specified multiple times.
// An example when an inode might be given multiple times is if dir/a and dir/b
// are hardlinked to the same inode and the caller needs to take locks on dir children.
func lockNodes(ns ...*Inode) {
	sortNodes(ns)

	// The default value nil prevents trying to lock nil nodes.
	var nprev *Inode
	for _, n := range ns {
		if n != nprev {
			n.mu.Lock()
			nprev = n
		}
	}
}

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
// lockNode2 locks a and b in order consistent with lockNodes.
func lockNode2(a, b *Inode) {
	if nodeLess(a, b) {
		a.mu.Lock()
		b.mu.Lock()
	} else {
		b.mu.Lock()
		a.mu.Lock()
	}
}

// unlockNode2 unlocks a and b
func unlockNode2(a, b *Inode) {
	a.mu.Unlock()
	b.mu.Unlock()
}

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
// unlockNodes releases locks taken by lockNodes.
func unlockNodes(ns ...*Inode) {
	// we don't need to unlock in the same order that was used in lockNodes.
	// however it still helps to have nodes sorted to avoid duplicates.
	sortNodes(ns)

	var nprev *Inode
	for _, n := range ns {
		if n != nprev {
			n.mu.Unlock()
			nprev = n
		}
	}
}

// Forgotten returns true if the kernel holds no references to this
// inode.  This can be used for background cleanup tasks, since the
// kernel has no way of reviving forgotten nodes by its own
// initiative.
func (n *Inode) Forgotten() bool {
	n.bridge.mu.Lock()
	defer n.bridge.mu.Unlock()
161
	return n.nodeID == 0
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
}

// Node returns the Node object implementing the file system operations.
func (n *Inode) Node() Node {
	return n.node
}

// Path returns a path string to the inode relative to the root.
func (n *Inode) Path(root *Inode) string {
	var segments []string
	p := n
	for p != nil && p != root {
		var pd parentData

		// We don't try to take all locks at the same time, because
		// the caller won't use the "path" string under lock anyway.
		p.mu.Lock()
		for pd = range p.parents {
			break
		}
		p.mu.Unlock()
		if pd.parent == nil {
			break
		}

		segments = append(segments, pd.name)
		p = pd.parent
	}

	if p == nil {
		// NOSUBMIT - should replace rather than append?
		segments = append(segments, ".deleted")
	}

	i := 0
	j := len(segments) - 1

	for i < j {
		segments[i], segments[j] = segments[j], segments[i]
		i++
		j--
	}

	path := strings.Join(segments, "/")
	return path
}

// Finds a child with the given name and filetype.  Returns nil if not
// found.
func (n *Inode) FindChildByMode(name string, mode uint32) *Inode {
	mode ^= 07777

	n.mu.Lock()
	defer n.mu.Unlock()

	ch := n.children[name]

	if ch != nil && ch.mode == mode {
		return ch
	}

	return nil
}

// Finds a child with the given name and ID. Returns nil if not found.
func (n *Inode) FindChildByOpaqueID(name string, opaqueID uint64) *Inode {
	n.mu.Lock()
	defer n.mu.Unlock()

	ch := n.children[name]

	if ch != nil && ch.opaqueID == opaqueID {
		return ch
	}

	return nil
}

// setEntry does `iparent[name] = ichild` linking.
//
// setEntry must not be called simultaneously for any of iparent or ichild.
// This, for example could be satisfied if both iparent and ichild are locked,
// but it could be also valid if only iparent is locked and ichild was just
// created and only one goroutine keeps referencing it.
func (iparent *Inode) setEntry(name string, ichild *Inode) {
	ichild.parents[parentData{name, iparent}] = struct{}{}
	iparent.children[name] = ichild
	ichild.changeCounter++
	iparent.changeCounter++
}

func (n *Inode) clearParents() {
	for {
		lockme := []*Inode{n}
		n.mu.Lock()
		ts := n.changeCounter
		for p := range n.parents {
			lockme = append(lockme, p.parent)
		}
		n.mu.Unlock()

		lockNodes(lockme...)
		success := false
		if ts == n.changeCounter {
			for p := range n.parents {
				delete(p.parent.children, p.name)
				p.parent.changeCounter++
			}
			n.parents = map[parentData]struct{}{}
			n.changeCounter++
			success = true
		}
		unlockNodes(lockme...)

		if success {
			return
		}
	}
}

282 283 284 285 286 287 288 289 290 291
// NewPersistentInode returns an Inode whose lifetime is not in
// control of the kernel.
func (n *Inode) NewPersistentInode(node Node, mode uint32, opaque uint64) *Inode {
	return n.newInode(node, mode, opaque, true)
}

// ForgetPersistent manually marks the node as no longer important. If
// it has no children, and if the kernel as no references, the nodes
// gets removed from the tree.
func (n *Inode) ForgetPersistent() {
292
	n.removeRef(0, true)
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
}

// NewInode returns an inode for the given Node. The mode should be
// standard mode argument (eg. S_IFDIR). The opaqueID argument can be
// used to signal changes in the tree structure during lookup (see
// FindChildByOpaqueID). For a loopback file system, the inode number
// of the underlying file is a good candidate.
func (n *Inode) NewInode(node Node, mode uint32, opaqueID uint64) *Inode {
	return n.newInode(node, mode, opaqueID, false)
}

func (n *Inode) newInode(node Node, mode uint32, opaqueID uint64, persistent bool) *Inode {
	ch := &Inode{
		mode:       mode ^ 07777,
		node:       node,
		bridge:     n.bridge,
		persistent: persistent,
		parents:    make(map[parentData]struct{}),
	}
	if mode&fuse.S_IFDIR != 0 {
		ch.children = make(map[string]*Inode)
314
	}
315 316 317 318 319 320
	if node.setInode(ch) {
		return ch
	}

	return node.inode()
}
321

322 323 324 325
// removeRef decreases references. Returns if this operation caused
// the node to be forgotten (for kernel references), and whether it is
// live (ie. was not dropped from the tree)
func (n *Inode) removeRef(nlookup uint64, dropPersistence bool) (forgotten bool, live bool) {
326
	var lockme []*Inode
327 328 329 330 331 332 333 334 335 336 337 338 339 340
	var parents []parentData

	n.mu.Lock()
	if nlookup > 0 && dropPersistence {
		panic("only one allowed")
	} else if nlookup > 0 {
		n.lookupCount -= nlookup
		n.changeCounter++
	} else if dropPersistence && n.persistent {
		n.persistent = false
		n.changeCounter++
	}

retry:
341 342
	for {
		lockme = append(lockme[:0], n)
343 344 345 346 347 348 349
		parents = parents[:0]
		nChange := n.changeCounter
		live = n.lookupCount > 0 || len(n.children) > 0 || n.persistent
		forgotten = n.lookupCount == 0
		for p := range n.parents {
			parents = append(parents, p)
			lockme = append(lockme, p.parent)
350 351 352
		}
		n.mu.Unlock()

353 354 355 356
		if live {
			return forgotten, live
		}

357
		lockNodes(lockme...)
358 359 360 361
		if n.changeCounter != nChange {
			unlockNodes(lockme...)
			n.mu.Lock() // TODO could avoid unlocking and relocking n here.
			continue retry
362 363
		}

364 365 366
		for _, p := range parents {
			delete(p.parent.children, p.name)
			p.parent.changeCounter++
367
		}
368 369
		n.parents = map[parentData]struct{}{}
		n.changeCounter++
370 371 372 373 374 375 376 377 378 379 380 381

		if n.lookupCount != 0 {
			panic("lookupCount changed")
		}

		if n.nodeID != 0 {
			n.bridge.mu.Lock()
			n.bridge.unregisterNode(n.nodeID)
			n.bridge.mu.Unlock()
			n.nodeID = 0
		}

382 383
		unlockNodes(lockme...)
		break
384 385
	}

386 387 388
	for _, p := range lockme {
		if p != n {
			p.removeRef(0, false)
389 390
		}
	}
391
	return forgotten, false
392 393
}

394 395 396 397 398 399 400 401
// RmChild removes multiple children.  Returns whether the removal
// succeeded and whether the node is still live afterward. The removal
// is transactional: it only succeeds if all names are children, and
// if they all were removed successfully.  If the removal was
// successful, and there are no children left, the node may be removed
// from the FS tree. In that case, RmChild returns live==false.
func (n *Inode) RmChild(names ...string) (success, live bool) {
	var lockme []*Inode
402

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
retry:
	for {
		n.mu.Lock()
		lockme = append(lockme[:0], n)
		nChange := n.changeCounter
		for _, nm := range names {
			ch := n.children[nm]
			if ch == nil {
				n.mu.Unlock()
				return false, true
			}
			lockme = append(lockme, ch)
		}
		n.mu.Unlock()

		lockNodes(lockme...)
		if n.changeCounter != nChange {
			unlockNodes(lockme...)
			n.mu.Lock() // TODO could avoid unlocking and relocking n here.
			continue retry
		}

		for _, nm := range names {
			ch := n.children[nm]
			delete(n.children, nm)
			ch.changeCounter++
		}
		n.changeCounter++

		live = n.lookupCount > 0 || len(n.children) > 0 || n.persistent
		unlockNodes(lockme...)

		// removal successful
		break
437
	}
438 439 440 441

	if !live {
		_, live := n.removeRef(0, false)
		return true, live
442 443
	}

444
	return true, true
445
}