summaryrefslogtreecommitdiffstats
path: root/include/my_sys.h
blob: 8316975c0e0046c3fa0666cbe73bdeab8214957d (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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
/* Copyright (c) 2000, 2013, Oracle and/or its affiliates.
   Copyright (c) 2010, 2022, MariaDB Corporation.

   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; version 2 of the License.

   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-1335  USA */

#ifndef _my_sys_h
#define _my_sys_h

#include <m_string.h>
#include <mysql/psi/mysql_memory.h>

C_MODE_START


#include <my_valgrind.h>
#include <my_pthread.h>
#include <m_ctype.h>                    /* for CHARSET_INFO */
#include <stdarg.h>
#include <typelib.h>
#include <my_alloca.h>
#include <mysql/plugin.h>
#include <mysql/service_my_print_error.h>

#define MY_INIT(name)   { my_progname= name; my_init(); }

/**
  Max length of an error message generated by mysys utilities.
  Some mysys functions produce error messages. These mostly go
  to stderr.
  This constant defines the size of the buffer used to format
  the message. It should be kept in sync with MYSQL_ERRMSG_SIZE,
  since sometimes mysys errors are stored in the server diagnostics
  area, and we would like to avoid unexpected truncation.
*/
#define MYSYS_ERRMSG_SIZE   (512)
#define MYSYS_STRERROR_SIZE (128)

#define MY_FILE_ERROR	((size_t) -1)

	/* General bitmaps for my_func's */
#define MY_FFNF		1U	/* Fatal if file not found */
#define MY_FNABP	2U	/* Fatal if not all bytes read/written */
#define MY_NABP		4U	/* Error if not all bytes read/written */
#define MY_FAE		8U	/* Fatal if any error */
#define MY_WME		16U	/* Write message on error */
#define MY_WAIT_IF_FULL 32U	/* Wait and try again if disk full error */
#define MY_IGNORE_BADFD 32U     /* my_sync(): ignore 'bad descriptor' errors */
#define MY_IGNORE_ENOENT 32U    /* my_delete() ignores ENOENT (no such file) */
#define MY_ENCRYPT      64U     /* Encrypt IO_CACHE temporary files */
#define MY_TEMPORARY    64U     /* create_temp_file(): delete file at once */
#define MY_NOSYMLINKS  512U     /* my_open(): don't follow symlinks */
#define MY_FULL_IO     512U     /* my_read(): loop until I/O is complete */
#define MY_DONT_CHECK_FILESIZE 128U /* Option to init_io_cache() */
#define MY_LINK_WARNING 32U	/* my_redel() gives warning if links */
#define MY_COPYTIME	64U	/* my_redel() copies time */
#define MY_DELETE_OLD	256U	/* my_create_with_symlink() */
#define MY_RESOLVE_LINK 128U	/* my_realpath(); Only resolve links */
#define MY_HOLD_ORIGINAL_MODES 128U  /* my_copy() holds to file modes */
#define MY_REDEL_MAKE_BACKUP 256U
#define MY_SEEK_NOT_DONE 32U	/* my_lock may have to do a seek */
#define MY_SHORT_WAIT	64U	/* my_lock() don't wait if can't lock */
#define MY_FORCE_LOCK   128U    /* use my_lock() even if disable_locking */
#define MY_NO_WAIT      256U	/* my_lock() don't wait at all */
#define MY_NO_REGISTER  8196U   /* my_open(), no malloc for file name */
/*
  If old_mode is UTF8_IS_UTF8MB3, then pass this flag. It mean utf8 is
  alias for utf8mb3. Otherwise utf8 is alias for utf8mb4.
*/
#define MY_UTF8_IS_UTF8MB3 1024U
/*
  init_dynamic_array() has init buffer; Internal flag, not to be used by
  caller.
*/
#define MY_INIT_BUFFER_USED 256U
#define MY_ZEROFILL	32U	/* my_malloc(), fill array with zero */
#define MY_ALLOW_ZERO_PTR 64U	/* my_realloc() ; zero ptr -> malloc */
#define MY_FREE_ON_ERROR 128U	/* my_realloc() ; Free old ptr on error */
#define MY_DONT_OVERWRITE_FILE 2048U /* my_copy: Don't overwrite file */
#define MY_THREADSAFE 2048U     /* my_seek(): lock fd mutex */
#define MY_SYNC       4096U     /* my_copy(): sync dst file */
#define MY_SYNC_DIR   32768U    /* my_create/delete/rename: sync directory */
#define MY_THREAD_SPECIFIC 0x10000U /* my_malloc(): thread specific */
#define MY_ROOT_USE_MPROTECT 0x20000U /* init_alloc_root: read only segments */
/* Tree that should delete things automatically */
#define MY_TREE_WITH_DELETE 0x40000U

#define MY_CHECK_ERROR	1U	/* Params to my_end; Check open-close */
#define MY_GIVE_INFO	2U	/* Give time info about process*/
#define MY_DONT_FREE_DBUG 4U    /* Do not call DBUG_END() in my_end() */

#define ME_BELL           4U    /* Ring bell then printing message */
#define ME_ERROR_LOG      64    /**< write the error message to error log */
#define ME_ERROR_LOG_ONLY 128   /**< write the error message to error log only */
#define ME_NOTE           1024  /**< not error but just info */
#define ME_WARNING        2048  /**< not error but just warning */
#define ME_FATAL          4096  /**< fatal statement error */

	/* Bits in last argument to fn_format */
#define MY_REPLACE_DIR		1U	/* replace dir in name with 'dir' */
#define MY_REPLACE_EXT		2U	/* replace extension with 'ext' */
#define MY_UNPACK_FILENAME	4U	/* Unpack name (~ -> home) */
#define MY_PACK_FILENAME	8U	/* Pack name (home -> ~) */
#define MY_RESOLVE_SYMLINKS	16U	/* Resolve all symbolic links */
#define MY_RETURN_REAL_PATH	32U	/* return full path for file */
#define MY_SAFE_PATH		64U	/* Return NULL if too long path */
#define MY_RELATIVE_PATH	128U	/* name is relative to 'dir' */
#define MY_APPEND_EXT           256U    /* add 'ext' as additional extension*/


	/* My seek flags */
#define MY_SEEK_SET	0
#define MY_SEEK_CUR	1
#define MY_SEEK_END	2

	/* Some constants */
#define MY_WAIT_FOR_USER_TO_FIX_PANIC	60	/* in seconds */
#define MY_WAIT_GIVE_USER_A_MESSAGE	10	/* Every 10 times of prev */
#define MIN_COMPRESS_LENGTH		50	/* Don't compress small bl. */
#define DFLT_INIT_HITS  3

	/* root_alloc flags */
#define MY_KEEP_PREALLOC	1U
#define MY_MARK_BLOCKS_FREE     2U /* move used to free list and reuse them */

	/* Internal error numbers (for assembler functions) */
#define MY_ERRNO_EDOM		33
#define MY_ERRNO_ERANGE		34

	/* Bits for get_date timeflag */
#define GETDATE_DATE_TIME	1U
#define GETDATE_SHORT_DATE	2U
#define GETDATE_HHMMSSTIME	4U
#define GETDATE_GMT		8U
#define GETDATE_FIXEDLENGTH	16U

/* Extra length needed for filename if one calls my_create_backup_name */
#define MY_BACKUP_NAME_EXTRA_LENGTH 17

char *guess_malloc_library();

/* If we have our own safemalloc (for debugging) */
#if defined(SAFEMALLOC)
void sf_report_leaked_memory(my_thread_id id);
int sf_sanity();
extern my_thread_id (*sf_malloc_dbug_id)(void);
#define SAFEMALLOC_REPORT_MEMORY(X) sf_report_leaked_memory(X)
#else
#define SAFEMALLOC_REPORT_MEMORY(X) do {} while(0)
#endif

typedef void (*MALLOC_SIZE_CB) (long long size, my_bool is_thread_specific); 
extern void set_malloc_size_cb(MALLOC_SIZE_CB func);
extern MALLOC_SIZE_CB update_malloc_size;

	/* defines when allocating data */
extern void *my_malloc(PSI_memory_key key, size_t size, myf MyFlags);
extern void *my_multi_malloc(PSI_memory_key key, myf MyFlags, ...);
extern void *my_multi_malloc_large(PSI_memory_key key, myf MyFlags, ...);
extern void *my_realloc(PSI_memory_key key, void *ptr, size_t size, myf MyFlags);
extern void my_free(void *ptr);
extern void *my_memdup(PSI_memory_key key, const void *from,size_t length,myf MyFlags);
extern char *my_strdup(PSI_memory_key key, const char *from,myf MyFlags);
extern char *my_strndup(PSI_memory_key key, const char *from, size_t length, myf MyFlags);

int my_init_large_pages(my_bool super_large_pages);
uchar *my_large_malloc(size_t *size, myf my_flags);
void my_large_free(void *ptr, size_t size);
void my_large_page_truncate(size_t *size);

#ifdef _WIN32
extern BOOL my_obtain_privilege(LPCSTR lpPrivilege);
#endif

void my_init_atomic_write(void);
#ifdef __linux__
my_bool my_test_if_atomic_write(File handle, int pagesize);
my_bool my_test_if_thinly_provisioned(File handle);
#else
# define my_test_if_atomic_write(A, B)      0
# define my_test_if_thinly_provisioned(A)   0
#endif /* __linux__ */
extern my_bool my_may_have_atomic_write;

#if defined(HAVE_ALLOCA) && !defined(HAVE_valgrind)
#define my_alloca(SZ) alloca((size_t) (SZ))
#define my_afree(PTR) ((void)0)
#define MAX_ALLOCA_SZ 4096
#define my_safe_alloca(size) (((size) <= MAX_ALLOCA_SZ) ? \
                               my_alloca(size) : \
                               my_malloc(PSI_NOT_INSTRUMENTED, (size), MYF(MY_THREAD_SPECIFIC|MY_WME)))
