summaryrefslogtreecommitdiff
path: root/lib/pthreadpool/pthreadpool_tevent.c
blob: 7088202d97cae8751de73b39a119622207aa6e0e (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
/*
 * Unix SMB/CIFS implementation.
 * threadpool implementation based on pthreads
 * Copyright (C) Volker Lendecke 2009,2011
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "replace.h"
#include "system/select.h"
#include "system/threads.h"
#include "system/filesys.h"
#include "pthreadpool_tevent.h"
#include "pthreadpool.h"
#include "lib/util/tevent_unix.h"
#include "lib/util/dlinklist.h"
#include "lib/util/attr.h"

/*
 * We try to give some hints to helgrind/drd
 *
 * Note ANNOTATE_BENIGN_RACE_SIZED(address, size, describtion)
 * takes an memory address range that ignored by helgrind/drd
 * 'description' is just ignored...
 *
 *
 * Note that ANNOTATE_HAPPENS_*(unique_uintptr)
 * just takes a DWORD/(void *) as unique key
 * for the barrier.
 */
#ifdef HAVE_VALGRIND_HELGRIND_H
#include <valgrind/helgrind.h>
#endif
#ifndef ANNOTATE_BENIGN_RACE_SIZED
#define ANNOTATE_BENIGN_RACE_SIZED(address, size, describtion)
#endif
#ifndef ANNOTATE_HAPPENS_BEFORE
#define ANNOTATE_HAPPENS_BEFORE(unique_uintptr)
#endif
#ifndef ANNOTATE_HAPPENS_AFTER
#define ANNOTATE_HAPPENS_AFTER(unique_uintptr)
#endif
#ifndef ANNOTATE_HAPPENS_BEFORE_FORGET_ALL
#define ANNOTATE_HAPPENS_BEFORE_FORGET_ALL(unique_uintptr)
#endif

#define PTHREAD_TEVENT_JOB_THREAD_FENCE_INIT(__job) do { \
	_UNUSED_ const struct pthreadpool_tevent_job *__j = __job; \
	ANNOTATE_BENIGN_RACE_SIZED(&__j->needs_fence, \
				   sizeof(__j->needs_fence), \
				   "race by design, protected by fence"); \
} while(0);

#ifdef WITH_PTHREADPOOL
/*
 * configure checked we have pthread and atomic_thread_fence() available
 */
#define __PTHREAD_TEVENT_JOB_THREAD_FENCE(__order) do { \
	atomic_thread_fence(__order); \
} while(0)
#else
/*
 * we're using lib/pthreadpool/pthreadpool_sync.c ...
 */
#define __PTHREAD_TEVENT_JOB_THREAD_FENCE(__order) do { } while(0)
#ifndef HAVE___THREAD
#define __thread
#endif
#endif

#define PTHREAD_TEVENT_JOB_THREAD_FENCE(__job) do { \
	_UNUSED_ const struct pthreadpool_tevent_job *__j = __job; \
	ANNOTATE_HAPPENS_BEFORE(&__job->needs_fence); \
	__PTHREAD_TEVENT_JOB_THREAD_FENCE(memory_order_seq_cst); \
	ANNOTATE_HAPPENS_AFTER(&__job->needs_fence); \
} while(0);

#define PTHREAD_TEVENT_JOB_THREAD_FENCE_FINI(__job) do { \
	_UNUSED_ const struct pthreadpool_tevent_job *__j = __job; \
	ANNOTATE_HAPPENS_BEFORE_FORGET_ALL(&__job->needs_fence); \
} while(0);

struct pthreadpool_tevent_job_state;

/*
 * We need one pthreadpool_tevent_glue object per unique combintaion of tevent
 * contexts and pthreadpool_tevent objects. Maintain a list of used tevent
 * contexts in a pthreadpool_tevent.
 */
struct pthreadpool_tevent_glue {
	struct pthreadpool_tevent_glue *prev, *next;
	struct pthreadpool_tevent *pool; /* back-pointer to owning object. */
	/* Tuple we are keeping track of in this list. */
	struct tevent_context *ev;
	struct tevent_threaded_context *tctx;
	/* recheck monitor fd event */
	struct tevent_fd *fde;
	/* Pointer to link object owned by *ev. */
	struct pthreadpool_tevent_glue_ev_link *ev_link;
	/* active jobs */
	struct pthreadpool_tevent_job_state *states;
};

/*
 * The pthreadpool_tevent_glue_ev_link and its destructor ensure we remove the
 * tevent context from our list of active event contexts if the event context
 * is destroyed.
 * This structure is talloc()'ed from the struct tevent_context *, and is a
 * back-pointer allowing the related struct pthreadpool_tevent_glue object
 * to be removed from the struct pthreadpool_tevent glue list if the owning
 * tevent_context is talloc_free()'ed.
 */
struct pthreadpool_tevent_glue_ev_link {
	struct pthreadpool_tevent_glue *glue;
};

