Home | History | Annotate | Download | only in gpu
      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef CONTENT_BROWSER_GPU_GPU_PROCESS_HOST_H_
      6 #define CONTENT_BROWSER_GPU_GPU_PROCESS_HOST_H_
      7 
      8 #include <map>
      9 #include <queue>
     10 #include <set>
     11 #include <string>
     12 
     13 #include "base/callback.h"
     14 #include "base/containers/hash_tables.h"
     15 #include "base/memory/weak_ptr.h"
     16 #include "base/threading/non_thread_safe.h"
     17 #include "base/time/time.h"
     18 #include "content/browser/gpu/gpu_surface_tracker.h"
     19 #include "content/common/content_export.h"
     20 #include "content/common/gpu/gpu_memory_uma_stats.h"
     21 #include "content/common/gpu/gpu_process_launch_causes.h"
     22 #include "content/common/gpu/gpu_result_codes.h"
     23 #include "content/public/browser/browser_child_process_host_delegate.h"
     24 #include "content/public/browser/gpu_data_manager.h"
     25 #include "gpu/command_buffer/common/constants.h"
     26 #include "gpu/config/gpu_info.h"
     27 #include "ipc/ipc_sender.h"
     28 #include "ipc/message_filter.h"
     29 #include "ui/gfx/native_widget_types.h"
     30 #include "ui/gfx/size.h"
     31 #include "url/gurl.h"
     32 
     33 struct GPUCreateCommandBufferConfig;
     34 
     35 namespace gfx {
     36 struct GpuMemoryBufferHandle;
     37 }
     38 
     39 namespace IPC {
     40 struct ChannelHandle;
     41 }
     42 
     43 namespace content {
     44 class BrowserChildProcessHostImpl;
     45 class GpuMainThread;
     46 class RenderWidgetHostViewFrameSubscriber;
     47 class ShaderDiskCache;
     48 
     49 typedef base::Thread* (*GpuMainThreadFactoryFunction)(const std::string& id);
     50 
     51 class GpuProcessHost : public BrowserChildProcessHostDelegate,
     52                        public IPC::Sender,
     53                        public base::NonThreadSafe {
     54  public:
     55   enum GpuProcessKind {
     56     GPU_PROCESS_KIND_UNSANDBOXED,
     57     GPU_PROCESS_KIND_SANDBOXED,
     58     GPU_PROCESS_KIND_COUNT
     59   };
     60 
     61   typedef base::Callback<void(const IPC::ChannelHandle&, const gpu::GPUInfo&)>
     62       EstablishChannelCallback;
     63 
     64   typedef base::Callback<void(CreateCommandBufferResult)>
     65       CreateCommandBufferCallback;
     66 
     67   typedef base::Callback<void(const gfx::GpuMemoryBufferHandle& handle)>
     68       CreateGpuMemoryBufferCallback;
     69 
     70   static bool gpu_enabled() { return gpu_enabled_; }
     71   static int gpu_crash_count() { return gpu_crash_count_; }
     72 
     73   // Creates a new GpuProcessHost or gets an existing one, resulting in the
     74   // launching of a GPU process if required.  Returns null on failure. It
     75   // is not safe to store the pointer once control has returned to the message
     76   // loop as it can be destroyed. Instead store the associated GPU host ID.
     77   // This could return NULL if GPU access is not allowed (blacklisted).
     78   CONTENT_EXPORT static GpuProcessHost* Get(GpuProcessKind kind,
     79                                             CauseForGpuLaunch cause);
     80 
     81   // Retrieves a list of process handles for all gpu processes.
     82   static void GetProcessHandles(
     83       const GpuDataManager::GetGpuProcessHandlesCallback& callback);
     84 
     85   // Helper function to send the given message to the GPU process on the IO
     86   // thread.  Calls Get and if a host is returned, sends it.  Can be called from
     87   // any thread.  Deletes the message if it cannot be sent.
     88   CONTENT_EXPORT static void SendOnIO(GpuProcessKind kind,
     89                                       CauseForGpuLaunch cause,
     90                                       IPC::Message* message);
     91 
     92   CONTENT_EXPORT static void RegisterGpuMainThreadFactory(
     93       GpuMainThreadFactoryFunction create);
     94 
     95   // Get the GPU process host for the GPU process with the given ID. Returns
     96   // null if the process no longer exists.
     97   static GpuProcessHost* FromID(int host_id);
     98   int host_id() const { return host_id_; }
     99 
    100   // IPC::Sender implementation.
    101   virtual bool Send(IPC::Message* msg) OVERRIDE;
    102 
    103   // Adds a message filter to the GpuProcessHost's channel.
    104   void AddFilter(IPC::MessageFilter* filter);
    105 
    106   // Tells the GPU process to create a new channel for communication with a
    107   // client. Once the GPU process responds asynchronously with the IPC handle
    108   // and GPUInfo, we call the callback.
    109   void EstablishGpuChannel(int client_id,
    110                            bool share_context,
    111                            bool allow_future_sync_points,
    112                            const EstablishChannelCallback& callback);
    113 
    114   // Tells the GPU process to create a new command buffer that draws into the
    115   // given surface.
    116   void CreateViewCommandBuffer(
    117       const gfx::GLSurfaceHandle& compositing_surface,
    118       int surface_id,
    119       int client_id,
    120       const GPUCreateCommandBufferConfig& init_params,
    121       int route_id,
    122       const CreateCommandBufferCallback& callback);
    123 
    124   // Tells the GPU process to create a new GPU memory buffer using the given
    125   // handle.
    126   void CreateGpuMemoryBuffer(const gfx::GpuMemoryBufferHandle& handle,
    127                              const gfx::Size& size,
    128                              unsigned internalformat,
    129                              unsigned usage,
    130                              const CreateGpuMemoryBufferCallback& callback);
    131 
    132   // Tells the GPU process to destroy GPU memory buffer.
    133   void DestroyGpuMemoryBuffer(const gfx::GpuMemoryBufferHandle& handle,
    134                               int sync_point);
    135 
    136   // What kind of GPU process, e.g. sandboxed or unsandboxed.
    137   GpuProcessKind kind();
    138 
    139   void ForceShutdown();
    140 
    141   void BeginFrameSubscription(
    142       int surface_id,
    143       base::WeakPtr<RenderWidgetHostViewFrameSubscriber> subscriber);
    144   void EndFrameSubscription(int surface_id);
    145   void LoadedShader(const std::string& key, const std::string& data);
    146 
    147  private:
    148   static bool ValidateHost(GpuProcessHost* host);
    149 
    150   GpuProcessHost(int host_id, GpuProcessKind kind);
    151   virtual ~GpuProcessHost();
    152 
    153   bool Init();
    154 
    155   // Post an IPC message to the UI shim's message handler on the UI thread.
    156   void RouteOnUIThread(const IPC::Message& message);
    157 
    158   // BrowserChildProcessHostDelegate implementation.
    159   virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
    160   virtual void OnChannelConnected(int32 peer_pid) OVERRIDE;
    161   virtual void OnProcessLaunched() OVERRIDE;
    162   virtual void OnProcessCrashed(int exit_code) OVERRIDE;
    163 
    164   // Message handlers.
    165   void OnInitialized(bool result, const gpu::GPUInfo& gpu_info);
    166   void OnChannelEstablished(const IPC::ChannelHandle& channel_handle);
    167   void OnCommandBufferCreated(CreateCommandBufferResult result);
    168   void OnDestroyCommandBuffer(int32 surface_id);
    169   void OnGpuMemoryBufferCreated(const gfx::GpuMemoryBufferHandle& handle);
    170   void OnDidCreateOffscreenContext(const GURL& url);
    171   void OnDidLoseContext(bool offscreen,
    172                         gpu::error::ContextLostReason reason,
    173                         const GURL& url);
    174   void OnDidDestroyOffscreenContext(const GURL& url);
    175   void OnGpuMemoryUmaStatsReceived(const GPUMemoryUmaStats& stats);
    176 #if defined(OS_MACOSX)
    177   void OnAcceleratedSurfaceBuffersSwapped(const IPC::Message& message);
    178 #endif
    179 
    180   void CreateChannelCache(int32 client_id);
    181   void OnDestroyChannel(int32 client_id);
    182   void OnCacheShader(int32 client_id, const std::string& key,
    183                      const std::string& shader);
    184 
    185   bool LaunchGpuProcess(const std::string& channel_id);
    186 
    187   void SendOutstandingReplies();
    188 
    189   void BlockLiveOffscreenContexts();
    190 
    191   // Update GPU crash counters.  Disable GPU if crash limit is reached.
    192   void RecordProcessCrash();
    193 
    194   std::string GetShaderPrefixKey();
    195 
    196   // The serial number of the GpuProcessHost / GpuProcessHostUIShim pair.
    197   int host_id_;
    198 
    199   // These are the channel requests that we have already sent to
    200   // the GPU process, but haven't heard back about yet.
    201   std::queue<EstablishChannelCallback> channel_requests_;
    202 
    203   // The pending create command buffer requests we need to reply to.
    204   std::queue<CreateCommandBufferCallback> create_command_buffer_requests_;
    205 
    206   // The pending create gpu memory buffer requests we need to reply to.
    207   std::queue<CreateGpuMemoryBufferCallback> create_gpu_memory_buffer_requests_;
    208 
    209   // Qeueud messages to send when the process launches.
    210   std::queue<IPC::Message*> queued_messages_;
    211 
    212   // Whether the GPU process is valid, set to false after Send() failed.
    213   bool valid_;
    214 
    215   // Whether we are running a GPU thread inside the browser process instead
    216   // of a separate GPU process.
    217   bool in_process_;
    218 
    219   bool swiftshader_rendering_;
    220   GpuProcessKind kind_;
    221 
    222   scoped_ptr<base::Thread> in_process_gpu_thread_;
    223 
    224   // Whether we actually launched a GPU process.
    225   bool process_launched_;
    226 
    227   // Whether the GPU process successfully initialized.
    228   bool initialized_;
    229 
    230   // Time Init started.  Used to log total GPU process startup time to UMA.
    231   base::TimeTicks init_start_time_;
    232 
    233   // Whether this host recorded a GPU crash or not.
    234   bool gpu_crash_recorded_;
    235 
    236   // Master switch for enabling/disabling GPU acceleration for the current
    237   // browser session. It does not change the acceleration settings for
    238   // existing tabs, just the future ones.
    239   static bool gpu_enabled_;
    240 
    241   static bool hardware_gpu_enabled_;
    242 
    243   static int gpu_crash_count_;
    244   static int gpu_recent_crash_count_;
    245   static bool crashed_before_;
    246   static int swiftshader_crash_count_;
    247 
    248   scoped_ptr<BrowserChildProcessHostImpl> process_;
    249 
    250   // Track the URLs of the pages which have live offscreen contexts,
    251   // assumed to be associated with untrusted content such as WebGL.
    252   // For best robustness, when any context lost notification is
    253   // received, assume all of these URLs are guilty, and block
    254   // automatic execution of 3D content from those domains.
    255   std::multiset<GURL> urls_with_live_offscreen_contexts_;
    256 
    257   // Statics kept around to send to UMA histograms on GPU process lost.
    258   bool uma_memory_stats_received_;
    259   GPUMemoryUmaStats uma_memory_stats_;
    260 
    261   // This map of frame subscribers are listening for frame presentation events.
    262   // The key is the surface id and value is the subscriber.
    263   typedef base::hash_map<int,
    264                          base::WeakPtr<RenderWidgetHostViewFrameSubscriber> >
    265   FrameSubscriberMap;
    266   FrameSubscriberMap frame_subscribers_;
    267 
    268   typedef std::map<int32, scoped_refptr<ShaderDiskCache> >
    269       ClientIdToShaderCacheMap;
    270   ClientIdToShaderCacheMap client_id_to_shader_cache_;
    271 
    272   std::string shader_prefix_key_;
    273 
    274   // Keep an extra reference to the SurfaceRef stored in the GpuSurfaceTracker
    275   // in this map so that we don't destroy it whilst the GPU process is
    276   // drawing to it.
    277   typedef std::multimap<int, scoped_refptr<GpuSurfaceTracker::SurfaceRef> >
    278       SurfaceRefMap;
    279   SurfaceRefMap surface_refs_;
    280 
    281   DISALLOW_COPY_AND_ASSIGN(GpuProcessHost);
    282 };
    283 
    284 }  // namespace content
    285 
    286 #endif  // CONTENT_BROWSER_GPU_GPU_PROCESS_HOST_H_
    287