File: ecs_mem_usage.c

package info (click to toggle)
code-saturne 5.3.2%2Brepack-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 76,868 kB
  • sloc: ansic: 338,582; f90: 118,487; python: 65,227; makefile: 4,429; cpp: 3,826; xml: 3,078; sh: 1,205; lex: 170; yacc: 100
file content (453 lines) | stat: -rw-r--r-- 11,502 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/*============================================================================
 * Base memory usage information (System and Library dependent)
 *============================================================================*/

/*
  This file is part of Code_Saturne, a general-purpose CFD tool.

  Copyright (C) 1998-2018 EDF S.A.

  This program is free software; you can redistribute it and/or modify it under
  the terms of the GNU General Public License as published by the Free Software
  Foundation; either version 2 of the License, or (at your option) any later
  version.

  This program is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
  details.

  You should have received a copy of the GNU General Public License along with
  this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
  Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

/*----------------------------------------------------------------------------*/

#include "ecs_def.h"

/* OS type */

#if defined(__linux__) || defined(__linux) || defined(linux)
#define ECS_OS_Linux

#elif defined(__sun__) || defined(__sun) || defined(sun)
#define ECS_OS_Solaris

#endif

/* On Solaris, procfs may not be compiled in a largefile environment,
 * so we redefine macros before including any system header file. */

#if defined(ECS_OS_Solaris) && defined(HAVE_UNISTD_H) \
 && defined(HAVE_SYS_PROCFS_H) && !defined(__cplusplus)
#define _STRUCTURED_PROC 1
#undef _FILE_OFFSET_BITS
#define _FILE_OFFSET_BITS 32
#endif

/*
 * Standard C library headers
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if defined (ECS_OS_Linux) && defined(HAVE_SYS_STAT_H) \
 && defined(HAVE_SYS_TYPES_H) && defined(HAVE_UNISTD_H) \

#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

#elif defined(ECS_OS_Solaris) && defined(HAVE_UNISTD_H) \
   && defined(HAVE_SYS_PROCFS_H) && !defined(__cplusplus)
#include <sys/types.h>
#include <sys/procfs.h>
#include <unistd.h>

#elif defined (ECS_OS_AIX) && defined(HAVE_GETRUSAGE)
#include <sys/times.h>
#include <sys/resource.h>

#elif defined(HAVE_GETRUSAGE)
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#endif

#if defined(HAVE_UNISTD_H) && defined(HAVE_SBRK)
#if defined(__blrts__) || defined(__bgp_)
#define USE_SBRK 1
#elif defined (ECS_OS_Linux)
#define __USE_MISC 1
#endif
#include <unistd.h>
#endif

#if defined(HAVE_STDDEF_H)
#include <stddef.h>
#endif

/*
 * Optional library and ECS headers
 */

#include "ecs_mem_usage.h"

/*-----------------------------------------------------------------------------*/

BEGIN_C_DECLS

/*-------------------------------------------------------------------------------
 * Local type definitions
 *-----------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------
 * Local static variable definitions
 *-----------------------------------------------------------------------------*/

static int  _ecs_mem_usage_global_initialized = 0;

static size_t _ecs_mem_usage_global_max_pr = 0;

#if defined(USE_SBRK)
static void  *_ecs_mem_usage_global_init_sbrk = NULL;
#endif

#if defined (ECS_OS_Linux) && defined(HAVE_SYS_STAT_H) \
                             && defined(HAVE_SYS_TYPES_H)
static int  _ecs_mem_usage_proc_file_init = 0;
#endif

/*-----------------------------------------------------------------------------
 * Local function definitions
 *-----------------------------------------------------------------------------*/

#if defined (ECS_OS_Linux) && defined(HAVE_SYS_STAT_H) \
                             && defined(HAVE_SYS_TYPES_H)

/*!
 * \brief Initialize current process memory use count depending on system.
 */