struct pthreadpool_tevent_wrapper {
	struct pthreadpool_tevent *main_tp;
	struct pthreadpool_tevent *wrap_tp;
	const struct pthreadpool_tevent_wrapper_ops *ops;
	void *private_state;
	bool force_per_thread_cwd;
};

struct pthreadpool_tevent {
	struct pthreadpool_tevent *prev, *next;

	struct pthreadpool *pool;
	struct pthreadpool_tevent_glue *glue_list;

	struct pthreadpool_tevent_job *jobs;

	struct {
		/*
		 * This is used on the main context
		 */
		struct pthreadpool_tevent *list;

		/*
		 * This is used on the wrapper context
		 */
		struct pthreadpool_tevent_wrapper *ctx;
	} wrapper;
};

struct pthreadpool_tevent_job_state {
	struct pthreadpool_tevent_job_state *prev, *next;
	struct pthreadpool_tevent_glue *glue;
	struct tevent_context *ev;
	struct tevent_req *req;
	struct pthreadpool_tevent_job *job;
};

struct pthreadpool_tevent_job {
	struct pthreadpool_tevent_job *prev, *next;

	struct pthreadpool_tevent *pool;
	struct pthreadpool_tevent_wrapper *wrapper;
	struct pthreadpool_tevent_job_state *state;
	struct tevent_immediate *im;

	void (*fn)(void *private_data);
	void *private_data;

	/*
	 * Coordination between threads
	 *
	 * There're only one side writing each element
	 * either the main process or the job thread.
	 *
	 * The coordination is done by a full memory
	 * barrier using atomic_thread_fence(memory_order_seq_cst)
	 * wrapped in PTHREAD_TEVENT_JOB_THREAD_FENCE()
	 */
	struct {
		/*
		 * 'maycancel'
		 * set when tevent_req_cancel() is called.
		 * (only written by main thread!)
		 */
		bool maycancel;

		/*
		 * 'orphaned'
		 * set when talloc_free is called on the job request,
		 * tevent_context or pthreadpool_tevent.
		 * (only written by main thread!)
		 */
		bool orphaned;

		/*
		 * 'started'
		 * set when the job is picked up by a worker thread
		 * (only written by job thread!)
		 */
		bool started;

		/*
		 * 'wrapper'
		 * set before calling the wrapper before_job() or
		 * after_job() hooks.
		 * unset again check the hook finished.
		 * (only written by job thread!)
		 */
		bool wrapper;

		/*
		 * 'executed'
		 * set once the job function returned.
		 * (only written by job thread!)
		 */
		bool executed;

		/*
		 * 'finished'
		 * set when pthreadpool_tevent_job_signal() is entered
		 * (only written by job thread!)
		 */
		bool finished;

		/*
		 * 'dropped'
		 * set when pthreadpool_tevent_job_signal() leaves with
		 * orphaned already set.
		 * (only written by job thread!)
		 */
		bool dropped;

		/*
		 * 'signaled'
		 * set when pthreadpool_tevent_job_signal() leaves normal
		 * and the immediate event was scheduled.
		 * (only written by job thread!)
		 */
		bool signaled;

		/*
		 * 'exit_thread'
		 * maybe set during pthreadpool_tevent_job_fn()
		 * if some wrapper related code generated an error
		 * and the environment isn't safe anymore.
		 *
		 * In such a case pthreadpool_tevent_job_signal()
		 * will pick this up and therminate the current
		 * worker thread by returning -1.
		 */
		bool exit_thread; /* only written/read by job thread! */
	} needs_fence;

	bool per_thread_cwd;
};

static int pthreadpool_tevent_destructor(struct pthreadpool_tevent *pool);

static void pthreadpool_tevent_job_orphan(struct pthreadpool_tevent_job *job);

static struct pthreadpool_tevent_job *orphaned_jobs;

void pthreadpool_tevent_cleanup_orphaned_jobs(void)
{
	struct pthreadpool_tevent_job *job = NULL;
	struct pthreadpool_tevent_job *njob = NULL;

	for (job = orphaned_jobs; job != NULL; job = njob) {
		njob = job->next;

		/*
		 * The job destructor keeps the job alive
		 * (and in the list) or removes it from the list.
		 */
		TALLOC_FREE(job);
	}
}

static int pthreadpool_tevent_job_signal(int jobid,
					 void (*job_fn)(void *private_data),
					 void *job_private_data,
					 void *private_data);

int pthreadpool_tevent_init(TALLOC_CTX *mem_ctx, unsigned max_threads,
			    struct pthreadpool_tevent **presult)
{
	struct pthreadpool_tevent *pool;
	int ret;

	pthreadpool_tevent_cleanup_orphaned_jobs();

	pool = talloc_zero(mem_ctx, struct pthreadpool_tevent);
	if (pool == NULL) {
		return ENOMEM;
	}

