]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/dircache.c
Logging assert macro AFP_ASSERT
[netatalk.git] / etc / afpd / dircache.c
1 /*
2   $Id: dircache.c,v 1.1.2.7 2010-02-11 13:06:54 franklahm Exp $
3   Copyright (c) 2010 Frank Lahm <franklahm@gmail.com>
4
5   This program is free software; you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation; either version 2 of the License, or
8   (at your option) any later version.
9
10   This program is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14 */
15
16 #ifdef HAVE_CONFIG_H
17 #include "config.h"
18 #endif /* HAVE_CONFIG_H */
19
20 #include <string.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <errno.h>
24 #include <assert.h>
25
26 #include <atalk/util.h>
27 #include <atalk/cnid.h>
28 #include <atalk/logger.h>
29 #include <atalk/volume.h>
30 #include <atalk/directory.h>
31 #include <atalk/queue.h>
32 #include <atalk/bstrlib.h>
33 #include <atalk/bstradd.h>
34
35 #include "dircache.h"
36 #include "directory.h"
37 #include "hash.h"
38 #include "globals.h"
39
40 /*
41  * Dircache and indexes
42  * ====================
43  * The maximum dircache size is:
44  * max(DEFAULT_MAX_DIRCACHE_SIZE, min(size, MAX_POSSIBLE_DIRCACHE_SIZE)).
45  * It is a hashtable which we use to store "struct dir"s in. If the cache get full, oldest
46  * entries are evicted in chunks of DIRCACHE_FREE.
47  * We have/need two indexes:
48  * - a DID/name index on the main dircache, another hashtable
49  * - a queue index on the dircache, for evicting the oldest entries
50  * The cache supports locking of struct dir elements through the DIRF_CACHELOCK flag. A dir
51  * locked this way wont ever be removed from the cache, so be careful.
52  */
53
54 /********************************************************
55  * Local funcs and variables
56  ********************************************************/
57
58 /*****************************
59  *       THE dircache        */
60
61 static hash_t       *dircache;        /* The actual cache */
62 static unsigned int dircache_maxsize; /* cache maximum size */
63
64 /* FNV 1a */
65 static hash_val_t hash_vid_did(const void *key)
66 {
67     const struct dir *k = (const struct dir *)key;
68     hash_val_t hash = 2166136261;
69
70     hash ^= k->d_vid >> 8;
71     hash *= 16777619;
72     hash ^= k->d_vid;
73     hash *= 16777619;
74
75     hash ^= k->d_did >> 24;
76     hash *= 16777619;
77     hash ^= (k->d_did >> 16) & 0xff;
78     hash *= 16777619;
79     hash ^= (k->d_did >> 8) & 0xff;
80     hash *= 16777619;
81     hash ^= (k->d_did >> 0) & 0xff;
82     hash *= 16777619;
83
84     return hash;
85 }
86
87 static int hash_comp_vid_did(const void *key1, const void *key2)
88 {
89     const struct dir *k1 = key1;
90     const struct dir *k2 = key2;
91
92     return !(k1->d_did == k2->d_did && k1->d_vid == k2->d_vid);
93 }
94
95 /**************************************************
96  * DID/name index on dircache (another hashtable) */
97
98 static hash_t *index_didname;
99
100 #undef get16bits
101 #if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__)    \
102     || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
103 #define get16bits(d) (*((const uint16_t *) (d)))
104 #endif
105
106 #if !defined (get16bits)
107 #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)    \
108                       +(uint32_t)(((const uint8_t *)(d))[0]) )
109 #endif
110
111 static hash_val_t hash_didname(const void *p)
112 {
113     const struct dir *key = (const struct dir *)p;
114     const unsigned char *data = key->d_u_name->data;
115     int len = key->d_u_name->slen;
116     hash_val_t hash = key->d_pdid + key->d_vid;
117     hash_val_t tmp;
118
119     int rem = len & 3;
120     len >>= 2;
121
122     /* Main loop */
123     for (;len > 0; len--) {
124         hash  += get16bits (data);
125         tmp    = (get16bits (data+2) << 11) ^ hash;
126         hash   = (hash << 16) ^ tmp;
127         data  += 2*sizeof (uint16_t);
128         hash  += hash >> 11;
129     }
130
131     /* Handle end cases */
132     switch (rem) {
133     case 3: hash += get16bits (data);
134         hash ^= hash << 16;
135         hash ^= data[sizeof (uint16_t)] << 18;
136         hash += hash >> 11;
137         break;
138     case 2: hash += get16bits (data);
139         hash ^= hash << 11;
140         hash += hash >> 17;
141         break;
142     case 1: hash += *data;
143         hash ^= hash << 10;
144         hash += hash >> 1;
145     }
146
147     /* Force "avalanching" of final 127 bits */
148     hash ^= hash << 3;
149     hash += hash >> 5;
150     hash ^= hash << 4;
151     hash += hash >> 17;
152     hash ^= hash << 25;
153     hash += hash >> 6;
154
155     return hash;
156 }
157
158 static int hash_comp_didname(const void *k1, const void *k2)
159 {
160     const struct dir *key1 = (const struct dir *)k1;
161     const struct dir *key2 = (const struct dir *)k2;
162
163     return ! (key1->d_vid == key2->d_vid
164               && key1->d_pdid == key2->d_pdid
165               && (bstrcmp(key1->d_u_name, key2->d_u_name) == 0) );
166 }
167
168 /***************************
169  * queue index on dircache */
170
171 static queue_t *index_queue;    /* the index itself */
172 static unsigned int queue_count;
173 static const int dircache_free_quantum = 256; /* number of entries to free */
174
175 /*!
176  * @brief Remove a fixed number of (oldest) entries from the cache and indexes
177  *
178  * The default is to remove the 256 oldest entries from the cache.
179  * 1. Get the oldest entry
180  * 2. If it's in use ie open forks reference it or it's curdir requeue it,
181  *    or it's locked (from catsearch) dont remove it
182  * 3. Remove the dir from the main cache and the didname index
183  * 4. Free the struct dir structure and all its members
184  */
185 static void dircache_evict(void)
186 {
187     int i = dircache_free_quantum;
188     struct dir *dir;
189
190     LOG(log_debug, logtype_afpd, "dircache: {starting cache eviction}");
191
192     while (i--) {
193         if ((dir = (struct dir *)dequeue(index_queue)) == NULL) { /* 1 */
194             dircache_dump();
195             exit(EXITERR_SYS);
196         }
197         queue_count--;
198
199         if (curdir == dir
200             || dir->d_ofork
201             || (dir->d_flags & DIRF_CACHELOCK)) {     /* 2 */
202             if ((dir->qidx_node = enqueue(index_queue, dir)) == NULL) {
203                 dircache_dump();
204                 exit(EXITERR_SYS);
205             }
206             queue_count++;
207             continue;
208         }
209
210         dircache_remove(NULL, dir, DIRCACHE | DIDNAME_INDEX); /* 3 */
211         dir_free(dir);                                        /* 4 */
212     }
213
214    AFP_ASSERT(queue_count == dircache->hash_nodecount);
215
216     LOG(log_debug, logtype_afpd, "dircache: {finished cache eviction}");
217 }
218
219
220 /********************************************************
221  * Interface
222  ********************************************************/
223
224 /*!
225  * @brief Search the dircache via a DID
226  *
227  * @param vol    (r) pointer to struct vol
228  * @param did    (r) CNID of the directory
229  *
230  * @returns Pointer to struct dir if found, else NULL
231  */
232 struct dir *dircache_search_by_did(const struct vol *vol, cnid_t did)
233 {
234     struct dir *cdir = NULL;
235     struct dir key;
236     hnode_t *hn;
237
238    AFP_ASSERT(vol);
239    AFP_ASSERT(ntohl(did) >= CNID_START);
240
241     key.d_vid = vol->v_vid;
242     key.d_did = did;
243     if ((hn = hash_lookup(dircache, &key)))
244         cdir = hnode_get(hn);
245
246     if (cdir)
247         LOG(log_debug, logtype_afpd, "dircache(did:%u): {cached: path:'%s'}", ntohl(did), cfrombstring(cdir->d_fullpath));
248     else
249         LOG(log_debug, logtype_afpd, "dircache(did:%u): {not in cache}", ntohl(did));
250
251     return cdir;
252 }
253
254 /*!
255  * @brief Search the cache via did/name hashtable
256  *
257  * @param vol    (r) volume
258  * @param dir    (r) directory
259  * @param name   (r) name (server side encoding)
260  * @parma len    (r) strlen of name
261  *
262  * @returns pointer to struct dir if found in cache, else NULL
263  */
264 struct dir *dircache_search_by_name(const struct vol *vol, const struct dir *dir, char *name, int len)
265 {
266     struct dir *cdir = NULL;
267     struct dir key;
268     hnode_t *hn;
269     static_bstring uname = {-1, len, (unsigned char *)name};
270
271    AFP_ASSERT(vol);
272    AFP_ASSERT(dir);
273    AFP_ASSERT(name);
274    AFP_ASSERT(len == strlen(name));
275    AFP_ASSERT(len < 256);
276
277     if (dir->d_did != DIRDID_ROOT_PARENT) {
278         key.d_vid = vol->v_vid;
279         key.d_pdid = dir->d_did;
280         key.d_u_name = &uname;
281
282         if ((hn = hash_lookup(index_didname, &key)))
283             cdir = hnode_get(hn);
284     }
285
286     if (cdir)
287         LOG(log_debug, logtype_afpd, "dircache(pdid:%u, did:%u, '%s'): {found in cache}",
288             ntohl(dir->d_did), ntohl(cdir->d_did), cfrombstring(cdir->d_fullpath));
289     else
290         LOG(log_debug, logtype_afpd, "dircache(pdid:%u,'%s/%s'): {not in cache}",
291             ntohl(dir->d_did), cfrombstring(dir->d_fullpath), name);
292
293     return cdir;
294 }
295
296 /*!
297  * @brief create struct dir from struct path
298  *
299  * Add a struct dir to the cache and its indexes.
300  *
301  * @param dir   (r) pointer to parrent directory
302  *
303  * @returns 0 on success, -1 on error which should result in an abort
304  */
305 int dircache_add(struct dir *dir)
306 {
307    AFP_ASSERT(dir);
308    AFP_ASSERT(ntohl(dir->d_pdid) >= 2);
309    AFP_ASSERT(ntohl(dir->d_did) >= CNID_START);
310    AFP_ASSERT(dir->d_fullpath);
311    AFP_ASSERT(dir->d_u_name);
312    AFP_ASSERT(dir->d_vid);
313    AFP_ASSERT(dircache->hash_nodecount <= dircache_maxsize);
314
315     /* Check if cache is full */
316     if (dircache->hash_nodecount == dircache_maxsize)
317         dircache_evict();
318
319     /* Add it to the main dircache */
320     if (hash_alloc_insert(dircache, dir, dir) == 0) {
321         dircache_dump();
322         exit(EXITERR_SYS);
323     }
324
325     /* Add it to the did/name index */
326     if (hash_alloc_insert(index_didname, dir, dir) == 0) {
327         dircache_dump();
328         exit(EXITERR_SYS);
329     }
330
331     /* Add it to the fifo queue index */
332     if ((dir->qidx_node = enqueue(index_queue, dir)) == NULL) {
333         dircache_dump();
334         exit(EXITERR_SYS);
335     } else {
336         queue_count++;
337     }
338
339     LOG(log_debug, logtype_afpd, "dircache(did:%u,'%s'): {added}", ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
340
341    AFP_ASSERT(queue_count == index_didname->hash_nodecount 
342            && queue_count == dircache->hash_nodecount);
343
344     return 0;
345 }
346
347 /*!
348   * @brief Remove an entry from the dircache
349   *
350   * Callers outside of dircache.c should call this with
351   * flags = QUEUE_INDEX | DIDNAME_INDEX | DIRCACHE.
352   */
353 void dircache_remove(const struct vol *vol _U_, struct dir *dir, int flags)
354 {
355     hnode_t *hn;
356
357    AFP_ASSERT(dir);
358    AFP_ASSERT((flags & ~(QUEUE_INDEX | DIDNAME_INDEX | DIRCACHE)) == 0);
359
360     if (dir->d_flags & DIRF_CACHELOCK)
361         return;
362
363     if (flags & QUEUE_INDEX) {
364         /* remove it from the queue index */
365         dequeue(dir->qidx_node->prev); /* this effectively deletes the dequeued node */
366         queue_count--;
367     }
368
369     if (flags & DIDNAME_INDEX) {
370         if ((hn = hash_lookup(index_didname, dir)) == NULL) {
371             LOG(log_error, logtype_default, "dircache_remove(%u,%s): not in didname index", 
372                 ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
373             dircache_dump();
374             exit(EXITERR_SYS);
375         }
376         hash_delete(index_didname, hn);
377     }
378
379     if (flags & DIRCACHE) {
380         if ((hn = hash_lookup(dircache, dir)) == NULL) {
381             LOG(log_error, logtype_default, "dircache_remove(%u,%s): not in dircache", 
382                 ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
383             dircache_dump();
384             exit(EXITERR_SYS);
385         }
386         hash_delete(dircache, hn);
387     }
388
389     LOG(log_debug, logtype_afpd, "dircache(did:%u,'%s'): {removed}", ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
390
391    AFP_ASSERT(queue_count == index_didname->hash_nodecount 
392            && queue_count == dircache->hash_nodecount);
393 }
394
395 /*!
396  * @brief Initialize the dircache and indexes
397  *
398  * This is called in child afpd initialisation. The maximum cache size will be
399  * max(DEFAULT_MAX_DIRCACHE_SIZE, min(size, MAX_POSSIBLE_DIRCACHE_SIZE)).
400  * It initializes a hashtable which we use to store a directory cache in.
401  * It also initializes two indexes:
402  * - a DID/name index on the main dircache
403  * - a queue index on the dircache
404  *
405  * @param size   (r) requested maximum size from afpd.conf
406  *
407  * @return 0 on success, -1 on error
408  */
409 int dircache_init(int reqsize)
410 {
411     dircache_maxsize = DEFAULT_MAX_DIRCACHE_SIZE;
412
413     /* Initialize the main dircache */
414     if (reqsize > DEFAULT_MAX_DIRCACHE_SIZE && reqsize < MAX_POSSIBLE_DIRCACHE_SIZE) {
415         while ((dircache_maxsize < MAX_POSSIBLE_DIRCACHE_SIZE) && (dircache_maxsize < reqsize))
416                dircache_maxsize *= 2;
417     }
418     if ((dircache = hash_create(dircache_maxsize, hash_comp_vid_did, hash_vid_did)) == NULL)
419         return -1;
420     
421     LOG(log_debug, logtype_afpd, "dircache_init: done. max dircache size: %u", dircache_maxsize);
422
423     /* Initialize did/name index hashtable */
424     if ((index_didname = hash_create(dircache_maxsize, hash_comp_didname, hash_didname)) == NULL)
425         return -1;
426
427     /* Initialize index queue */
428     if ((index_queue = queue_init()) == NULL)
429         return -1;
430     else
431         queue_count = 0;
432
433     /* As long as directory.c hasn't got its own initializer call, we do it for it */
434     rootParent.d_did = DIRDID_ROOT_PARENT;
435     rootParent.d_fullpath = bfromcstr("ROOT_PARENT");
436     rootParent.d_m_name = bfromcstr("ROOT_PARENT");
437     rootParent.d_u_name = rootParent.d_m_name;
438
439     return 0;
440 }
441
442 /*!
443  * @brief Dump dircache to /tmp/dircache.PID
444  */
445 void dircache_dump(void)
446 {
447     char tmpnam[64];
448     FILE *dump;
449     qnode_t *n = index_queue->next;
450     const struct dir *dir;
451
452     LOG(log_warning, logtype_afpd, "Dumping directory cache...");
453
454     sprintf(tmpnam, "/tmp/dircache.%u", getpid());
455     if ((dump = fopen(tmpnam, "w+")) == NULL) {
456         LOG(log_error, logtype_afpd, "dircache_dump: %s", strerror(errno));
457         return;
458     }
459     setbuf(dump, NULL);
460
461     fprintf(dump, "Number of cache entries: %u\n", queue_count);
462     fprintf(dump, "Configured maximum cache size: %u\n", dircache_maxsize);
463     fprintf(dump, "==================================================\n\n");
464
465     for (int i = 1; i <= queue_count; i++) {
466         if (n == index_queue)
467             break;
468         dir = (struct dir *)n->data;
469         fprintf(dump, "%05u: vid:%u, pdid:%6u, did:%6u, path:%s, locked:%3s, oforks:%s\n",
470                 i, ntohs(dir->d_vid), ntohl(dir->d_pdid), ntohl(dir->d_did), cfrombstring(dir->d_fullpath),
471                 (dir->d_flags & DIRF_CACHELOCK) ? "yes" : "no",
472                 dir->d_ofork ? "yes" : "no");
473         n = n->next;
474     }
475
476     fprintf(dump, "\n");
477     return;
478 }