#define my_safe_afree(ptr, size) \
                  do { if ((size) > MAX_ALLOCA_SZ) my_free(ptr); } while(0)
#else
#define my_alloca(SZ) my_malloc(PSI_NOT_INSTRUMENTED, SZ,MYF(MY_FAE))
#define my_afree(PTR) my_free(PTR)
#define my_safe_alloca(size) my_alloca(size)
#define my_safe_afree(ptr, size) my_afree(ptr)
#endif /* HAVE_ALLOCA */

#ifndef errno				/* did we already get it? */
#ifdef HAVE_ERRNO_AS_DEFINE
#include <errno.h>			/* errno is a define */
#else
extern int errno;			/* declare errno */
#endif
#endif					/* #ifndef errno */
extern char *home_dir;			/* Home directory for user */
extern MYSQL_PLUGIN_IMPORT char  *mysql_data_home;
extern const char *my_progname;		/* program-name (printed in errors) */
extern const char *my_progname_short;	/* like above but without directory */
extern char curr_dir[];		/* Current directory for user */
extern void (*error_handler_hook)(uint my_err, const char *str,myf MyFlags);
extern void (*fatal_error_handler_hook)(uint my_err, const char *str,
				       myf MyFlags);
extern uint my_file_limit;
extern ulonglong my_thread_stack_size;
extern int sf_leaking_memory; /* set to 1 to disable memleak detection */

extern void (*proc_info_hook)(void *, const PSI_stage_info *, PSI_stage_info *,
                              const char *, const char *, const unsigned int);

/* charsets */
#define MY_ALL_CHARSETS_SIZE 4096
extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *default_charset_info;
extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *all_charsets[MY_ALL_CHARSETS_SIZE];
extern struct charset_info_st compiled_charsets[];

/* Collation properties and use statistics */
extern my_bool my_collation_is_known_id(uint id);
extern ulonglong my_collation_statistics_get_use_count(uint id);
extern const char *my_collation_get_tailoring(uint id);

/* statistics */
extern ulong    my_stream_opened, my_tmp_file_created;
extern ulong    my_file_total_opened;
extern ulong    my_sync_count;
extern uint	mysys_usage_id;
extern int32    my_file_opened;
extern my_bool	my_init_done, my_thr_key_mysys_exists;
extern my_bool my_assert;
extern my_bool  my_assert_on_error;
extern myf      my_global_flags;        /* Set to MY_WME for more error messages */
					/* Point to current my_message() */
extern void (*my_sigtstp_cleanup)(void),
					/* Executed before jump to shell */
	    (*my_sigtstp_restart)(void);
					/* Executed when coming from shell */
extern MYSQL_PLUGIN_IMPORT int my_umask;		/* Default creation mask  */
extern int my_umask_dir,
	   my_recived_signals,	/* Signals we have got */
	   my_safe_to_handle_signal, /* Set when allowed to SIGTSTP */
	   my_dont_interrupt;	/* call remember_intr when set */
#ifdef _WIN32
extern SECURITY_ATTRIBUTES my_dir_security_attributes;
LPSECURITY_ATTRIBUTES my_win_file_secattr();
#endif
extern MYSQL_PLUGIN_IMPORT my_bool my_use_symdir;

extern ulong	my_default_record_cache_size;
extern MYSQL_PLUGIN_IMPORT my_bool my_disable_locking;
extern my_bool  my_disable_async_io,
                my_disable_flush_key_blocks, my_disable_symlinks;
extern my_bool my_disable_sync, my_disable_copystat_in_redel;
extern char	wild_many,wild_one,wild_prefix;
extern const char *charsets_dir;
extern size_t my_system_page_size;