	ret = pthreadpool_init(max_threads, &pool->pool,
			       pthreadpool_tevent_job_signal, pool);
	if (ret != 0) {
		TALLOC_FREE(pool);
		return ret;
	}

	talloc_set_destructor(pool, pthreadpool_tevent_destructor);

	*presult = pool;
	return 0;
}

static struct pthreadpool_tevent *pthreadpool_tevent_unwrap(
	struct pthreadpool_tevent *pool)
{
	struct pthreadpool_tevent_wrapper *wrapper = pool->wrapper.ctx;

	if (wrapper != NULL) {
		return wrapper->main_tp;
	}

	return pool;
}

size_t pthreadpool_tevent_max_threads(struct pthreadpool_tevent *pool)
{
	pool = pthreadpool_tevent_unwrap(pool);

	if (pool->pool == NULL) {
		return 0;
	}

	return pthreadpool_max_threads(pool->pool);
}

size_t pthreadpool_tevent_queued_jobs(struct pthreadpool_tevent *pool)
{
	pool = pthreadpool_tevent_unwrap(pool);

	if (pool->pool == NULL) {
		return 0;
	}

	return pthreadpool_queued_jobs(pool->pool);
}

bool pthreadpool_tevent_per_thread_cwd(struct pthreadpool_tevent *pool)
{
	struct pthreadpool_tevent_wrapper *wrapper = pool->wrapper.ctx;

	if (wrapper != NULL && wrapper->force_per_thread_cwd) {
		return true;
	}

	pool = pthreadpool_tevent_unwrap(pool);

	if (pool->pool == NULL) {
		return false;
	}

	return pthreadpool_per_thread_cwd(pool->pool);
}

static int pthreadpool_tevent_destructor(struct pthreadpool_tevent *pool)
{
	struct pthreadpool_tevent_job *job = NULL;
	struct pthreadpool_tevent_job *njob = NULL;
	struct pthreadpool_tevent *wrap_tp = NULL;
	struct pthreadpool_tevent *nwrap_tp = NULL;
	struct pthreadpool_tevent_glue *glue = NULL;
	int ret;

	if (pool->wrapper.ctx != NULL) {
		struct pthreadpool_tevent_wrapper *wrapper = pool->wrapper.ctx;

		pool->wrapper.ctx = NULL;
		pool = wrapper->main_tp;

		DLIST_REMOVE(pool->wrapper.list, wrapper->wrap_tp);

		for (job = pool->jobs; job != NULL; job = njob) {
			njob = job->next;

			if (job->wrapper != wrapper) {
				continue;
			}

			/*
			 * This removes the job from the list
			 *
			 * Note that it waits in case
			 * the wrapper hooks are currently
			 * executing on the job.
			 */
			pthreadpool_tevent_job_orphan(job);
		}

		/*
		 * At this point we're sure that no job
		 * still references the pthreadpool_tevent_wrapper
		 * structure, so we can free it.
		 */
		TALLOC_FREE(wrapper);

		pthreadpool_tevent_cleanup_orphaned_jobs();
		return 0;
	}

	if (pool->pool == NULL) {
		/*
		 * A dangling wrapper without main_tp.
		 */
		return 0;
	}

	ret = pthreadpool_stop(pool->pool);
	if (ret != 0) {
		return ret;
	}

	/*
	 * orphan all jobs (including wrapper jobs)
	 */
	for (job = pool->jobs; job != NULL; job = njob) {
		njob = job->next;

		/*
		 * The job this removes it from the list
		 *
		 * Note that it waits in case
		 * the wrapper hooks are currently
		 * executing on the job (thread).
		 */
		pthreadpool_tevent_job_orphan(job);
	}

	/*
	 * cleanup all existing wrappers, remember we just orphaned
	 * all jobs (including the once of the wrappers).
	 *
	 * So we just mark as broken, so that
	 * pthreadpool_tevent_job_send() won't accept new jobs.
	 */
	for (wrap_tp = pool->wrapper.list; wrap_tp != NULL; wrap_tp = nwrap_tp) {
		nwrap_tp = wrap_tp->next;

		/*
		 * Just mark them as broken, so that we can't
		 * get more jobs.
		 */
		TALLOC_FREE(wrap_tp->wrapper.ctx);

		DLIST_REMOVE(pool->wrapper.list, wrap_tp);
	}

	/*
	 * Delete all the registered
	 * tevent_context/tevent_threaded_context
	 * pairs.
	 */
	for (glue = pool->glue_list; glue != NULL; glue = pool->glue_list) {
		/* The glue destructor removes it from the list */
		TALLOC_FREE(glue);
	}
	pool->glue_list = NULL;

	ret = pthreadpool_destroy(pool->pool);
	if (ret != 0) {
		return ret;
	}
	pool->pool = NULL;

	pthreadpool_tevent_cleanup_orphaned_jobs();

	return 0;
}

