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