enum cache_type
{
  TYPE_NOT_SET= 0, READ_CACHE, WRITE_CACHE,
  SEQ_READ_APPEND		/* sequential read or append */,
  READ_FIFO, READ_NET};

enum flush_type
{
  FLUSH_KEEP,           /* flush block and keep it in the cache */
  FLUSH_RELEASE,        /* flush block and remove it from the cache */
  FLUSH_IGNORE_CHANGED, /* remove block from the cache */
  /*
    As my_disable_flush_pagecache_blocks is always 0, the following option
    is strictly equivalent to FLUSH_KEEP
  */
  FLUSH_FORCE_WRITE,
  /**
     @brief like FLUSH_KEEP but return immediately if file is already being
     flushed (even partially) by another thread; only for page cache,
     forbidden for key cache.
  */
  FLUSH_KEEP_LAZY
};

typedef struct st_record_cache	/* Used when caching records */
{
  File file;
  int	rc_seek,error,inited;
  uint	rc_length,read_length,reclength;
  my_off_t rc_record_pos,end_of_file;
  uchar *rc_buff,*rc_buff2,*rc_pos,*rc_end,*rc_request_pos;
  enum cache_type type;
} RECORD_CACHE;

enum file_type
{
  UNOPEN = 0, FILE_BY_OPEN, FILE_BY_CREATE, STREAM_BY_FOPEN, STREAM_BY_FDOPEN,
  FILE_BY_O_TMPFILE, FILE_BY_MKSTEMP, FILE_BY_DUP
};

struct st_my_file_info
{
  char  *name;
#ifdef _WIN32
  HANDLE fhandle;   /* win32 file handle */
  int    oflag;     /* open flags, e.g O_APPEND */
#endif
  enum   file_type	type;
};

extern struct st_my_file_info *my_file_info;

/* Free function pointer */
typedef void (*FREE_FUNC)(void *);

typedef struct st_dynamic_array
{
  uchar *buffer;
  size_t elements, max_element;
  size_t alloc_increment;
  size_t size_of_element;
  PSI_memory_key m_psi_key;
  myf malloc_flags;
} DYNAMIC_ARRAY;

typedef struct st_my_tmpdir
{
  DYNAMIC_ARRAY full_list;
  char **list;
  size_t cur, max;
  mysql_mutex_t mutex;
} MY_TMPDIR;

typedef struct st_dynamic_string
{
  char *str;
  size_t length,max_length,alloc_increment;
} DYNAMIC_STRING;

struct st_io_cache;

typedef struct st_io_cache_share
{
  mysql_mutex_t       mutex;           /* To sync on reads into buffer. */
  mysql_cond_t        cond;            /* To wait for signals. */
  mysql_cond_t        cond_writer;     /* For a synchronized writer. */
  /* Offset in file corresponding to the first byte of buffer. */
  my_off_t              pos_in_file;
  /* If a synchronized write cache is the source of the data. */
  struct st_io_cache    *source_cache;
  uchar                 *buffer;         /* The read buffer. */
  uchar                 *read_end;       /* Behind last valid byte of buffer. */
  int                   running_threads; /* threads not in lock. */
  int                   total_threads;   /* threads sharing the cache. */
  int                   error;           /* Last error. */
#ifdef NOT_YET_IMPLEMENTED
  /* whether the structure should be free'd */
  my_bool alloced;
#endif
} IO_CACHE_SHARE;

typedef struct st_io_cache		/* Used when caching files */
{
  /* Offset in file corresponding to the first byte of uchar* buffer. */
  my_off_t pos_in_file;
  /*
    The offset of end of file for READ_CACHE and WRITE_CACHE.
    For SEQ_READ_APPEND it the maximum of the actual end of file and
    the position represented by read_end.
  */
  my_off_t end_of_file;
  /* Points to current read position in the buffer */
  uchar	*read_pos;
  /* the non-inclusive boundary in the buffer for the currently valid read */
  uchar  *read_end;
  uchar  *buffer;				/* The read buffer */
  /* Used in ASYNC_IO */
  uchar  *request_pos;

  /* Only used in WRITE caches and in SEQ_READ_APPEND to buffer writes */
  uchar  *write_buffer;
  /*
    Only used in SEQ_READ_APPEND, and points to the current read position
    in the write buffer. Note that reads in SEQ_READ_APPEND caches can
    happen from both read buffer (uchar* buffer) and write buffer
    (uchar* write_buffer).
  */
  uchar *append_read_pos;
  /* Points to current write position in the write buffer */
  uchar *write_pos;
  /* The non-inclusive boundary of the valid write area */
  uchar *write_end;

  /*
    The lock is for append buffer used in SEQ_READ_APPEND cache
    need mutex copying from append buffer to read buffer.
  */
  mysql_mutex_t append_buffer_lock;
  /*
    The following is used when several threads are reading the
    same file in parallel. They are synchronized on disk
    accesses reading the cached part of the file asynchronously.
    It should be set to NULL to disable the feature.  Only
    READ_CACHE mode is supported.
  */
  IO_CACHE_SHARE *share;

  /*
    A caller will use my_b_read() macro to read from the cache
    if the data is already in cache, it will be simply copied with
    memcpy() and internal variables will be accordingly updated with
    no functions invoked. However, if the data is not fully in the cache,
    my_b_read() will call read_function to fetch the data. read_function
    must never be invoked directly.
  */
  int (*read_function)(struct st_io_cache *,uchar *,size_t);
  /*
    Same idea as in the case of read_function, except my_b_write() needs to
    be replaced with my_b_append() for a SEQ_READ_APPEND cache
  */
  int (*write_function)(struct st_io_cache *,const uchar *,size_t);
  /*
    Specifies the type of the cache. Depending on the type of the cache
    certain operations might not be available and yield unpredicatable
    results. Details to be documented later
  */
  enum cache_type type;
  /*
    Counts the number of times, when we were forced to use disk. We use it to
    increase the binlog_cache_disk_use and binlog_stmt_cache_disk_use status
    variables.
  */
  ulong disk_writes;
  char *file_name;			/* if used with 'open_cached_file' */
  const char *dir;
  char prefix[3];
  File file; /* file descriptor */

  struct st_io_cache *next_file_user;
  /*
    seek_not_done is set by my_b_seek() to inform the upcoming read/write
    operation that a seek needs to be preformed prior to the actual I/O
    error is 0 if the cache operation was successful, -1 if there was a
    "hard" error, and the actual number of I/O-ed bytes if the read/write was
    partial.
  */
  int	seek_not_done,error;
  /* length of the buffer used for storing un-encrypted data */
  size_t	buffer_length;
  /* read_length is the same as buffer_length except when we use async io */
  size_t  read_length;
  myf	myflags;			/* Flags used to my_read/my_write */
  /*
    alloced_buffer is set to the size of the buffer allocated for the IO_CACHE.
    Includes the overhead(storing key to encrypt and decrypt) for encryption.
    Set to 0 if nothing is allocated.
    Currently READ_NET is the only one that will use a buffer allocated
    somewhere else
  */
  size_t alloced_buffer;
} IO_CACHE;

