GrResourceCache2 manages scratch texture.

BUG=skia:2889

Review URL: https://codereview.chromium.org/608883003
diff --git a/src/gpu/GrResourceCache2.cpp b/src/gpu/GrResourceCache2.cpp
index e0ba26a..85e66a7 100644
--- a/src/gpu/GrResourceCache2.cpp
+++ b/src/gpu/GrResourceCache2.cpp
@@ -8,7 +8,8 @@
 
 
 #include "GrResourceCache2.h"
-#include "GrGpuResource.h"
+#include "GrGpuResource.h"  
+#include "SkRefCnt.h"
 
 GrResourceCache2::~GrResourceCache2() {
     this->releaseAll();
@@ -55,3 +56,32 @@
     SkASSERT(!fScratchMap.count());
     SkASSERT(!fCount);
 }
+
+class GrResourceCache2::AvailableForScratchUse {
+public:
+    AvailableForScratchUse(bool calledDuringFlush) : fFlushing(calledDuringFlush) { }
+
+    bool operator()(const GrGpuResource* resource) const {
+        if (fFlushing) {
+            // If this request is coming during draw buffer flush then no refs are allowed
+            // either by drawing code or for pending io operations.
+            // This will be removed when flush no longer creates resources.
+            return resource->reffedOnlyByCache() && !resource->internalHasPendingIO() &&
+                   GrGpuResource::kYes_IsScratch == resource->fIsScratch;
+        } else {
+            // Because duties are currently shared between GrResourceCache and GrResourceCache2, the
+            // current interpretation of this rule is that only GrResourceCache has a ref but that
+            // it has been marked as a scratch resource.
+            return resource->reffedOnlyByCache() &&
+                GrGpuResource::kYes_IsScratch == resource->fIsScratch;
+        }
+    }
+private:
+    bool fFlushing;
+};
+
+GrGpuResource* GrResourceCache2::findAndRefScratchResource(const GrResourceKey& scratchKey,
+                                                           bool calledDuringFlush) {
+    SkASSERT(scratchKey.isScratch());
+    return SkSafeRef(fScratchMap.find(scratchKey, AvailableForScratchUse(calledDuringFlush)));
+}