| 1 |
// Copyright 2019+ Klaus Post. All rights reserved. |
| 2 |
// License information can be found in the LICENSE file. |
| 3 |
// Based on work by Yann Collet, released under BSD License. |
| 4 |
|
| 5 |
package zstd |
| 6 |
|
| 7 |
import ( |
| 8 |
"fmt" |
| 9 |
rdebug "runtime/debug" |
| 10 |
"sync" |
| 11 |
) |
| 12 |
|
| 13 |
type encJob struct { |
| 14 |
prefix []byte // overlap from previous job (nil for first) |
| 15 |
input []byte // job's own input data (swapped from filling) |
| 16 |
last bool // last block of last job gets last=true |
| 17 |
output []byte // compressed blocks (filled by worker) |
| 18 |
err error // encoding error |
| 19 |
done chan struct{} // closed when complete |
| 20 |
} |
| 21 |
|
| 22 |
type jobState struct { |
| 23 |
jobSize int |
| 24 |
overlapSize int |
| 25 |
filling []byte // accumulates input up to jobSize |
| 26 |
nextPrefix []byte // overlap prefix prepared for the next dispatched job |
| 27 |
|
| 28 |
jobSeq int // next job sequence number |
| 29 |
|
| 30 |
jobCh chan *encJob // dispatch to workers |
| 31 |
resultCh chan *encJob // ordered results to flusher |
| 32 |
|
| 33 |
workerWg sync.WaitGroup |
| 34 |
flusherWg sync.WaitGroup |
| 35 |
|
| 36 |
mu sync.Mutex |
| 37 |
flushedSeq int // last flushed sequence number |
| 38 |
cond *sync.Cond |
| 39 |
|
| 40 |
flusherErr error |
| 41 |
started bool |
| 42 |
|
| 43 |
inputPool sync.Pool // *[]byte buffers of jobSize cap |
| 44 |
outputPool sync.Pool // *[]byte buffers for compressed output |
| 45 |
overlapPool sync.Pool // *[]byte buffers for overlap prefixes |
| 46 |
} |
| 47 |
|
| 48 |
func (e *Encoder) startJobWorkers() { |
| 49 |
js := &e.state.jobs |
| 50 |
n := e.o.concurrent |
| 51 |
js.jobCh = make(chan *encJob, n) |
| 52 |
js.resultCh = make(chan *encJob, n) |
| 53 |
js.flushedSeq = 0 |
| 54 |
js.cond = sync.NewCond(&js.mu) |
| 55 |
|
| 56 |
// Workers borrow encoders from the shared e.encoders pool per-job. |
| 57 |
// Ensure the pool is initialized before any worker tries to borrow. |
| 58 |
e.init.Do(e.initialize) |
| 59 |
|
| 60 |
for range n { |
| 61 |
js.workerWg.Add(1) |
| 62 |
go e.jobWorker() |
| 63 |
} |
| 64 |
js.flusherWg.Add(1) |
| 65 |
go e.jobFlusher() |
| 66 |
js.started = true |
| 67 |
} |
| 68 |
|
| 69 |
func (e *Encoder) jobWorker() { |
| 70 |
js := &e.state.jobs |
| 71 |
defer js.workerWg.Done() |
| 72 |
for job := range js.jobCh { |
| 73 |
enc := <-e.encoders |
| 74 |
e.compressJob(enc, job) |
| 75 |
e.encoders <- enc |
| 76 |
close(job.done) |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
func (e *Encoder) compressJob(enc encoder, job *encJob) { |
| 81 |
defer func() { |
| 82 |
if r := recover(); r != nil { |
| 83 |
job.err = fmt.Errorf("panic in parallel job: %v", r) |
| 84 |
rdebug.PrintStack() |
| 85 |
} |
| 86 |
}() |
| 87 |
|
| 88 |
if len(job.prefix) > 0 { |
| 89 |
enc.ResetPrefix(job.prefix) |
| 90 |
} else { |
| 91 |
enc.Reset(nil, false) |
| 92 |
} |
| 93 |
|
| 94 |
data := job.input |
| 95 |
if len(data) == 0 && job.last { |
| 96 |
blk := enc.Block() |
| 97 |
blk.reset(nil) |
| 98 |
blk.last = true |
| 99 |
blk.encodeRaw(nil) |
| 100 |
job.output = append(job.output, blk.output...) |
| 101 |
return |
| 102 |
} |
| 103 |
|
| 104 |
blk := enc.Block() |
| 105 |
for len(data) > 0 { |
| 106 |
todo := data |
| 107 |
if len(todo) > e.o.blockSize { |
| 108 |
todo = todo[:e.o.blockSize] |
| 109 |
} |
| 110 |
data = data[len(todo):] |
| 111 |
|
| 112 |
blk.pushOffsets() |
| 113 |
enc.Encode(blk, todo) |
| 114 |
blk.last = len(data) == 0 && job.last |
| 115 |
|
| 116 |
err := blk.encode(todo, e.o.noEntropy, !e.o.allLitEntropy) |
| 117 |
if err != nil { |
| 118 |
job.err = err |
| 119 |
return |
| 120 |
} |
| 121 |
job.output = append(job.output, blk.output...) |
| 122 |
blk.reset(nil) |
| 123 |
} |
| 124 |
} |
| 125 |
|
| 126 |
func (js *jobState) getInputBuf(size int) []byte { |
| 127 |
if v := js.inputPool.Get(); v != nil { |
| 128 |
bp := v.(*[]byte) |
| 129 |
b := *bp |
| 130 |
if cap(b) >= size { |
| 131 |
return b[:0] |
| 132 |
} |
| 133 |
} |
| 134 |
return make([]byte, 0, size) |
| 135 |
} |
| 136 |
|
| 137 |
func (js *jobState) putInputBuf(b []byte) { |
| 138 |
if cap(b) > 0 { |
| 139 |
b = b[:0] |
| 140 |
js.inputPool.Put(&b) |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
func (js *jobState) getOutputBuf(size int) []byte { |
| 145 |
if v := js.outputPool.Get(); v != nil { |
| 146 |
bp := v.(*[]byte) |
| 147 |
b := *bp |
| 148 |
if cap(b) >= size { |
| 149 |
return b[:0] |
| 150 |
} |
| 151 |
} |
| 152 |
return make([]byte, 0, size) |
| 153 |
} |
| 154 |
|
| 155 |
func (js *jobState) putOutputBuf(b []byte) { |
| 156 |
if cap(b) > 0 { |
| 157 |
b = b[:0] |
| 158 |
js.outputPool.Put(&b) |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
func (js *jobState) getOverlapBuf(size int) []byte { |
| 163 |
if v := js.overlapPool.Get(); v != nil { |
| 164 |
bp := v.(*[]byte) |
| 165 |
b := *bp |
| 166 |
if cap(b) >= size { |
| 167 |
return b[:size] |
| 168 |
} |
| 169 |
} |
| 170 |
return make([]byte, size) |
| 171 |
} |
| 172 |
|
| 173 |
func (js *jobState) putOverlapBuf(b []byte) { |
| 174 |
if cap(b) > 0 { |
| 175 |
b = b[:0] |
| 176 |
js.overlapPool.Put(&b) |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
func (e *Encoder) jobFlusher() { |
| 181 |
js := &e.state.jobs |
| 182 |
defer js.flusherWg.Done() |
| 183 |
for job := range js.resultCh { |
| 184 |
<-job.done |
| 185 |
// Worker has fully exited compressJob, so the prefix is no longer |
| 186 |
// in use. Return it to the pool regardless of outcome. |
| 187 |
if job.prefix != nil { |
| 188 |
js.putOverlapBuf(job.prefix) |
| 189 |
job.prefix = nil |
| 190 |
} |
| 191 |
if job.err != nil { |
| 192 |
js.mu.Lock() |
| 193 |
js.flusherErr = job.err |
| 194 |
js.cond.Broadcast() |
| 195 |
js.mu.Unlock() |
| 196 |
for range js.resultCh { |
| 197 |
} |
| 198 |
return |
| 199 |
} |
| 200 |
if len(job.output) > 0 { |
| 201 |
_, err := e.state.w.Write(job.output) |
| 202 |
if err != nil { |
| 203 |
js.mu.Lock() |
| 204 |
js.flusherErr = err |
| 205 |
js.cond.Broadcast() |
| 206 |
js.mu.Unlock() |
| 207 |
for range js.resultCh { |
| 208 |
} |
| 209 |
return |
| 210 |
} |
| 211 |
e.state.nWritten += int64(len(job.output)) |
| 212 |
} |
| 213 |
// Return buffers to pools. |
| 214 |
js.putInputBuf(job.input) |
| 215 |
js.putOutputBuf(job.output) |
| 216 |
job.input = nil |
| 217 |
job.output = nil |
| 218 |
|
| 219 |
js.mu.Lock() |
| 220 |
js.flushedSeq++ |
| 221 |
js.cond.Broadcast() |
| 222 |
js.mu.Unlock() |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
func (e *Encoder) shutdownJobWorkers() { |
| 227 |
js := &e.state.jobs |
| 228 |
if !js.started { |
| 229 |
return |
| 230 |
} |
| 231 |
close(js.jobCh) |
| 232 |
js.workerWg.Wait() |
| 233 |
close(js.resultCh) |
| 234 |
js.flusherWg.Wait() |
| 235 |
js.started = false |
| 236 |
} |
| 237 |
|
| 238 |
// waitAllJobs blocks until all dispatched jobs have been flushed. |
| 239 |
func (e *Encoder) waitAllJobs() { |
| 240 |
js := &e.state.jobs |
| 241 |
if !js.started { |
| 242 |
return |
| 243 |
} |
| 244 |
js.mu.Lock() |
| 245 |
for js.flushedSeq < js.jobSeq && js.flusherErr == nil { |
| 246 |
js.cond.Wait() |
| 247 |
} |
| 248 |
js.mu.Unlock() |
| 249 |
} |
| 250 |
|
| 251 |
func (e *Encoder) dispatchJob(final bool) error { |
| 252 |
s := &e.state |
| 253 |
js := &s.jobs |
| 254 |
|
| 255 |
js.mu.Lock() |
| 256 |
fErr := js.flusherErr |
| 257 |
js.mu.Unlock() |
| 258 |
if fErr != nil { |
| 259 |
return fErr |
| 260 |
} |
| 261 |
|
| 262 |
if !s.headerWritten { |
| 263 |
// Single-block optimization: fall through to encodeAll path. |
| 264 |
if final && len(js.filling) > 0 && len(js.filling) <= e.o.blockSize { |
| 265 |
s.current = e.encodeAll(s.encoder, js.filling, s.current[:0]) |
| 266 |
var n2 int |
| 267 |
n2, s.err = s.w.Write(s.current) |
| 268 |
if s.err != nil { |
| 269 |
return s.err |
| 270 |
} |
| 271 |
s.nWritten += int64(n2) |
| 272 |
s.nInput += int64(len(js.filling)) |
| 273 |
s.current = s.current[:0] |
| 274 |
js.filling = js.filling[:0] |
| 275 |
s.headerWritten = true |
| 276 |
s.fullFrameWritten = true |
| 277 |
s.eofWritten = true |
| 278 |
return nil |
| 279 |
} |
| 280 |
if final && len(js.filling) == 0 && !e.o.fullZero { |
| 281 |
s.headerWritten = true |
| 282 |
s.fullFrameWritten = true |
| 283 |
s.eofWritten = true |
| 284 |
return nil |
| 285 |
} |
| 286 |
|
| 287 |
var tmp [maxHeaderSize]byte |
| 288 |
fh := frameHeader{ |
| 289 |
ContentSize: uint64(s.frameContentSize), |
| 290 |
WindowSize: uint32(s.encoder.WindowSize(s.frameContentSize)), |
| 291 |
SingleSegment: false, |
| 292 |
Checksum: e.o.crc, |
| 293 |
DictID: 0, |
| 294 |
} |
| 295 |
dst := fh.appendTo(tmp[:0]) |
| 296 |
var n2 int |
| 297 |
n2, s.err = s.w.Write(dst) |
| 298 |
if s.err != nil { |
| 299 |
return s.err |
| 300 |
} |
| 301 |
s.nWritten += int64(n2) |
| 302 |
s.headerWritten = true |
| 303 |
} |
| 304 |
|
| 305 |
if len(js.filling) == 0 && !final { |
| 306 |
return nil |
| 307 |
} |
| 308 |
|
| 309 |
if !js.started { |
| 310 |
e.startJobWorkers() |
| 311 |
} |
| 312 |
|
| 313 |
// Estimate output size for pooled buffer. |
| 314 |
outputEst := max(len(js.filling)/2, 512) |
| 315 |
|
| 316 |
job := &encJob{ |
| 317 |
last: final, |
| 318 |
done: make(chan struct{}), |
| 319 |
output: js.getOutputBuf(outputEst), |
| 320 |
} |
| 321 |
|
| 322 |
// Each job owns its prefix slice; the flusher returns it to the pool |
| 323 |
// after <-job.done, so workers and dispatch never share a buffer. |
| 324 |
if js.nextPrefix != nil { |
| 325 |
job.prefix = js.nextPrefix |
| 326 |
js.nextPrefix = nil |
| 327 |
} |
| 328 |
|
| 329 |
// Build the next job's prefix from the tail of this job's input. |
| 330 |
if !final && len(js.filling) > 0 { |
| 331 |
overlapLen := min(js.overlapSize, len(js.filling)) |
| 332 |
np := js.getOverlapBuf(overlapLen) |
| 333 |
copy(np, js.filling[len(js.filling)-overlapLen:]) |
| 334 |
js.nextPrefix = np |
| 335 |
} |
| 336 |
|
| 337 |
// Swap filling buffer into job — zero-copy for the input data. |
| 338 |
job.input = js.filling |
| 339 |
js.filling = js.getInputBuf(js.jobSize) |
| 340 |
|
| 341 |
s.nInput += int64(len(job.input)) |
| 342 |
js.jobSeq++ |
| 343 |
|
| 344 |
if final { |
| 345 |
s.eofWritten = true |
| 346 |
} |
| 347 |
|
| 348 |
js.resultCh <- job |
| 349 |
js.jobCh <- job |
| 350 |
|
| 351 |
return nil |
| 352 |
} |