typedef int (*qsort2_cmp)(const void *, const void *, const void *);

typedef void (*my_error_reporter)(enum loglevel level, const char *format, ...)
  ATTRIBUTE_FORMAT_FPTR(printf, 2, 3);

extern my_error_reporter my_charset_error_reporter;

extern PSI_file_key key_file_io_cache;

/* inline functions for mf_iocache */

extern int my_b_flush_io_cache(IO_CACHE *info, int need_append_buffer_lock);
extern int _my_b_get(IO_CACHE *info);
extern int _my_b_read(IO_CACHE *info,uchar *Buffer,size_t Count);
extern int _my_b_write(IO_CACHE *info,const uchar *Buffer,size_t Count);

/* Test if buffer is inited */
static inline void my_b_clear(IO_CACHE *info) { info->buffer= 0; }
static inline int my_b_inited(IO_CACHE *info) { return MY_TEST(info->buffer); }
#define my_b_EOF INT_MIN

static inline int my_b_read(IO_CACHE *info, uchar *Buffer, size_t Count)
{
  if (info->read_pos + Count <= info->read_end)
  {
    memcpy(Buffer, info->read_pos, Count);
    info->read_pos+= Count;
    return 0;
  }
  return _my_b_read(info, Buffer, Count);
}

static inline int my_b_write(IO_CACHE *info, const uchar *Buffer, size_t Count)
{
  MEM_CHECK_DEFINED(Buffer, Count);
  if (info->write_pos + Count <= info->write_end)
  {
    if (Count)
    {
      memcpy(info->write_pos, Buffer, Count);
      info->write_pos+= Count;
    }
    return 0;
  }
  return _my_b_write(info, Buffer, Count);
}

static inline int my_b_get(IO_CACHE *info)
{
  if (info->read_pos != info->read_end)
  {
    info->read_pos++;
    return info->read_pos[-1];
  }
  return _my_b_get(info);
}

static inline my_bool my_b_write_byte(IO_CACHE *info, uchar chr)
{
  MEM_CHECK_DEFINED(&chr, 1);
  if (info->write_pos >= info->write_end)
    if (my_b_flush_io_cache(info, 1))
      return 1;
  *info->write_pos++= chr;
  return 0;
}

/**
  Fill buffer of the cache.

  @note It assumes that you have already used all characters in the CACHE,
        independent of the read_pos value!

  @returns
        0     On error or EOF (info->error = -1 on error)
        #     Number of characters
*/
static inline size_t my_b_fill(IO_CACHE *info)
{
  info->read_pos= info->read_end;
  return _my_b_read(info,0,0) ? 0 : (size_t) (info->read_end - info->read_pos);
}

static inline my_off_t my_b_tell(const IO_CACHE *info)
{
  if (info->type == WRITE_CACHE) {
    return info->pos_in_file + (my_off_t)(info->write_pos - info->request_pos);

  }
  return info->pos_in_file + (my_off_t) (info->read_pos - info->request_pos);
}

static inline my_off_t my_b_write_tell(const IO_CACHE *info)
{
  return info->pos_in_file + (my_off_t) (info->write_pos - info->write_buffer);
}

static inline uchar* my_b_get_buffer_start(const IO_CACHE *info)
{
  return info->request_pos;
}

static inline size_t my_b_get_bytes_in_buffer(const IO_CACHE *info)
{
  return (size_t) (info->read_end - info->request_pos);
}

static inline my_off_t my_b_get_pos_in_file(const IO_CACHE *info)
{
  return info->pos_in_file;
}

static inline size_t my_b_bytes_in_cache(const IO_CACHE *info)
{
  if (info->type == WRITE_CACHE) {
    return (size_t) (info->write_end - info->write_pos);
  }
  return (size_t) (info->read_end - info->read_pos);
}

int my_b_copy_to_file    (IO_CACHE *cache, FILE *file, size_t count);
int my_b_copy_all_to_file(IO_CACHE *cache, FILE *file);

my_off_t my_b_append_tell(IO_CACHE* info);
my_off_t my_b_safe_tell(IO_CACHE* info); /* picks the correct tell() */
int my_b_pread(IO_CACHE *info, uchar *Buffer, size_t Count, my_off_t pos);

typedef uint32 ha_checksum;

extern int (*mysys_test_invalid_symlink)(const char *filename);
#include <my_alloc.h>

	/* Prototypes for mysys and my_func functions */

extern int my_copy(const char *from,const char *to,myf MyFlags);
extern int my_delete(const char *name,myf MyFlags);
extern int my_rmtree(const char *name, myf Myflags);
extern int my_getwd(char * buf,size_t size,myf MyFlags);
extern int my_setwd(const char *dir,myf MyFlags);
extern int my_lock(File fd,int op,my_off_t start, my_off_t length,myf MyFlags);
extern void *my_once_alloc(size_t Size,myf MyFlags);
extern void my_once_free(void);
extern char *my_once_strdup(const char *src,myf myflags);
extern void *my_once_memdup(const void *src, size_t len, myf myflags);
extern File my_open(const char *FileName,int Flags,myf MyFlags);
extern File my_register_filename(File fd, const char *FileName,
				 enum file_type type_of_file,
				 uint error_message_number, myf MyFlags);
extern File my_create(const char *FileName,int CreateFlags,
		      int AccessFlags, myf MyFlags);
extern int my_close(File Filedes,myf MyFlags);
extern int my_mkdir(const char *dir, int Flags, myf MyFlags);
extern int my_readlink(char *to, const char *filename, myf MyFlags);
extern int my_is_symlink(const char *filename);
extern int my_realpath(char *to, const char *filename, myf MyFlags);
extern File my_create_with_symlink(const char *linkname, const char *filename,
				   int createflags, int access_flags,
				   myf MyFlags);
extern int my_rename_with_symlink(const char *from,const char *to,myf MyFlags);
extern int my_symlink(const char *content, const char *linkname, myf MyFlags);
extern int my_handler_delete_with_symlink(const char *filename, myf sync_dir);

extern size_t my_read(File Filedes,uchar *Buffer,size_t Count,myf MyFlags);
extern size_t my_pread(File Filedes,uchar *Buffer,size_t Count,my_off_t offset,
		     myf MyFlags);
extern int my_rename(const char *from,const char *to,myf MyFlags);
extern my_off_t my_seek(File fd,my_off_t pos,int whence,myf MyFlags);
extern my_off_t my_tell(File fd,myf MyFlags);
extern size_t my_write(File Filedes,const uchar *Buffer,size_t Count,
		     myf MyFlags);
extern size_t my_pwrite(File Filedes,const uchar *Buffer,size_t Count,
		      my_off_t offset,myf MyFlags);
