package stores import ( "context" "github.com/filecoin-project/lotus/extern/sector-storage/storiface" "sync" "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/abi" ) type sectorLock struct { cond *ctxCond r [storiface.FileTypes]uint w storiface.SectorFileType refs uint // access with indexLocks.lk } func (l *sectorLock) canLock(read storiface.SectorFileType, write storiface.SectorFileType) bool { for i, b := range write.All() { if b && l.r[i] > 0 { return false } } // check that there are no locks taken for either read or write file types we want return l.w&read == 0 && l.w&write == 0 } func (l *sectorLock) tryLock(read storiface.SectorFileType, write storiface.SectorFileType) bool { if !l.canLock(read, write) { return false } for i, set := range read.All() { if set { l.r[i]++ } } l.w |= write return true } type lockFn func(l *sectorLock, ctx context.Context, read storiface.SectorFileType, write storiface.SectorFileType) (bool, error) func (l *sectorLock) tryLockSafe(ctx context.Context, read storiface.SectorFileType, write storiface.SectorFileType) (bool, error) { l.cond.L.Lock() defer l.cond.L.Unlock() return l.tryLock(read, write), nil } func (l *sectorLock) lock(ctx context.Context, read storiface.SectorFileType, write storiface.SectorFileType) (bool, error) { l.cond.L.Lock() defer l.cond.L.Unlock() for !l.tryLock(read, write) { if err := l.cond.Wait(ctx); err != nil { return false, err } } return true, nil } func (l *sectorLock) unlock(read storiface.SectorFileType, write storiface.SectorFileType) { l.cond.L.Lock() defer l.cond.L.Unlock() for i, set := range read.All() { if set { l.r[i]-- } } l.w &= ^write l.cond.Broadcast() } type indexLocks struct { lk sync.Mutex locks map[abi.SectorID]*sectorLock } func (i *indexLocks) lockWith(ctx context.Context, lockFn lockFn, sector abi.SectorID, read storiface.SectorFileType, write storiface.SectorFileType) (bool, error) { if read|write == 0 { return false, nil } if read|write > (1<