chiark / gitweb /
This patch replaces the existing OsLayer::VirtualToPhysical stub with
[stressapptest] / src / os.h
1 // Copyright 2006 Google Inc. All Rights Reserved.
2 // Author: nsanders, menderico
3
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7
8 //      http://www.apache.org/licenses/LICENSE-2.0
9
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15
16 #ifndef STRESSAPPTEST_OS_H_  // NOLINT
17 #define STRESSAPPTEST_OS_H_
18
19 #include <dirent.h>
20 #include <string>
21 #include <list>
22 #include <map>
23 #include <vector>
24
25 // This file must work with autoconf on its public version,
26 // so these includes are correct.
27 #include "adler32memcpy.h"  // NOLINT
28 #include "sattypes.h"       // NOLINT
29
30 const char kPagemapPath[] = "/proc/self/pagemap";
31 const char kSysfsPath[] = "/sys/bus/pci/devices";
32
33 struct PCIDevice {
34   int32 domain;
35   uint16 bus;
36   uint8 dev;
37   uint8 func;
38   uint16 vendor_id;
39   uint16 device_id;
40   uint64 base_addr[6];
41   uint64 size[6];
42 };
43
44 typedef vector<PCIDevice*> PCIDevices;
45
46 class ErrorDiag;
47
48 // This class implements OS/Platform specific funtions.
49 class OsLayer {
50  public:
51   OsLayer();
52   virtual ~OsLayer();
53
54   // Set the minimum amount of hugepages that should be available for testing.
55   // Must be set before Initialize().
56   void SetMinimumHugepagesSize(int64 min_bytes) {
57     min_hugepages_bytes_ = min_bytes;
58   }
59
60   // Initializes data strctures and open files.
61   // Returns false on error.
62   virtual bool Initialize();
63
64   // Virtual to physical. This implementation is optional for
65   // subclasses to implement.
66   // Takes a pointer, and returns the corresponding bus address.
67   virtual uint64 VirtualToPhysical(void *vaddr);
68
69   // Prints failed dimm. This implementation is optional for
70   // subclasses to implement.
71   // Takes a bus address and string, and prints the DIMM name
72   // into the string. Returns error status.
73   virtual int FindDimm(uint64 addr, char *buf, int len);
74   // Print dimm info, plus more available info.
75   virtual int FindDimmExtended(uint64 addr, char *buf, int len) {
76     return FindDimm(addr, buf, len);
77   }
78
79
80   // Classifies addresses according to "regions"
81   // This may mean different things on different platforms.
82   virtual int32 FindRegion(uint64 paddr);
83   // Find cpu cores associated with a region. Either NUMA or arbitrary.
84   virtual cpu_set_t *FindCoreMask(int32 region);
85   // Return cpu cores associated with a region in a hex string.
86   virtual string FindCoreMaskFormat(int32 region);
87
88   // Returns the HD device that contains this file.
89   virtual string FindFileDevice(string filename);
90
91   // Returns a list of paths coresponding to HD devices found on this machine.
92   virtual list<string> FindFileDevices();
93
94   // Polls for errors. This implementation is optional.
95   // This will poll once for errors and return zero iff no errors were found.
96   virtual int ErrorPoll();
97
98   // Delay an appropriate amount of time between polling.
99   virtual void ErrorWait();
100
101   // Report errors. This implementation is mandatory.
102   // This will output a machine readable line regarding the error.
103   virtual bool ErrorReport(const char *part, const char *symptom, int count);
104
105   // Flushes page cache. Used to circumvent the page cache when doing disk
106   // I/O.  This will be a NOP until ActivateFlushPageCache() is called, which
107   // is typically done when opening a file with O_DIRECT fails.
108   // Returns false on error, true on success or NOP.
109   // Subclasses may implement this in machine specific ways..
110   virtual bool FlushPageCache(void);
111   // Enable FlushPageCache() to actually do the flush instead of being a NOP.
112   virtual void ActivateFlushPageCache(void);
113
114   // Flushes cacheline. Used to distinguish read or write errors.
115   // Subclasses may implement this in machine specific ways..
116   // Takes a pointer, and flushed the cacheline containing that pointer.
117   virtual void Flush(void *vaddr);
118
119   // Fast flush, for use in performance critical code.
120   // This is bound at compile time, and will not pick up
121   // any runtime machine configuration info.
122   inline static void FastFlush(void *vaddr) {
123 #ifdef STRESSAPPTEST_CPU_PPC
124     asm volatile("dcbf 0,%0; sync" : : "r" (vaddr));
125 #elif defined(STRESSAPPTEST_CPU_X86_64) || defined(STRESSAPPTEST_CPU_I686)
126     // Put mfence before and after clflush to make sure:
127     // 1. The write before the clflush is committed to memory bus;
128     // 2. The read after the clflush is hitting the memory bus.
129     //
130     // From Intel manual:
131     // CLFLUSH is only ordered by the MFENCE instruction. It is not guaranteed
132     // to be ordered by any other fencing, serializing or other CLFLUSH
133     // instruction. For example, software can use an MFENCE instruction to
134     // insure that previous stores are included in the write-back.
135     asm volatile("mfence");
136     asm volatile("clflush (%0)" :: "r" (vaddr));
137     asm volatile("mfence");
138 #elif defined(STRESSAPPTEST_CPU_ARMV7A)
139   #warning "Unsupported CPU type ARMV7A: Unable to force cache flushes."
140 #else
141   #warning "Unsupported CPU type: Unable to force cache flushes."
142 #endif
143   }
144
145   // Get time in cpu timer ticks. Useful for matching MCEs with software
146   // actions.
147   inline static uint64 GetTimestamp(void) {
148     uint64 tsc;
149 #ifdef STRESSAPPTEST_CPU_PPC
150     uint32 tbl, tbu, temp;
151     __asm __volatile(
152       "1:\n"
153       "mftbu  %2\n"
154       "mftb   %0\n"
155       "mftbu  %1\n"
156       "cmpw   %2,%1\n"
157       "bne    1b\n"
158       : "=r"(tbl), "=r"(tbu), "=r"(temp)
159       :
160       : "cc");
161
162     tsc = (static_cast<uint64>(tbu) << 32) | static_cast<uint64>(tbl);
163 #elif defined(STRESSAPPTEST_CPU_X86_64) || defined(STRESSAPPTEST_CPU_I686)
164     datacast_t data;
165     __asm __volatile("rdtsc" : "=a" (data.l32.l), "=d"(data.l32.h));
166     tsc = data.l64;
167 #elif defined(STRESSAPPTEST_CPU_ARMV7A)
168   #warning "Unsupported CPU type ARMV7A: your build may not function correctly"
169     tsc = 0;
170 #else
171   #warning "Unsupported CPU type: your build may not function correctly"
172     tsc = 0;
173 #endif
174     return (tsc);
175   }
176
177   // Find the free memory on the machine.
178   virtual int64 FindFreeMemSize();
179
180   // Allocates test memory of length bytes.
181   // Subclasses must implement this.
182   // Call PepareTestMem to get a pointer.
183   virtual int64 AllocateAllMem();  // Returns length.
184   // Returns success.
185   virtual bool AllocateTestMem(int64 length, uint64 paddr_base);
186   virtual void FreeTestMem();
187
188   // Prepares the memory for use. You must call this
189   // before using test memory, and after you are done.
190   virtual void *PrepareTestMem(uint64 offset, uint64 length);
191   virtual void ReleaseTestMem(void *addr, uint64 offset, uint64 length);
192
193   // Machine type detected. Can we implement all these functions correctly?
194   // Returns true if machine type is detected and implemented.
195   virtual bool IsSupported();
196
197   // Returns 32 for 32-bit, 64 for 64-bit.
198   virtual int AddressMode();
199   // Update OsLayer state regarding cpu support for various features.
200   virtual void GetFeatures();
201
202   // Open, read, write pci cfg through /proc/bus/pci. fd is /proc/pci file.
203   virtual int PciOpen(int bus, int device, int function);
204   virtual void PciWrite(int fd, uint32 offset, uint32 value, int width);
205   virtual uint32 PciRead(int fd, uint32 offset, int width);
206
207   // Read MSRs
208   virtual bool ReadMSR(uint32 core, uint32 address, uint64 *data);
209   virtual bool WriteMSR(uint32 core, uint32 address, uint64 *data);
210
211   // Extract bits [n+len-1, n] from a 32 bit word.
212   // so GetBitField(0x0f00, 8, 4) == 0xf.
213   virtual uint32 GetBitField(uint32 val, uint32 n, uint32 len);
214
215   // Platform and CPU specific CPU-stressing function.
216   // Returns true on success, false otherwise.
217   virtual bool CpuStressWorkload();
218
219   // Causes false errors for unittesting.
220   // Setting to "true" causes errors to be injected.
221   void set_error_injection(bool errors) { error_injection_ = errors; }
222   bool error_injection() const { return error_injection_; }
223
224   // Is SAT using normal malloc'd memory, or exotic mmap'd memory.
225   bool normal_mem() const { return normal_mem_; }
226
227   // Get numa config, if available..
228   int num_nodes() const { return num_nodes_; }
229   int num_cpus() const { return num_cpus_; }
230
231   // Handle to platform-specific error diagnoser.
232   ErrorDiag *error_diagnoser_;
233
234   // Detect all PCI Devices.
235   virtual PCIDevices GetPCIDevices();
236
237   // Disambiguate between different "warm" memcopies.
238   virtual bool AdlerMemcpyWarm(uint64 *dstmem, uint64 *srcmem,
239                                unsigned int size_in_bytes,
240                                AdlerChecksum *checksum);
241
242   // Store a callback to use to print
243   // app-specific info about the last error location.
244   // This call back is called with a physical address, and the app can fill in
245   // the most recent transaction that occurred at that address.
246   typedef bool (*ErrCallback)(uint64 paddr, string *buf);
247   void set_err_log_callback(
248     ErrCallback err_log_callback) {
249     err_log_callback_ = err_log_callback;
250   }
251   ErrCallback get_err_log_callback() { return err_log_callback_; }
252
253  protected:
254   void *testmem_;                // Location of test memory.
255   uint64 testmemsize_;           // Size of test memory.
256   int64 totalmemsize_;           // Size of available memory.
257   int64 min_hugepages_bytes_;    // Minimum hugepages size.
258   bool  error_injection_;        // Do error injection?
259   bool  normal_mem_;             // Memory DMA capable?
260   bool  use_hugepages_;          // Use hugepage shmem?
261   bool  use_posix_shm_;          // Use 4k page shmem?
262   bool  dynamic_mapped_shmem_;   // Conserve virtual address space.
263   int   shmid_;                  // Handle to shmem
264
265   int64 regionsize_;             // Size of memory "regions"
266   int   regioncount_;            // Number of memory "regions"
267   int   num_cpus_;               // Number of cpus in the system.
268   int   num_nodes_;              // Number of nodes in the system.
269   int   num_cpus_per_node_;      // Number of cpus per node in the system.
270   int   address_mode_;           // Are we running 32 or 64 bit?
271   bool  has_sse2_;               // Do we have sse2 instructions?
272   bool  has_clflush_;            // Do we have clflush instructions?
273   bool  use_flush_page_cache_;   // Do we need to flush the page cache?
274
275
276   time_t time_initialized_;      // Start time of test.
277
278   vector<cpu_set_t> cpu_sets_;   // Cache for cpu masks.
279   vector<bool> cpu_sets_valid_;  // If the cpu mask cache is valid.
280
281   // Get file descriptor for dev msr.
282   virtual int OpenMSR(uint32 core, uint32 address);
283   // Auxiliary methods for PCI device configuration
284   int PCIGetValue(string name, string object);
285   int PCIGetResources(string name, PCIDevice *device);
286
287   // Look up how many hugepages there are.
288   virtual int64 FindHugePages();
289
290   // Link to find last transaction at an error location.
291   ErrCallback err_log_callback_;
292
293  private:
294   DISALLOW_COPY_AND_ASSIGN(OsLayer);
295 };
296
297 // Selects and returns the proper OS and hardware interface.  Does not call
298 // OsLayer::Initialize() on the new object.
299 OsLayer *OsLayerFactory(const std::map<std::string, std::string> &options);
300
301 #endif  // STRESSAPPTEST_OS_H_ NOLINT