extern size_t my_fread(FILE *stream,uchar *Buffer,size_t Count,myf MyFlags);
extern size_t my_fwrite(FILE *stream,const uchar *Buffer,size_t Count,
		      myf MyFlags);
extern my_off_t my_fseek(FILE *stream,my_off_t pos,int whence,myf MyFlags);
extern my_off_t my_ftell(FILE *stream,myf MyFlags);

/* implemented in my_memmem.c */
extern void *my_memmem(const void *haystack, size_t haystacklen,
                       const void *needle, size_t needlelen);


#ifdef _WIN32
extern int      my_access(const char *path, int amode);
#define my_check_user(A,B) (NULL)
#define my_set_user(A,B,C) (0)
#else
#define my_access access
struct passwd *my_check_user(const char *user, myf MyFlags);
int my_set_user(const char *user, struct passwd *user_info, myf MyFlags);
#endif

extern int check_if_legal_filename(const char *path);
extern int check_if_legal_tablename(const char *path);

#ifdef _WIN32
extern my_bool is_filename_allowed(const char *name, size_t length,
                   my_bool allow_current_dir);
#else /* _WIN32 */
# define is_filename_allowed(name, length, allow_cwd) (TRUE)
#endif /* _WIN32 */ 

#ifdef _WIN32
/* Windows-only functions (CRT equivalents)*/
extern HANDLE   my_get_osfhandle(File fd);
extern File     my_win_handle2File(HANDLE hFile);
extern void     my_osmaperr(unsigned long last_error);
#endif

extern void init_glob_errs(void);
extern const char** get_global_errmsgs(int nr);
extern void wait_for_free_space(const char *filename, int errors);
extern FILE *my_fopen(const char *FileName,int Flags,myf MyFlags);
extern FILE *my_fdopen(File Filedes,const char *name, int Flags,myf MyFlags);
extern FILE *my_freopen(const char *path, const char *mode, FILE *stream);
extern int my_fclose(FILE *fd,myf MyFlags);
extern int my_vfprintf(FILE *stream, const char* format, va_list args);
extern const char* my_strerror(char *buf, size_t len, int nr);
extern int my_fprintf(FILE *stream, const char* format, ...);
extern File my_fileno(FILE *fd);
extern int my_chsize(File fd,my_off_t newlength, int filler, myf MyFlags);
extern int my_chmod(const char *name, mode_t mode, myf my_flags);
extern const char *my_basename(const char *filename);
extern void thr_set_sync_wait_callback(void (*before_sync)(void),
                                       void (*after_sync)(void));
extern int my_sync(File fd, myf my_flags);
extern int my_sync_dir(const char *dir_name, myf my_flags);
extern int my_sync_dir_by_file(const char *file_name, myf my_flags);
extern const char *my_get_err_msg(uint nr);
extern int my_error_register(const char** (*get_errmsgs) (int nr),
                             uint first, uint last);
extern my_bool my_error_unregister(uint first, uint last);
extern void my_message(uint my_err, const char *str,myf MyFlags);
extern void my_message_stderr(uint my_err, const char *str, myf MyFlags);
extern my_bool my_init(void);
extern void my_end(int infoflag);
extern int my_redel(const char *from, const char *to, time_t backup_time_stamp,
                    myf MyFlags);
void my_create_backup_name(char *to, const char *from,
                           time_t backup_time_stamp);
extern int my_copystat(const char *from, const char *to, int MyFlags);
extern char * my_filename(File fd);

extern my_bool init_tmpdir(MY_TMPDIR *tmpdir, const char *pathlist);
extern char *my_tmpdir(MY_TMPDIR *tmpdir);
extern void free_tmpdir(MY_TMPDIR *tmpdir);

extern void my_remember_signal(int signal_number,sig_handler (*func)(int));
extern size_t dirname_part(char * to,const char *name, size_t *to_res_length);
extern size_t dirname_length(const char *name);
#define base_name(A) (A+dirname_length(A))
extern int test_if_hard_path(const char *dir_name);
extern my_bool has_path(const char *name);
extern char *convert_dirname(char *to, const char *from, const char *from_end);
extern void to_unix_path(char * name);
extern char * fn_ext(const char *name);
extern char * fn_ext2(const char *name);
extern char * fn_same(char * toname,const char *name,int flag);
extern char * fn_format(char * to,const char *name,const char *dir,
			   const char *form, uint flag);
extern size_t strlength(const char *str);
extern void pack_dirname(char * to,const char *from);
extern size_t normalize_dirname(char * to, const char *from);
extern size_t unpack_dirname(char * to,const char *from);
extern size_t cleanup_dirname(char * to,const char *from);
extern size_t system_filename(char * to,const char *from);
extern size_t unpack_filename(char * to,const char *from);
extern char * intern_filename(char * to,const char *from);
extern int pack_filename(char * to, const char *name, size_t max_length);
extern char * my_path(char * to,const char *progname,
			 const char *own_pathname_part);
extern char * my_load_path(char * to, const char *path,
			      const char *own_path_prefix);
extern int wild_compare(const char *str,const char *wildstr,
                        pbool str_is_pattern);
extern my_bool array_append_string_unique(const char *str,
                                          const char **array, size_t size);
extern void get_date(char * to,int timeflag,time_t use_time);
extern void soundex(CHARSET_INFO *, char * out_pntr, char * in_pntr,
                    pbool remove_garbage);
extern int init_record_cache(RECORD_CACHE *info,size_t cachesize,File file,
			     size_t reclength,enum cache_type type,
			     pbool use_async_io);
extern int read_cache_record(RECORD_CACHE *info,uchar *to);
extern int end_record_cache(RECORD_CACHE *info);
extern int write_cache_record(RECORD_CACHE *info,my_off_t filepos,
			      const uchar *record,size_t length);
extern int flush_write_cache(RECORD_CACHE *info);
extern void handle_recived_signals(void);

extern sig_handler my_set_alarm_variable(int signo);
extern my_bool radixsort_is_appliccable(uint n_items, size_t size_of_element);
extern void my_string_ptr_sort(uchar *base,uint items,size_t size);
extern void radixsort_for_str_ptr(uchar* base[], uint number_of_elements,
				  size_t size_of_element,uchar *buffer[]);
extern qsort_t my_qsort(void *base_ptr, size_t total_elems, size_t size,
                        qsort_cmp cmp);
extern qsort_t my_qsort2(void *base_ptr, size_t total_elems, size_t size,
                         qsort2_cmp cmp, void *cmp_argument);
extern qsort2_cmp get_ptr_compare(size_t);
void my_store_ptr(uchar *buff, size_t pack_length, my_off_t pos);
my_off_t my_get_ptr(uchar *ptr, size_t pack_length);
extern int init_io_cache(IO_CACHE *info,File file,size_t cachesize,
			 enum cache_type type,my_off_t seek_offset,
			 my_bool use_async_io, myf cache_myflags);
