summaryrefslogtreecommitdiff
path: root/magick/resource.c
blob: c9fc6f7e43913744addc130d91c02f34eb71f014 (plain)
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
/*
% Copyright (C) 2003 - 2022 GraphicsMagick Group
% Copyright (C) 2002 ImageMagick Studio
%
% This program is covered by multiple licenses, which are described in
% Copyright.txt. You should have received a copy of Copyright.txt with this
% package; otherwise see http://www.graphicsmagick.org/www/Copyright.html.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%           RRRR    EEEEE   SSSSS   OOO   U   U  RRRR    CCCC  EEEEE          %
%           R   R   E       SS     O   O  U   U  R   R  C      E              %
%           RRRR    EEE      SSS   O   O  U   U  RRRR   C      EEE            %
%           R R     E          SS  O   O  U   U  R R    C      E              %
%           R  R    EEEEE   SSSSS   OOO    UUU   R  R    CCCC  EEEEE          %
%                                                                             %
%                                                                             %
%                        Get/Set ImageMagick Resources.                       %
%                                                                             %
%                                                                             %
%                              Software Design                                %
%                                John Cristy                                  %
%                               September 2002                                %
%                                                                             %
%                            Completely Re-written                            %
%                               Bob Friesenhahn                               %
%                                 April 2008                                  %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/

/*
  Include declarations.
*/
#include "magick/studio.h"
#include "magick/log.h"
#include "magick/resource.h"
#include "magick/semaphore.h"
#include "magick/utility.h"

/*
  Define  declarations.
*/
#define ResourceInfinity ((magick_int64_t) (~((magick_uint64_t) 0) >> 1))
#define ResourceInfoMaxIndex ((unsigned int) (sizeof(resource_info)/sizeof(resource_info[0])-1))

/*
  Typedef declarations.
*/
typedef enum
{
  AbsoluteLimit,
  SummationLimit
} LimitType;

/*
  Definition of a resource.  We intentionally use signed types to
  store 'value' and 'limit'.
*/
typedef struct _ResourceInfo
{
  const char
    *name,
    *units,
    *env;

  magick_int64_t
    value;

  magick_int64_t
    minimum,
    maximum;

  LimitType
    limit_type;

  SemaphoreInfo
    *semaphore;

} ResourceInfo;

/*
  Global declarations.
*/

/*
  Array must be in same order as ResourceType enum
*/
#define PIXEL_LIMIT (INT_MAX/(sizeof(PixelPacket)))
static ResourceInfo
  resource_info[] =
  {
    { "",       "",  "",                    0, 0,     ResourceInfinity, AbsoluteLimit, 0  },
    { "disk",   "B", "MAGICK_LIMIT_DISK",   0, 0,     ResourceInfinity, SummationLimit, 0 },
    { "files",  "",  "MAGICK_LIMIT_FILES",  0, 32,    256,              SummationLimit, 0 },
    { "map",    "B", "MAGICK_LIMIT_MAP",    0, 0,     ResourceInfinity, SummationLimit, 0 },
    { "memory", "B", "MAGICK_LIMIT_MEMORY", 0, 0,     ResourceInfinity, SummationLimit, 0 },
    { "pixels", "P", "MAGICK_LIMIT_PIXELS", 0, 1,     ResourceInfinity, AbsoluteLimit, 0  },
    { "threads", "", "OMP_NUM_THREADS",     1, 1,     ResourceInfinity, AbsoluteLimit, 0  },
    { "width",  "P", "MAGICK_LIMIT_WIDTH",  0, 1,     PIXEL_LIMIT,      AbsoluteLimit, 0  },
    { "height", "P", "MAGICK_LIMIT_HEIGHT", 0, 1,     PIXEL_LIMIT,      AbsoluteLimit, 0  },
    { "read",   "B", "MAGICK_LIMIT_READ",   0, 4096,  ResourceInfinity, AbsoluteLimit, 0  }
  };

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   A c q u i r e M a g i c k R e s o u r c e                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  AcquireMagickResource() acquires resources of the specified type.  True is
%  returned if the specified resource is available otherwise False.
%
%  The format of the AcquireMagickResource() method is:
%
%      MagickPassFail AcquireMagickResource(const ResourceType type,
%        const magick_int64_t size)
%
%  A description of each parameter follows:
%
%    o type: The type of resource.
%
%    o size: The number of bytes needed from for this resource.
%
%
*/
static ResourceInfo *GetResourceInfo(const ResourceType type)
{
  ResourceInfo
    *info;

  unsigned int
    index;

  info = (ResourceInfo *) NULL;
  index = type;
  if ((index != 0) && (index <= ResourceInfoMaxIndex))
    info = &resource_info[index];

  return info;
}