struct pthreadpool_tevent *_pthreadpool_tevent_wrapper_create(
				struct pthreadpool_tevent *main_tp,
				TALLOC_CTX *mem_ctx,
				const struct pthreadpool_tevent_wrapper_ops *ops,
				void *pstate,
				size_t psize,
				const char *type,
				const char *location)
{
	void **ppstate = (void **)pstate;
	struct pthreadpool_tevent *wrap_tp = NULL;
	struct pthreadpool_tevent_wrapper *wrapper = NULL;

	pthreadpool_tevent_cleanup_orphaned_jobs();

	if (main_tp->wrapper.ctx != NULL) {
		/*
		 * stacking of wrappers is not supported
		 */
		errno = EINVAL;
		return NULL;
	}

	if (main_tp->pool == NULL) {
		/*
		 * The pool is no longer valid,
		 * most likely it was a wrapper context
		 * where the main pool was destroyed.
		 */
		errno = EINVAL;
		return NULL;
	}

	wrap_tp = talloc_zero(mem_ctx, struct pthreadpool_tevent);
	if (wrap_tp == NULL) {
		return NULL;
	}

	wrapper = talloc_zero(wrap_tp, struct pthreadpool_tevent_wrapper);
	if (wrapper == NULL) {
		TALLOC_FREE(wrap_tp);
		return NULL;
	}
	wrapper->main_tp = main_tp;
	wrapper->wrap_tp = wrap_tp;
	wrapper->ops = ops;
	wrapper->private_state = talloc_zero_size(wrapper, psize);
	if (wrapper->private_state == NULL) {
		TALLOC_FREE(wrap_tp);
		return NULL;
	}
	talloc_set_name_const(wrapper->private_state, type);

	wrap_tp->wrapper.ctx = wrapper;

	DLIST_ADD_END(main_tp->wrapper.list, wrap_tp);

	talloc_set_destructor(wrap_tp, pthreadpool_tevent_destructor);

	*ppstate = wrapper->private_state;
	return wrap_tp;
}

void pthreadpool_tevent_force_per_thread_cwd(struct pthreadpool_tevent *pool,
					     const void *private_state)
{
	struct pthreadpool_tevent_wrapper *wrapper = pool->wrapper.ctx;

	if (wrapper == NULL) {
		abort();
	}

	if (wrapper->private_state != private_state) {
		abort();
	}

	wrapper->force_per_thread_cwd = true;
}

static int pthreadpool_tevent_glue_destructor(
	struct pthreadpool_tevent_glue *glue)
{
	struct pthreadpool_tevent_job_state *state = NULL;
	struct pthreadpool_tevent_job_state *nstate = NULL;

	TALLOC_FREE(glue->fde);

	for (state = glue->states; state != NULL; state = nstate) {
		nstate = state->next;

		/* The job this removes it from the list */
		pthreadpool_tevent_job_orphan(state->job);
	}

	if (glue->pool->glue_list != NULL) {
		DLIST_REMOVE(glue->pool->glue_list, glue);
	}

	/* Ensure the ev_link destructor knows we're gone */
	glue->ev_link->glue = NULL;

	TALLOC_FREE(glue->ev_link);
	TALLOC_FREE(glue->tctx);

	return 0;
}

/*
 * Destructor called either explicitly from
 * pthreadpool_tevent_glue_destructor(), or indirectly
 * when owning tevent_context is destroyed.
 *
 * When called from pthreadpool_tevent_glue_destructor()
 * ev_link->glue is already NULL, so this does nothing.
 *
 * When called from talloc_free() of the owning
 * tevent_context we must ensure we also remove the
 * linked glue object from the list inside
 * struct pthreadpool_tevent.
 */
static int pthreadpool_tevent_glue_link_destructor(
	struct pthreadpool_tevent_glue_ev_link *ev_link)
{
	TALLOC_FREE(ev_link->glue);
	return 0;
}

static void pthreadpool_tevent_glue_monitor(struct tevent_context *ev,
					    struct tevent_fd *fde,
					    uint16_t flags,
					    void *private_data)
{
	struct pthreadpool_tevent_glue *glue =
		talloc_get_type_abort(private_data,
		struct pthreadpool_tevent_glue);
	struct pthreadpool_tevent_job *job = NULL;
	struct pthreadpool_tevent_job *njob = NULL;
	int ret = -1;

	ret = pthreadpool_restart_check_monitor_drain(glue->pool->pool);
	if (ret != 0) {
		TALLOC_FREE(glue->fde);
	}

	ret = pthreadpool_restart_check(glue->pool->pool);
	if (ret == 0) {
		/*
		 * success...
		 */
		goto done;
	}

	/*
	 * There's a problem and the pool
	 * has not a single thread available
	 * for pending jobs, so we can only
	 * stop the jobs and return an error.
	 * This is similar to a failure from
	 * pthreadpool_add_job().
	 */
	for (job = glue->pool->jobs; job != NULL; job = njob) {
		njob = job->next;

		tevent_req_defer_callback(job->state->req,
					  job->state->ev);
		tevent_req_error(job->state->req, ret);
	}

done:
	if (glue->states == NULL) {
		/*
		 * If the glue doesn't have any pending jobs
		 * we remove the glue.
		 *
		 * In order to remove the fd event.
		 */
		TALLOC_FREE(glue);
	}
}