extern int init_io_cache_ext(IO_CACHE *info, File file, size_t cachesize,
                              enum cache_type type, my_off_t seek_offset,
                              pbool use_async_io, myf cache_myflags,
                              PSI_file_key file_key);
extern my_bool reinit_io_cache(IO_CACHE *info,enum cache_type type,
			       my_off_t seek_offset, my_bool use_async_io,
			       my_bool clear_cache);
extern void init_io_cache_share(IO_CACHE *read_cache, IO_CACHE_SHARE *cshare,
                                IO_CACHE *write_cache, uint num_threads);

extern int init_slave_io_cache(IO_CACHE *master, IO_CACHE *slave);
void end_slave_io_cache(IO_CACHE *cache);
void seek_io_cache(IO_CACHE *cache, my_off_t needed_offset);

extern void remove_io_thread(IO_CACHE *info);
extern int my_b_append(IO_CACHE *info,const uchar *Buffer,size_t Count);
extern int my_b_safe_write(IO_CACHE *info,const uchar *Buffer,size_t Count);

extern int my_block_write(IO_CACHE *info, const uchar *Buffer,
			  size_t Count, my_off_t pos);

#define flush_io_cache(info) my_b_flush_io_cache((info),1)

extern int end_io_cache(IO_CACHE *info);
extern void my_b_seek(IO_CACHE *info,my_off_t pos);
extern size_t my_b_gets(IO_CACHE *info, char *to, size_t max_length);
extern my_off_t my_b_filelength(IO_CACHE *info);
extern my_bool my_b_write_backtick_quote(IO_CACHE *info, const char *str,
                                         size_t len);
extern my_bool my_b_printf(IO_CACHE *info, const char* fmt, ...);
extern size_t my_b_vprintf(IO_CACHE *info, const char* fmt, va_list ap);
extern my_bool open_cached_file(IO_CACHE *cache,const char *dir,
				 const char *prefix, size_t cache_size,
				 myf cache_myflags);
extern my_bool real_open_cached_file(IO_CACHE *cache);
extern void close_cached_file(IO_CACHE *cache);
File create_temp_file(char *to, const char *dir, const char *pfx,
		      int mode, myf MyFlags);
#define my_init_dynamic_array(A,B,C,D,E,F) init_dynamic_array2(A,B,C,NULL,D,E,F)
#define my_init_dynamic_array2(A,B,C,D,E,F,G) init_dynamic_array2(A,B,C,D,E,F,G)
extern my_bool init_dynamic_array2(PSI_memory_key psi_key, DYNAMIC_ARRAY *array,
                                   size_t element_size, void *init_buffer,
                                   size_t init_alloc, size_t alloc_increment,
                                   myf my_flags);
extern my_bool insert_dynamic(DYNAMIC_ARRAY *array, const void* element);
extern void *alloc_dynamic(DYNAMIC_ARRAY *array);
extern void *pop_dynamic(DYNAMIC_ARRAY*);
extern my_bool set_dynamic(DYNAMIC_ARRAY *array, const void *element,
                           size_t array_index);
extern my_bool allocate_dynamic(DYNAMIC_ARRAY *array, size_t max_elements);
extern void get_dynamic(DYNAMIC_ARRAY *array, void *element, size_t array_index);
extern void delete_dynamic(DYNAMIC_ARRAY *array);
extern void delete_dynamic_element(DYNAMIC_ARRAY *array, size_t array_index);
extern void delete_dynamic_with_callback(DYNAMIC_ARRAY *array, FREE_FUNC f);
extern void freeze_size(DYNAMIC_ARRAY *array);
#define dynamic_array_ptr(array,array_index) ((array)->buffer+(array_index)*(array)->size_of_element)
#define dynamic_element(array,array_index,type) ((type)((array)->buffer) +(array_index))
#define push_dynamic(A,B) insert_dynamic((A),(B))
#define reset_dynamic(array) ((array)->elements= 0)
#define sort_dynamic(A,cmp) my_qsort((A)->buffer, (A)->elements, (A)->size_of_element, (cmp))

extern my_bool init_dynamic_string(DYNAMIC_STRING *str, const char *init_str,
				   size_t init_alloc,size_t alloc_increment);
extern my_bool dynstr_append(DYNAMIC_STRING *str, const char *append);
my_bool dynstr_append_mem(DYNAMIC_STRING *str, const char *append,
			  size_t length);
extern my_bool dynstr_append_os_quoted(DYNAMIC_STRING *str, const char *append,
                                       ...);
extern my_bool dynstr_append_quoted(DYNAMIC_STRING *str,
                                    const char *append, size_t len,
                                    char quote);
extern my_bool dynstr_set(DYNAMIC_STRING *str, const char *init_str);
extern my_bool dynstr_realloc(DYNAMIC_STRING *str, size_t additional_size);
extern my_bool dynstr_trunc(DYNAMIC_STRING *str, size_t n);
extern void dynstr_free(DYNAMIC_STRING *str);
extern uint32 copy_and_convert_extended(char *to, uint32 to_length,
                                        CHARSET_INFO *to_cs,
                                        const char *from, uint32 from_length,
                                        CHARSET_INFO *from_cs, uint *errors);
extern void dynstr_reassociate(DYNAMIC_STRING *str, char **res, size_t *length,
                               size_t *alloc_length);
extern uint32 copy_and_convert_extended(char *to, uint32 to_length,
                                        CHARSET_INFO *to_cs,
                                        const char *from, uint32 from_length,
                                        CHARSET_INFO *from_cs, uint *errors);
#ifdef HAVE_MLOCK
extern void *my_malloc_lock(size_t length,myf flags);
extern void my_free_lock(void *ptr);
#else
#define my_malloc_lock(A,B) my_malloc(PSI_INSTRUMENT_ME, (A),(B))
#define my_free_lock(A) my_free((A))
#endif
#define alloc_root_inited(A) ((A)->min_malloc != 0)
#define clear_alloc_root(A) do { (A)->free= (A)->used= (A)->pre_alloc= 0; (A)->min_malloc=0;} while(0)
extern void init_alloc_root(PSI_memory_key key, MEM_ROOT *mem_root,
                            size_t block_size, size_t pre_alloc_size,
                            myf my_flags);
extern void *alloc_root(MEM_ROOT *mem_root, size_t Size);
extern void *multi_alloc_root(MEM_ROOT *mem_root, ...);
extern void free_root(MEM_ROOT *root, myf MyFLAGS);
extern void set_prealloc_root(MEM_ROOT *root, char *ptr);
extern void reset_root_defaults(MEM_ROOT *mem_root, size_t block_size,
                                size_t prealloc_size);
