- Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathMetaName.cpp
492 lines (425 loc) · 11.9 KB
/
MetaName.cpp
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
/*
* PROGRAM: Client/Server Common Code
* MODULE: MetaName.cpp
* DESCRIPTION: metadata name holder
*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
* http://www.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl.
*
* Software distributed under the License is distributed AS IS,
* WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights
* and limitations under the License.
*
* The Original Code was created by Alexander Peshkov
* for the Firebird Open Source RDBMS project.
*
* Copyright (c) 2005, 2020 Alexander Peshkov <peshkoff@mail.ru>
* and all contributors signed below.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
*
*/
#include"firebird.h"
#include<stdarg.h>
#include"../jrd/MetaName.h"
#include"../common/classes/MetaString.h"
#include"../common/classes/RefMutex.h"
#include"../jrd/jrd.h"
namespaceJrd {
intMetaName::compare(constchar* s, FB_SIZE_T len) const
{
if (s)
{
adjustLength(s, len);
FB_SIZE_T x = length() < len ? length() : len;
int rc = memcmp(c_str(), s, x);
if (rc)
{
return rc;
}
}
else
len = 0;
returnlength() - len;
}
voidMetaName::adjustLength(constchar* const s, FB_SIZE_T& len)
{
if (len > MAX_SQL_IDENTIFIER_LEN)
{
fb_assert(s);
#ifdef DEV_BUILD
for (FB_SIZE_T i = MAX_SQL_IDENTIFIER_LEN; i < len; ++i)
fb_assert(s[i] == '\0' || s[i] == '');
#endif
len = MAX_SQL_IDENTIFIER_LEN;
}
while (len)
{
if (s[len - 1] != '')
{
break;
}
--len;
}
}
voidMetaName::printf(constchar* format, ...)
{
char data[MAX_SQL_IDENTIFIER_LEN + 1];
va_list params;
va_start(params, format);
int len = VSNPRINTF(data, MAX_SQL_IDENTIFIER_LEN, format, params);
va_end(params);
if (len < 0 || FB_SIZE_T(len) > MAX_SQL_IDENTIFIER_LEN)
{
len = MAX_SQL_IDENTIFIER_LEN;
}
data[len] = 0;
word = get(data, len);
}
FB_SIZE_T MetaName::copyTo(char* to, FB_SIZE_T toSize) const
{
fb_assert(to);
fb_assert(toSize);
if (--toSize > length())
{
toSize = length();
}
memcpy(to, c_str(), toSize);
to[toSize] = 0;
return toSize;
}
MetaName::operatorFirebird::MetaString() const
{
returnFirebird::MetaString(c_str(), length());
}
MetaName::MetaName(const Firebird::MetaString& s)
{
assign(s.c_str(), s.length());
}
MetaName& MetaName::operator=(const Firebird::MetaString& s)
{
returnassign(s.c_str(), s.length());
}
voidMetaName::test()
{
#if defined(DEV_BUILD) || GROW_DEBUG > 0
if (word)
{
Dictionary::Word* checkWord = get(word->c_str(), word->length());
fb_assert(checkWord == word);
#ifndef DEV_BUILD
if (word != checkWord)
abort();
#endif
}
#endif
}
constchar* MetaName::EMPTY = "";
#if GROW_DEBUG > 1
staticconstunsignedint hashSize[] = {1000, 2000, 4000, 6000, 8000, 10000,
12000, 14000, 16000, 18000, 20000,
22000, 24000, 26000, 28000, 30000,
32000, 34000, 36000, 38000, 40000,
42000, 44000, 46000, 48000, 50000,
52000, 54000, 56000, 58000, 60000};
#else
staticconstunsignedint hashSize[] = { 10007, 100003, 1000003 };
#endif
Dictionary::Dictionary(MemoryPool& p)
: Firebird::PermanentStorage(p),
#if DIC_STATS > 0
words(0), totLength(0), lostWords(0), conflicts(0), retriesHash(0), retriesSegment(0),
#endif
hashTable(FB_NEW_POOL(getPool()) HashTable(getPool(), 0)),
nextLevel(0),
segment(FB_NEW_POOL(getPool()) Segment),
segCount(1)
{ }
#if DIC_STATS > 0
Dictionary::~Dictionary()
{
#defineLINESEP"\n\t\t"
gds__log("Dictionary statistics:" LINESEP
"words %" UQUADFORMAT LINESEP
"average length %.02f" LINESEP
"hash size at level %u is %u" LINESEP
"lost words %" UQUADFORMAT LINESEP
"conflicts on mutex %" UQUADFORMAT LINESEP
"retries in hash table %" UQUADFORMAT LINESEP
"segments total %u" LINESEP
"retries in segment %" UQUADFORMAT "\n",
words.load(), double(totLength) / words.load(),
hashTable.load()->level, hashSize[hashTable.load()->level],
lostWords.load(), conflicts.load(),
retriesHash.load(), segCount, retriesSegment.load());
}
#endif
Dictionary::HashTable::HashTable(MemoryPool& p, unsigned lvl)
: level(lvl),
table(FB_NEW_POOL(p) TableData[hashSize[level]])
{
for (unsigned n = 0; n < hashSize[level]; ++n)
table[n].store(nullptr, std::memory_order_relaxed);
}
unsignedDictionary::HashTable::getMaxLevel()
{
returnFB_NELEM(hashSize) - 1;
}
voidDictionary::Word::assign(constchar* s, FB_SIZE_T len)
{
fb_assert(len < MAX_UCHAR);
textLen = len;
memcpy(text, s, len);
text[len] = '\0';
}
Dictionary::Word* MetaName::get(constchar* s, FB_SIZE_T len)
{
// normalize metadata name
adjustLength(s, len);
if (!len)
returnnullptr;
// get dictionary from TLS
thread_db* tdbb = JRD_get_thread_data();
fb_assert(tdbb);
fb_assert(tdbb->getDatabase());
Dictionary& dic = tdbb->getDatabase()->dbb_dic;
// use that dictionary to find appropriate word
return dic.get(s, len);
}
Dictionary::TableData* Dictionary::HashTable::getEntryByHash(constchar* s, FB_SIZE_T len)
{
unsigned h = Firebird::InternalHash::hash(len, reinterpret_cast<const UCHAR*>(s), hashSize[level]);
return &table[h];
}
boolDictionary::checkConsistency(Dictionary::HashTable* oldValue)
{
return oldValue->level == nextLevel.load();
}
Dictionary::Word* Dictionary::get(constchar* s, FB_SIZE_T len)
{
Word* newWord = nullptr;
// first of all get current hash table and entry appropriate for a string
HashTable* t = hashTable.load(std::memory_order_acquire);
TableData* d = t->getEntryByHash(s, len);
// restart loop
for(;;)
{
// to be used if adding new word to hash later
Word* hashWord = d->load(std::memory_order_acquire);
// try to find existing word
Word* word = hashWord;
while (word)
{
if (word->length() == len && memcmp(word->c_str(), s, len) == 0)
{
// Avoid finding duplicate - if at this step when word is located
// hash level did not change we definitely got correct word
if (!checkConsistency(t))
break;
#if DIC_STATS > 0
if (newWord)
++lostWords;
#endif
return word;
}
word = word->next;
}
// check for previously allocated space presence
if (!newWord)
{
// we have not done anything tragic yet
// now it's good time to check - does anyone increments hash size
if (!checkConsistency(t))
{
// Wait for completion, switch to new hash table & repeat everything
t = waitForMutex();
d = t->getEntryByHash(s, len);
continue;
}
// allocate space for new word
newWord = segment->getSpace(len DIC_STAT_SEGMENT_CALL);
if (!newWord)
{
Firebird::MutexEnsureUnlock guard(mutex, FB_FUNCTION);
if (guard.tryEnter())
{
// retry allocation to avoid a case when someone already changed segment
newWord = segment->getSpace(len DIC_STAT_SEGMENT_CALL);
// do we really need new segment?
if (!newWord)
{
segment = FB_NEW_POOL(getPool()) Segment;
++segCount;
unsigned lvl = nextLevel.load();
if (lvl < HashTable::getMaxLevel() &&
segCount * Segment::getWordCapacity() > hashSize[lvl])
{
growHash();
}
}
else
newWord->assign(s, len);
}
else
{
// somebody already changes segment and/or grows hash size - let's wait for it
HashTable* tNew = waitForMutex();
if (tNew != t)
{
t = tNew;
d = t->getEntryByHash(s, len);
}
}
continue;
}
// fill allocated space
newWord->assign(s, len);
}
// by all means minimize a chance of getting duplicate word:
// check consistency right before adding word to dictionary
if (!checkConsistency(t))
{
// Wait for completion, switch to new hash table & repeat everything
t = waitForMutex();
d = t->getEntryByHash(s, len);
continue;
}
// complete operation - try to replace hash pointer
newWord->next = hashWord;
if (d->compare_exchange_weak(hashWord, newWord, std::memory_order_release, std::memory_order_relaxed))
{
// very rare case - finally avoid having duplicates
if (!checkConsistency(t))
{
// we do not know when did shit happen
// let's check new word and fix things if something gone wrong
t = waitForMutex(&newWord);
if (t)
{
// must repeat with new hash table
d = t->getEntryByHash(s, len);
continue;
}
}
#if DIC_STATS > 0
++words;
totLength += len;
#endif
return newWord;
}
#if DIC_STATS > 0
++retriesHash;
#endif
}
}
voidDictionary::growHash()
{
fb_assert(mutex.locked());
// move one level up size of hash table
HashTable* tab = hashTable.load();
unsigned lvl = ++nextLevel;
fb_assert(lvl == tab->level + 1);
fb_assert(lvl <= HashTable::getMaxLevel());
#if GROW_DEBUG > 0
fprintf(stderr, "Hash grow to %d\n", hashSize[lvl]);
#endif
// create new hash table
HashTable* newTab = FB_NEW_POOL(getPool()) HashTable(getPool(), lvl);
// we have mutex locked - but it does not mean others will not touch old hash table
// that's why do not forget to be careful when getting elements from it
// on the other hand new table may be modified freely - it's local for this thread after creation
for (unsigned n = 0; n < hashSize[tab->level]; ++n)
{
// detach list of words from old table in safe way
TableData* tableEntry = &tab->table[n];
Word* list = tableEntry->load(std::memory_order_acquire);
while(!tableEntry->compare_exchange_weak(list, nullptr, std::memory_order_release, std::memory_order_acquire))
; // empty body of the loop
// append detached list of words to new table word by word
while (list)
{
Word* next = list->next;
TableData* e = newTab->getEntryByHash(list->c_str(), list->length());
list->next = e->load(std::memory_order_relaxed);
e->store(list, std::memory_order_relaxed);
list = next;
}
}
// new hash table is ready - install it
// noone will concurrently modify it but it can be read, i.e. membar is needed
hashTable.store(newTab);
}
Dictionary::HashTable* Dictionary::waitForMutex(Jrd::Dictionary::Word** checkWordPtr)
{
Firebird::MutexLockGuard guard(mutex, FB_FUNCTION);
#if DIC_STATS > 0
++conflicts;
#endif
HashTable* t = hashTable.load();
if (!checkWordPtr)
return t;
// may be we already have that word in new table
FB_SIZE_T len = (*checkWordPtr)->length();
constchar* s = (*checkWordPtr)->c_str();
Word* word = t->getEntryByHash(s, len)->load();
while (word)
{
if (word->length() == len && memcmp(word->c_str(), s, len) == 0)
{
// successfully found same word in new table - use it
*checkWordPtr = word;
// no need performing any more ops with hash table
returnnullptr;
}
word = word->next;
}
// checkWord was added to old hash table right now & is missing in new one
// we should repeat adding it to the new hash table
return t;
}
Dictionary::Segment::Segment()
{
position.store(0, std::memory_order_relaxed);
}
unsignedDictionary::Segment::getWordCapacity()
{
constunsigned AVERAGE_BYTES_LEN = 16;
return SEG_BUFFER_SIZE / getWordLength(AVERAGE_BYTES_LEN);
}
unsignedDictionary::Segment::getWordLength(FB_SIZE_T len)
{
// calculate length in sizeof(Word*)
len += 2;
return1 + (len / sizeof(Word*)) + (len % sizeof(Word*) ? 1 : 0);
}
Dictionary::Word* Dictionary::Segment::getSpace(FB_SIZE_T len DIC_STAT_SEGMENT_PAR)
{
len = getWordLength(len);
// get old position value
unsigned oldPos = position.load(std::memory_order_acquire);
// restart loop
for(;;)
{
// calculate and check new position
unsigned newPos = oldPos + len;
if (newPos >= SEG_BUFFER_SIZE)
break;
// try to store it safely in segment header
if (position.compare_exchange_weak(oldPos, newPos, std::memory_order_release, std::memory_order_acquire))
{
returnreinterpret_cast<Word*>(&buffer[oldPos]);
}
#if DIC_STATS > 0
++retries;
#endif
}
// Segment out of space
returnnullptr;
}
} // namespace Jrd