static int pthreadpool_tevent_register_ev(
				struct pthreadpool_tevent *pool,
				struct pthreadpool_tevent_job_state *state)
{
	struct tevent_context *ev = state->ev;
	struct pthreadpool_tevent_glue *glue = NULL;
	struct pthreadpool_tevent_glue_ev_link *ev_link = NULL;
	int monitor_fd = -1;

	/*
	 * See if this tevent_context was already registered by
	 * searching the glue object list. If so we have nothing
	 * to do here - we already have a tevent_context/tevent_threaded_context
	 * pair.
	 */
	for (glue = pool->glue_list; glue != NULL; glue = glue->next) {
		if (glue->ev == state->ev) {
			state->glue = glue;
			DLIST_ADD_END(glue->states, state);
			return 0;
		}
	}

	/*
	 * Event context not yet registered - create a new glue
	 * object containing a tevent_context/tevent_threaded_context
	 * pair and put it on the list to remember this registration.
	 * We also need a link object to ensure the event context
	 * can't go away without us knowing about it.
	 */
	glue = talloc_zero(pool, struct pthreadpool_tevent_glue);
	if (glue == NULL) {
		return ENOMEM;
	}
	*glue = (struct pthreadpool_tevent_glue) {
		.pool = pool,
		.ev = ev,
	};
	talloc_set_destructor(glue, pthreadpool_tevent_glue_destructor);

	monitor_fd = pthreadpool_restart_check_monitor_fd(pool->pool);
	if (monitor_fd == -1 && errno != ENOSYS) {
		int saved_errno = errno;
		TALLOC_FREE(glue);
		return saved_errno;
	}

	if (monitor_fd != -1) {
		glue->fde = tevent_add_fd(ev,
					  glue,
					  monitor_fd,
					  TEVENT_FD_READ,
					  pthreadpool_tevent_glue_monitor,
					  glue);
		if (glue->fde == NULL) {
			close(monitor_fd);
			TALLOC_FREE(glue);
			return ENOMEM;
		}
		tevent_fd_set_auto_close(glue->fde);
	}

	/*
	 * Now allocate the link object to the event context. Note this
	 * is allocated OFF THE EVENT CONTEXT ITSELF, so if the event
	 * context is freed we are able to cleanup the glue object
	 * in the link object destructor.
	 */

	ev_link = talloc_zero(ev, struct pthreadpool_tevent_glue_ev_link);
	if (ev_link == NULL) {
		TALLOC_FREE(glue);
		return ENOMEM;
	}
	ev_link->glue = glue;
	talloc_set_destructor(ev_link, pthreadpool_tevent_glue_link_destructor);

	glue->ev_link = ev_link;

#ifdef HAVE_PTHREAD
	glue->tctx = tevent_threaded_context_create(glue, ev);
	if (glue->tctx == NULL) {
		TALLOC_FREE(ev_link);
		TALLOC_FREE(glue);
		return ENOMEM;
	}
#endif

	state->glue = glue;
	DLIST_ADD_END(glue->states, state);

	DLIST_ADD(pool->glue_list, glue);
	return 0;
}

static void pthreadpool_tevent_job_fn(void *private_data);
static void pthreadpool_tevent_job_done(struct tevent_context *ctx,
					struct tevent_immediate *im,
					void *private_data);
static bool pthreadpool_tevent_job_cancel(struct tevent_req *req);

static int pthreadpool_tevent_job_destructor(struct pthreadpool_tevent_job *job)
{
	/*
	 * We should never be called with needs_fence.orphaned == false.
	 * Only pthreadpool_tevent_job_orphan() will call TALLOC_FREE(job)
	 * after detaching from the request state, glue and pool list.
	 */
	if (!job->needs_fence.orphaned) {
		abort();
	}

	/*
	 * If the job is not finished (job->im still there)
	 * and it's still attached to the pool,
	 * we try to cancel it (before it was starts)
	 */
	if (job->im != NULL && job->pool != NULL) {
		size_t num;

		num = pthreadpool_cancel_job(job->pool->pool, 0,
					     pthreadpool_tevent_job_fn,
					     job);
		if (num != 0) {
			/*
			 * It was not too late to cancel the request.
			 *
			 * We can remove job->im, as it will never be used.
			 */
			TALLOC_FREE(job->im);
		}
	}

	PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
	if (job->needs_fence.dropped) {
		/*
		 * The signal function saw job->needs_fence.orphaned
		 * before it started the signaling via the immediate
		 * event. So we'll never geht triggered and can
		 * remove job->im and let the whole job go...
		 */
		TALLOC_FREE(job->im);
	}

	/*
	 * TODO?: We could further improve this by adjusting
	 * tevent_threaded_schedule_immediate_destructor()
	 * and allow TALLOC_FREE() during its time
	 * in the main_ev->scheduled_immediates list.
	 *
	 * PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
	 * if (state->needs_fence.signaled) {
	 *       *
	 *       * The signal function is completed
	 *       * in future we may be allowed
	 *       * to call TALLOC_FREE(job->im).
	 *       *
	 *      TALLOC_FREE(job->im);
	 * }
	 */

	/*
	 * pthreadpool_tevent_job_orphan() already removed
	 * it from pool->jobs. And we don't need try
	 * pthreadpool_cancel_job() again.
	 */
	job->pool = NULL;

	if (job->im != NULL) {
		/*
		 * state->im still there means, we need to wait for the
		 * immediate event to be triggered or just leak the memory.
		 *
		 * Move it to the orphaned list, if it's not already there.
		 */
		return -1;
	}

	/*
	 * Finally remove from the orphaned_jobs list
	 * and let talloc destroy us.
	 */
	DLIST_REMOVE(orphaned_jobs, job);

	PTHREAD_TEVENT_JOB_THREAD_FENCE_FINI(job);
	return 0;
}