extern USED_MEM *get_last_memroot_block(MEM_ROOT* root);
extern void free_all_new_blocks(MEM_ROOT *root, USED_MEM *last_block);
extern void protect_root(MEM_ROOT *root, int prot);
extern char *strdup_root(MEM_ROOT *root,const char *str);
static inline char *safe_strdup_root(MEM_ROOT *root, const char *str)
{
  return str ? strdup_root(root, str) : 0;
}
extern char *strmake_root(MEM_ROOT *root,const char *str,size_t len);
extern void *memdup_root(MEM_ROOT *root,const void *str, size_t len);

extern LEX_CSTRING safe_lexcstrdup_root(MEM_ROOT *root, const LEX_CSTRING str);
extern my_bool my_compress(uchar *, size_t *, size_t *);
extern my_bool my_uncompress(uchar *, size_t , size_t *);
extern uchar *my_compress_alloc(const uchar *packet, size_t *len,
                                size_t *complen);
extern void *my_az_allocator(void *dummy, unsigned int items, unsigned int size);
extern void my_az_free(void *dummy, void *address);
extern int my_compress_buffer(uchar *dest, size_t *destLen,
                              const uchar *source, size_t sourceLen);
extern int packfrm(const uchar *, size_t, uchar **, size_t *);
extern int unpackfrm(uchar **, size_t *, const uchar *);

extern uint32 my_checksum(uint32, const void *, size_t);
extern uint32 my_crc32c(uint32, const void *, size_t);

extern const char *my_crc32c_implementation();

#ifdef DBUG_ASSERT_EXISTS
extern void my_debug_put_break_here(void);
#else
#define my_debug_put_break_here() do {} while(0)
#endif

extern void my_sleep(ulong m_seconds);
extern uint my_set_max_open_files(uint files);
void my_free_open_file_info(void);

extern my_bool my_gethwaddr(uchar *to);
extern int my_getncpus(void);

#define HRTIME_RESOLUTION               1000000ULL  /* microseconds */
typedef struct {ulonglong val;} my_hrtime_t;
void my_time_init(void);
extern my_hrtime_t my_hrtime(void);

#ifdef _WIN32
extern my_hrtime_t my_hrtime_coarse();
#else
#define my_hrtime_coarse() my_hrtime()
#endif

extern ulonglong my_interval_timer(void);
extern ulonglong my_getcputime(void);

#define microsecond_interval_timer()    (my_interval_timer()/1000)
#define hrtime_to_time(X)               ((time_t)((X).val/HRTIME_RESOLUTION))
#define hrtime_from_time(X)             ((ulonglong)((X)*HRTIME_RESOLUTION))
#define hrtime_to_double(X)             ((X).val/(double)HRTIME_RESOLUTION)
#define hrtime_sec_part(X)              ((ulong)((X).val % HRTIME_RESOLUTION))
#define my_time(X)                      hrtime_to_time(my_hrtime_coarse())

/**
  Make high resolution time from two parts.
*/

static inline my_hrtime_t make_hr_time(my_time_t time, ulong time_sec_part)
{
  my_hrtime_t res= {((ulonglong) time)*1000000 + time_sec_part};
  return res;
}


#if STACK_DIRECTION < 0
#define available_stack_size(CUR,END) (long) ((char*)(CUR) - (char*)(END))
#else
#define available_stack_size(CUR,END) (long) ((char*)(END) - (char*)(CUR))
#endif

#ifndef MAP_SYNC
#define MAP_SYNC 0x80000
#endif
#ifndef MAP_SHARED_VALIDATE
#define MAP_SHARED_VALIDATE 0x03
#endif

#ifdef HAVE_SYS_MMAN_H
#ifndef MAP_NOSYNC
#define MAP_NOSYNC      0
#endif
#ifndef MAP_NORESERVE
#define MAP_NORESERVE 0         /* For irix and AIX */
#endif

#ifdef HAVE_MMAP64
#define my_mmap(a,b,c,d,e,f)    mmap64(a,b,c,d,e,f)
#else
#define my_mmap(a,b,c,d,e,f)    mmap(a,b,c,d,e,f)
#endif
#define my_munmap(a,b)          munmap((a),(b))

#else
/* not a complete set of mmap() flags, but only those that necessary */
#define PROT_READ        1
#define PROT_WRITE       2
#define MAP_NORESERVE    0
#define MAP_SHARED       0x0001
#define MAP_PRIVATE      0x0002
#define MAP_NOSYNC       0x0800
#define MAP_FAILED       ((void *)-1)
#define MS_SYNC          0x0000

#define HAVE_MMAP
void *my_mmap(void *, size_t, int, int, int, my_off_t);
int my_munmap(void *, size_t);
#endif

#ifdef _WIN32
extern FILE* my_win_popen(const char*, const char*);
extern int my_win_pclose(FILE*);
#define my_popen(A,B) my_win_popen(A,B)
#define my_pclose(A) my_win_pclose(A)
#else
#define my_popen(A,B) popen(A,B)
#define my_pclose(A) pclose(A)
#endif

/* my_getpagesize */
#ifdef HAVE_GETPAGESIZE
#define my_getpagesize()        getpagesize()
#else
int my_getpagesize(void);
#endif

int my_msync(int, void *, size_t, int);

#define MY_UUID_SIZE 16
#define MY_UUID_BARE_STRING_LENGTH (8+4+4+4+12)
#define MY_UUID_SEPARATORS 4
#define MY_UUID_STRING_LENGTH (MY_UUID_BARE_STRING_LENGTH + MY_UUID_SEPARATORS)

void my_uuid_init(ulong seed1, ulong seed2);
void my_uuid(uchar *guid);
void my_uuid_end(void);

static inline void my_uuid2str(const uchar *guid, char *s, int with_separators)
{
  int i;
  int mask= with_separators ? ((1 << 3) | (1 << 5) | (1 << 7) | (1 << 9)) : 0;
  for (i=0; i < MY_UUID_SIZE; i++, mask >>= 1)
  {
    *s++= _dig_vec_lower[guid[i] >>4];
    *s++= _dig_vec_lower[guid[i] & 15];
    if (mask & 1)
      *s++= '-';
  }
}


const char *my_dlerror(const char *dlpath);

/* character sets */
extern void my_charset_loader_init_mysys(MY_CHARSET_LOADER *loader);
extern uint get_charset_number(const char *cs_name, uint cs_flags, myf flags);
extern uint get_collation_number(const char *name,myf flags);
extern const char *get_charset_name(uint cs_number);

extern CHARSET_INFO *get_charset(uint cs_number, myf flags);
extern CHARSET_INFO *get_charset_by_name(const char *cs_name, myf flags);
extern CHARSET_INFO *my_collation_get_by_name(MY_CHARSET_LOADER *loader,
                                              const char *name, myf flags);
extern CHARSET_INFO *get_charset_by_csname(const char *cs_name,
					   uint cs_flags, myf my_flags);
