Skip to content

Commit

Permalink
Hold a reference while calling p9.pathNode.removeWithName() callback.
Browse files Browse the repository at this point in the history
This prevents a racing clunk() call from destroying the file while the
callback is running, leading to potential data races.

Signed-off-by: Chris Koch <chrisko@google.com>
  • Loading branch information
nlacasse authored and hugelgupf committed Aug 22, 2023
1 parent 9385f79 commit 74365fc
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
11 changes: 10 additions & 1 deletion p9/path_tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,17 @@ func (p *pathNode) removeWithName(name string, fn func(ref *fidRef)) *pathNode {
for ref := range m {
delete(m, ref)
delete(p.childRefNames, ref)
if fn != nil {
if fn == nil {
continue
}

// Attempt to hold a reference while calling fn() to
// prevent concurrent destruction of the child, which
// can lead to data races. If the child has already
// been destroyed, then we can skip the callback.
if ref.TryIncRef() {
fn(ref)
ref.DecRef()
}
}
}
Expand Down
14 changes: 14 additions & 0 deletions p9/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,20 @@ func (f *fidRef) DecRef() error {
return nil
}

// TryIncRef returns true if a new reference is taken on the fid, and false if
// the fid has been destroyed.
func (f *fidRef) TryIncRef() bool {
for {
r := atomic.LoadInt64(&f.refs)
if r <= 0 {
return false
}
if atomic.CompareAndSwapInt64(&f.refs, r, r+1) {
return true
}
}
}

// isDeleted returns true if this fidRef has been deleted.
//
// Precondition: this must be called via safelyRead, safelyWrite or
Expand Down

0 comments on commit 74365fc

Please sign in to comment.