static void pthreadpool_tevent_job_orphan(struct pthreadpool_tevent_job *job)
{
	job->needs_fence.orphaned = true;
	PTHREAD_TEVENT_JOB_THREAD_FENCE(job);

	/*
	 * We're the only function that sets
	 * job->state = NULL;
	 */
	if (job->state == NULL) {
		abort();
	}

	/*
	 * Once we marked the request as 'orphaned'
	 * we spin/loop if 'wrapper' is marked as active.
	 *
	 * We need to wait until the wrapper hook finished
	 * before we can set job->wrapper = NULL.
	 *
	 * This is some kind of spinlock, but with
	 * 1 millisecond sleeps in between, in order
	 * to give the thread more cpu time to finish.
	 */
	PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
	while (job->needs_fence.wrapper) {
		(void)poll(NULL, 0, 1);
		PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
	}
	job->wrapper = NULL;

	/*
	 * Once we marked the request as 'orphaned'
	 * we spin/loop if it's already marked
	 * as 'finished' (which means that
	 * pthreadpool_tevent_job_signal() was entered.
	 * If it saw 'orphaned' it will exit after setting
	 * 'dropped', otherwise it dereferences
	 * job->state->glue->{tctx,ev} until it exited
	 * after setting 'signaled'.
	 *
	 * We need to close this potential gab before
	 * we can set job->state = NULL.
	 *
	 * This is some kind of spinlock, but with
	 * 1 millisecond sleeps in between, in order
	 * to give the thread more cpu time to finish.
	 */
	PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
	while (job->needs_fence.finished) {
		if (job->needs_fence.dropped) {
			break;
		}
		if (job->needs_fence.signaled) {
			break;
		}
		(void)poll(NULL, 0, 1);
		PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
	}

	/*
	 * Once the gab is closed, we can remove
	 * the glue link.
	 */
	DLIST_REMOVE(job->state->glue->states, job->state);
	job->state->glue = NULL;

	/*
	 * We need to reparent to a long term context.
	 * And detach from the request state.
	 * Maybe the destructor will keep the memory
	 * and leak it for now.
	 */
	(void)talloc_reparent(job->state, NULL, job);
	job->state->job = NULL;
	job->state = NULL;

	/*
	 * job->pool will only be set to NULL
	 * in the first destructur run.
	 */
	if (job->pool == NULL) {
		abort();
	}

	/*
	 * Dettach it from the pool.
	 *
	 * The job might still be running,
	 * so we keep job->pool.
	 * The destructor will set it to NULL
	 * after trying pthreadpool_cancel_job()
	 */
	DLIST_REMOVE(job->pool->jobs, job);

	/*
	 * Add it to the list of orphaned jobs,
	 * which may be cleaned up later.
	 *
	 * The destructor removes it from the list
	 * when possible or it denies the free
	 * and keep it in the list.
	 */
	DLIST_ADD_END(orphaned_jobs, job);
	TALLOC_FREE(job);
}

static void pthreadpool_tevent_job_cleanup(struct tevent_req *req,
					   enum tevent_req_state req_state)
{
	struct pthreadpool_tevent_job_state *state =
		tevent_req_data(req,
		struct pthreadpool_tevent_job_state);

	if (state->job == NULL) {
		/*
		 * The job request is not scheduled in the pool
		 * yet or anymore.
		 */
		if (state->glue != NULL) {
			DLIST_REMOVE(state->glue->states, state);
			state->glue = NULL;
		}
		return;
	}

	/*
	 * We need to reparent to a long term context.
	 * Maybe the destructor will keep the memory
	 * and leak it for now.
	 */
	pthreadpool_tevent_job_orphan(state->job);
	state->job = NULL; /* not needed but looks better */
	return;
}

