forked from OSGeo/gdal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gdalrasterblock.cpp
1300 lines (1128 loc) · 41.4 KB
/
gdalrasterblock.cpp
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
*
* Project: GDAL Core
* Purpose: Implementation of GDALRasterBlock class and related global
* raster block cache management.
* Author: Frank Warmerdam, [email protected]
*
**********************************************************************
* Copyright (c) 1998, Frank Warmerdam <[email protected]>
* Copyright (c) 2008-2013, Even Rouault <even dot rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_port.h"
#include "gdal.h"
#include "gdal_priv.h"
#include <algorithm>
#include <climits>
#include <cstring>
#include "cpl_atomic_ops.h"
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_multiproc.h"
#include "cpl_string.h"
#include "cpl_vsi.h"
CPL_CVSID("$Id$")
static bool bCacheMaxInitialized = false;
// Will later be overridden by the default 5% if GDAL_CACHEMAX not defined.
static GIntBig nCacheMax = 40 * 1024 * 1024;
static GIntBig nCacheUsed = 0;
static GDALRasterBlock *poOldest = nullptr; // Tail.
static GDALRasterBlock *poNewest = nullptr; // Head.
static int nDisableDirtyBlockFlushCounter = 0;
#if 0
static CPLMutex *hRBLock = nullptr;
#define INITIALIZE_LOCK CPLMutexHolderD( &hRBLock )
#define TAKE_LOCK CPLMutexHolderOptionalLockD( hRBLock )
#define DESTROY_LOCK CPLDestroyMutex( hRBLock )
#else
static CPLLock* hRBLock = nullptr;
static bool bDebugContention = false;
static bool bSleepsForBockCacheDebug = false;
static CPLLockType GetLockType()
{
static int nLockType = -1;
if( nLockType < 0 )
{
const char* pszLockType =
CPLGetConfigOption("GDAL_RB_LOCK_TYPE", "ADAPTIVE");
if( EQUAL(pszLockType, "ADAPTIVE") )
nLockType = LOCK_ADAPTIVE_MUTEX;
else if( EQUAL(pszLockType, "RECURSIVE") )
nLockType = LOCK_RECURSIVE_MUTEX;
else if( EQUAL(pszLockType, "SPIN") )
nLockType = LOCK_SPIN;
else
{
CPLError(
CE_Warning, CPLE_NotSupported,
"GDAL_RB_LOCK_TYPE=%s not supported. Falling back to ADAPTIVE",
pszLockType);
nLockType = LOCK_ADAPTIVE_MUTEX;
}
bDebugContention = CPLTestBool(
CPLGetConfigOption("GDAL_RB_LOCK_DEBUG_CONTENTION", "NO"));
}
return static_cast<CPLLockType>(nLockType);
}
#define INITIALIZE_LOCK CPLLockHolderD( &hRBLock, GetLockType() ); \
CPLLockSetDebugPerf(hRBLock, bDebugContention)
#define TAKE_LOCK CPLLockHolderOptionalLockD( hRBLock )
#define DESTROY_LOCK CPLDestroyLock( hRBLock )
#endif
//#define ENABLE_DEBUG
/************************************************************************/
/* GDALSetCacheMax() */
/************************************************************************/
/**
* \brief Set maximum cache memory.
*
* This function sets the maximum amount of memory that GDAL is permitted
* to use for GDALRasterBlock caching. The unit of the value is bytes.
*
* The maximum value is 2GB, due to the use of a signed 32 bit integer.
* Use GDALSetCacheMax64() to be able to set a higher value.
*
* @param nNewSizeInBytes the maximum number of bytes for caching.
*/
void CPL_STDCALL GDALSetCacheMax( int nNewSizeInBytes )
{
GDALSetCacheMax64(nNewSizeInBytes);
}
/************************************************************************/
/* GDALSetCacheMax64() */
/************************************************************************/
/**
* \brief Set maximum cache memory.
*
* This function sets the maximum amount of memory that GDAL is permitted
* to use for GDALRasterBlock caching. The unit of the value is bytes.
*
* Note: On 32 bit platforms, the maximum amount of memory that can be addressed
* by a process might be 2 GB or 3 GB, depending on the operating system
* capabilities. This function will not make any attempt to check the
* consistency of the passed value with the effective capabilities of the OS.
*
* @param nNewSizeInBytes the maximum number of bytes for caching.
*
* @since GDAL 1.8.0
*/
void CPL_STDCALL GDALSetCacheMax64( GIntBig nNewSizeInBytes )
{
#if 0
if( nNewSizeInBytes == 12346789 )
{
GDALRasterBlock::DumpAll();
return;
}
#endif
{
INITIALIZE_LOCK;
}
bCacheMaxInitialized = true;
nCacheMax = nNewSizeInBytes;
/* -------------------------------------------------------------------- */
/* Flush blocks till we are under the new limit or till we */
/* can't seem to flush anymore. */
/* -------------------------------------------------------------------- */
while( nCacheUsed > nCacheMax )
{
const GIntBig nOldCacheUsed = nCacheUsed;
GDALFlushCacheBlock();
if( nCacheUsed == nOldCacheUsed )
break;
}
}
/************************************************************************/
/* GDALGetCacheMax() */
/************************************************************************/
/**
* \brief Get maximum cache memory.
*
* Gets the maximum amount of memory available to the GDALRasterBlock
* caching system for caching GDAL read/write imagery.
*
* The first type this function is called, it will read the GDAL_CACHEMAX
* configuration option to initialize the maximum cache memory.
* Starting with GDAL 2.1, the value can be expressed as x% of the usable
* physical RAM (which may potentially be used by other processes). Otherwise
* it is expected to be a value in MB.
*
* This function cannot return a value higher than 2 GB. Use
* GDALGetCacheMax64() to get a non-truncated value.
*
* @return maximum in bytes.
*/
int CPL_STDCALL GDALGetCacheMax()
{
GIntBig nRes = GDALGetCacheMax64();
if (nRes > INT_MAX)
{
static bool bHasWarned = false;
if (!bHasWarned)
{
CPLError( CE_Warning, CPLE_AppDefined,
"Cache max value doesn't fit on a 32 bit integer. "
"Call GDALGetCacheMax64() instead" );
bHasWarned = true;
}
nRes = INT_MAX;
}
return static_cast<int>(nRes);
}
/************************************************************************/
/* GDALGetCacheMax64() */
/************************************************************************/
/**
* \brief Get maximum cache memory.
*
* Gets the maximum amount of memory available to the GDALRasterBlock
* caching system for caching GDAL read/write imagery.
*
* The first type this function is called, it will read the GDAL_CACHEMAX
* configuration option to initialize the maximum cache memory.
* Starting with GDAL 2.1, the value can be expressed as x% of the usable
* physical RAM (which may potentially be used by other processes). Otherwise
* it is expected to be a value in MB.
*
* @return maximum in bytes.
*
* @since GDAL 1.8.0
*/
GIntBig CPL_STDCALL GDALGetCacheMax64()
{
if( !bCacheMaxInitialized )
{
{
INITIALIZE_LOCK;
}
bSleepsForBockCacheDebug = CPLTestBool(
CPLGetConfigOption("GDAL_DEBUG_BLOCK_CACHE", "NO"));
const char* pszCacheMax = CPLGetConfigOption("GDAL_CACHEMAX","5%");
GIntBig nNewCacheMax;
if( strchr(pszCacheMax, '%') != nullptr )
{
GIntBig nUsablePhysicalRAM = CPLGetUsablePhysicalRAM();
if( nUsablePhysicalRAM > 0 )
{
// For some reason, coverity pretends that this will overflow.
// "Multiply operation overflows on operands static_cast<double>(
// nUsablePhysicalRAM ) and CPLAtof(pszCacheMax). Example values for
// operands: CPLAtof( pszCacheMax ) = 2251799813685248,
// static_cast<double>(nUsablePhysicalRAM) = -9223372036854775808."
// coverity[overflow,tainted_data]
double dfCacheMax =
static_cast<double>(nUsablePhysicalRAM) *
CPLAtof(pszCacheMax) / 100.0;
if( dfCacheMax >= 0 && dfCacheMax < 1e15 )
nNewCacheMax = static_cast<GIntBig>(dfCacheMax);
else
nNewCacheMax = nCacheMax;
}
else
{
CPLDebug("GDAL",
"Cannot determine usable physical RAM.");
nNewCacheMax = nCacheMax;
}
}
else
{
nNewCacheMax = CPLAtoGIntBig(pszCacheMax);
if( nNewCacheMax < 100000 )
{
if (nNewCacheMax < 0)
{
CPLError(
CE_Failure, CPLE_NotSupported,
"Invalid value for GDAL_CACHEMAX. "
"Using default value.");
GIntBig nUsablePhysicalRAM = CPLGetUsablePhysicalRAM();
if( nUsablePhysicalRAM )
nNewCacheMax = nUsablePhysicalRAM / 20;
else
{
CPLDebug("GDAL",
"Cannot determine usable physical RAM.");
nNewCacheMax = nCacheMax;
}
}
else
{
nNewCacheMax *= 1024 * 1024;
}
}
}
nCacheMax = nNewCacheMax;
CPLDebug( "GDAL", "GDAL_CACHEMAX = " CPL_FRMT_GIB " MB",
nCacheMax / (1024 * 1024));
bCacheMaxInitialized = true;
}
// coverity[overflow_sink]
return nCacheMax;
}
/************************************************************************/
/* GDALGetCacheUsed() */
/************************************************************************/
/**
* \brief Get cache memory used.
*
* @return the number of bytes of memory currently in use by the
* GDALRasterBlock memory caching.
*/
int CPL_STDCALL GDALGetCacheUsed()
{
if (nCacheUsed > INT_MAX)
{
static bool bHasWarned = false;
if (!bHasWarned)
{
CPLError( CE_Warning, CPLE_AppDefined,
"Cache used value doesn't fit on a 32 bit integer. "
"Call GDALGetCacheUsed64() instead" );
bHasWarned = true;
}
return INT_MAX;
}
return static_cast<int>(nCacheUsed);
}
/************************************************************************/
/* GDALGetCacheUsed64() */
/************************************************************************/
/**
* \brief Get cache memory used.
*
* @return the number of bytes of memory currently in use by the
* GDALRasterBlock memory caching.
*
* @since GDAL 1.8.0
*/
GIntBig CPL_STDCALL GDALGetCacheUsed64() { return nCacheUsed; }
/************************************************************************/
/* GDALFlushCacheBlock() */
/* */
/* The workhorse of cache management! */
/************************************************************************/
/**
* \brief Try to flush one cached raster block
*
* This function will search the first unlocked raster block and will
* flush it to release the associated memory.
*
* @return TRUE if one block was flushed, FALSE if there are no cached blocks
* or if they are currently locked.
*/
int CPL_STDCALL GDALFlushCacheBlock()
{
return GDALRasterBlock::FlushCacheBlock();
}
/************************************************************************/
/* ==================================================================== */
/* GDALRasterBlock */
/* ==================================================================== */
/************************************************************************/
/**
* \class GDALRasterBlock "gdal_priv.h"
*
* GDALRasterBlock objects hold one block of raster data for one band
* that is currently stored in the GDAL raster cache. The cache holds
* some blocks of raster data for zero or more GDALRasterBand objects
* across zero or more GDALDataset objects in a global raster cache with
* a least recently used (LRU) list and an upper cache limit (see
* GDALSetCacheMax()) under which the cache size is normally kept.
*
* Some blocks in the cache may be modified relative to the state on disk
* (they are marked "Dirty") and must be flushed to disk before they can
* be discarded. Other (Clean) blocks may just be discarded if their memory
* needs to be recovered.
*
* In normal situations applications do not interact directly with the
* GDALRasterBlock - instead it it utilized by the RasterIO() interfaces
* to implement caching.
*
* Some driver classes are implemented in a fashion that completely avoids
* use of the GDAL raster cache (and GDALRasterBlock) though this is not very
* common.
*/
/************************************************************************/
/* FlushCacheBlock() */
/* */
/* Note, if we have a lot of blocks locked for a long time, this */
/* method is going to get slow because it will have to traverse */
/* the linked list a long ways looking for a flushing */
/* candidate. It might help to re-touch locked blocks to push */
/* them to the top of the list. */
/************************************************************************/
/**
* \brief Attempt to flush at least one block from the cache.
*
* This static method is normally used to recover memory when a request
* for a new cache block would put cache memory use over the established
* limit.
*
* C++ analog to the C function GDALFlushCacheBlock().
*
* @param bDirtyBlocksOnly Only flushes dirty blocks.
* @return TRUE if successful or FALSE if no flushable block is found.
*/
int GDALRasterBlock::FlushCacheBlock( int bDirtyBlocksOnly )
{
GDALRasterBlock *poTarget;
{
INITIALIZE_LOCK;
poTarget = poOldest;
while( poTarget != nullptr )
{
if( !bDirtyBlocksOnly ||
(poTarget->GetDirty() && nDisableDirtyBlockFlushCounter == 0) )
{
if( CPLAtomicCompareAndExchange(
&(poTarget->nLockCount), 0, -1) )
break;
}
poTarget = poTarget->poPrevious;
}
if( poTarget == nullptr )
return FALSE;
if( bSleepsForBockCacheDebug )
{
// coverity[tainted_data]
const double dfDelay = CPLAtof(
CPLGetConfigOption(
"GDAL_RB_FLUSHBLOCK_SLEEP_AFTER_DROP_LOCK", "0"));
if( dfDelay > 0 )
CPLSleep(dfDelay);
}
poTarget->Detach_unlocked();
poTarget->GetBand()->UnreferenceBlock(poTarget);
}
if( bSleepsForBockCacheDebug )
{
// coverity[tainted_data]
const double dfDelay = CPLAtof(
CPLGetConfigOption("GDAL_RB_FLUSHBLOCK_SLEEP_AFTER_RB_LOCK", "0"));
if( dfDelay > 0 )
CPLSleep(dfDelay);
}
if( poTarget->GetDirty() )
{
const CPLErr eErr = poTarget->Write();
if( eErr != CE_None )
{
// Save the error for later reporting.
poTarget->GetBand()->SetFlushBlockErr(eErr);
}
}
VSIFreeAligned(poTarget->pData);
poTarget->pData = nullptr;
poTarget->GetBand()->AddBlockToFreeList(poTarget);
return TRUE;
}
/************************************************************************/
/* FlushDirtyBlocks() */
/************************************************************************/
/**
* \brief Flush all dirty blocks from cache.
*
* This static method is normally used to recover memory and is especially
* useful when doing multi-threaded code that can trigger the block cache.
*
* Due to the current design of the block cache, dirty blocks belonging to a
* same dataset could be pushed simultaneously to the IWriteBlock() method of
* that dataset from different threads, causing races.
*
* Calling this method before that code can help workarounding that issue,
* in a multiple readers, one writer scenario.
*
* @since GDAL 2.0
*/
void GDALRasterBlock::FlushDirtyBlocks()
{
while( FlushCacheBlock(TRUE) )
{
/* go on */
}
}
/************************************************************************/
/* EnterDisableDirtyBlockFlush() */
/************************************************************************/
/**
* \brief Starts preventing dirty blocks from being flushed
*
* This static method is used to prevent dirty blocks from being flushed.
* This might be useful when in a IWriteBlock() method, whose implementation
* can directly/indirectly cause the block cache to evict new blocks, to
* be recursively called on the same dataset.
*
* This method implements a reference counter and is thread-safe.
*
* This call must be paired with a corresponding LeaveDisableDirtyBlockFlush().
*
* @since GDAL 2.2.2
*/
void GDALRasterBlock::EnterDisableDirtyBlockFlush()
{
CPLAtomicInc(&nDisableDirtyBlockFlushCounter);
}
/************************************************************************/
/* LeaveDisableDirtyBlockFlush() */
/************************************************************************/
/**
* \brief Ends preventing dirty blocks from being flushed.
*
* Undoes the effect of EnterDisableDirtyBlockFlush().
*
* @since GDAL 2.2.2
*/
void GDALRasterBlock::LeaveDisableDirtyBlockFlush()
{
CPLAtomicDec(&nDisableDirtyBlockFlushCounter);
}
/************************************************************************/
/* GDALRasterBlock() */
/************************************************************************/
/**
* @brief GDALRasterBlock Constructor
*
* Normally only called from GDALRasterBand::GetLockedBlockRef().
*
* @param poBandIn the raster band used as source of raster block
* being constructed.
*
* @param nXOffIn the horizontal block offset, with zero indicating
* the left most block, 1 the next block and so forth.
*
* @param nYOffIn the vertical block offset, with zero indicating
* the top most block, 1 the next block and so forth.
*/
GDALRasterBlock::GDALRasterBlock( GDALRasterBand *poBandIn,
int nXOffIn, int nYOffIn ) :
eType(poBandIn->GetRasterDataType()),
bDirty(false),
nLockCount(0),
nXOff(nXOffIn),
nYOff(nYOffIn),
nXSize(0),
nYSize(0),
pData(nullptr),
poBand(poBandIn),
poNext(nullptr),
poPrevious(nullptr),
bMustDetach(true)
{
CPLAssert( poBandIn != nullptr );
poBand->GetBlockSize( &nXSize, &nYSize );
}
/************************************************************************/
/* GDALRasterBlock() */
/************************************************************************/
/**
* @brief GDALRasterBlock Constructor (for GDALHashSetBandBlockAccess purpose)
*
* Normally only called from GDALHashSetBandBlockAccess class. Such a block
* is completely non functional and only meant as being used to do a look-up
* in the hash set of GDALHashSetBandBlockAccess
*
* @param nXOffIn the horizontal block offset, with zero indicating
* the left most block, 1 the next block and so forth.
*
* @param nYOffIn the vertical block offset, with zero indicating
* the top most block, 1 the next block and so forth.
*/
GDALRasterBlock::GDALRasterBlock( int nXOffIn, int nYOffIn ) :
eType(GDT_Unknown),
bDirty(false),
nLockCount(0),
nXOff(nXOffIn),
nYOff(nYOffIn),
nXSize(0),
nYSize(0),
pData(nullptr),
poBand(nullptr),
poNext(nullptr),
poPrevious(nullptr),
bMustDetach(false)
{}
/************************************************************************/
/* RecycleFor() */
/************************************************************************/
/**
* Recycle an existing block (of the same band)
*
* Normally called from GDALAbstractBandBlockCache::CreateBlock().
*/
void GDALRasterBlock::RecycleFor( int nXOffIn, int nYOffIn )
{
CPLAssert(pData == nullptr);
pData = nullptr;
bDirty = false;
nLockCount = 0;
poNext = nullptr;
poPrevious = nullptr;
nXOff = nXOffIn;
nYOff = nYOffIn;
bMustDetach = true;
}
/************************************************************************/
/* ~GDALRasterBlock() */
/************************************************************************/
/**
* Block destructor.
*
* Normally called from GDALRasterBand::FlushBlock().
*/
GDALRasterBlock::~GDALRasterBlock()
{
Detach();
if( pData != nullptr )
{
VSIFreeAligned( pData );
}
CPLAssert( nLockCount <= 0 );
#ifdef ENABLE_DEBUG
Verify();
#endif
}
/************************************************************************/
/* GetEffectiveBlockSize() */
/************************************************************************/
static size_t GetEffectiveBlockSize(GPtrDiff_t nBlockSize)
{
// The real cost of a block allocation is more than just nBlockSize
// As we allocate with 64-byte alignment, use 64 as a multiple.
// We arbitrarily add 2 * sizeof(GDALRasterBlock) to account for that
return static_cast<size_t>(
std::min(static_cast<GUIntBig>(UINT_MAX),
static_cast<GUIntBig>(DIV_ROUND_UP(nBlockSize, 64)) * 64 +
2 * sizeof(GDALRasterBlock)));
}
/************************************************************************/
/* Detach() */
/************************************************************************/
/**
* Remove block from cache.
*
* This method removes the current block from the linked list used to keep
* track of all cached blocks in order of age. It does not affect whether
* the block is referenced by a GDALRasterBand nor does it destroy or flush
* the block.
*/
void GDALRasterBlock::Detach()
{
if( bMustDetach )
{
TAKE_LOCK;
Detach_unlocked();
}
}
void GDALRasterBlock::Detach_unlocked()
{
if( poOldest == this )
poOldest = poPrevious;
if( poNewest == this )
{
poNewest = poNext;
}
if( poPrevious != nullptr )
poPrevious->poNext = poNext;
if( poNext != nullptr )
poNext->poPrevious = poPrevious;
poPrevious = nullptr;
poNext = nullptr;
bMustDetach = false;
if( pData )
nCacheUsed -= GetEffectiveBlockSize(GetBlockSize());
#ifdef ENABLE_DEBUG
Verify();
#endif
}
/************************************************************************/
/* Verify() */
/************************************************************************/
/**
* Confirms (via assertions) that the block cache linked list is in a
* consistent state.
*/
#ifdef ENABLE_DEBUG
void GDALRasterBlock::Verify()
{
TAKE_LOCK;
CPLAssert( (poNewest == nullptr && poOldest == nullptr)
|| (poNewest != nullptr && poOldest != nullptr) );
if( poNewest != nullptr )
{
CPLAssert( poNewest->poPrevious == nullptr );
CPLAssert( poOldest->poNext == nullptr );
GDALRasterBlock* poLast = nullptr;
for( GDALRasterBlock *poBlock = poNewest;
poBlock != nullptr;
poBlock = poBlock->poNext )
{
CPLAssert( poBlock->poPrevious == poLast );
poLast = poBlock;
}
CPLAssert( poOldest == poLast );
}
}
#else
void GDALRasterBlock::Verify() {}
#endif
#ifdef notdef
void GDALRasterBlock::CheckNonOrphanedBlocks( GDALRasterBand* poBand )
{
TAKE_LOCK;
for( GDALRasterBlock *poBlock = poNewest;
poBlock != nullptr;
poBlock = poBlock->poNext )
{
if ( poBlock->GetBand() == poBand )
{
printf("Cache has still blocks of band %p\n", poBand);/*ok*/
printf("Band : %d\n", poBand->GetBand());/*ok*/
printf("nRasterXSize = %d\n", poBand->GetXSize());/*ok*/
printf("nRasterYSize = %d\n", poBand->GetYSize());/*ok*/
int nBlockXSize, nBlockYSize;
poBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
printf("nBlockXSize = %d\n", nBlockXSize);/*ok*/
printf("nBlockYSize = %d\n", nBlockYSize);/*ok*/
printf("Dataset : %p\n", poBand->GetDataset());/*ok*/
if( poBand->GetDataset() )
printf("Dataset : %s\n",/*ok*/
poBand->GetDataset()->GetDescription());
}
}
}
#endif
/************************************************************************/
/* Write() */
/************************************************************************/
/**
* Force writing of the current block, if dirty.
*
* The block is written using GDALRasterBand::IWriteBlock() on its
* corresponding band object. Even if the write fails the block will
* be marked clean.
*
* @return CE_None otherwise the error returned by IWriteBlock().
*/
CPLErr GDALRasterBlock::Write()
{
if( !GetDirty() )
return CE_None;
if( poBand == nullptr )
return CE_Failure;
MarkClean();
if (poBand->eFlushBlockErr == CE_None)
{
int bCallLeaveReadWrite = poBand->EnterReadWrite(GF_Write);
CPLErr eErr = poBand->IWriteBlock( nXOff, nYOff, pData );
if( bCallLeaveReadWrite ) poBand->LeaveReadWrite();
return eErr;
}
else
return poBand->eFlushBlockErr;
}
/************************************************************************/
/* Touch() */
/************************************************************************/
/**
* Push block to top of LRU (least-recently used) list.
*
* This method is normally called when a block is used to keep track
* that it has been recently used.
*/
void GDALRasterBlock::Touch()
{
// Can be safely tested outside the lock
if( poNewest == this )
return;
TAKE_LOCK;
Touch_unlocked();
}
void GDALRasterBlock::Touch_unlocked()
{
// Could happen even if tested in Touch() before taking the lock
// Scenario would be :
// 0. this is the second block (the one pointed by poNewest->poNext)
// 1. Thread 1 calls Touch() and poNewest != this at that point
// 2. Thread 2 detaches poNewest
// 3. Thread 1 arrives here
if( poNewest == this )
return;
// We should not try to touch a block that has been detached.
// If that happen, corruption has already occurred.
CPLAssert(bMustDetach);
if( poOldest == this )
poOldest = this->poPrevious;
if( poPrevious != nullptr )
poPrevious->poNext = poNext;
if( poNext != nullptr )
poNext->poPrevious = poPrevious;
poPrevious = nullptr;
poNext = poNewest;
if( poNewest != nullptr )
{
CPLAssert( poNewest->poPrevious == nullptr );
poNewest->poPrevious = this;
}
poNewest = this;
if( poOldest == nullptr )
{
CPLAssert( poPrevious == nullptr && poNext == nullptr );
poOldest = this;
}
#ifdef ENABLE_DEBUG
Verify();
#endif
}
/************************************************************************/
/* Internalize() */
/************************************************************************/
/**
* Allocate memory for block.
*
* This method allocates memory for the block, and attempts to flush other
* blocks, if necessary, to bring the total cache size back within the limits.
* The newly allocated block is touched and will be considered most recently
* used in the LRU list.
*
* @return CE_None on success or CE_Failure if memory allocation fails.
*/
CPLErr GDALRasterBlock::Internalize()
{
CPLAssert( pData == nullptr );
void *pNewData = nullptr;
// This call will initialize the hRBLock mutex. Other call places can
// only be called if we have go through there.
const GIntBig nCurCacheMax = GDALGetCacheMax64();
// No risk of overflow as it is checked in GDALRasterBand::InitBlockInfo().
const auto nSizeInBytes = GetBlockSize();
/* -------------------------------------------------------------------- */
/* Flush old blocks if we are nearing our memory limit. */
/* -------------------------------------------------------------------- */
bool bFirstIter = true;
bool bLoopAgain = false;
GDALDataset* poThisDS = poBand->GetDataset();
do
{
bLoopAgain = false;
GDALRasterBlock* apoBlocksToFree[64] = { nullptr };
int nBlocksToFree = 0;
{
TAKE_LOCK;
if( bFirstIter )
nCacheUsed += GetEffectiveBlockSize(nSizeInBytes);
GDALRasterBlock *poTarget = poOldest;
while( nCacheUsed > nCurCacheMax )
{
GDALRasterBlock* poDirtyBlockOtherDataset = nullptr;
// In this first pass, only discard dirty blocks of this
// dataset. We do this to decrease significantly the likelihood
// of the following weakness of the block cache design:
// 1. Thread 1 fills block B with ones
// 2. Thread 2 evicts this dirty block, while thread 1 almost
// at the same time (but slightly after) tries to reacquire
// this block. As it has been removed from the block cache
// array/set, thread 1 now tries to read block B from disk,
// so gets the old value.
while( poTarget != nullptr )
{
if( !poTarget->GetDirty() )
{
if( CPLAtomicCompareAndExchange(
&(poTarget->nLockCount), 0, -1) )
break;
}
else if (nDisableDirtyBlockFlushCounter == 0)
{
if( poTarget->poBand->GetDataset() == poThisDS )
{
if( CPLAtomicCompareAndExchange(
&(poTarget->nLockCount), 0, -1) )
break;
}
else if( poDirtyBlockOtherDataset == nullptr )
{
poDirtyBlockOtherDataset = poTarget;