static void
_ecs_mem_usage_pr_size_init(void)
{
  char  buf[512]; /* should be large enough for "/proc/%lu/status"
                     then beginning of file content */
  int fd;
  size_t  r_size, i;
  _Bool   status_has_peak = false;
  const pid_t  pid = getpid();

  /*
    Under Linux with procfs, one line of the pseudo-file "/proc/pid/status"
    (where pid is the process number) is of the following form:
    VmSize:     xxxx kB
    This line may be the 12th to 13th for a 2.6.x kernel.
    On more recent 2.6.x kernels, another line (the 12th) is of the form:
    VmPeak:     xxxx kB
  */

  if (_ecs_mem_usage_proc_file_init != 0)
    return;

  sprintf(buf, "/proc/%lu/status", (unsigned long) pid);

  fd = open(buf, O_RDONLY);

  if (fd != -1) {

    r_size = read(fd, buf, 512);

    if (r_size > 32) { /* Leave a margin for "VmPeak" or "VmSize:" line */
      r_size -= 32;
      for (i = 0; i < r_size; i++) {
        if (buf[i] == 'V' && strncmp(buf+i, "VmPeak:", 7) == 0) {
          status_has_peak = true;
          break;
        }
      }
      for (i = 0; i < r_size; i++) {
        if (buf[i] == 'V' && strncmp(buf+i, "VmSize:", 7) == 0)
          break;
      }
      /* If VmSize was found, proc file may be used */
      if (i < r_size) {
        if (status_has_peak == true)
          _ecs_mem_usage_proc_file_init = 1;
      }
    }

    (void)close(fd);
  }

  /* If initialization failed for some reason (proc file unavailable or does
     or does not contain the required fields), mark method as unusable */
  if (_ecs_mem_usage_proc_file_init == 0)
    _ecs_mem_usage_proc_file_init = -1;
}

/*!
 * \brief Finalize current process memory use count depending on system.
 */

static void
_ecs_mem_usage_pr_size_end(void)
{
  if (_ecs_mem_usage_proc_file_init != 1)
    return;
}

#else  /* defined (ECS_OS_Linux) && ... */

#define _ecs_mem_usage_pr_size_init()
#define _ecs_mem_usage_pr_size_end()

#endif /* defined (ECS_OS_Linux) && ... */

/*============================================================================
 * Public function definitions
 *============================================================================*/

/*!
 * \brief Initialize memory usage count depending on system.
 *
 * This functions checks if it has already been called, so
 * it is safe to call more than once (though it is not
 * thread-safe). Only the first call is effective.
 */

void
ecs_mem_usage_init(void)
{
  if (_ecs_mem_usage_global_initialized != 0)
    return;

#if defined(USE_SBRK)

  /*
    We use sbrk() to know the size of the heap. This is not of any use
    to guess at allocated memory when some part of the memory may
    be allocated with mmap(), such as with glibc on Linux.
  */

  _ecs_mem_usage_global_init_sbrk = (void *) sbrk(0);

#endif /* (USE_SBRK) */

  _ecs_mem_usage_global_initialized = 1;
}

/*!
 * \brief End memory usage count depending on system.
 */

void
ecs_mem_usage_end(void)
{
  _ecs_mem_usage_pr_size_end();
}

/*!
 * \brief Indicates if ecs_mem_usage_...() functions are initialized.
 *
 * \returns 1 if ecs_mem_usage_init has been called, 0 otherwise.
 */

int
ecs_mem_usage_initialized(void)
{
  return _ecs_mem_usage_global_initialized;
}

/*!
 * \brief Return current process memory use (in kB) depending on system.
 *
 * If the information is not available (depending on availability of
 * non-portable function calls), 0 is returned.
 */

#if defined (ECS_OS_Linux) && defined(HAVE_SYS_STAT_H) \
                           && defined(HAVE_SYS_TYPES_H)