struct tevent_req *pthreadpool_tevent_job_send(
	TALLOC_CTX *mem_ctx, struct tevent_context *ev,
	struct pthreadpool_tevent *pool,
	void (*fn)(void *private_data), void *private_data)
{
	struct tevent_req *req = NULL;
	struct pthreadpool_tevent_job_state *state = NULL;
	struct pthreadpool_tevent_job *job = NULL;
	int ret;
	struct pthreadpool_tevent *caller_pool = pool;
	struct pthreadpool_tevent_wrapper *wrapper = pool->wrapper.ctx;

	pthreadpool_tevent_cleanup_orphaned_jobs();

	if (wrapper != NULL) {
		pool = wrapper->main_tp;
	}

	req = tevent_req_create(mem_ctx, &state,
				struct pthreadpool_tevent_job_state);
	if (req == NULL) {
		return NULL;
	}
	state->ev = ev;
	state->req = req;

	tevent_req_set_cleanup_fn(req, pthreadpool_tevent_job_cleanup);

	if (pool == NULL) {
		tevent_req_error(req, EINVAL);
		return tevent_req_post(req, ev);
	}
	if (pool->pool == NULL) {
		tevent_req_error(req, EINVAL);
		return tevent_req_post(req, ev);
	}

	ret = pthreadpool_tevent_register_ev(pool, state);
	if (tevent_req_error(req, ret)) {
		return tevent_req_post(req, ev);
	}

	job = talloc_zero(state, struct pthreadpool_tevent_job);
	if (tevent_req_nomem(job, req)) {
		return tevent_req_post(req, ev);
	}
	job->pool = pool;
	job->wrapper = wrapper;
	job->fn = fn;
	job->private_data = private_data;
	job->im = tevent_create_immediate(state->job);
	if (tevent_req_nomem(job->im, req)) {
		return tevent_req_post(req, ev);
	}
	PTHREAD_TEVENT_JOB_THREAD_FENCE_INIT(job);
	job->per_thread_cwd = pthreadpool_tevent_per_thread_cwd(caller_pool);
	talloc_set_destructor(job, pthreadpool_tevent_job_destructor);
	DLIST_ADD_END(job->pool->jobs, job);
	job->state = state;
	state->job = job;

	ret = pthreadpool_add_job(job->pool->pool, 0,
				  pthreadpool_tevent_job_fn,
				  job);
	if (tevent_req_error(req, ret)) {
		return tevent_req_post(req, ev);
	}

	tevent_req_set_cancel_fn(req, pthreadpool_tevent_job_cancel);
	return req;
}

static __thread struct pthreadpool_tevent_job *current_job;

bool pthreadpool_tevent_current_job_canceled(void)
{
	if (current_job == NULL) {
		/*
		 * Should only be called from within
		 * the job function.
		 */
		abort();
		return false;
	}

	PTHREAD_TEVENT_JOB_THREAD_FENCE(current_job);
	return current_job->needs_fence.maycancel;
}

bool pthreadpool_tevent_current_job_orphaned(void)
{
	if (current_job == NULL) {
		/*
		 * Should only be called from within
		 * the job function.
		 */
		abort();
		return false;
	}

	PTHREAD_TEVENT_JOB_THREAD_FENCE(current_job);
	return current_job->needs_fence.orphaned;
}

bool pthreadpool_tevent_current_job_continue(void)
{
	if (current_job == NULL) {
		/*
		 * Should only be called from within
		 * the job function.
		 */
		abort();
		return false;
	}

	PTHREAD_TEVENT_JOB_THREAD_FENCE(current_job);
	if (current_job->needs_fence.maycancel) {
		return false;
	}
	PTHREAD_TEVENT_JOB_THREAD_FENCE(current_job);
	if (current_job->needs_fence.orphaned) {
		return false;
	}

	return true;
}

bool pthreadpool_tevent_current_job_per_thread_cwd(void)
{
	if (current_job == NULL) {
		/*
		 * Should only be called from within
		 * the job function.
		 */
		abort();
		return false;
	}

	return current_job->per_thread_cwd;
}

