1 /*-------------------------------------------------------------------------
4 * Implement shared memory using win32 facilities
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
9 * $PostgreSQL: pgsql/src/backend/port/win32_shmem.c,v 1.9 2009/05/05 09:48:51 mha Exp $
11 *-------------------------------------------------------------------------
15 #include "miscadmin.h"
16 #include "storage/ipc.h"
17 #include "storage/pg_shmem.h"
19 unsigned long UsedShmemSegID = 0;
20 void *UsedShmemSegAddr = NULL;
22 static void pgwin32_SharedMemoryDelete(int status, Datum shmId);
25 * Generate shared memory segment name. Expand the data directory, to generate
26 * an identifier unique for this data directory. Then replace all backslashes
27 * with forward slashes, since backslashes aren't permitted in global object names.
29 * Store the shared memory segment in the Global\ namespace (requires NT2 TSE or
30 * 2000, but that's all we support for other reasons as well), to make sure you can't
31 * open two postmasters in different sessions against the same data directory.
33 * XXX: What happens with junctions? It's only someone breaking things on purpose,
34 * and this is still better than before, but we might want to do something about
35 * that sometime in the future.
38 GetSharedMemName(void)
45 bufsize = GetFullPathName(DataDir, 0, NULL, NULL);
47 elog(FATAL, "could not get size for full pathname of datadir %s: %lu",
48 DataDir, GetLastError());
50 retptr = malloc(bufsize + 18); /* 18 for Global\PostgreSQL: */
52 elog(FATAL, "could not allocate memory for shared memory name");
54 strcpy(retptr, "Global\\PostgreSQL:");
55 r = GetFullPathName(DataDir, bufsize, retptr + 18, NULL);
56 if (r == 0 || r > bufsize)
57 elog(FATAL, "could not generate full pathname for datadir %s: %lu",
58 DataDir, GetLastError());
61 * XXX: Intentionally overwriting the Global\ part here. This was not the
62 * original approach, but putting it in the actual Global\ namespace
63 * causes permission errors in a lot of cases, so we leave it in
64 * the default namespace for now.
66 for (cp = retptr; *cp; cp++)
75 * PGSharedMemoryIsInUse
77 * Is a previously-existing shmem segment still existing and in use?
79 * The point of this exercise is to detect the case where a prior postmaster
80 * crashed, but it left child backends that are still running. Therefore
81 * we only care about shmem segments that are associated with the intended
82 * DataDir. This is an important consideration since accidental matches of
83 * shmem segment IDs are reasonably common.
87 PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2)
92 szShareMem = GetSharedMemName();
94 hmap = OpenFileMapping(FILE_MAP_READ, FALSE, szShareMem);
107 * PGSharedMemoryCreate
109 * Create a shared memory segment of the given size and initialize its
112 * makePrivate means to always create a new segment, rather than attach to
113 * or recycle any existing segment. On win32, we always create a new segment,
114 * since there is no need for recycling (segments go away automatically
115 * when the last backend exits)
119 PGSharedMemoryCreate(Size size, bool makePrivate, int port)
128 /* Room for a header? */
129 Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
131 szShareMem = GetSharedMemName();
133 UsedShmemSegAddr = NULL;
136 * When recycling a shared memory segment, it may take a short while
137 * before it gets dropped from the global namespace. So re-try after
138 * sleeping for a second, and continue retrying 10 times.
139 * (both the 1 second time and the 10 retries are completely arbitrary)
141 for (i = 0; i < 10; i++)
143 /* In case CreateFileMapping() doesn't set the error code to 0 on success */
146 hmap = CreateFileMapping((HANDLE) 0xFFFFFFFF, /* Use the pagefile */
147 NULL, /* Default security attrs */
148 PAGE_READWRITE, /* Memory is Read/Write */
149 0L, /* Size Upper 32 Bits */
150 (DWORD) size, /* Size Lower 32 bits */
155 (errmsg("could not create shared memory segment: %lu", GetLastError()),
156 errdetail("Failed system call was CreateFileMapping(size=%lu, name=%s).",
157 (unsigned long) size, szShareMem)));
160 * If the segment already existed, CreateFileMapping() will return a
161 * handle to the existing one.
163 if (GetLastError() == ERROR_ALREADY_EXISTS)
165 CloseHandle(hmap); /* Close the old handle, since we got a valid
166 * one to the previous segment. */
174 * If the last call in the loop still returned ERROR_ALREADY_EXISTS, this shared memory
175 * segment exists and we assume it belongs to somebody else.
177 if (GetLastError() == ERROR_ALREADY_EXISTS)
179 (errmsg("pre-existing shared memory block is still in use"),
180 errhint("Check if there are any old server processes still running, and terminate them.")));
185 * Make the handle inheritable
187 if (!DuplicateHandle(GetCurrentProcess(), hmap, GetCurrentProcess(), &hmap2, 0, TRUE, DUPLICATE_SAME_ACCESS))
189 (errmsg("could not create shared memory segment: %lu", GetLastError()),
190 errdetail("Failed system call was DuplicateHandle.")));
193 * Close the old, non-inheritable handle. If this fails we don't really
196 if (!CloseHandle(hmap))
197 elog(LOG, "could not close handle to shared memory: %lu", GetLastError());
200 /* Register on-exit routine to delete the new segment */
201 on_shmem_exit(pgwin32_SharedMemoryDelete, Int32GetDatum((unsigned long) hmap2));
204 * Get a pointer to the new shared memory segment. Map the whole segment
205 * at once, and let the system decide on the initial address.
207 memAddress = MapViewOfFileEx(hmap2, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, 0, NULL);
210 (errmsg("could not create shared memory segment: %lu", GetLastError()),
211 errdetail("Failed system call was MapViewOfFileEx.")));
216 * OK, we created a new segment. Mark it as created by this process. The
217 * order of assignments here is critical so that another Postgres process
218 * can't see the header as valid but belonging to an invalid PID!
220 hdr = (PGShmemHeader *) memAddress;
221 hdr->creatorPID = getpid();
222 hdr->magic = PGShmemMagic;
225 * Initialize space allocation status for segment.
227 hdr->totalsize = size;
228 hdr->freeoffset = MAXALIGN(sizeof(PGShmemHeader));
230 /* Save info for possible future use */
231 UsedShmemSegAddr = memAddress;
232 UsedShmemSegID = (unsigned long) hmap2;
238 * PGSharedMemoryReAttach
240 * Re-attach to an already existing shared memory segment. Use the
241 * handle inherited from the postmaster.
243 * UsedShmemSegID and UsedShmemSegAddr are implicit parameters to this
244 * routine. The caller must have already restored them to the postmaster's
248 PGSharedMemoryReAttach(void)
251 void *origUsedShmemSegAddr = UsedShmemSegAddr;
253 Assert(UsedShmemSegAddr != NULL);
254 Assert(IsUnderPostmaster);
256 hdr = (PGShmemHeader *) MapViewOfFileEx((HANDLE) UsedShmemSegID, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0, UsedShmemSegAddr);
258 elog(FATAL, "could not reattach to shared memory (key=%d, addr=%p): %lu",
259 (int) UsedShmemSegID, UsedShmemSegAddr, GetLastError());
260 if (hdr != origUsedShmemSegAddr)
261 elog(FATAL, "reattaching to shared memory returned unexpected address (got %p, expected %p)",
262 hdr, origUsedShmemSegAddr);
263 if (hdr->magic != PGShmemMagic)
264 elog(FATAL, "reattaching to shared memory returned non-PostgreSQL memory");
266 UsedShmemSegAddr = hdr; /* probably redundant */
270 * PGSharedMemoryDetach
272 * Detach from the shared memory segment, if still attached. This is not
273 * intended for use by the process that originally created the segment. Rather,
274 * this is for subprocesses that have inherited an attachment and want to
278 PGSharedMemoryDetach(void)
280 if (UsedShmemSegAddr != NULL)
282 if (!UnmapViewOfFile(UsedShmemSegAddr))
283 elog(LOG, "could not unmap view of shared memory: %lu", GetLastError());
285 UsedShmemSegAddr = NULL;
291 * pgwin32_SharedMemoryDelete(status, shmId) deletes a shared memory segment
292 * (called as an on_shmem_exit callback, hence funny argument list)
295 pgwin32_SharedMemoryDelete(int status, Datum shmId)
297 PGSharedMemoryDetach();
298 if (!CloseHandle((HANDLE) DatumGetInt32(shmId)))
299 elog(LOG, "could not close handle to shared memory: %lu", GetLastError());