-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathppagecache.c
More file actions
3665 lines (3477 loc) · 126 KB
/
ppagecache.c
File metadata and controls
3665 lines (3477 loc) · 126 KB
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2014 Anton Titov.
* Copyright (c) 2014 pCloud Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of pCloud Ltd nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL pCloud Ltd BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "ppagecache.h"
#include "psettings.h"
#include "plibs.h"
#include "ptimer.h"
#include "pnetlibs.h"
#include "pstatus.h"
#include "pcache.h"
#include "pfsupload.h"
#include "pfscrypto.h"
#include "pcrc32c.h"
#include <errno.h>
#include <string.h>
#include <stdio.h>
#define CACHE_PAGES (PSYNC_FS_MEMORY_CACHE/PSYNC_FS_PAGE_SIZE)
#define CACHE_HASH (CACHE_PAGES/2)
#define PAGE_WAITER_HASH 1024
#define DB_CACHE_UPDATE_HASH (32*1024)
#define PAGE_TYPE_FREE 0
#define PAGE_TYPE_READ 1
#define PAGE_TYPE_CACHE 2
#define PAGE_TASK_TYPE_CREAT 0
#define PAGE_TASK_TYPE_MODIFY 1
#define pagehash_by_hash_and_pageid(hash, pageid) (((hash)+(pageid))%CACHE_HASH)
#define waiterhash_by_hash_and_pageid(hash, pageid) (((hash)+(pageid))%PAGE_WAITER_HASH)
#define lock_wait(hash) pthread_mutex_lock(&wait_page_mutex)
#define unlock_wait(hash) pthread_mutex_unlock(&wait_page_mutex)
typedef struct {
psync_list list;
psync_list flushlist;
char *page;
uint64_t hash;
uint64_t pageid;
time_t lastuse;
uint32_t size;
uint32_t usecnt;
uint32_t flushpageid;
uint32_t crc;
uint8_t type;
} psync_cache_page_t;
typedef struct {
uint64_t pagecacheid;
time_t lastuse;
uint32_t usecnt;
} psync_cachepage_to_update;
typedef struct {
/* list is an element of hash table for pages */
psync_list list;
/* list is root of a listpage elements of psync_page_waiter_t, if empty, nobody waits for this page */
psync_list waiters;
uint64_t hash;
uint64_t pageid;
psync_fileid_t fileid;
} psync_page_wait_t;
typedef struct {
/* listpage is node element of psync_page_wait_t waiters list */
psync_list listpage;
/* listwaiter is node element of pages that are needed for current request */
psync_list listwaiter;
pthread_cond_t cond;
psync_page_wait_t *waiting_for;
char *buff;
uint32_t pageidx;
uint32_t rsize;
uint32_t size;
uint32_t off;
int error;
uint8_t ready;
} psync_page_waiter_t;
typedef struct {
psync_list list;
uint64_t offset;
uint64_t length;
} psync_request_range_t;
typedef struct {
psync_list ranges;
psync_openfile_t *of;
psync_fileid_t fileid;
uint64_t hash;
int needkey;
} psync_request_t;
typedef struct {
uint64_t hash;
psync_tree tree;
binresult *urls;
uint32_t refcnt;
uint32_t status;
} psync_urls_t;
typedef struct _psync_crypto_auth_page {
psync_list list;
psync_page_waiter_t *waiter;
struct _psync_crypto_auth_page *parent;
uint64_t firstpageid;
uint32_t size;
uint32_t idinparent;
uint32_t level;
psync_crypto_auth_sector_t auth;
} psync_crypto_auth_page;
typedef struct {
psync_crypto_auth_page *authpage;
psync_page_waiter_t *waiter;
char *buff;
uint32_t pagesize;
uint8_t freebuff;
} psync_crypto_data_page;
static psync_list cache_hash[CACHE_HASH];
static uint32_t cache_pages_in_hash=0;
static uint32_t cache_pages_free;
static int cache_pages_reset=1;
static psync_list free_pages;
static psync_list wait_page_hash[PAGE_WAITER_HASH];
static char *pages_base;
static uint32_t free_page_waiters=0;
static int flush_page_running=0;
static psync_cachepage_to_update cachepages_to_update[DB_CACHE_UPDATE_HASH];
static uint32_t cachepages_to_update_cnt=0;
static uint32_t free_db_pages;
static pthread_mutex_t clean_cache_mutex=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t clean_cache_cond=PTHREAD_COND_INITIALIZER;
static pthread_mutex_t cache_mutex=PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t flush_cache_mutex=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t free_page_cond=PTHREAD_COND_INITIALIZER;
static pthread_mutex_t url_cache_mutex=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t url_cache_cond=PTHREAD_COND_INITIALIZER;
static pthread_mutex_t wait_page_mutex;
static pthread_cond_t enc_key_cond=PTHREAD_COND_INITIALIZER;
static uint32_t clean_cache_stoppers=0;
static uint32_t clean_cache_waiters=0;
static uint32_t clean_cache_in_progress=0;
static int flushedbetweentimers=0;
static int flushcacherun=0;
static int upload_to_cache_thread_run=0;
static uint64_t db_cache_in_pages;
static uint64_t db_cache_max_page;
static psync_file_t readcache=INVALID_HANDLE_VALUE;
static psync_tree *url_cache_tree=PSYNC_TREE_EMPTY;
static int flush_pages(int nosleep);
static void flush_pages_noret(){
flush_pages(0);
}
static psync_cache_page_t *psync_pagecache_get_free_page_if_available(){
psync_cache_page_t *page;
int runthread;
runthread=0;
pthread_mutex_lock(&cache_mutex);
if (unlikely(cache_pages_free<=CACHE_PAGES*25/100 && !flushcacherun)){
flushcacherun=1;
runthread=1;
}
if (likely(!psync_list_isempty(&free_pages)))
page=psync_list_remove_head_element(&free_pages, psync_cache_page_t, list);
else
page=NULL;
pthread_mutex_unlock(&cache_mutex);
if (runthread)
psync_run_thread("flush pages get free page ifav", flush_pages_noret);
return page;
}
static psync_cache_page_t *psync_pagecache_get_free_page(int runflushcacheinside){
psync_cache_page_t *page;
int runthread;
runthread=0;
pthread_mutex_lock(&cache_mutex);
if (unlikely(cache_pages_free<=CACHE_PAGES*25/100 && !flushcacherun)){
flushcacherun=1;
if (runflushcacheinside){
pthread_mutex_unlock(&cache_mutex);
debug(D_NOTICE, "running flush cache on this thread");
flush_pages(2);
pthread_mutex_lock(&cache_mutex);
}
else
runthread=1;
}
if (likely(!psync_list_isempty(&free_pages)))
page=psync_list_remove_head_element(&free_pages, psync_cache_page_t, list);
else{
if (flush_page_running){
debug(D_NOTICE, "no free pages, but somebody is flushing cache, waiting for a page");
do {
free_page_waiters++;
pthread_cond_wait(&free_page_cond, &cache_mutex);
free_page_waiters--;
} while (flush_page_running && psync_list_isempty(&free_pages));
}
if (psync_list_isempty(&free_pages)){
debug(D_NOTICE, "no free pages, flushing cache");
pthread_mutex_unlock(&cache_mutex);
flush_pages(1);
pthread_mutex_lock(&cache_mutex);
while (unlikely(psync_list_isempty(&free_pages))){
pthread_mutex_unlock(&cache_mutex);
debug(D_NOTICE, "no free pages after flush, sleeping");
psync_milisleep(200);
flush_pages(1);
pthread_mutex_lock(&cache_mutex);
}
}
else
debug(D_NOTICE, "waited for a free page");
page=psync_list_remove_head_element(&free_pages, psync_cache_page_t, list);
}
cache_pages_free--;
pthread_mutex_unlock(&cache_mutex);
if (runthread)
psync_run_thread("flush pages get free page", flush_pages_noret);
return page;
}
static int psync_api_send_read_request(psync_socket *api, psync_fileid_t fileid, uint64_t hash, uint64_t offset, uint64_t length){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("fileid", fileid), P_NUM("hash", hash), P_NUM("offset", offset), P_NUM("count", length)};
return send_command_no_res(api, "readfile", params)==PTR_OK?0:-1;
}
static int psync_api_send_read_request_thread(psync_socket *api, psync_fileid_t fileid, uint64_t hash, uint64_t offset, uint64_t length){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("fileid", fileid), P_NUM("hash", hash), P_NUM("offset", offset), P_NUM("count", length)};
return send_command_no_res_thread(api, "readfile", params)==PTR_OK?0:-1;
}
static void psync_pagecache_send_page_wait_page(psync_page_wait_t *pw, psync_cache_page_t *page){
psync_page_waiter_t *pwt;
psync_list_del(&pw->list);
psync_list_for_each_element(pwt, &pw->waiters, psync_page_waiter_t, listpage){
page->usecnt++;
if (pwt->off+pwt->size>page->size){
if (pwt->off>=page->size)
pwt->rsize=0;
else
pwt->rsize=page->size-pwt->off;
}
else
pwt->rsize=pwt->size;
memcpy(pwt->buff, page->page+pwt->off, pwt->rsize);
pwt->error=0;
pwt->ready=1;
pwt->waiting_for=NULL;
pthread_cond_broadcast(&pwt->cond);
}
psync_free(pw);
}
static void psync_pagecache_return_free_page_locked(psync_cache_page_t *page){
psync_list_add_head(&free_pages, &page->list);
cache_pages_free++;
}
static void psync_pagecache_return_free_page(psync_cache_page_t *page){
pthread_mutex_lock(&cache_mutex);
psync_pagecache_return_free_page_locked(page);
pthread_mutex_unlock(&cache_mutex);
}
static int psync_pagecache_read_range_from_api(psync_request_t *request, psync_request_range_t *range, psync_socket *api){
uint64_t first_page_id, dlen;
psync_page_wait_t *pw;
psync_cache_page_t *page;
binresult *res;
psync_uint_t len, i, h;
int rb;
first_page_id=range->offset/PSYNC_FS_PAGE_SIZE;
len=range->length/PSYNC_FS_PAGE_SIZE;
res=get_result_thread(api);
if (unlikely_log(!res))
return -2;
dlen=psync_find_result(res, "result", PARAM_NUM)->num;
if (unlikely(dlen)){
psync_free(res);
debug(D_WARNING, "readfile returned error %lu", (long unsigned)dlen);
psync_process_api_error(dlen);
return -2;
}
dlen=psync_find_result(res, "data", PARAM_DATA)->num;
psync_free(res);
for (i=0; i<len; i++){
page=psync_pagecache_get_free_page(0);
rb=psync_socket_readall_download_thread(api, page->page, dlen<PSYNC_FS_PAGE_SIZE?dlen:PSYNC_FS_PAGE_SIZE);
if (unlikely_log(rb<=0)){
psync_pagecache_return_free_page(page);
psync_timer_notify_exception();
return i==0?-2:-1;
}
dlen-=rb;
page->hash=request->hash;
page->pageid=first_page_id+i;
page->lastuse=psync_timer_time();
page->size=rb;
page->usecnt=0;
page->crc=psync_crc32c(PSYNC_CRC_INITIAL, page->page, rb);
page->type=PAGE_TYPE_READ;
h=waiterhash_by_hash_and_pageid(page->hash, page->pageid);
lock_wait(page->hash);
psync_list_for_each_element(pw, &wait_page_hash[h], psync_page_wait_t, list)
if (pw->hash==page->hash && pw->pageid==page->pageid){
psync_pagecache_send_page_wait_page(pw, page);
break;
}
unlock_wait(page->hash);
pthread_mutex_lock(&cache_mutex);
psync_list_add_tail(&cache_hash[pagehash_by_hash_and_pageid(page->hash, page->pageid)], &page->list);
cache_pages_in_hash++;
pthread_mutex_unlock(&cache_mutex);
}
return 0;
}
typedef struct {
psync_list list;
pthread_cond_t cond;
psync_socket *api;
} shared_api_waiter_t;
static pthread_mutex_t sharedapi_mutex=PTHREAD_MUTEX_INITIALIZER;
static psync_socket *sharedapi=NULL;
static psync_list sharedapiwaiters=PSYNC_LIST_STATIC_INIT(sharedapiwaiters);
static void mark_api_shared(psync_socket *api){
pthread_mutex_lock(&sharedapi_mutex);
if (!sharedapi)
sharedapi=api;
pthread_mutex_unlock(&sharedapi_mutex);
}
static void signal_all_waiters(){
shared_api_waiter_t *waiter;
while (!psync_list_isempty(&sharedapiwaiters)){
waiter=psync_list_remove_head_element(&sharedapiwaiters, shared_api_waiter_t, list);
waiter->api=(psync_socket *)-1;
pthread_cond_signal(&waiter->cond);
}
}
static void mark_shared_api_bad(psync_socket *api){
pthread_mutex_lock(&sharedapi_mutex);
if (sharedapi==api){
sharedapi=NULL;
signal_all_waiters();
}
pthread_mutex_unlock(&sharedapi_mutex);
}
static int pass_shared_api(psync_socket *api){
shared_api_waiter_t *waiter;
int ret;
pthread_mutex_lock(&sharedapi_mutex);
if (api!=sharedapi)
ret=-1;
else if (psync_list_isempty(&sharedapiwaiters)){
ret=-1;
sharedapi=NULL;
}
else{
ret=0;
waiter=psync_list_remove_head_element(&sharedapiwaiters, shared_api_waiter_t, list);
waiter->api=api;
pthread_cond_signal(&waiter->cond);
debug(D_NOTICE, "passing shared api connection");
}
pthread_mutex_unlock(&sharedapi_mutex);
return ret;
}
static psync_socket *get_shared_api(){
pthread_mutex_lock(&sharedapi_mutex);
if (sharedapi)
return sharedapi; // not supposed to unlock, it will happen in wait_shared_api
pthread_mutex_unlock(&sharedapi_mutex);
return NULL;
}
static void release_bad_shared_api(psync_socket *api){
if (sharedapi==api){
sharedapi=NULL;
signal_all_waiters();
}
pthread_mutex_unlock(&sharedapi_mutex);
}
static int wait_shared_api(){
shared_api_waiter_t *waiter;
psync_socket *capi;
int ret;
capi=sharedapi;
waiter=psync_new(shared_api_waiter_t);
pthread_cond_init(&waiter->cond, NULL);
waiter->api=NULL;
psync_list_add_tail(&sharedapiwaiters, &waiter->list);
debug(D_NOTICE, "waiting for shared API connection");
do {
pthread_cond_wait(&waiter->cond, &sharedapi_mutex);
} while (!waiter->api);
if (waiter->api!=capi){
assertw(waiter->api==(psync_socket *)-1);
ret=-1;
}
else{
debug(D_NOTICE, "waited for shared API connection");
ret=0;
}
pthread_mutex_unlock(&sharedapi_mutex);
pthread_cond_destroy(&waiter->cond);
psync_free(waiter);
return ret;
}
static void set_urls(psync_urls_t *urls, binresult *res){
pthread_mutex_lock(&url_cache_mutex);
if (res){
urls->status=1;
urls->urls=res;
if (urls->refcnt++>0)
pthread_cond_broadcast(&url_cache_cond);
}
else{
psync_tree_del(&url_cache_tree, &urls->tree);
if (urls->refcnt){
urls->status=2;
pthread_cond_broadcast(&url_cache_cond);
}
else
psync_free(urls);
}
pthread_mutex_unlock(&url_cache_mutex);
}
static void psync_pagecache_set_bad_encoder(psync_openfile_t *of){
psync_fs_lock_file(of);
if (likely(of->encoder==PSYNC_CRYPTO_LOADING_SECTOR_ENCODER)){
of->encoder=PSYNC_CRYPTO_FAILED_SECTOR_ENCODER;
pthread_cond_broadcast(&enc_key_cond);
}
pthread_mutex_unlock(&of->mutex);
}
static int send_key_request(psync_socket *api, psync_request_t *request){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("fileid", request->fileid)};
return send_command_no_res(api, "crypto_getfilekey", params)!=PTR_OK?-1:0;
}
static int get_urls(psync_request_t *request, psync_urls_t *urls){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("fileid", request->fileid), P_NUM("hash", request->hash),
P_STR("timeformat", "timestamp"), P_BOOL("skipfilename", 1)};
psync_socket *api;
binresult *ret;
psync_request_range_t *range;
psync_list *l1, *l2;
const binresult *hosts;
uint64_t totalreqlen;
unsigned long result;
int tries;
debug(D_NOTICE, "getting file URLs of fileid %lu, hash %lu together with requests%s",
(unsigned long)request->fileid, (unsigned long)request->hash, request->needkey?" and encryption key":"");
tries=0;
while (tries++<=5){
api=psync_apipool_get();
if (unlikely_log(!api))
continue;
psync_socket_set_write_buffered(api);
if (unlikely(send_command_no_res(api, "getfilelink", params)!=PTR_OK))
goto err1;
if (request->needkey && send_key_request(api, request))
goto err1;
totalreqlen=0;
psync_list_for_each_element(range, &request->ranges, psync_request_range_t, list){
debug(D_NOTICE, "sending request for offset %lu, size %lu to API", (unsigned long)range->offset, (unsigned long)range->length);
if (unlikely(psync_api_send_read_request(api, request->fileid, request->hash, range->offset, range->length)))
goto err1;
totalreqlen+=range->length;
}
mark_api_shared(api);
ret=get_result_thread(api);
if (unlikely_log(!ret)){
mark_shared_api_bad(api);
goto err1;
}
result=psync_find_result(ret, "result", PARAM_NUM)->num;
if (unlikely(result!=0)){
debug(D_WARNING, "getfilelink returned error %lu", result);
psync_free(ret);
mark_shared_api_bad(api);
psync_apipool_release_bad(api);
psync_process_api_error(result);
break;
}
hosts=psync_find_result(ret, "hosts", PARAM_ARRAY);
debug(D_NOTICE, "got file URLs of fileid %lu, hash %lu", (unsigned long)request->fileid, (unsigned long)request->hash);
if (likely_log(hosts->length && hosts->array[0]->type==PARAM_STR) && request->of->initialsize>totalreqlen)
psync_http_connect_and_cache_host(hosts->array[0]->str);
/*if (of->initialsize>=PSYNC_FS_FILESIZE_FOR_2CONN && hosts->length>1 && hosts->array[1]->type==PARAM_STR)
psync_http_connect_and_cache_host(hosts->array[1]->str);*/
set_urls(urls, ret);
if (request->needkey){
psync_crypto_aes256_sector_encoder_decoder_t enc;
ret=get_result_thread(api);
if (unlikely_log(!ret))
goto err3;
result=psync_find_result(ret, "result", PARAM_NUM)->num;
if (unlikely(result!=0)){
debug(D_WARNING, "crypto_getfilekey returned error %lu", result);
psync_process_api_error(result);
goto err4;
}
enc=psync_cloud_crypto_get_file_encoder_from_binresult(request->fileid, ret);
if (unlikely_log(psync_crypto_is_error(enc)))
goto err4;
debug(D_NOTICE, "got key for fileid %lu", (unsigned long)request->fileid);
psync_free(ret);
psync_fs_lock_file(request->of);
if (likely_log(request->of->encoder==PSYNC_CRYPTO_LOADING_SECTOR_ENCODER)){
request->of->encoder=enc;
pthread_cond_broadcast(&enc_key_cond);
}
else
psync_cloud_crypto_release_file_encoder(request->fileid, request->hash, enc);
pthread_mutex_unlock(&request->of->mutex);
request->needkey=0;
}
psync_list_for_each_safe(l1, l2, &request->ranges){
range=psync_list_element(l1, psync_request_range_t, list);
if (psync_pagecache_read_range_from_api(request, range, api))
goto err2;
psync_list_del(l1);
debug(D_NOTICE, "request for offset %lu, size %lu read from API", (unsigned long)range->offset, (unsigned long)range->length);
psync_free(range);
}
if (pass_shared_api(api))
psync_apipool_release(api);
return 0;
err1:
psync_apipool_release_bad(api);
}
return -1;
err4:
psync_free(ret);
err3:
if (request->needkey)
psync_pagecache_set_bad_encoder(request->of);
err2:
mark_shared_api_bad(api);
psync_apipool_release_bad(api);
return 0;
}
static psync_urls_t *get_urls_for_request(psync_request_t *req){
char buff[16];
psync_tree *el, **pel;
psync_urls_t *urls;
binresult *res;
int64_t d;
pthread_mutex_lock(&url_cache_mutex);
el=url_cache_tree;
pel=&url_cache_tree;
d=-1;
while (el){
urls=psync_tree_element(el, psync_urls_t, tree);
d=req->hash-urls->hash;
if (d==0)
break;
else if (d<0){
if (el->left)
el=el->left;
else{
pel=&el->left;
break;
}
}
else{
if (el->right)
el=el->right;
else{
pel=&el->right;
break;
}
}
}
if (d==0){
urls->refcnt++;
while (urls->status==0)
pthread_cond_wait(&url_cache_cond, &url_cache_mutex);
if (likely(urls->status==1)){
pthread_mutex_unlock(&url_cache_mutex);
return urls;
}
if (--urls->refcnt==0)
psync_free(urls);
pthread_mutex_unlock(&url_cache_mutex);
return NULL;
}
urls=psync_new(psync_urls_t);
urls->hash=req->hash;
urls->refcnt=0;
urls->status=0;
*pel=&urls->tree;
psync_tree_added_at(&url_cache_tree, el, &urls->tree);
pthread_mutex_unlock(&url_cache_mutex);
psync_get_string_id(buff, "URLS", req->hash);
res=(binresult *)psync_cache_get(buff);
if (res){
set_urls(urls, res);
return urls;
}
if (get_urls(req, urls)){
set_urls(urls, NULL);
return NULL;
}
else
return urls;
}
static void release_urls(psync_urls_t *urls){
pthread_mutex_lock(&url_cache_mutex);
if (--urls->refcnt==0){
if (likely(urls->status==1)){
char buff[16];
time_t ctime, etime;
psync_tree_del(&url_cache_tree, &urls->tree);
ctime=psync_timer_time();
etime=psync_find_result(urls->urls, "expires", PARAM_NUM)->num;
if (etime>ctime+3600){
psync_get_string_id(buff, "URLS", urls->hash);
psync_cache_add(buff, urls->urls, etime-ctime-3600, psync_free, 2);
urls->urls=NULL;
}
}
pthread_mutex_unlock(&url_cache_mutex);
psync_free(urls->urls);
psync_free(urls);
return;
}
pthread_mutex_unlock(&url_cache_mutex);
}
static void release_bad_urls(psync_urls_t *urls){
pthread_mutex_lock(&url_cache_mutex);
if (urls->status==1){
urls->status=2;
psync_tree_del(&url_cache_tree, &urls->tree);
}
if (--urls->refcnt)
urls=NULL;
pthread_mutex_unlock(&url_cache_mutex);
if (urls){
psync_free(urls->urls);
psync_free(urls);
}
}
static uint64_t offset_round_down_to_page(uint64_t offset){
return offset&~(((uint64_t)PSYNC_FS_PAGE_SIZE)-1);
}
static uint64_t size_round_up_to_page(uint64_t size){
return ((size-1)|(((uint64_t)PSYNC_FS_PAGE_SIZE)-1))+1;
}
static int has_page_in_cache_by_hash(uint64_t hash, uint64_t pageid){
psync_cache_page_t *page;
psync_uint_t h;
h=pagehash_by_hash_and_pageid(hash, pageid);
pthread_mutex_lock(&cache_mutex);
psync_list_for_each_element(page, &cache_hash[h], psync_cache_page_t, list)
if (page->hash==hash && page->pageid==pageid){
pthread_mutex_unlock(&cache_mutex);
return 1;
}
pthread_mutex_unlock(&cache_mutex);
return 0;
}
static unsigned char *has_pages_in_db(uint64_t hash, uint64_t pageid, uint32_t pagecnt, int readahead){
psync_sql_res *res;
psync_uint_row row;
unsigned char *ret;
uint64_t fromid;
uint32_t fcnt;
if (unlikely(!pagecnt))
return NULL;
ret=psync_new_cnt(unsigned char, pagecnt);
memset(ret, 0, pagecnt);
fromid=0;
fcnt=0;
res=psync_sql_query_rdlock("SELECT pageid, id FROM pagecache WHERE type=+"NTO_STR(PAGE_TYPE_READ)" AND hash=? AND pageid>=? AND pageid<? ORDER BY pageid");
psync_sql_bind_uint(res, 1, hash);
psync_sql_bind_uint(res, 2, pageid);
psync_sql_bind_uint(res, 3, pageid+pagecnt);
while ((row=psync_sql_fetch_rowint(res))){
ret[row[0]-pageid]=1;
if (row[1]==fromid+fcnt)
fcnt++;
else{
if (fcnt && readahead)
psync_file_readahead(readcache, fromid*PSYNC_FS_PAGE_SIZE, fcnt*PSYNC_FS_PAGE_SIZE);
fromid=row[1];
fcnt=1;
}
}
psync_sql_free_result(res);
if (fcnt && readahead)
psync_file_readahead(readcache, fromid*PSYNC_FS_PAGE_SIZE, fcnt*PSYNC_FS_PAGE_SIZE);
return ret;
}
static int has_page_in_db(uint64_t hash, uint64_t pageid){
psync_sql_res *res;
psync_uint_row row;
res=psync_sql_query_rdlock("SELECT pageid FROM pagecache WHERE type=+"NTO_STR(PAGE_TYPE_READ)" AND hash=? AND pageid=?");
psync_sql_bind_uint(res, 1, hash);
psync_sql_bind_uint(res, 2, pageid);
row=psync_sql_fetch_rowint(res);
psync_sql_free_result(res);
return row!=NULL;
}
static psync_int_t check_page_in_memory_by_hash(uint64_t hash, uint64_t pageid, char *buff, psync_uint_t size, psync_uint_t off){
psync_cache_page_t *page;
psync_uint_t h;
psync_int_t ret;
uint32_t crc;
time_t tm;
ret=-1;
h=pagehash_by_hash_and_pageid(hash, pageid);
pthread_mutex_lock(&cache_mutex);
psync_list_for_each_element(page, &cache_hash[h], psync_cache_page_t, list)
if (page->hash==hash && page->pageid==pageid){
psync_prefetch(page->page);
tm=psync_timer_time();
if (tm>page->lastuse+5){
page->usecnt++;
page->lastuse=tm;
}
crc=psync_crc32c(PSYNC_CRC_INITIAL, page->page, page->size);
if (unlikely(crc!=page->crc)){
debug(D_WARNING, "memory page CRC does not match %u!=%u, this is most likely memory fault or corruption, pageid %u",
(unsigned)crc, (unsigned)page->crc, (unsigned)page->pageid);
psync_list_del(&page->list);
psync_pagecache_return_free_page_locked(page);
cache_pages_in_hash--;
break;
}
if (size+off>page->size){
if (off>page->size)
size=0;
else
size=page->size-off;
}
memcpy(buff, page->page+off, size);
ret=size;
}
pthread_mutex_unlock(&cache_mutex);
return ret;
}
static int switch_memory_page_to_hash(uint64_t oldhash, uint64_t newhash, uint64_t pageid){
psync_cache_page_t *page;
psync_uint_t ho, hn;
ho=pagehash_by_hash_and_pageid(oldhash, pageid);
hn=pagehash_by_hash_and_pageid(newhash, pageid);
pthread_mutex_lock(&cache_mutex);
psync_list_for_each_element(page, &cache_hash[ho], psync_cache_page_t, list)
if (page->hash==oldhash && page->pageid==pageid && page->type==PAGE_TYPE_READ){
psync_list_del(&page->list);
page->hash=newhash;
psync_list_add_tail(&cache_hash[hn], &page->list);
pthread_mutex_unlock(&cache_mutex);
return 1;
}
pthread_mutex_unlock(&cache_mutex);
return 0;
}
typedef struct {
uint32_t lastuse;
uint32_t id;
uint16_t usecnt;
int8_t isfirst;
int8_t isxfirst;
} pagecache_entry;
static int pagecache_entry_cmp_lastuse(const void *p1, const void *p2){
const pagecache_entry *e1, *e2;
e1=(const pagecache_entry *)p1;
e2=(const pagecache_entry *)p2;
return (int)((int64_t)e2->lastuse-(int64_t)e1->lastuse);
}
static int pagecache_entry_cmp_usecnt_lastuse2(const void *p1, const void *p2){
const pagecache_entry *e1, *e2;
e1=(const pagecache_entry *)p1;
e2=(const pagecache_entry *)p2;
if (e1->usecnt>=2 && e2->usecnt<2)
return -1;
else if (e2->usecnt>=2 && e1->usecnt<2)
return 1;
else
return (int)((int64_t)e2->lastuse-(int64_t)e1->lastuse);
}
static int pagecache_entry_cmp_usecnt_lastuse4(const void *p1, const void *p2){
const pagecache_entry *e1, *e2;
e1=(const pagecache_entry *)p1;
e2=(const pagecache_entry *)p2;
if (e1->usecnt>=4 && e2->usecnt<4)
return -1;
else if (e2->usecnt>=4 && e1->usecnt<4)
return 1;
else
return (int)((int64_t)e2->lastuse-(int64_t)e1->lastuse);
}
static int pagecache_entry_cmp_usecnt_lastuse8(const void *p1, const void *p2){
const pagecache_entry *e1, *e2;
e1=(const pagecache_entry *)p1;
e2=(const pagecache_entry *)p2;
if (e1->usecnt>=8 && e2->usecnt<8)
return -1;
else if (e2->usecnt>=8 && e1->usecnt<8)
return 1;
else
return (int)((int64_t)e2->lastuse-(int64_t)e1->lastuse);
}
static int pagecache_entry_cmp_usecnt_lastuse16(const void *p1, const void *p2){
const pagecache_entry *e1, *e2;
e1=(const pagecache_entry *)p1;
e2=(const pagecache_entry *)p2;
if (e1->usecnt>=16 && e2->usecnt<16)
return -1;
else if (e2->usecnt>=16 && e1->usecnt<16)
return 1;
else
return (int)((int64_t)e2->lastuse-(int64_t)e1->lastuse);
}
static int pagecache_entry_cmp_id(const void *p1, const void *p2){
return (int)((const pagecache_entry *)p1)->id-(int)((const pagecache_entry *)p2)->id;
}
static int pagecache_entry_cmp_first_pages(const void *p1, const void *p2){
const pagecache_entry *e1, *e2;
int d;
e1=(const pagecache_entry *)p1;
e2=(const pagecache_entry *)p2;
d=(int)e2->isfirst-(int)e1->isfirst;
if (d)
return d;
else if (e1->isfirst)
return (int)((int64_t)e2->lastuse-(int64_t)e1->lastuse);
else{
d=(int)e2->isxfirst-(int)e1->isxfirst;
if (d)
return d;
else
return (int)((int64_t)e2->lastuse-(int64_t)e1->lastuse);
}
}
static int pagecache_entry_cmp_xfirst_pages(const void *p1, const void *p2){
const pagecache_entry *e1, *e2;
int d;
e1=(const pagecache_entry *)p1;
e2=(const pagecache_entry *)p2;
d=(int)e2->isxfirst-(int)e1->isxfirst;
if (d)
return d;
else
return (int)((int64_t)e2->lastuse-(int64_t)e1->lastuse);
}
/* sum should be around 90-95 percent, so after a run cache get smaller */
#define PSYNC_FS_CACHE_LRU_PERCENT 40
#define PSYNC_FS_CACHE_LRU2_PERCENT 20
#define PSYNC_FS_CACHE_LRU4_PERCENT 15
#define PSYNC_FS_CACHE_LRU8_PERCENT 10
#define PSYNC_FS_CACHE_LRU16_PERCENT 5
/* first pages percent pages are first reserved for the least recently used first pages and the above percents are
* only applied to the remainder, so it is OK if first pages percent plus all the above go above 100%
*/
#define PSYNC_FS_CACHE_LRU_FIRST_PAGES_PERCENT 15
#define PSYNC_FS_CACHE_LRU_XFIRST_PAGES_PERCENT 5
#define PSYNC_FS_FIRST_PAGES_UNDER_ID (PSYNC_FS_MIN_READAHEAD_START/PSYNC_FS_PAGE_SIZE)
#define PSYNC_FS_XFIRST_PAGES_UNDER_ID (1024*1024/PSYNC_FS_PAGE_SIZE)
static void clean_cache(){
psync_sql_res *res;
uint64_t ocnt, cnt, rcnt, i, e;
psync_uint_row row;
pagecache_entry *entries, *oentries;
debug(D_NOTICE, "cleaning cache, free cache pages %u", (unsigned)free_db_pages);
if (pthread_mutex_trylock(&clean_cache_mutex)){
debug(D_NOTICE, "cache clean already in progress, skipping");
return;
}
while (clean_cache_stoppers){
clean_cache_waiters++;
pthread_cond_wait(&clean_cache_cond, &clean_cache_mutex);
if (--clean_cache_waiters){
// leave the last waiter to do the job
pthread_mutex_unlock(&clean_cache_mutex);
return;
}
}
cnt=psync_sql_cellint("SELECT MAX(id) FROM pagecache", 0);
if (!cnt){
pthread_mutex_unlock(&clean_cache_mutex);
debug(D_NOTICE, "no entries in pagecache, cancelling cache clean");
return;
}
clean_cache_in_progress=1;
psync_sql_sync();
entries=(pagecache_entry *)psync_malloc(cnt*sizeof(pagecache_entry));
i=0;
e=0;
while (i<cnt){
res=psync_sql_query_rdlock("SELECT id, pageid, lastuse, usecnt, type FROM pagecache WHERE id>? ORDER BY id LIMIT 50000");
psync_sql_bind_uint(res, 1, e);
row=psync_sql_fetch_rowint(res);
if (unlikely(!row)){
psync_sql_free_result(res);
break;
}
do{
if (unlikely(i>=cnt))
break;
e=row[0];
if (likely(row[4]==PAGE_TYPE_READ)){
entries[i].lastuse=row[2];
entries[i].id=row[0];
if (row[3]>UINT16_MAX)
entries[i].usecnt=UINT16_MAX;
else
entries[i].usecnt=row[3];
entries[i].isfirst=row[2]<PSYNC_FS_FIRST_PAGES_UNDER_ID;
entries[i].isxfirst=row[2]<PSYNC_FS_XFIRST_PAGES_UNDER_ID;
i++;
if ((i&0x3ff)==0x3ff && psync_sql_has_waiters())
break;
}