1 /*-------------------------------------------------------------------------
2  *
3  * miscadmin.h
4  *	  This file contains general postgres administration and initialization
5  *	  stuff that used to be spread out between the following files:
6  *		globals.h						global variables
7  *		pdir.h							directory path crud
8  *		pinit.h							postgres initialization
9  *		pmod.h							processing modes
10  *	  Over time, this has also become the preferred place for widely known
11  *	  resource-limitation stuff, such as work_mem and check_stack_depth().
12  *
13  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
14  * Portions Copyright (c) 1994, Regents of the University of California
15  *
16  * src/include/miscadmin.h
17  *
18  * NOTES
19  *	  some of the information in this file should be moved to other files.
20  *
21  *-------------------------------------------------------------------------
22  */
23 #ifndef MISCADMIN_H
24 #define MISCADMIN_H
25 
26 #include <signal.h>
27 
28 #include "datatype/timestamp.h" /* for TimestampTZ */
29 #include "pgtime.h"				/* for pg_time_t */
30 
31 
32 #define InvalidPid				(-1)
33 
34 
35 /*****************************************************************************
36  *	  System interrupt and critical section handling
37  *
38  * There are two types of interrupts that a running backend needs to accept
39  * without messing up its state: QueryCancel (SIGINT) and ProcDie (SIGTERM).
40  * In both cases, we need to be able to clean up the current transaction
41  * gracefully, so we can't respond to the interrupt instantaneously ---
42  * there's no guarantee that internal data structures would be self-consistent
43  * if the code is interrupted at an arbitrary instant.  Instead, the signal
44  * handlers set flags that are checked periodically during execution.
45  *
46  * The CHECK_FOR_INTERRUPTS() macro is called at strategically located spots
47  * where it is normally safe to accept a cancel or die interrupt.  In some
48  * cases, we invoke CHECK_FOR_INTERRUPTS() inside low-level subroutines that
49  * might sometimes be called in contexts that do *not* want to allow a cancel
50  * or die interrupt.  The HOLD_INTERRUPTS() and RESUME_INTERRUPTS() macros
51  * allow code to ensure that no cancel or die interrupt will be accepted,
52  * even if CHECK_FOR_INTERRUPTS() gets called in a subroutine.  The interrupt
53  * will be held off until CHECK_FOR_INTERRUPTS() is done outside any
54  * HOLD_INTERRUPTS() ... RESUME_INTERRUPTS() section.
55  *
56  * There is also a mechanism to prevent query cancel interrupts, while still
57  * allowing die interrupts: HOLD_CANCEL_INTERRUPTS() and
58  * RESUME_CANCEL_INTERRUPTS().
59  *
60  * Note that ProcessInterrupts() has also acquired a number of tasks that
61  * do not necessarily cause a query-cancel-or-die response.  Hence, it's
62  * possible that it will just clear InterruptPending and return.
63  *
64  * INTERRUPTS_PENDING_CONDITION() can be checked to see whether an
65  * interrupt needs to be serviced, without trying to do so immediately.
66  * Some callers are also interested in INTERRUPTS_CAN_BE_PROCESSED(),
67  * which tells whether ProcessInterrupts is sure to clear the interrupt.
68  *
69  * Special mechanisms are used to let an interrupt be accepted when we are
70  * waiting for a lock or when we are waiting for command input (but, of
71  * course, only if the interrupt holdoff counter is zero).  See the
72  * related code for details.
73  *
74  * A lost connection is handled similarly, although the loss of connection
75  * does not raise a signal, but is detected when we fail to write to the
76  * socket. If there was a signal for a broken connection, we could make use of
77  * it by setting ClientConnectionLost in the signal handler.
78  *
79  * A related, but conceptually distinct, mechanism is the "critical section"
80  * mechanism.  A critical section not only holds off cancel/die interrupts,
81  * but causes any ereport(ERROR) or ereport(FATAL) to become ereport(PANIC)
82  * --- that is, a system-wide reset is forced.  Needless to say, only really
83  * *critical* code should be marked as a critical section!	Currently, this
84  * mechanism is only used for XLOG-related code.
85  *
86  *****************************************************************************/
87 
88 /* in globals.c */
89 /* these are marked volatile because they are set by signal handlers: */
90 extern PGDLLIMPORT volatile sig_atomic_t InterruptPending;
91 extern PGDLLIMPORT volatile sig_atomic_t QueryCancelPending;
92 extern PGDLLIMPORT volatile sig_atomic_t ProcDiePending;
93 extern PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending;
94 extern PGDLLIMPORT volatile sig_atomic_t ConfigReloadPending;
95 
96 extern PGDLLIMPORT volatile sig_atomic_t ClientConnectionLost;
97 
98 /* these are marked volatile because they are examined by signal handlers: */
99 extern PGDLLIMPORT volatile uint32 InterruptHoldoffCount;
100 extern PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount;
101 extern PGDLLIMPORT volatile uint32 CritSectionCount;
102 
103 /* in tcop/postgres.c */
104 extern void ProcessInterrupts(void);
105 
106 /* Test whether an interrupt is pending */
107 #ifndef WIN32
108 #define INTERRUPTS_PENDING_CONDITION() \
109 	(unlikely(InterruptPending))
110 #else
111 #define INTERRUPTS_PENDING_CONDITION() \
112 	(unlikely(UNBLOCKED_SIGNAL_QUEUE()) ? pgwin32_dispatch_queued_signals() : 0, \
113 	 unlikely(InterruptPending))
114 #endif
115 
116 /* Service interrupt, if one is pending and it's safe to service it now */
117 #define CHECK_FOR_INTERRUPTS() \
118 do { \
119 	if (INTERRUPTS_PENDING_CONDITION()) \
120 		ProcessInterrupts(); \
121 } while(0)
122 
123 /* Is ProcessInterrupts() guaranteed to clear InterruptPending? */
124 #define INTERRUPTS_CAN_BE_PROCESSED() \
125 	(InterruptHoldoffCount == 0 && CritSectionCount == 0 && \
126 	 QueryCancelHoldoffCount == 0)
127 
128 #define HOLD_INTERRUPTS()  (InterruptHoldoffCount++)
129 
130 #define RESUME_INTERRUPTS() \
131 do { \
132 	Assert(InterruptHoldoffCount > 0); \
133 	InterruptHoldoffCount--; \
134 } while(0)
135 
136 #define HOLD_CANCEL_INTERRUPTS()  (QueryCancelHoldoffCount++)
137 
138 #define RESUME_CANCEL_INTERRUPTS() \
139 do { \
140 	Assert(QueryCancelHoldoffCount > 0); \
141 	QueryCancelHoldoffCount--; \
142 } while(0)
143 
144 #define START_CRIT_SECTION()  (CritSectionCount++)
145 
146 #define END_CRIT_SECTION() \
147 do { \
148 	Assert(CritSectionCount > 0); \
149 	CritSectionCount--; \
150 } while(0)
151 
152 
153 /*****************************************************************************
154  *	  globals.h --															 *
155  *****************************************************************************/
156 
157 /*
158  * from utils/init/globals.c
159  */
160 extern PGDLLIMPORT pid_t PostmasterPid;
161 extern PGDLLIMPORT bool IsPostmasterEnvironment;
162 extern PGDLLIMPORT bool IsUnderPostmaster;
163 extern PGDLLIMPORT bool IsBackgroundWorker;
164 extern PGDLLIMPORT bool IsBinaryUpgrade;
165 
166 extern PGDLLIMPORT bool ExitOnAnyError;
167 
168 extern PGDLLIMPORT char *DataDir;
169 extern PGDLLIMPORT int data_directory_mode;
170 
171 extern PGDLLIMPORT int NBuffers;
172 extern PGDLLIMPORT int MaxBackends;
173 extern PGDLLIMPORT int MaxConnections;
174 extern PGDLLIMPORT int max_worker_processes;
175 extern PGDLLIMPORT int max_parallel_workers;
176 
177 extern PGDLLIMPORT int MyProcPid;
178 extern PGDLLIMPORT pg_time_t MyStartTime;
179 extern PGDLLIMPORT TimestampTz MyStartTimestamp;
180 extern PGDLLIMPORT struct Port *MyProcPort;
181 extern PGDLLIMPORT struct Latch *MyLatch;
182 extern int32 MyCancelKey;
183 extern int	MyPMChildSlot;
184 
185 extern char OutputFileName[];
186 extern PGDLLIMPORT char my_exec_path[];
187 extern char pkglib_path[];
188 
189 #ifdef EXEC_BACKEND
190 extern char postgres_exec_path[];
191 #endif
192 
193 /*
194  * done in storage/backendid.h for now.
195  *
196  * extern BackendId    MyBackendId;
197  */
198 extern PGDLLIMPORT Oid MyDatabaseId;
199 
200 extern PGDLLIMPORT Oid MyDatabaseTableSpace;
201 
202 /*
203  * Date/Time Configuration
204  *
205  * DateStyle defines the output formatting choice for date/time types:
206  *	USE_POSTGRES_DATES specifies traditional Postgres format
207  *	USE_ISO_DATES specifies ISO-compliant format
208  *	USE_SQL_DATES specifies Oracle/Ingres-compliant format
209  *	USE_GERMAN_DATES specifies German-style dd.mm/yyyy
210  *
211  * DateOrder defines the field order to be assumed when reading an
212  * ambiguous date (anything not in YYYY-MM-DD format, with a four-digit
213  * year field first, is taken to be ambiguous):
214  *	DATEORDER_YMD specifies field order yy-mm-dd
215  *	DATEORDER_DMY specifies field order dd-mm-yy ("European" convention)
216  *	DATEORDER_MDY specifies field order mm-dd-yy ("US" convention)
217  *
218  * In the Postgres and SQL DateStyles, DateOrder also selects output field
219  * order: day comes before month in DMY style, else month comes before day.
220  *
221  * The user-visible "DateStyle" run-time parameter subsumes both of these.
222  */
223 
224 /* valid DateStyle values */
225 #define USE_POSTGRES_DATES		0
226 #define USE_ISO_DATES			1
227 #define USE_SQL_DATES			2
228 #define USE_GERMAN_DATES		3
229 #define USE_XSD_DATES			4
230 
231 /* valid DateOrder values */
232 #define DATEORDER_YMD			0
233 #define DATEORDER_DMY			1
234 #define DATEORDER_MDY			2
235 
236 extern PGDLLIMPORT int DateStyle;
237 extern PGDLLIMPORT int DateOrder;
238 
239 /*
240  * IntervalStyles
241  *	 INTSTYLE_POSTGRES			   Like Postgres < 8.4 when DateStyle = 'iso'
242  *	 INTSTYLE_POSTGRES_VERBOSE	   Like Postgres < 8.4 when DateStyle != 'iso'
243  *	 INTSTYLE_SQL_STANDARD		   SQL standard interval literals
244  *	 INTSTYLE_ISO_8601			   ISO-8601-basic formatted intervals
245  */
246 #define INTSTYLE_POSTGRES			0
247 #define INTSTYLE_POSTGRES_VERBOSE	1
248 #define INTSTYLE_SQL_STANDARD		2
249 #define INTSTYLE_ISO_8601			3
250 
251 extern PGDLLIMPORT int IntervalStyle;
252 
253 #define MAXTZLEN		10		/* max TZ name len, not counting tr. null */
254 
255 extern bool enableFsync;
256 extern PGDLLIMPORT bool allowSystemTableMods;
257 extern PGDLLIMPORT int work_mem;
258 extern PGDLLIMPORT int maintenance_work_mem;
259 extern PGDLLIMPORT int max_parallel_maintenance_workers;
260 
261 extern int	VacuumCostPageHit;
262 extern int	VacuumCostPageMiss;
263 extern int	VacuumCostPageDirty;
264 extern int	VacuumCostLimit;
265 extern double VacuumCostDelay;
266 
267 extern int	VacuumPageHit;
268 extern int	VacuumPageMiss;
269 extern int	VacuumPageDirty;
270 
271 extern int	VacuumCostBalance;
272 extern bool VacuumCostActive;
273 
274 extern double vacuum_cleanup_index_scale_factor;
275 
276 
277 /* in tcop/postgres.c */
278 
279 #if defined(__ia64__) || defined(__ia64)
280 typedef struct
281 {
282 	char	   *stack_base_ptr;
283 	char	   *register_stack_base_ptr;
284 } pg_stack_base_t;
285 #else
286 typedef char *pg_stack_base_t;
287 #endif
288 
289 extern pg_stack_base_t set_stack_base(void);
290 extern void restore_stack_base(pg_stack_base_t base);
291 extern void check_stack_depth(void);
292 extern bool stack_is_too_deep(void);
293 
294 extern void PostgresSigHupHandler(SIGNAL_ARGS);
295 
296 /* in tcop/utility.c */
297 extern void PreventCommandIfReadOnly(const char *cmdname);
298 extern void PreventCommandIfParallelMode(const char *cmdname);
299 extern void PreventCommandDuringRecovery(const char *cmdname);
300 
301 /* in utils/misc/guc.c */
302 extern int	trace_recovery_messages;
303 extern int	trace_recovery(int trace_level);
304 
305 /*****************************************************************************
306  *	  pdir.h --																 *
307  *			POSTGRES directory path definitions.                             *
308  *****************************************************************************/
309 
310 /* flags to be OR'd to form sec_context */
311 #define SECURITY_LOCAL_USERID_CHANGE	0x0001
312 #define SECURITY_RESTRICTED_OPERATION	0x0002
313 #define SECURITY_NOFORCE_RLS			0x0004
314 
315 extern char *DatabasePath;
316 
317 /* now in utils/init/miscinit.c */
318 extern void InitPostmasterChild(void);
319 extern void InitStandaloneProcess(const char *argv0);
320 
321 extern void SetDatabasePath(const char *path);
322 
323 extern char *GetUserNameFromId(Oid roleid, bool noerr);
324 extern Oid	GetUserId(void);
325 extern Oid	GetOuterUserId(void);
326 extern Oid	GetSessionUserId(void);
327 extern Oid	GetAuthenticatedUserId(void);
328 extern void GetUserIdAndSecContext(Oid *userid, int *sec_context);
329 extern void SetUserIdAndSecContext(Oid userid, int sec_context);
330 extern bool InLocalUserIdChange(void);
331 extern bool InSecurityRestrictedOperation(void);
332 extern bool InNoForceRLSOperation(void);
333 extern void GetUserIdAndContext(Oid *userid, bool *sec_def_context);
334 extern void SetUserIdAndContext(Oid userid, bool sec_def_context);
335 extern void InitializeSessionUserId(const char *rolename, Oid useroid);
336 extern void InitializeSessionUserIdStandalone(void);
337 extern void SetSessionAuthorization(Oid userid, bool is_superuser);
338 extern Oid	GetCurrentRoleId(void);
339 extern void SetCurrentRoleId(Oid roleid, bool is_superuser);
340 
341 extern void checkDataDir(void);
342 extern void SetDataDir(const char *dir);
343 extern void ChangeToDataDir(void);
344 
345 extern void SwitchToSharedLatch(void);
346 extern void SwitchBackToLocalLatch(void);
347 
348 /* in utils/misc/superuser.c */
349 extern bool superuser(void);	/* current user is superuser */
350 extern bool superuser_arg(Oid roleid);	/* given user is superuser */
351 
352 
353 /*****************************************************************************
354  *	  pmod.h --																 *
355  *			POSTGRES processing mode definitions.                            *
356  *****************************************************************************/
357 
358 /*
359  * Description:
360  *		There are three processing modes in POSTGRES.  They are
361  * BootstrapProcessing or "bootstrap," InitProcessing or
362  * "initialization," and NormalProcessing or "normal."
363  *
364  * The first two processing modes are used during special times. When the
365  * system state indicates bootstrap processing, transactions are all given
366  * transaction id "one" and are consequently guaranteed to commit. This mode
367  * is used during the initial generation of template databases.
368  *
369  * Initialization mode: used while starting a backend, until all normal
370  * initialization is complete.  Some code behaves differently when executed
371  * in this mode to enable system bootstrapping.
372  *
373  * If a POSTGRES backend process is in normal mode, then all code may be
374  * executed normally.
375  */
376 
377 typedef enum ProcessingMode
378 {
379 	BootstrapProcessing,		/* bootstrap creation of template database */
380 	InitProcessing,				/* initializing system */
381 	NormalProcessing			/* normal processing */
382 } ProcessingMode;
383 
384 extern ProcessingMode Mode;
385 
386 #define IsBootstrapProcessingMode() (Mode == BootstrapProcessing)
387 #define IsInitProcessingMode()		(Mode == InitProcessing)
388 #define IsNormalProcessingMode()	(Mode == NormalProcessing)
389 
390 #define GetProcessingMode() Mode
391 
392 #define SetProcessingMode(mode) \
393 	do { \
394 		AssertArg((mode) == BootstrapProcessing || \
395 				  (mode) == InitProcessing || \
396 				  (mode) == NormalProcessing); \
397 		Mode = (mode); \
398 	} while(0)
399 
400 
401 /*
402  * Auxiliary-process type identifiers.  These used to be in bootstrap.h
403  * but it seems saner to have them here, with the ProcessingMode stuff.
404  * The MyAuxProcType global is defined and set in bootstrap.c.
405  */
406 
407 typedef enum
408 {
409 	NotAnAuxProcess = -1,
410 	CheckerProcess = 0,
411 	BootstrapProcess,
412 	StartupProcess,
413 	BgWriterProcess,
414 	CheckpointerProcess,
415 	WalWriterProcess,
416 	WalReceiverProcess,
417 
418 	NUM_AUXPROCTYPES			/* Must be last! */
419 } AuxProcType;
420 
421 extern AuxProcType MyAuxProcType;
422 
423 #define AmBootstrapProcess()		(MyAuxProcType == BootstrapProcess)
424 #define AmStartupProcess()			(MyAuxProcType == StartupProcess)
425 #define AmBackgroundWriterProcess() (MyAuxProcType == BgWriterProcess)
426 #define AmCheckpointerProcess()		(MyAuxProcType == CheckpointerProcess)
427 #define AmWalWriterProcess()		(MyAuxProcType == WalWriterProcess)
428 #define AmWalReceiverProcess()		(MyAuxProcType == WalReceiverProcess)
429 
430 
431 /*****************************************************************************
432  *	  pinit.h --															 *
433  *			POSTGRES initialization and cleanup definitions.                 *
434  *****************************************************************************/
435 
436 /* in utils/init/postinit.c */
437 extern void pg_split_opts(char **argv, int *argcp, const char *optstr);
438 extern void InitializeMaxBackends(void);
439 extern void InitPostgres(const char *in_dbname, Oid dboid, const char *username,
440 						 Oid useroid, char *out_dbname, bool override_allow_connections);
441 extern void BaseInit(void);
442 
443 /* in utils/init/miscinit.c */
444 extern bool IgnoreSystemIndexes;
445 extern PGDLLIMPORT bool process_shared_preload_libraries_in_progress;
446 extern char *session_preload_libraries_string;
447 extern char *shared_preload_libraries_string;
448 extern char *local_preload_libraries_string;
449 
450 extern void CreateDataDirLockFile(bool amPostmaster);
451 extern void CreateSocketLockFile(const char *socketfile, bool amPostmaster,
452 								 const char *socketDir);
453 extern void TouchSocketLockFiles(void);
454 extern void AddToDataDirLockFile(int target_line, const char *str);
455 extern bool RecheckDataDirLockFile(void);
456 extern void ValidatePgVersion(const char *path);
457 extern void process_shared_preload_libraries(void);
458 extern void process_session_preload_libraries(void);
459 extern void pg_bindtextdomain(const char *domain);
460 extern bool has_rolreplication(Oid roleid);
461 
462 /* in access/transam/xlog.c */
463 extern bool BackupInProgress(void);
464 extern void CancelBackup(void);
465 
466 #endif							/* MISCADMIN_H */
467