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