size_t
ecs_mem_usage_pr_size(void)
{
  size_t sys_mem_usage = 0;

  /*
    Under Linux with procfs, one line of the pseudo-file "/proc/pid/status"
    (where pid is the process number) is of the following form:
    VmSize:     xxxx kB
    With more recent kernels, we also have a line of the form:
    VmPeak:     xxxx kB
  */

  {
    if (_ecs_mem_usage_proc_file_init == 0)
      _ecs_mem_usage_pr_size_init();

    if (_ecs_mem_usage_proc_file_init == 1) {

      char  buf[81]; /* should be large enough for "/proc/%lu/status" */
      const pid_t  pid = getpid();

      FILE *fp;
      unsigned long val;
      char *s;

      sprintf(buf, "/proc/%lu/status", (unsigned long) pid);
      fp = fopen(buf, "r");

      if (fp != NULL) {

        int fields_read = 0;

        while (fields_read < 2) {
          s = fgets(buf, 80, fp);
          if (s == NULL)
            break;
          if (strncmp(s, "VmSize:", 7) == 0) {
            sscanf (s + 7, "%lu", &val);
            sys_mem_usage = (size_t) val;
            fields_read += 1;
          }
          else if (strncmp(s, "VmPeak:", 7) == 0) {
            sscanf (s + 7, "%lu", &val);
            if ((size_t) val > _ecs_mem_usage_global_max_pr)
              _ecs_mem_usage_global_max_pr = (size_t) val;
            fields_read += 1;
          }
        }

        fclose(fp);

      }
    }

    _ecs_mem_usage_pr_size_end();
  }

  if (sys_mem_usage > _ecs_mem_usage_global_max_pr)
    _ecs_mem_usage_global_max_pr = sys_mem_usage;

  return sys_mem_usage;
}

#elif defined(ECS_OS_Solaris) && defined(HAVE_UNISTD_H) \
   && defined(HAVE_SYS_PROCFS_H) && !defined(__cplusplus)

size_t
ecs_mem_usage_pr_size(void)
{
  size_t sys_mem_usage = 0;

  {
    /* We have binary pseudo-files /proc/pid/status and /proc/pid/psinfo */

    char   buf[81];     /* should be large enough for "/proc/%lu/status" */
    const  unsigned long  pid = getpid ();

    FILE     *fp;
    int       val;
    char     *s ;
    size_t    ret;
    psinfo_t  pid_info;

    sprintf (buf, "/proc/%lu/psinfo", pid);

    fp = fopen (buf, "r");
    if (fp != NULL) {
      ret = fread(&pid_info, sizeof(pid_info), 1, fp);
      if (ret == 1)
        sys_mem_usage = pid_info.pr_size;
      fclose (fp);
    }

  }

  if (sys_mem_usage > _ecs_mem_usage_global_max_pr)
    _ecs_mem_usage_global_max_pr = sys_mem_usage;

  return sys_mem_usage;
}

#elif defined(USE_SBRK)

size_t
ecs_mem_usage_pr_size(void)
{
  size_t alloc_size = 0;

  if (_ecs_mem_usage_global_initialized) {
    void    *end_addr;

    end_addr = (void *) sbrk(0);

#if defined(HAVE_PTRDIFF_T)
    alloc_size = (size_t)(  (ptrdiff_t)end_addr
                          - (ptrdiff_t)_ecs_mem_usage_global_init_sbrk) / 1024;
#else
    alloc_size = (end_addr - _ecs_mem_usage_global_init_sbrk) / 1024;
#endif

  }

  if (alloc_size > _ecs_mem_usage_global_max_pr)
    _ecs_mem_usage_global_max_pr = alloc_size;

  return alloc_size;
}

#elif defined(HAVE_GETRUSAGE)

size_t
ecs_mem_usage_pr_size(void)
{
  size_t sys_mem_usage = 0;
  struct rusage usage;

  getrusage(RUSAGE_SELF, &usage);

  sys_mem_usage = usage.ru_maxrss / 1024;

  return sys_mem_usage;
}

#else /* Default case */

size_t
ecs_mem_usage_pr_size(void)
{
  return 0;
}

#endif /* ECS_OS_Linux, ... */

/*
 * \brief Return maximum process memory use (in kB) depending on OS.
 *
 * The returned value is the maximum returned by ecs_mem_usage_pr_size()
 * during the program's lifetime. With memory allocations which return
 * memory to the system (such as the GNU glibc on Linux systems),
 * this value will be correct only if allocation is tracked. This should
 * be the case if malloc hooks are used with the glibc allocation
 * functions (ECS library's default configuration/installation option),
 * but may give results lower than the true maximum in other cases.
 */

size_t
ecs_mem_usage_max_pr_size(void)
{
  (void) ecs_mem_usage_pr_size();

  return _ecs_mem_usage_global_max_pr;
}

/*----------------------------------------------------------------------------*/

END_C_DECLS