]> granicus.if.org Git - postgresql/blob - src/backend/utils/cache/relmapper.c
pgindent run for 9.4
[postgresql] / src / backend / utils / cache / relmapper.c
1 /*-------------------------------------------------------------------------
2  *
3  * relmapper.c
4  *        Catalog-to-filenode mapping
5  *
6  * For most tables, the physical file underlying the table is specified by
7  * pg_class.relfilenode.  However, that obviously won't work for pg_class
8  * itself, nor for the other "nailed" catalogs for which we have to be able
9  * to set up working Relation entries without access to pg_class.  It also
10  * does not work for shared catalogs, since there is no practical way to
11  * update other databases' pg_class entries when relocating a shared catalog.
12  * Therefore, for these special catalogs (henceforth referred to as "mapped
13  * catalogs") we rely on a separately maintained file that shows the mapping
14  * from catalog OIDs to filenode numbers.  Each database has a map file for
15  * its local mapped catalogs, and there is a separate map file for shared
16  * catalogs.  Mapped catalogs have zero in their pg_class.relfilenode entries.
17  *
18  * Relocation of a normal table is committed (ie, the new physical file becomes
19  * authoritative) when the pg_class row update commits.  For mapped catalogs,
20  * the act of updating the map file is effectively commit of the relocation.
21  * We postpone the file update till just before commit of the transaction
22  * doing the rewrite, but there is necessarily a window between.  Therefore
23  * mapped catalogs can only be relocated by operations such as VACUUM FULL
24  * and CLUSTER, which make no transactionally-significant changes: it must be
25  * safe for the new file to replace the old, even if the transaction itself
26  * aborts.  An important factor here is that the indexes and toast table of
27  * a mapped catalog must also be mapped, so that the rewrites/relocations of
28  * all these files commit in a single map file update rather than being tied
29  * to transaction commit.
30  *
31  * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
32  * Portions Copyright (c) 1994, Regents of the University of California
33  *
34  *
35  * IDENTIFICATION
36  *        src/backend/utils/cache/relmapper.c
37  *
38  *-------------------------------------------------------------------------
39  */
40 #include "postgres.h"
41
42 #include <fcntl.h>
43 #include <sys/stat.h>
44 #include <unistd.h>
45
46 #include "access/xact.h"
47 #include "catalog/catalog.h"
48 #include "catalog/pg_tablespace.h"
49 #include "catalog/storage.h"
50 #include "miscadmin.h"
51 #include "storage/fd.h"
52 #include "storage/lwlock.h"
53 #include "utils/inval.h"
54 #include "utils/relmapper.h"
55
56
57 /*
58  * The map file is critical data: we have no automatic method for recovering
59  * from loss or corruption of it.  We use a CRC so that we can detect
60  * corruption.  To minimize the risk of failed updates, the map file should
61  * be kept to no more than one standard-size disk sector (ie 512 bytes),
62  * and we use overwrite-in-place rather than playing renaming games.
63  * The struct layout below is designed to occupy exactly 512 bytes, which
64  * might make filesystem updates a bit more efficient.
65  *
66  * Entries in the mappings[] array are in no particular order.  We could
67  * speed searching by insisting on OID order, but it really shouldn't be
68  * worth the trouble given the intended size of the mapping sets.
69  */
70 #define RELMAPPER_FILENAME              "pg_filenode.map"
71
72 #define RELMAPPER_FILEMAGIC             0x592717                /* version ID value */
73
74 #define MAX_MAPPINGS                    62              /* 62 * 8 + 16 = 512 */
75
76 typedef struct RelMapping
77 {
78         Oid                     mapoid;                 /* OID of a catalog */
79         Oid                     mapfilenode;    /* its filenode number */
80 } RelMapping;
81
82 typedef struct RelMapFile
83 {
84         int32           magic;                  /* always RELMAPPER_FILEMAGIC */
85         int32           num_mappings;   /* number of valid RelMapping entries */
86         RelMapping      mappings[MAX_MAPPINGS];
87         int32           crc;                    /* CRC of all above */
88         int32           pad;                    /* to make the struct size be 512 exactly */
89 } RelMapFile;
90
91 /*
92  * The currently known contents of the shared map file and our database's
93  * local map file are stored here.  These can be reloaded from disk
94  * immediately whenever we receive an update sinval message.
95  */
96 static RelMapFile shared_map;
97 static RelMapFile local_map;
98
99 /*
100  * We use the same RelMapFile data structure to track uncommitted local
101  * changes in the mappings (but note the magic and crc fields are not made
102  * valid in these variables).  Currently, map updates are not allowed within
103  * subtransactions, so one set of transaction-level changes is sufficient.
104  *
105  * The active_xxx variables contain updates that are valid in our transaction
106  * and should be honored by RelationMapOidToFilenode.  The pending_xxx
107  * variables contain updates we have been told about that aren't active yet;
108  * they will become active at the next CommandCounterIncrement.  This setup
109  * lets map updates act similarly to updates of pg_class rows, ie, they
110  * become visible only at the next CommandCounterIncrement boundary.
111  */
112 static RelMapFile active_shared_updates;
113 static RelMapFile active_local_updates;
114 static RelMapFile pending_shared_updates;
115 static RelMapFile pending_local_updates;
116
117
118 /* non-export function prototypes */
119 static void apply_map_update(RelMapFile *map, Oid relationId, Oid fileNode,
120                                  bool add_okay);
121 static void merge_map_updates(RelMapFile *map, const RelMapFile *updates,
122                                   bool add_okay);
123 static void load_relmap_file(bool shared);
124 static void write_relmap_file(bool shared, RelMapFile *newmap,
125                                   bool write_wal, bool send_sinval, bool preserve_files,
126                                   Oid dbid, Oid tsid, const char *dbpath);
127 static void perform_relmap_update(bool shared, const RelMapFile *updates);
128
129
130 /*
131  * RelationMapOidToFilenode
132  *
133  * The raison d' etre ... given a relation OID, look up its filenode.
134  *
135  * Although shared and local relation OIDs should never overlap, the caller
136  * always knows which we need --- so pass that information to avoid useless
137  * searching.
138  *
139  * Returns InvalidOid if the OID is not known (which should never happen,
140  * but the caller is in a better position to report a meaningful error).
141  */
142 Oid
143 RelationMapOidToFilenode(Oid relationId, bool shared)
144 {
145         const RelMapFile *map;
146         int32           i;
147
148         /* If there are active updates, believe those over the main maps */
149         if (shared)
150         {
151                 map = &active_shared_updates;
152                 for (i = 0; i < map->num_mappings; i++)
153                 {
154                         if (relationId == map->mappings[i].mapoid)
155                                 return map->mappings[i].mapfilenode;
156                 }
157                 map = &shared_map;
158                 for (i = 0; i < map->num_mappings; i++)
159                 {
160                         if (relationId == map->mappings[i].mapoid)
161                                 return map->mappings[i].mapfilenode;
162                 }
163         }
164         else
165         {
166                 map = &active_local_updates;
167                 for (i = 0; i < map->num_mappings; i++)
168                 {
169                         if (relationId == map->mappings[i].mapoid)
170                                 return map->mappings[i].mapfilenode;
171                 }
172                 map = &local_map;
173                 for (i = 0; i < map->num_mappings; i++)
174                 {
175                         if (relationId == map->mappings[i].mapoid)
176                                 return map->mappings[i].mapfilenode;
177                 }
178         }
179
180         return InvalidOid;
181 }
182
183 /*
184  * RelationMapFilenodeToOid
185  *
186  * Do the reverse of the normal direction of mapping done in
187  * RelationMapOidToFilenode.
188  *
189  * This is not supposed to be used during normal running but rather for
190  * information purposes when looking at the filesystem or xlog.
191  *
192  * Returns InvalidOid if the OID is not known; this can easily happen if the
193  * relfilenode doesn't pertain to a mapped relation.
194  */
195 Oid
196 RelationMapFilenodeToOid(Oid filenode, bool shared)
197 {
198         const RelMapFile *map;
199         int32           i;
200
201         /* If there are active updates, believe those over the main maps */
202         if (shared)
203         {
204                 map = &active_shared_updates;
205                 for (i = 0; i < map->num_mappings; i++)
206                 {
207                         if (filenode == map->mappings[i].mapfilenode)
208                                 return map->mappings[i].mapoid;
209                 }
210                 map = &shared_map;
211                 for (i = 0; i < map->num_mappings; i++)
212                 {
213                         if (filenode == map->mappings[i].mapfilenode)
214                                 return map->mappings[i].mapoid;
215                 }
216         }
217         else
218         {
219                 map = &active_local_updates;
220                 for (i = 0; i < map->num_mappings; i++)
221                 {
222                         if (filenode == map->mappings[i].mapfilenode)
223                                 return map->mappings[i].mapoid;
224                 }
225                 map = &local_map;
226                 for (i = 0; i < map->num_mappings; i++)
227                 {
228                         if (filenode == map->mappings[i].mapfilenode)
229                                 return map->mappings[i].mapoid;
230                 }
231         }
232
233         return InvalidOid;
234 }
235
236 /*
237  * RelationMapUpdateMap
238  *
239  * Install a new relfilenode mapping for the specified relation.
240  *
241  * If immediate is true (or we're bootstrapping), the mapping is activated
242  * immediately.  Otherwise it is made pending until CommandCounterIncrement.
243  */
244 void
245 RelationMapUpdateMap(Oid relationId, Oid fileNode, bool shared,
246                                          bool immediate)
247 {
248         RelMapFile *map;
249
250         if (IsBootstrapProcessingMode())
251         {
252                 /*
253                  * In bootstrap mode, the mapping gets installed in permanent map.
254                  */
255                 if (shared)
256                         map = &shared_map;
257                 else
258                         map = &local_map;
259         }
260         else
261         {
262                 /*
263                  * We don't currently support map changes within subtransactions. This
264                  * could be done with more bookkeeping infrastructure, but it doesn't
265                  * presently seem worth it.
266                  */
267                 if (GetCurrentTransactionNestLevel() > 1)
268                         elog(ERROR, "cannot change relation mapping within subtransaction");
269
270                 if (immediate)
271                 {
272                         /* Make it active, but only locally */
273                         if (shared)
274                                 map = &active_shared_updates;
275                         else
276                                 map = &active_local_updates;
277                 }
278                 else
279                 {
280                         /* Make it pending */
281                         if (shared)
282                                 map = &pending_shared_updates;
283                         else
284                                 map = &pending_local_updates;
285                 }
286         }
287         apply_map_update(map, relationId, fileNode, true);
288 }
289
290 /*
291  * apply_map_update
292  *
293  * Insert a new mapping into the given map variable, replacing any existing
294  * mapping for the same relation.
295  *
296  * In some cases the caller knows there must be an existing mapping; pass
297  * add_okay = false to draw an error if not.
298  */
299 static void
300 apply_map_update(RelMapFile *map, Oid relationId, Oid fileNode, bool add_okay)
301 {
302         int32           i;
303
304         /* Replace any existing mapping */
305         for (i = 0; i < map->num_mappings; i++)
306         {
307                 if (relationId == map->mappings[i].mapoid)
308                 {
309                         map->mappings[i].mapfilenode = fileNode;
310                         return;
311                 }
312         }
313
314         /* Nope, need to add a new mapping */
315         if (!add_okay)
316                 elog(ERROR, "attempt to apply a mapping to unmapped relation %u",
317                          relationId);
318         if (map->num_mappings >= MAX_MAPPINGS)
319                 elog(ERROR, "ran out of space in relation map");
320         map->mappings[map->num_mappings].mapoid = relationId;
321         map->mappings[map->num_mappings].mapfilenode = fileNode;
322         map->num_mappings++;
323 }
324
325 /*
326  * merge_map_updates
327  *
328  * Merge all the updates in the given pending-update map into the target map.
329  * This is just a bulk form of apply_map_update.
330  */
331 static void
332 merge_map_updates(RelMapFile *map, const RelMapFile *updates, bool add_okay)
333 {
334         int32           i;
335
336         for (i = 0; i < updates->num_mappings; i++)
337         {
338                 apply_map_update(map,
339                                                  updates->mappings[i].mapoid,
340                                                  updates->mappings[i].mapfilenode,
341                                                  add_okay);
342         }
343 }
344
345 /*
346  * RelationMapRemoveMapping
347  *
348  * Remove a relation's entry in the map.  This is only allowed for "active"
349  * (but not committed) local mappings.  We need it so we can back out the
350  * entry for the transient target file when doing VACUUM FULL/CLUSTER on
351  * a mapped relation.
352  */
353 void
354 RelationMapRemoveMapping(Oid relationId)
355 {
356         RelMapFile *map = &active_local_updates;
357         int32           i;
358
359         for (i = 0; i < map->num_mappings; i++)
360         {
361                 if (relationId == map->mappings[i].mapoid)
362                 {
363                         /* Found it, collapse it out */
364                         map->mappings[i] = map->mappings[map->num_mappings - 1];
365                         map->num_mappings--;
366                         return;
367                 }
368         }
369         elog(ERROR, "could not find temporary mapping for relation %u",
370                  relationId);
371 }
372
373 /*
374  * RelationMapInvalidate
375  *
376  * This routine is invoked for SI cache flush messages.  We must re-read
377  * the indicated map file.  However, we might receive a SI message in a
378  * process that hasn't yet, and might never, load the mapping files;
379  * for example the autovacuum launcher, which *must not* try to read
380  * a local map since it is attached to no particular database.
381  * So, re-read only if the map is valid now.
382  */
383 void
384 RelationMapInvalidate(bool shared)
385 {
386         if (shared)
387         {
388                 if (shared_map.magic == RELMAPPER_FILEMAGIC)
389                         load_relmap_file(true);
390         }
391         else
392         {
393                 if (local_map.magic == RELMAPPER_FILEMAGIC)
394                         load_relmap_file(false);
395         }
396 }
397
398 /*
399  * RelationMapInvalidateAll
400  *
401  * Reload all map files.  This is used to recover from SI message buffer
402  * overflow: we can't be sure if we missed an inval message.
403  * Again, reload only currently-valid maps.
404  */
405 void
406 RelationMapInvalidateAll(void)
407 {
408         if (shared_map.magic == RELMAPPER_FILEMAGIC)
409                 load_relmap_file(true);
410         if (local_map.magic == RELMAPPER_FILEMAGIC)
411                 load_relmap_file(false);
412 }
413
414 /*
415  * AtCCI_RelationMap
416  *
417  * Activate any "pending" relation map updates at CommandCounterIncrement time.
418  */
419 void
420 AtCCI_RelationMap(void)
421 {
422         if (pending_shared_updates.num_mappings != 0)
423         {
424                 merge_map_updates(&active_shared_updates,
425                                                   &pending_shared_updates,
426                                                   true);
427                 pending_shared_updates.num_mappings = 0;
428         }
429         if (pending_local_updates.num_mappings != 0)
430         {
431                 merge_map_updates(&active_local_updates,
432                                                   &pending_local_updates,
433                                                   true);
434                 pending_local_updates.num_mappings = 0;
435         }
436 }
437
438 /*
439  * AtEOXact_RelationMap
440  *
441  * Handle relation mapping at main-transaction commit or abort.
442  *
443  * During commit, this must be called as late as possible before the actual
444  * transaction commit, so as to minimize the window where the transaction
445  * could still roll back after committing map changes.  Although nothing
446  * critically bad happens in such a case, we still would prefer that it
447  * not happen, since we'd possibly be losing useful updates to the relations'
448  * pg_class row(s).
449  *
450  * During abort, we just have to throw away any pending map changes.
451  * Normal post-abort cleanup will take care of fixing relcache entries.
452  */
453 void
454 AtEOXact_RelationMap(bool isCommit)
455 {
456         if (isCommit)
457         {
458                 /*
459                  * We should not get here with any "pending" updates.  (We could
460                  * logically choose to treat such as committed, but in the current
461                  * code this should never happen.)
462                  */
463                 Assert(pending_shared_updates.num_mappings == 0);
464                 Assert(pending_local_updates.num_mappings == 0);
465
466                 /*
467                  * Write any active updates to the actual map files, then reset them.
468                  */
469                 if (active_shared_updates.num_mappings != 0)
470                 {
471                         perform_relmap_update(true, &active_shared_updates);
472                         active_shared_updates.num_mappings = 0;
473                 }
474                 if (active_local_updates.num_mappings != 0)
475                 {
476                         perform_relmap_update(false, &active_local_updates);
477                         active_local_updates.num_mappings = 0;
478                 }
479         }
480         else
481         {
482                 /* Abort --- drop all local and pending updates */
483                 active_shared_updates.num_mappings = 0;
484                 active_local_updates.num_mappings = 0;
485                 pending_shared_updates.num_mappings = 0;
486                 pending_local_updates.num_mappings = 0;
487         }
488 }
489
490 /*
491  * AtPrepare_RelationMap
492  *
493  * Handle relation mapping at PREPARE.
494  *
495  * Currently, we don't support preparing any transaction that changes the map.
496  */
497 void
498 AtPrepare_RelationMap(void)
499 {
500         if (active_shared_updates.num_mappings != 0 ||
501                 active_local_updates.num_mappings != 0 ||
502                 pending_shared_updates.num_mappings != 0 ||
503                 pending_local_updates.num_mappings != 0)
504                 ereport(ERROR,
505                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
506                                  errmsg("cannot PREPARE a transaction that modified relation mapping")));
507 }
508
509 /*
510  * CheckPointRelationMap
511  *
512  * This is called during a checkpoint.  It must ensure that any relation map
513  * updates that were WAL-logged before the start of the checkpoint are
514  * securely flushed to disk and will not need to be replayed later.  This
515  * seems unlikely to be a performance-critical issue, so we use a simple
516  * method: we just take and release the RelationMappingLock.  This ensures
517  * that any already-logged map update is complete, because write_relmap_file
518  * will fsync the map file before the lock is released.
519  */
520 void
521 CheckPointRelationMap(void)
522 {
523         LWLockAcquire(RelationMappingLock, LW_SHARED);
524         LWLockRelease(RelationMappingLock);
525 }
526
527 /*
528  * RelationMapFinishBootstrap
529  *
530  * Write out the initial relation mapping files at the completion of
531  * bootstrap.  All the mapped files should have been made known to us
532  * via RelationMapUpdateMap calls.
533  */
534 void
535 RelationMapFinishBootstrap(void)
536 {
537         Assert(IsBootstrapProcessingMode());
538
539         /* Shouldn't be anything "pending" ... */
540         Assert(active_shared_updates.num_mappings == 0);
541         Assert(active_local_updates.num_mappings == 0);
542         Assert(pending_shared_updates.num_mappings == 0);
543         Assert(pending_local_updates.num_mappings == 0);
544
545         /* Write the files; no WAL or sinval needed */
546         write_relmap_file(true, &shared_map, false, false, false,
547                                           InvalidOid, GLOBALTABLESPACE_OID, NULL);
548         write_relmap_file(false, &local_map, false, false, false,
549                                           MyDatabaseId, MyDatabaseTableSpace, DatabasePath);
550 }
551
552 /*
553  * RelationMapInitialize
554  *
555  * This initializes the mapper module at process startup.  We can't access the
556  * database yet, so just make sure the maps are empty.
557  */
558 void
559 RelationMapInitialize(void)
560 {
561         /* The static variables should initialize to zeroes, but let's be sure */
562         shared_map.magic = 0;           /* mark it not loaded */
563         local_map.magic = 0;
564         shared_map.num_mappings = 0;
565         local_map.num_mappings = 0;
566         active_shared_updates.num_mappings = 0;
567         active_local_updates.num_mappings = 0;
568         pending_shared_updates.num_mappings = 0;
569         pending_local_updates.num_mappings = 0;
570 }
571
572 /*
573  * RelationMapInitializePhase2
574  *
575  * This is called to prepare for access to pg_database during startup.
576  * We should be able to read the shared map file now.
577  */
578 void
579 RelationMapInitializePhase2(void)
580 {
581         /*
582          * In bootstrap mode, the map file isn't there yet, so do nothing.
583          */
584         if (IsBootstrapProcessingMode())
585                 return;
586
587         /*
588          * Load the shared map file, die on error.
589          */
590         load_relmap_file(true);
591 }
592
593 /*
594  * RelationMapInitializePhase3
595  *
596  * This is called as soon as we have determined MyDatabaseId and set up
597  * DatabasePath.  At this point we should be able to read the local map file.
598  */
599 void
600 RelationMapInitializePhase3(void)
601 {
602         /*
603          * In bootstrap mode, the map file isn't there yet, so do nothing.
604          */
605         if (IsBootstrapProcessingMode())
606                 return;
607
608         /*
609          * Load the local map file, die on error.
610          */
611         load_relmap_file(false);
612 }
613
614 /*
615  * load_relmap_file -- load data from the shared or local map file
616  *
617  * Because the map file is essential for access to core system catalogs,
618  * failure to read it is a fatal error.
619  *
620  * Note that the local case requires DatabasePath to be set up.
621  */
622 static void
623 load_relmap_file(bool shared)
624 {
625         RelMapFile *map;
626         char            mapfilename[MAXPGPATH];
627         pg_crc32        crc;
628         int                     fd;
629
630         if (shared)
631         {
632                 snprintf(mapfilename, sizeof(mapfilename), "global/%s",
633                                  RELMAPPER_FILENAME);
634                 map = &shared_map;
635         }
636         else
637         {
638                 snprintf(mapfilename, sizeof(mapfilename), "%s/%s",
639                                  DatabasePath, RELMAPPER_FILENAME);
640                 map = &local_map;
641         }
642
643         /* Read data ... */
644         fd = OpenTransientFile(mapfilename,
645                                                    O_RDONLY | PG_BINARY, S_IRUSR | S_IWUSR);
646         if (fd < 0)
647                 ereport(FATAL,
648                                 (errcode_for_file_access(),
649                                  errmsg("could not open relation mapping file \"%s\": %m",
650                                                 mapfilename)));
651
652         /*
653          * Note: we could take RelationMappingLock in shared mode here, but it
654          * seems unnecessary since our read() should be atomic against any
655          * concurrent updater's write().  If the file is updated shortly after we
656          * look, the sinval signaling mechanism will make us re-read it before we
657          * are able to access any relation that's affected by the change.
658          */
659         if (read(fd, map, sizeof(RelMapFile)) != sizeof(RelMapFile))
660                 ereport(FATAL,
661                                 (errcode_for_file_access(),
662                                  errmsg("could not read relation mapping file \"%s\": %m",
663                                                 mapfilename)));
664
665         CloseTransientFile(fd);
666
667         /* check for correct magic number, etc */
668         if (map->magic != RELMAPPER_FILEMAGIC ||
669                 map->num_mappings < 0 ||
670                 map->num_mappings > MAX_MAPPINGS)
671                 ereport(FATAL,
672                                 (errmsg("relation mapping file \"%s\" contains invalid data",
673                                                 mapfilename)));
674
675         /* verify the CRC */
676         INIT_CRC32(crc);
677         COMP_CRC32(crc, (char *) map, offsetof(RelMapFile, crc));
678         FIN_CRC32(crc);
679
680         if (!EQ_CRC32(crc, map->crc))
681                 ereport(FATAL,
682                   (errmsg("relation mapping file \"%s\" contains incorrect checksum",
683                                   mapfilename)));
684 }
685
686 /*
687  * Write out a new shared or local map file with the given contents.
688  *
689  * The magic number and CRC are automatically updated in *newmap.  On
690  * success, we copy the data to the appropriate permanent static variable.
691  *
692  * If write_wal is TRUE then an appropriate WAL message is emitted.
693  * (It will be false for bootstrap and WAL replay cases.)
694  *
695  * If send_sinval is TRUE then a SI invalidation message is sent.
696  * (This should be true except in bootstrap case.)
697  *
698  * If preserve_files is TRUE then the storage manager is warned not to
699  * delete the files listed in the map.
700  *
701  * Because this may be called during WAL replay when MyDatabaseId,
702  * DatabasePath, etc aren't valid, we require the caller to pass in suitable
703  * values.  The caller is also responsible for being sure no concurrent
704  * map update could be happening.
705  */
706 static void
707 write_relmap_file(bool shared, RelMapFile *newmap,
708                                   bool write_wal, bool send_sinval, bool preserve_files,
709                                   Oid dbid, Oid tsid, const char *dbpath)
710 {
711         int                     fd;
712         RelMapFile *realmap;
713         char            mapfilename[MAXPGPATH];
714
715         /*
716          * Fill in the overhead fields and update CRC.
717          */
718         newmap->magic = RELMAPPER_FILEMAGIC;
719         if (newmap->num_mappings < 0 || newmap->num_mappings > MAX_MAPPINGS)
720                 elog(ERROR, "attempt to write bogus relation mapping");
721
722         INIT_CRC32(newmap->crc);
723         COMP_CRC32(newmap->crc, (char *) newmap, offsetof(RelMapFile, crc));
724         FIN_CRC32(newmap->crc);
725
726         /*
727          * Open the target file.  We prefer to do this before entering the
728          * critical section, so that an open() failure need not force PANIC.
729          */
730         if (shared)
731         {
732                 snprintf(mapfilename, sizeof(mapfilename), "global/%s",
733                                  RELMAPPER_FILENAME);
734                 realmap = &shared_map;
735         }
736         else
737         {
738                 snprintf(mapfilename, sizeof(mapfilename), "%s/%s",
739                                  dbpath, RELMAPPER_FILENAME);
740                 realmap = &local_map;
741         }
742
743         fd = OpenTransientFile(mapfilename,
744                                                    O_WRONLY | O_CREAT | PG_BINARY,
745                                                    S_IRUSR | S_IWUSR);
746         if (fd < 0)
747                 ereport(ERROR,
748                                 (errcode_for_file_access(),
749                                  errmsg("could not open relation mapping file \"%s\": %m",
750                                                 mapfilename)));
751
752         if (write_wal)
753         {
754                 xl_relmap_update xlrec;
755                 XLogRecData rdata[2];
756                 XLogRecPtr      lsn;
757
758                 /* now errors are fatal ... */
759                 START_CRIT_SECTION();
760
761                 xlrec.dbid = dbid;
762                 xlrec.tsid = tsid;
763                 xlrec.nbytes = sizeof(RelMapFile);
764
765                 rdata[0].data = (char *) (&xlrec);
766                 rdata[0].len = MinSizeOfRelmapUpdate;
767                 rdata[0].buffer = InvalidBuffer;
768                 rdata[0].next = &(rdata[1]);
769                 rdata[1].data = (char *) newmap;
770                 rdata[1].len = sizeof(RelMapFile);
771                 rdata[1].buffer = InvalidBuffer;
772                 rdata[1].next = NULL;
773
774                 lsn = XLogInsert(RM_RELMAP_ID, XLOG_RELMAP_UPDATE, rdata);
775
776                 /* As always, WAL must hit the disk before the data update does */
777                 XLogFlush(lsn);
778         }
779
780         errno = 0;
781         if (write(fd, newmap, sizeof(RelMapFile)) != sizeof(RelMapFile))
782         {
783                 /* if write didn't set errno, assume problem is no disk space */
784                 if (errno == 0)
785                         errno = ENOSPC;
786                 ereport(ERROR,
787                                 (errcode_for_file_access(),
788                                  errmsg("could not write to relation mapping file \"%s\": %m",
789                                                 mapfilename)));
790         }
791
792         /*
793          * We choose to fsync the data to disk before considering the task done.
794          * It would be possible to relax this if it turns out to be a performance
795          * issue, but it would complicate checkpointing --- see notes for
796          * CheckPointRelationMap.
797          */
798         if (pg_fsync(fd) != 0)
799                 ereport(ERROR,
800                                 (errcode_for_file_access(),
801                                  errmsg("could not fsync relation mapping file \"%s\": %m",
802                                                 mapfilename)));
803
804         if (CloseTransientFile(fd))
805                 ereport(ERROR,
806                                 (errcode_for_file_access(),
807                                  errmsg("could not close relation mapping file \"%s\": %m",
808                                                 mapfilename)));
809
810         /*
811          * Now that the file is safely on disk, send sinval message to let other
812          * backends know to re-read it.  We must do this inside the critical
813          * section: if for some reason we fail to send the message, we have to
814          * force a database-wide PANIC.  Otherwise other backends might continue
815          * execution with stale mapping information, which would be catastrophic
816          * as soon as others began to use the now-committed data.
817          */
818         if (send_sinval)
819                 CacheInvalidateRelmap(dbid);
820
821         /*
822          * Make sure that the files listed in the map are not deleted if the outer
823          * transaction aborts.  This had better be within the critical section
824          * too: it's not likely to fail, but if it did, we'd arrive at transaction
825          * abort with the files still vulnerable.  PANICing will leave things in a
826          * good state on-disk.
827          *
828          * Note: we're cheating a little bit here by assuming that mapped files
829          * are either in pg_global or the database's default tablespace.
830          */
831         if (preserve_files)
832         {
833                 int32           i;
834
835                 for (i = 0; i < newmap->num_mappings; i++)
836                 {
837                         RelFileNode rnode;
838
839                         rnode.spcNode = tsid;
840                         rnode.dbNode = dbid;
841                         rnode.relNode = newmap->mappings[i].mapfilenode;
842                         RelationPreserveStorage(rnode, false);
843                 }
844         }
845
846         /* Success, update permanent copy */
847         memcpy(realmap, newmap, sizeof(RelMapFile));
848
849         /* Critical section done */
850         if (write_wal)
851                 END_CRIT_SECTION();
852 }
853
854 /*
855  * Merge the specified updates into the appropriate "real" map,
856  * and write out the changes.  This function must be used for committing
857  * updates during normal multiuser operation.
858  */
859 static void
860 perform_relmap_update(bool shared, const RelMapFile *updates)
861 {
862         RelMapFile      newmap;
863
864         /*
865          * Anyone updating a relation's mapping info should take exclusive lock on
866          * that rel and hold it until commit.  This ensures that there will not be
867          * concurrent updates on the same mapping value; but there could easily be
868          * concurrent updates on different values in the same file. We cover that
869          * by acquiring the RelationMappingLock, re-reading the target file to
870          * ensure it's up to date, applying the updates, and writing the data
871          * before releasing RelationMappingLock.
872          *
873          * There is only one RelationMappingLock.  In principle we could try to
874          * have one per mapping file, but it seems unlikely to be worth the
875          * trouble.
876          */
877         LWLockAcquire(RelationMappingLock, LW_EXCLUSIVE);
878
879         /* Be certain we see any other updates just made */
880         load_relmap_file(shared);
881
882         /* Prepare updated data in a local variable */
883         if (shared)
884                 memcpy(&newmap, &shared_map, sizeof(RelMapFile));
885         else
886                 memcpy(&newmap, &local_map, sizeof(RelMapFile));
887
888         /*
889          * Apply the updates to newmap.  No new mappings should appear, unless
890          * somebody is adding indexes to system catalogs.
891          */
892         merge_map_updates(&newmap, updates, allowSystemTableMods);
893
894         /* Write out the updated map and do other necessary tasks */
895         write_relmap_file(shared, &newmap, true, true, true,
896                                           (shared ? InvalidOid : MyDatabaseId),
897                                           (shared ? GLOBALTABLESPACE_OID : MyDatabaseTableSpace),
898                                           DatabasePath);
899
900         /* Now we can release the lock */
901         LWLockRelease(RelationMappingLock);
902 }
903
904 /*
905  * RELMAP resource manager's routines
906  */
907 void
908 relmap_redo(XLogRecPtr lsn, XLogRecord *record)
909 {
910         uint8           info = record->xl_info & ~XLR_INFO_MASK;
911
912         /* Backup blocks are not used in relmap records */
913         Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));
914
915         if (info == XLOG_RELMAP_UPDATE)
916         {
917                 xl_relmap_update *xlrec = (xl_relmap_update *) XLogRecGetData(record);
918                 RelMapFile      newmap;
919                 char       *dbpath;
920
921                 if (xlrec->nbytes != sizeof(RelMapFile))
922                         elog(PANIC, "relmap_redo: wrong size %u in relmap update record",
923                                  xlrec->nbytes);
924                 memcpy(&newmap, xlrec->data, sizeof(newmap));
925
926                 /* We need to construct the pathname for this database */
927                 dbpath = GetDatabasePath(xlrec->dbid, xlrec->tsid);
928
929                 /*
930                  * Write out the new map and send sinval, but of course don't write a
931                  * new WAL entry.  There's no surrounding transaction to tell to
932                  * preserve files, either.
933                  *
934                  * There shouldn't be anyone else updating relmaps during WAL replay,
935                  * so we don't bother to take the RelationMappingLock.  We would need
936                  * to do so if load_relmap_file needed to interlock against writers.
937                  */
938                 write_relmap_file((xlrec->dbid == InvalidOid), &newmap,
939                                                   false, true, false,
940                                                   xlrec->dbid, xlrec->tsid, dbpath);
941
942                 pfree(dbpath);
943         }
944         else
945                 elog(PANIC, "relmap_redo: unknown op code %u", info);
946 }