static void pthreadpool_tevent_job_fn(void *private_data)
{
	struct pthreadpool_tevent_job *job =
		talloc_get_type_abort(private_data,
		struct pthreadpool_tevent_job);
	struct pthreadpool_tevent_wrapper *wrapper = NULL;

	current_job = job;
	job->needs_fence.started = true;
	PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
	if (job->needs_fence.orphaned) {
		current_job = NULL;
		return;
	}

	wrapper = job->wrapper;
	if (wrapper != NULL) {
		bool ok;

		job->needs_fence.wrapper = true;
		PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
		if (job->needs_fence.orphaned) {
			job->needs_fence.wrapper = false;
			PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
			current_job = NULL;
			return;
		}
		ok = wrapper->ops->before_job(wrapper->wrap_tp,
					      wrapper->private_state,
					      wrapper->main_tp,
					      __location__);
		job->needs_fence.wrapper = false;
		PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
		if (!ok) {
			job->needs_fence.exit_thread = true;
			PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
			current_job = NULL;
			return;
		}
	}

	job->fn(job->private_data);

	job->needs_fence.executed = true;
	PTHREAD_TEVENT_JOB_THREAD_FENCE(job);

	if (wrapper != NULL) {
		bool ok;

		job->needs_fence.wrapper = true;
		PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
		if (job->needs_fence.orphaned) {
			job->needs_fence.wrapper = false;
			job->needs_fence.exit_thread = true;
			PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
			current_job = NULL;
			return;
		}
		ok = wrapper->ops->after_job(wrapper->wrap_tp,
					     wrapper->private_state,
					     wrapper->main_tp,
					     __location__);
		job->needs_fence.wrapper = false;
		PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
		if (!ok) {
			job->needs_fence.exit_thread = true;
			PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
			current_job = NULL;
			return;
		}
	}

	current_job = NULL;
}

static int pthreadpool_tevent_job_signal(int jobid,
					 void (*job_fn)(void *private_data),
					 void *job_private_data,
					 void *private_data)
{
	struct pthreadpool_tevent_job *job =
		talloc_get_type_abort(job_private_data,
		struct pthreadpool_tevent_job);

	job->needs_fence.finished = true;
	PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
	if (job->needs_fence.orphaned) {
		/* Request already gone */
		job->needs_fence.dropped = true;
		PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
		if (job->needs_fence.exit_thread) {
			/*
			 * A problem with the wrapper the current job/worker
			 * thread needs to terminate.
			 *
			 * The pthreadpool_tevent is already gone.
			 */
			return -1;
		}
		return 0;
	}

	/*
	 * state and state->glue are valid,
	 * see the job->needs_fence.finished
	 * "spinlock" loop in
	 * pthreadpool_tevent_job_orphan()
	 */
	if (job->state->glue->tctx != NULL) {
		/* with HAVE_PTHREAD */
		tevent_threaded_schedule_immediate(job->state->glue->tctx,
						   job->im,
						   pthreadpool_tevent_job_done,
						   job);
	} else {
		/* without HAVE_PTHREAD */
		tevent_schedule_immediate(job->im,
					  job->state->glue->ev,
					  pthreadpool_tevent_job_done,
					  job);
	}

	job->needs_fence.signaled = true;
	PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
	if (job->needs_fence.exit_thread) {
		/*
		 * A problem with the wrapper the current job/worker
		 * thread needs to terminate.
		 *
		 * The pthreadpool_tevent is already gone.
		 */
		return -1;
	}
	return 0;
}

static void pthreadpool_tevent_job_done(struct tevent_context *ctx,
					struct tevent_immediate *im,
					void *private_data)
{
	struct pthreadpool_tevent_job *job =
		talloc_get_type_abort(private_data,
		struct pthreadpool_tevent_job);
	struct pthreadpool_tevent_job_state *state = job->state;

	TALLOC_FREE(job->im);

	if (state == NULL) {
		/* Request already gone */
		TALLOC_FREE(job);
		return;
	}

	/*
	 * pthreadpool_tevent_job_cleanup()
	 * (called by tevent_req_done() or
	 * tevent_req_error()) will destroy the job.
	 */

	if (job->needs_fence.executed) {
		tevent_req_done(state->req);
		return;
	}

	tevent_req_error(state->req, ENOEXEC);
	return;
}

static bool pthreadpool_tevent_job_cancel(struct tevent_req *req)
{
	struct pthreadpool_tevent_job_state *state =
		tevent_req_data(req,
		struct pthreadpool_tevent_job_state);
	struct pthreadpool_tevent_job *job = state->job;
	size_t num;

	if (job == NULL) {
		return false;
	}

	job->needs_fence.maycancel = true;
	PTHREAD_TEVENT_JOB_THREAD_FENCE(job);
	if (job->needs_fence.started) {
		/*
		 * It was too late to cancel the request.
		 *
		 * The job still has the chance to look
		 * at pthreadpool_tevent_current_job_canceled()
		 * or pthreadpool_tevent_current_job_continue()
		 */
		return false;
	}

	num = pthreadpool_cancel_job(job->pool->pool, 0,
				     pthreadpool_tevent_job_fn,
				     job);
	if (num == 0) {
		/*
		 * It was too late to cancel the request.
		 */
		return false;
	}

	/*
	 * It was not too late to cancel the request.
	 *
	 * We can remove job->im, as it will never be used.
	 */
	TALLOC_FREE(job->im);

	/*
	 * pthreadpool_tevent_job_cleanup()
	 * will destroy the job.
	 */
	tevent_req_defer_callback(req, state->ev);
	tevent_req_error(req, ECANCELED);
	return true;
}

int pthreadpool_tevent_job_recv(struct tevent_req *req)
{
	return tevent_req_simple_recv_unix(req);
}