extern CHARSET_INFO *my_charset_get_by_name(MY_CHARSET_LOADER *loader,
                                            const char *name,
                                            uint cs_flags, myf my_flags);
extern my_bool resolve_charset(const char *cs_name,
                               CHARSET_INFO *default_cs,
                               CHARSET_INFO **cs,
                               myf flags);
extern my_bool resolve_collation(const char *cl_name,
                                 CHARSET_INFO *default_cl,
                                 CHARSET_INFO **cl,
                                 myf my_flags);
extern void free_charsets(void);
extern char *get_charsets_dir(char *buf);
static inline my_bool my_charset_same(CHARSET_INFO *cs1, CHARSET_INFO *cs2)
{
  return (cs1->cs_name.str == cs2->cs_name.str);
}
extern my_bool init_compiled_charsets(myf flags);
extern void add_compiled_collation(struct charset_info_st *cs);
extern void add_compiled_extra_collation(struct charset_info_st *cs);
extern size_t escape_string_for_mysql(CHARSET_INFO *charset_info,
                                      char *to, size_t to_length,
                                      const char *from, size_t length,
                                      my_bool *overflow);
extern char *my_get_tty_password(const char *opt_message);
#ifdef _WIN32
#define BACKSLASH_MBTAIL
/* File system character set */
extern CHARSET_INFO *fs_character_set(void);
extern int my_set_console_cp(const char *name);
#else
#define my_set_console_cp(A) do {} while (0)
#endif
extern const char *my_default_csname(void);
extern size_t escape_quotes_for_mysql(CHARSET_INFO *charset_info,
                                      char *to, size_t to_length,
                                      const char *from, size_t length,
                                      my_bool *overflow);

extern void thd_increment_bytes_sent(void *thd, size_t length);
extern void thd_increment_bytes_received(void *thd, size_t length);
extern void thd_increment_net_big_packet_count(void *thd, size_t length);

#include <mysql/psi/psi.h>

#ifdef HAVE_PSI_INTERFACE
extern MYSQL_PLUGIN_IMPORT struct PSI_bootstrap *PSI_hook;
extern void set_psi_server(PSI *psi);
void my_init_mysys_psi_keys(void);
#endif

struct st_mysql_file;
extern struct st_mysql_file *mysql_stdin;
C_MODE_END


#ifdef __cplusplus

class Charset_loader_mysys: public MY_CHARSET_LOADER
{
public:
  Charset_loader_mysys()
  {
    my_charset_loader_init_mysys(this);
  }

  /**
    Get a CHARSET_INFO by a character set name.

    @param name      Collation name
    @param cs_flags  e.g. MY_CS_PRIMARY, MY_CS_BINARY
    @param my_flags  mysys flags (MY_WME, MY_UTF8_IS_UTF8MB3)
    @return
    @retval          NULL on error (e.g. not found)
    @retval          A CHARSET_INFO pointter on success
  */
  CHARSET_INFO *get_charset(const char *cs_name, uint cs_flags, myf my_flags)
  {
    error[0]= '\0'; // Need to clear in case of the second call
    return my_charset_get_by_name(this, cs_name, cs_flags, my_flags);
  }

  /**
    Get a CHARSET_INFO by an exact collation by name.

    @param name      Collation name
    @param my_flags  e.g. the utf8 translation flag
    @return
    @retval          NULL on error (e.g. not found)
    @retval          A CHARSET_INFO pointter on success
  */
  CHARSET_INFO *get_exact_collation(const char *name, myf my_flags)
  {
    error[0]= '\0'; // Need to clear in case of the second call
    return my_collation_get_by_name(this, name, my_flags);
  }

  /**
    Get a CHARSET_INFO by a context collation by name.
    The returned pointer must be further resolved to a character set.

    @param name      Collation name
    @param utf8_flag The utf8 translation flag
    @return
    @retval          NULL on error (e.g. not found)
    @retval          A CHARSET_INFO pointter on success
  */
  CHARSET_INFO *get_context_collation(const char *name, myf my_flags)
  {
    return get_exact_collation_by_context_name(&my_charset_utf8mb4_general_ci,
                                               name, my_flags);
  }

  /**
    Get an exact CHARSET_INFO by a contextually typed collation name.

    @param name      Collation name
    @param utf8_flag The utf8 translation flag
    @return
    @retval          NULL on error (e.g. not found)
    @retval          A CHARSET_INFO pointer on success
  */
  CHARSET_INFO *get_exact_collation_by_context_name(CHARSET_INFO *cs,
                                                    const char *name,
                                                    myf my_flags)
  {
    char tmp[MY_CS_COLLATION_NAME_SIZE];
    my_snprintf(tmp, sizeof(tmp), "%s_%s", cs->cs_name.str, name);
    return get_exact_collation(tmp, my_flags);
  }

  /*
    Find a collation with binary comparison rules
  */
  CHARSET_INFO *get_bin_collation(CHARSET_INFO *cs, myf my_flags)
  {
    /*
      We don't need to handle old_mode=UTF8_IS_UTF8MB3 here,
      This method assumes that "cs" points to a real character set name.
      It can be either "utf8mb3" or "utf8mb4". It cannot be "utf8".
      No thd->get_utf8_flag() flag passed to get_charset_by_csname().
    */
    DBUG_ASSERT(cs->cs_name.length !=4 || memcmp(cs->cs_name.str, "utf8", 4));
    /*
      CREATE TABLE t1 (a CHAR(10) BINARY)
        CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
      Nothing to do, we have the binary collation already.
    */
    if (cs->state & MY_CS_BINSORT)
      return cs;

    // CREATE TABLE t1 (a CHAR(10) BINARY) CHARACTER SET utf8mb4;/
    error[0]= '\0'; // Need in case of the second execution
    return get_charset(cs->cs_name.str, MY_CS_BINSORT, my_flags);
  }

  /*
    Find the default collation in the given character set
  */
  CHARSET_INFO *get_default_collation(CHARSET_INFO *cs, myf my_flags)
  {
    // See comments in find_bin_collation_or_error()
    DBUG_ASSERT(cs->cs_name.length !=4 || memcmp(cs->cs_name.str, "utf8", 4));
    /*
      CREATE TABLE t1 (a CHAR(10) COLLATE DEFAULT) CHARACTER SET utf8mb4;
      Nothing to do, we have the default collation already.
    */
    if (cs->state & MY_CS_PRIMARY)
      return cs;
    /*
      CREATE TABLE t1 (a CHAR(10) COLLATE DEFAULT)
        CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;

      Don't need to handle old_mode=UTF8_IS_UTF8MB3 here.
      See comments in find_bin_collation_or_error.
    */
    cs= get_charset(cs->cs_name.str, MY_CS_PRIMARY, my_flags);
    DBUG_ASSERT(cs);
    return cs;
  }
};

#endif /*__cplusplus */


#endif /* _my_sys_h */