MagickExport MagickPassFail
AcquireMagickResource(const ResourceType type,
                      const magick_uint64_t size)
{
  ResourceInfo
    *info;

  MagickPassFail
    status;

  status=MagickPass;

  if ((info=GetResourceInfo(type)))
    {
      magick_uint64_t
        value=0;

      switch(info->limit_type)
        {
        case AbsoluteLimit:
          {
            /*
              Limit depends only on the currently requested size.
            */
            value=info->value;
            if ((info->maximum != ResourceInfinity) &&
                (size > (magick_uint64_t) info->maximum))
              status=MagickFail;
            break;
          }
        case SummationLimit:
          {
            /*
              Limit depends on sum of previous allocations as well as
              the currently requested size.
            */
            LockSemaphoreInfo(info->semaphore);
            value=info->value+size;
            if ((info->maximum != ResourceInfinity) &&
                (value > (magick_uint64_t) info->maximum))
              {
                value=info->value;
                status=MagickFail;
              }
            else
              {
                info->value=value;
              }
            UnlockSemaphoreInfo(info->semaphore);
            break;
          }
        }
      if (IsEventLogged(ResourceEvent))
        {
          char
            f_limit[MaxTextExtent],
            f_size[MaxTextExtent],
            f_value[MaxTextExtent];

          if (info->maximum == ResourceInfinity)
            {
              strlcpy(f_limit,"Unlimited",sizeof(f_limit));
            }
          else
            {
              FormatSize(info->maximum, f_limit);
              strlcat(f_limit,info->units,sizeof(f_limit));
            }

          FormatSize(size, f_size);
          strlcat(f_size,info->units,sizeof(f_size));

          if (info->limit_type == AbsoluteLimit)
            {
              strlcpy(f_value,"----",sizeof(f_value));
            }
          else
            {
              FormatSize(value, f_value);
              strlcat(f_value,info->units,sizeof(f_value));
            }

          (void) LogMagickEvent(ResourceEvent,GetMagickModule(),
                                "%s %s%s/%s/%s",
                                info->name,
                                (status ? "+" : "!"),
                                f_size,
                                f_value,
                                f_limit);
        }
    }

  return(status);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
+   D e s t r o y M a g i c k R e s o u r c e s                               %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  DestroyMagickResources() destroys the resource environment.
%
%  The format of the DestroyMagickResources() method is:
%
%      DestroyMagickResources(void)
%
%
*/
MagickExport void DestroyMagickResources(void)
{
  size_t
    index;

#if defined(DEBUG_MAGICK_RESOURCES) && DEBUG_MAGICK_RESOURCES
  {
      const ResourceInfo *info;

      for (index = 1; index < ArraySize(resource_info); index++)
      {
          info=&resource_info[index];
          if (info->limit_type != SummationLimit)
              continue;

          if (info->value != 0)
          {
              fprintf(stderr,"Resource[%s] %s! %"MAGICK_INT64_F"d remaining\n",
                      info->name, info->value < 0 ? "underflow" : "leak", (magick_int64_t) info->value);
              assert(info->value == 0);
          }
      }
  }
#endif /* if defined(DEBUG_MAGICK_RESOURCES) && DEBUG_MAGICK_RESOURCES */

  for (index = 1; index < ArraySize(resource_info); index++)
    DestroySemaphoreInfo(&resource_info[index].semaphore);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   G e t M a g i c k R e s o u r c e                                         %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  GetMagickResource() returns the current consumption level for the
%  specified resource type.
%
%  The format of the GetMagickResource() method is:
%
%      magick_uint64_t GetMagickResource(const ResourceType type)
%
%  A description of each parameter follows:
%
%    o type: The type of resource.
%
%
*/
MagickExport magick_int64_t GetMagickResource(const ResourceType type)
{
  ResourceInfo
    *info;

  magick_int64_t
    resource;

  resource=0;

  if ((info=GetResourceInfo(type)))
    {
      LockSemaphoreInfo(info->semaphore);
      resource=info->value;
      UnlockSemaphoreInfo(info->semaphore);
    }

  return(resource);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   G e t M a g i c k R e s o u r c e L i m i t                               %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  GetMagickResourceLimit() returns the current maximum limit for the
%  specified resource type.  Returns a maximum 64-bit integer value if
%  the resource has not been limited.
%
%  The format of the GetMagickResourceLimit() method is:
%
%      magick_int64_t GetMagickResourceLimit(const ResourceType type)
%
%  A description of each parameter follows:
%
%    o type: The type of resource.
%
%
*/
MagickExport magick_int64_t GetMagickResourceLimit(const ResourceType type)
{
  ResourceInfo
    *info;

  magick_int64_t
    resource;

  resource=0;

  if ((info=GetResourceInfo(type)))
    {
      LockSemaphoreInfo(info->semaphore);
      resource=info->maximum;
      UnlockSemaphoreInfo(info->semaphore);
    }

  return(resource);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
+   I n i t i a l i z e M a g i c k R e s o u r c e s                         %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  InitializeMagickResources() initializes the resource environment.
%
%  The format of the InitializeMagickResources() method is:
%
%      InitializeMagickResources(void)
%
%
*/
MagickExport void InitializeMagickResources(void)
{
  magick_int64_t
    max_disk=-1,
    max_files=256,
    max_map=4096,
    max_memory=1024,
    max_pixels=-1,
    max_threads=1,
    max_width=-1,
    max_height=-1,
    max_read=-1;

  size_t
    index;

  /*
    Allocate semaphores.
  */
  for (index = 1; index < ArraySize(resource_info); index++)
    resource_info[index].semaphore=AllocateSemaphoreInfo();

  /*
    Set Magick resource limits.
  */
#if defined(POSIX)
  {
    unsigned long
      total_memory=0;

#  if  defined(HAVE_SYSCONF) && defined(_SC_PHYS_PAGES)
    {
      long
        pagesize=-1,
        pages=-1;
      /*
        Compute total physical memory based on number of memory pages,
        and page size.
      */
      pages=sysconf(_SC_PHYS_PAGES);
      pagesize = MagickGetMMUPageSize();

      if (pages > 0 && pagesize > 0)
        total_memory=((pages+512)/1024)*((pagesize+512)/1024);
      (void) LogMagickEvent(ResourceEvent,GetMagickModule(),
                            "Total physical memory %ld MB (%ld pages and %ld bytes per page)",
                            total_memory, pages, pagesize);
    }
#  elif defined(MAGICK_PHYSICAL_MEMORY_COMMAND) && defined(HAVE_POPEN)
    {
      double
        bytes=0;

      FILE
        *command;
      /*
        Execute the external command defined by
        MAGICK_PHYSICAL_MEMORY_COMMAND to obtain the total physical
        memory in bytes.  This external command should be quite speedy
        or else it will impact the time to start GraphicsMagick.
      */
      if ((command = popen(MAGICK_PHYSICAL_MEMORY_COMMAND, "r")) != NULL)
        {
          if (fscanf(command,"%lf",&bytes) == 1)
            total_memory=(bytes/(1024*1024));
          (void) pclose(command);
          (void) LogMagickEvent(ResourceEvent,GetMagickModule(),
                                "Total physical memory %ld MB",total_memory);
        }
    }
#  endif

    if (total_memory > 0)
      {
        /*
          We are not able to use more than size_t worth of address
          space.  On 32 bit systems, we can usually only use half or
          three quarters of it.  Regardless, we need address space
          for more than just image data.
        */
        size_t
          size_t_max = (size_t) ~0UL;

        size_t_max /= (1024U*1024U);
        max_memory = Min(size_t_max/2-100,total_memory);
        max_map = Min(size_t_max/2-100,2*total_memory);
      }
  }
#endif /* defined(POSIX) */

#if defined(MSWINDOWS)
  {
    long
      total_physical_memory=0,
      total_virtual_memory=0;

    /*
      GlobalMemoryStatusEx is necessary to handle results for
      large-memory (>4GB) machines (and to provide accurate results
      for 2 to 4 GB of memory), but it is not available on older
      versions of Windows.  Windows 32-bit applications are still
      usually limited to addressing only 2 GB of memory even if the
      system provides more (except for certain server versions of
      Windows with applications linked with the /LARGEADDRESSAWARE
      option). Test for API existence prior to using it.  MinGW
      headers currently lack support for this API so compilation of
      supportive code is made optional.
    */
#if defined(HAVE_GLOBALMEMORYSTATUSEX)
    if (NTKernelAPISupported("GlobalMemoryStatusEx"))
      {
        MEMORYSTATUSEX
          stat_ex;

        (void) memset(&stat_ex,0,sizeof(stat_ex));
        stat_ex.dwLength=sizeof(stat_ex);
        if (GlobalMemoryStatusEx(&stat_ex))
          {
            total_physical_memory=(long)(stat_ex.ullTotalPhys/1048576UL);
            total_virtual_memory=(long)(stat_ex.ullTotalVirtual/1048576UL);
          }
        else
          {
            (void) LogMagickEvent(ResourceEvent,GetMagickModule(),
                                  "GlobalMemoryStatusEx() call failed! (error %ld)",GetLastError());
          }
      }
#endif

    if (total_physical_memory == 0)
      {
        MEMORYSTATUS
          stat;

        GlobalMemoryStatus(&stat);
        total_physical_memory=stat.dwTotalPhys/1048576;
        total_virtual_memory=stat.dwTotalVirtual/1048576;
      }
    (void) LogMagickEvent(ResourceEvent,GetMagickModule(),
                          "Total physical memory %ld MB, Total virtual memory %ld MB",
                          total_physical_memory, total_virtual_memory);

    max_memory=Min(total_physical_memory,total_virtual_memory);
    /*
      We will default to using at most 80% of available memory for image data.
    */
    max_memory=(long)(0.8*max_memory);
    /*
      Use the maximum memory as our default memory map limit.  Memory
      mapping files larger than available RAM can cause VM thrashing.
      This implies that memory mapping won't get used much.  However,
      it is possible for heap memory allocations to fail (due to heap
      fragmentation) whereas memory mapping still succeeds.
    */
    max_map=max_memory;

    /*
      Windows lowio level supports up to 2048 open files.
      Reserve 512 handles for other uses.
    */
    max_files=2048-512;
  }
#endif /* defined(MSWINDOWS) */

  /*
    Compute fundamental limits based on build parameters.  Image size
    is fundamentally limited by how many pixels may reside in one row.
  */
  if (sizeof(size_t) == 4)
    max_pixels=(magick_int64_t) ((unsigned long) ULONG_MAX/(5*sizeof(Quantum)));


  /*
    Disk, map, and memory are in units of MB and need to be scaled up.
  */
  /* if (max_disk > 0) */
  /*   max_disk  *= 1024UL*1024UL; */
  if (max_map > 0)
    max_map   *= 1024UL*1024UL;
  if (max_memory > 0)
    max_memory *= 1024UL*1024UL;

  /*
    Support using environment variables to set limits
  */
  {
    const char
      *envp;

    if ((envp=getenv("MAGICK_LIMIT_DISK")))
      max_disk=MagickSizeStrToInt64(envp,1024);

    if ((envp=getenv("MAGICK_LIMIT_FILES")))
      max_files=MagickSizeStrToInt64(envp,1024);

    if ((envp=getenv("MAGICK_LIMIT_MAP")))
      max_map=MagickSizeStrToInt64(envp,1024);

    if ((envp=getenv("MAGICK_LIMIT_MEMORY")))
      max_memory=MagickSizeStrToInt64(envp,1024);

    if ((envp=getenv("MAGICK_LIMIT_PIXELS")))
      max_pixels=MagickSizeStrToInt64(envp,1024);

    if ((envp=getenv("MAGICK_LIMIT_WIDTH")))
      max_width=MagickSizeStrToInt64(envp,1024);

    if ((envp=getenv("MAGICK_LIMIT_HEIGHT")))
      max_height=MagickSizeStrToInt64(envp,1024);

    if ((envp=getenv("MAGICK_LIMIT_READ")))
      max_read=MagickSizeStrToInt64(envp,1024);

#if defined(HAVE_OPENMP)
    max_threads=omp_get_num_procs();
    (void) LogMagickEvent(ResourceEvent,GetMagickModule(),
                          "%i CPU cores are available",(int) max_threads);
    if ((envp=getenv("OMP_NUM_THREADS")))
      {
        max_threads=MagickSizeStrToInt64(envp,1024);
        (void) LogMagickEvent(ResourceEvent,GetMagickModule(),
                              "OMP_NUM_THREADS requests %i threads",(int) max_threads);
      }
    if (max_threads < 1)
      max_threads=1;
    omp_set_num_threads((int) max_threads);
    max_threads=omp_get_max_threads();
#endif /* HAVE_OPENMP */
  }

#if defined(POSIX)
#  if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
    {
      struct rlimit
        rlimits;

      rlim_t
        margin,
        target;

      margin=128;
      target=(rlim_t) max_files+margin;
      if (getrlimit(RLIMIT_NOFILE, &rlimits) != -1)
        {
          (void) LogMagickEvent(ResourceEvent,GetMagickModule(),
                                "System file open limits are %lu soft,"
                                " %lu hard",
                                (unsigned long) rlimits.rlim_cur,
                                (unsigned long) rlimits.rlim_max);
#    if defined(HAVE_SETRLIMIT)
          if (rlimits.rlim_max < target)
            rlimits.rlim_cur=rlimits.rlim_max;
          if (rlimits.rlim_cur < target)
            {
              (void) LogMagickEvent(ResourceEvent,GetMagickModule(),
                                    "Increasing file open soft limit from %lu "
                                    "to %lu",
                                    (unsigned long) rlimits.rlim_cur,
                                    (unsigned long) target);
              rlimits.rlim_cur=target;
              (void) setrlimit(RLIMIT_NOFILE, &rlimits);
            }
          if (getrlimit(RLIMIT_NOFILE, &rlimits) != -1)
            {
              if (rlimits.rlim_cur < target)
                {
                  if (rlimits.rlim_cur > margin*2)
                    max_files=rlimits.rlim_cur-margin;
                  else
                    max_files=rlimits.rlim_cur/2;
                }
            }
#    endif
        }
    }
#  elif defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
    {
      long
        margin,
        open_max,
        target;

      margin=128;
      target=max_files+margin;
      open_max=sysconf(_SC_OPEN_MAX);
      (void) LogMagickEvent(ResourceEvent,GetMagickModule(),
                            "System file open limit is %lu",
                            (unsigned long) open_max);
      if (open_max < target)
        {
          if (open_max > margin*2)
            max_files=open_max-margin;
          else
            max_files=open_max/2;
        }
    }
#  endif

#endif

  if (max_disk >= 0)
    (void) SetMagickResourceLimit(DiskResource,max_disk);
  if (max_files >= 0)
    (void) SetMagickResourceLimit(FileResource,max_files);
  if (max_map >= 0)
    (void) SetMagickResourceLimit(MapResource,max_map);
  if (max_memory >= 0)
    (void) SetMagickResourceLimit(MemoryResource,max_memory);
  if (max_pixels >= 0)
    (void) SetMagickResourceLimit(PixelsResource,max_pixels);
  if (max_threads >= 0)
    (void) SetMagickResourceLimit(ThreadsResource,max_threads);
  if (max_width >= 0)
    (void) SetMagickResourceLimit(WidthResource,max_width);
  if (max_height >= 0)
    (void) SetMagickResourceLimit(HeightResource,max_height);
  if (max_read >= 0)
    (void) SetMagickResourceLimit(ReadResource,max_read);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   L i b e r a t e M a g i c k R e s o u r c e                               %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  LiberateMagickResource() liberates resources of the specified type.
%
%  The format of the LiberateMagickResource() method is:
%
%      void LiberateMagickResource(const ResourceType type,
%        const magick_int64_t size)
%
%  A description of each parameter follows:
%
%    o type: The type of resource.
%
%    o size: The size of the resource.
%
%
*/
MagickExport void LiberateMagickResource(const ResourceType type,
  const magick_uint64_t size)
{
  ResourceInfo
    *info;

  if ((info=GetResourceInfo(type)))
    {
      magick_uint64_t
        value=0;

      switch(info->limit_type)
        {
        case AbsoluteLimit:
          {
            /*
              Limit depends only on the currently requested size.
            */
            break;
          }
        case SummationLimit:
          {
            /*
              Limit depends on sum of previous allocations as well as
              the currently requested size.
            */
            LockSemaphoreInfo(info->semaphore);
            info->value-=size;
#if defined(DEBUG_MAGICK_RESOURCES) && DEBUG_MAGICK_RESOURCES
            assert(info->value >= info->minimum);
#endif /* if defined(DEBUG_MAGICK_RESOURCES) && DEBUG_MAGICK_RESOURCES */
            value=info->value;
            UnlockSemaphoreInfo(info->semaphore);
            break;
          }
        }

      if (IsEventLogged(ResourceEvent))
        {
          char
            f_limit[MaxTextExtent],
            f_size[MaxTextExtent],
            f_value[MaxTextExtent];

          if (info->maximum == ResourceInfinity)
            {
              strlcpy(f_limit,"Unlimited",sizeof(f_limit));
            }
          else
            {
              FormatSize(info->maximum, f_limit);
              strlcat(f_limit,info->units,sizeof(f_limit));
            }

          FormatSize(size, f_size);
          strlcat(f_size,info->units,sizeof(f_size));

          if (info->limit_type == AbsoluteLimit)
            {
              strlcpy(f_value,"----",sizeof(f_value));
            }
          else
            {
              FormatSize(value, f_value);
              strlcat(f_value,info->units,sizeof(f_value));
            }

          (void) LogMagickEvent(ResourceEvent,GetMagickModule(),
                                "%s %s%s/%s/%s",
                                info->name,
                                "-",
                                f_size,
                                f_value,
                                f_limit);
        }
    }
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%  L i s t M a g i c k R e s o u r c e I n f o                                %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Method ListMagickResourceInfo lists the resource info to a file.
%
%  The format of the ListMagickResourceInfo method is:
%
%      unsigned int ListMagickResourceInfo(FILE *file,ExceptionInfo *exception)
%
%  A description of each parameter follows.
%
%    o file:  An pointer to a FILE.
%
%    o exception: Return any errors or warnings in this structure.
%
%
*/
MagickExport MagickPassFail ListMagickResourceInfo(FILE *file,
  ExceptionInfo *exception)
{
  unsigned int
    index;

  ARG_NOT_USED(exception);

  if (file == (const FILE *) NULL)
    file=stdout;

  fprintf(file,"Resource Limits (Q%d, %d bits/pixel, %dbit address)\n",
          QuantumDepth,4*QuantumDepth,
          (sizeof(PixelPacket *) > 4 ? 64 : 32));
  fprintf(file,"----------------------------------------------------\n");
  for (index=1 ; index <= ResourceInfoMaxIndex; index++)
    {
      char
        environment[MaxTextExtent],
        heading[MaxTextExtent],
        limit[MaxTextExtent];

      LockSemaphoreInfo(resource_info[index].semaphore);
      if (resource_info[index].maximum == ResourceInfinity)
        {
          strlcpy(limit,"Unlimited",sizeof(limit));
        }
      else
        {
          FormatSize(resource_info[index].maximum,limit);
          strlcat(limit,resource_info[index].units,sizeof(limit));
        }
      FormatString(heading,"%c%s",toupper((int) resource_info[index].name[0]),
                   resource_info[index].name+1);

      (void) strlcpy(environment,resource_info[index].env,sizeof(environment));

      fprintf(file,"%8s: %10s (%s)\n", heading, limit, environment);
      UnlockSemaphoreInfo(resource_info[index].semaphore);
    }
  fprintf(file,
          "\n"
          "  IEC Binary Ranges:\n"
          "    Ki = \"kibi\" (2^10)\n"
          "    Mi = \"mebi\" (2^20)\n"
          "    Gi = \"gibi\" (2^30)\n"
          "    Ti = \"tebi\" (2^40)\n"
          "    Pi = \"pebi\" (2^50)\n"
          "    Ei = \"exbi\" (2^60)\n"
          );

  (void) fflush(file);

  return(MagickPass);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   S e t M a g i c k R e s o u r c e L i m i t                               %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  SetMagickResourceLimit() sets the limit for a particular resource.  The
%  units for resource types are as follows:
%
%    DiskResource    -- Bytes
%    FileResource    -- Open files
%    MapResource     -- Bytes
%    MemoryResource  -- Bytes
%    PixelsResource  -- Pixels
%    ThreadsResource -- Threads
%    WidthResource   -- Pixels
%    HeightResource  -- Pixels
%
%  The format of the SetMagickResourceLimit() method is:
%
%      void SetMagickResourceLimit(const ResourceType type,
%        const unsigned long limit)
%
%  A description of each parameter follows:
%
%    o type: The type of resource.
%
%    o limit: The maximum limit for the resource.
%
%
*/
MagickExport MagickPassFail SetMagickResourceLimit(const ResourceType type,
                                                   const magick_int64_t limit)
{
  ResourceInfo
    *info;

  MagickPassFail
    status;

  status=MagickFail;

  if ((info=GetResourceInfo(type)))
    {
      LockSemaphoreInfo(info->semaphore);
      if (limit >= info->minimum)
        {
          char
            f_limit[MaxTextExtent];


          FormatSize((magick_int64_t) limit, f_limit);
          info->maximum = limit;
#if defined(HAVE_OPENMP)
          if (ThreadsResource == type)
            omp_set_num_threads((int) limit);
#endif /* HAVE_OPENMP */
          (void) LogMagickEvent(ResourceEvent,GetMagickModule(),
                                "Set %s resource limit to %s%s",
                                info->name,f_limit,info->units);
          status=MagickPass;
        }
      else
        {
          (void) LogMagickEvent(ResourceEvent,GetMagickModule(),
                                "Ignored bogus request to set %s resource limit to %ld%s",
                                info->name,(long) limit,info->units);
        }
      UnlockSemaphoreInfo(info->semaphore);
    }

  return(status);
}