aboutsummaryrefslogtreecommitdiffstats
path: root/module/spl/spl-taskq.c
blob: bfcf651af693b0b16eb7c15b5443e946f1db4a2e (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
/*
 *  Copyright (C) 2007-2010 Lawrence Livermore National Security, LLC.
 *  Copyright (C) 2007 The Regents of the University of California.
 *  Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
 *  Written by Brian Behlendorf <behlendorf1@llnl.gov>.
 *  UCRL-CODE-235197
 *
 *  This file is part of the SPL, Solaris Porting Layer.
 *  For details, see <http://zfsonlinux.org/>.
 *
 *  The SPL 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 2 of the License, or (at your
 *  option) any later version.
 *
 *  The SPL 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 the SPL.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  Solaris Porting Layer (SPL) Task Queue Implementation.
 */

#include <sys/taskq.h>
#include <sys/kmem.h>
#include <sys/tsd.h>

int spl_taskq_thread_bind = 0;
module_param(spl_taskq_thread_bind, int, 0644);
MODULE_PARM_DESC(spl_taskq_thread_bind, "Bind taskq thread to CPU by default");


int spl_taskq_thread_dynamic = 1;
module_param(spl_taskq_thread_dynamic, int, 0644);
MODULE_PARM_DESC(spl_taskq_thread_dynamic, "Allow dynamic taskq threads");

int spl_taskq_thread_priority = 1;
module_param(spl_taskq_thread_priority, int, 0644);
MODULE_PARM_DESC(spl_taskq_thread_priority,
	"Allow non-default priority for taskq threads");

int spl_taskq_thread_sequential = 4;
module_param(spl_taskq_thread_sequential, int, 0644);
MODULE_PARM_DESC(spl_taskq_thread_sequential,
	"Create new taskq threads after N sequential tasks");

/* Global system-wide dynamic task queue available for all consumers */
taskq_t *system_taskq;
EXPORT_SYMBOL(system_taskq);

/* Private dedicated taskq for creating new taskq threads on demand. */
static taskq_t *dynamic_taskq;
static taskq_thread_t *taskq_thread_create(taskq_t *);

/* List of all taskqs */
LIST_HEAD(tq_list);
DECLARE_RWSEM(tq_list_sem);
static uint_t taskq_tsd;

static int
task_km_flags(uint_t flags)
{
	if (flags & TQ_NOSLEEP)
		return (KM_NOSLEEP);

	if (flags & TQ_PUSHPAGE)
		return (KM_PUSHPAGE);

	return (KM_SLEEP);
}

/*
 * taskq_find_by_name - Find the largest instance number of a named taskq.
 */
static int
taskq_find_by_name(const char *name)
{
	struct list_head *tql;
	taskq_t *tq;

	list_for_each_prev(tql, &tq_list) {
		tq = list_entry(tql, taskq_t, tq_taskqs);
		if (strcmp(name, tq->tq_name) == 0)
			return tq->tq_instance;
	}
	return (-1);
}

/*
 * NOTE: Must be called with tq->tq_lock held, returns a list_t which
 * is not attached to the free, work, or pending taskq lists.
 */
static taskq_ent_t *
task_alloc(taskq_t *tq, uint_t flags, unsigned long *irqflags)
{
	taskq_ent_t *t;
	int count = 0;

	ASSERT(tq);
	ASSERT(spin_is_locked(&tq->tq_lock));
retry:
	/* Acquire taskq_ent_t's from free list if available */
	if (!list_empty(&tq->tq_free_list) && !(flags & TQ_NEW)) {
		t = list_entry(tq->tq_free_list.next, taskq_ent_t, tqent_list);

		ASSERT(!(t->tqent_flags & TQENT_FLAG_PREALLOC));
		ASSERT(!(t->tqent_flags & TQENT_FLAG_CANCEL));
		ASSERT(!timer_pending(&t->tqent_timer));

		list_del_init(&t->tqent_list);
		return (t);
	}

	/* Free list is empty and memory allocations are prohibited */
	if (flags & TQ_NOALLOC)
		return (NULL);

	/* Hit maximum taskq_ent_t pool size */
	if (tq->tq_nalloc >= tq->tq_maxalloc) {
		if (flags & TQ_NOSLEEP)
			return (NULL);

		/*
		 * Sleep periodically polling the free list for an available
		 * taskq_ent_t. Dispatching with TQ_SLEEP should always succeed
		 * but we cannot block forever waiting for an taskq_ent_t to
		 * show up in the free list, otherwise a deadlock can happen.
		 *
		 * Therefore, we need to allocate a new task even if the number
		 * of allocated tasks is above tq->tq_maxalloc, but we still
		 * end up delaying the task allocation by one second, thereby
		 * throttling the task dispatch rate.
		 */
		spin_unlock_irqrestore(&tq->tq_lock, *irqflags);
		schedule_timeout(HZ / 100);
		spin_lock_irqsave_nested(&tq->tq_lock, *irqflags,
		    tq->tq_lock_class);
		if (count < 100) {
			count++;
			goto retry;
		}
	}

	spin_unlock_irqrestore(&tq->tq_lock, *irqflags);
	t = kmem_alloc(sizeof (taskq_ent_t), task_km_flags(flags));
	spin_lock_irqsave_nested(&tq->tq_lock, *irqflags, tq->tq_lock_class);

	if (t) {
		taskq_init_ent(t);
		tq->tq_nalloc++;
	}

	return (t);
}

/*
 * NOTE: Must be called with tq->tq_lock held, expects the taskq_ent_t
 * to already be removed from the free, work, or pending taskq lists.
 */
static void
task_free(taskq_t *tq, taskq_ent_t *t)
{
	ASSERT(tq);
	ASSERT(t);
	ASSERT(spin_is_locked(&tq->tq_lock));
	ASSERT(list_empty(&t->tqent_list));
	ASSERT(!timer_pending(&t->tqent_timer));

	kmem_free(t, sizeof (taskq_ent_t));
	tq->tq_nalloc--;
}

/*
 * NOTE: Must be called with tq->tq_lock held, either destroys the
 * taskq_ent_t if too many exist or moves it to the free list for later use.
 */
static void
task_done(taskq_t *tq, taskq_ent_t *t)
{
	ASSERT(tq);
	ASSERT(t);
	ASSERT(spin_is_locked(&tq->tq_lock));

	/* Wake tasks blocked in taskq_wait_id() */
	wake_up_all(&t->tqent_waitq);

	list_del_init(&t->tqent_list);

	if (tq->tq_nalloc <= tq->tq_minalloc) {
		t->tqent_id = 0;
		t->tqent_func = NULL;
		t->tqent_arg = NULL;
		t->tqent_flags = 0;

		list_add_tail(&t->tqent_list, &tq->tq_free_list);
	} else {
		task_free(tq, t);
	}
}

/*
 * When a delayed task timer expires remove it from the delay list and
 * add it to the priority list in order for immediate processing.
 */
static void
task_expire(unsigned long data)
{
	taskq_ent_t *w, *t = (taskq_ent_t *)data;
	taskq_t *tq = t->tqent_taskq;
	struct list_head *l;
	unsigned long flags;

	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);

	if (t->tqent_flags & TQENT_FLAG_CANCEL) {
		ASSERT(list_empty(&t->tqent_list));
		spin_unlock_irqrestore(&tq->tq_lock, flags);
		return;
	}

	t->tqent_birth = jiffies;
	/*
	 * The priority list must be maintained in strict task id order
	 * from lowest to highest for lowest_id to be easily calculable.
	 */
	list_del(&t->tqent_list);
	list_for_each_prev(l, &tq->tq_prio_list) {
		w = list_entry(l, taskq_ent_t, tqent_list);
		if (w->tqent_id < t->tqent_id) {
			list_add(&t->tqent_list, l);
			break;
		}
	}
	if (l == &tq->tq_prio_list)
		list_add(&t->tqent_list, &tq->tq_prio_list);

	spin_unlock_irqrestore(&tq->tq_lock, flags);

	wake_up(&tq->tq_work_waitq);
}

/*
 * Returns the lowest incomplete taskqid_t.  The taskqid_t may
 * be queued on the pending list, on the priority list, on the
 * delay list, or on the work list currently being handled, but
 * it is not 100% complete yet.
 */
static taskqid_t
taskq_lowest_id(taskq_t *tq)
{
	taskqid_t lowest_id = tq->tq_next_id;
	taskq_ent_t *t;
	taskq_thread_t *tqt;

	ASSERT(tq);
	ASSERT(spin_is_locked(&tq->tq_lock));

	if (!list_empty(&tq->tq_pend_list)) {
		t = list_entry(tq->tq_pend_list.next, taskq_ent_t, tqent_list);
		lowest_id = MIN(lowest_id, t->tqent_id);
	}

	if (!list_empty(&tq->tq_prio_list)) {
		t = list_entry(tq->tq_prio_list.next, taskq_ent_t, tqent_list);
		lowest_id = MIN(lowest_id, t->tqent_id);
	}

	if (!list_empty(&tq->tq_delay_list)) {
		t = list_entry(tq->tq_delay_list.next, taskq_ent_t, tqent_list);
		lowest_id = MIN(lowest_id, t->tqent_id);
	}

	if (!list_empty(&tq->tq_active_list)) {
		tqt = list_entry(tq->tq_active_list.next, taskq_thread_t,
		    tqt_active_list);
		ASSERT(tqt->tqt_id != 0);
		lowest_id = MIN(lowest_id, tqt->tqt_id);
	}

	return (lowest_id);
}

/*
 * Insert a task into a list keeping the list sorted by increasing taskqid.
 */
static void
taskq_insert_in_order(taskq_t *tq, taskq_thread_t *tqt)
{
	taskq_thread_t *w;
	struct list_head *l;

	ASSERT(tq);
	ASSERT(tqt);
	ASSERT(spin_is_locked(&tq->tq_lock));

	list_for_each_prev(l, &tq->tq_active_list) {
		w = list_entry(l, taskq_thread_t, tqt_active_list);
		if (w->tqt_id < tqt->tqt_id) {
			list_add(&tqt->tqt_active_list, l);
			break;
		}
	}
	if (l == &tq->tq_active_list)
		list_add(&tqt->tqt_active_list, &tq->tq_active_list);
}

/*
 * Find and return a task from the given list if it exists.  The list
 * must be in lowest to highest task id order.
 */
static taskq_ent_t *
taskq_find_list(taskq_t *tq, struct list_head *lh, taskqid_t id)
{
	struct list_head *l;
	taskq_ent_t *t;

	ASSERT(spin_is_locked(&tq->tq_lock));

	list_for_each(l, lh) {
		t = list_entry(l, taskq_ent_t, tqent_list);

		if (t->tqent_id == id)
			return (t);

		if (t->tqent_id > id)
			break;
	}

	return (NULL);
}

/*
 * Find an already dispatched task given the task id regardless of what
 * state it is in.  If a task is still pending or executing it will be
 * returned and 'active' set appropriately.  If the task has already
 * been run then NULL is returned.
 */
static taskq_ent_t *
taskq_find(taskq_t *tq, taskqid_t id, int *active)
{
	taskq_thread_t *tqt;
	struct list_head *l;
	taskq_ent_t *t;

	ASSERT(spin_is_locked(&tq->tq_lock));
	*active = 0;

	t = taskq_find_list(tq, &tq->tq_delay_list, id);
	if (t)
		return (t);

	t = taskq_find_list(tq, &tq->tq_prio_list, id);
	if (t)
		return (t);

	t = taskq_find_list(tq, &tq->tq_pend_list, id);
	if (t)
		return (t);

	list_for_each(l, &tq->tq_active_list) {
		tqt = list_entry(l, taskq_thread_t, tqt_active_list);
		if (tqt->tqt_id == id) {
			t = tqt->tqt_task;
			*active = 1;
			return (t);
		}
	}

	return (NULL);
}

/*
 * Theory for the taskq_wait_id(), taskq_wait_outstanding(), and
 * taskq_wait() functions below.
 *
 * Taskq waiting is accomplished by tracking the lowest outstanding task
 * id and the next available task id.  As tasks are dispatched they are
 * added to the tail of the pending, priority, or delay lists.  As worker
 * threads become available the tasks are removed from the heads of these
 * lists and linked to the worker threads.  This ensures the lists are
 * kept sorted by lowest to highest task id.
 *
 * Therefore the lowest outstanding task id can be quickly determined by
 * checking the head item from all of these lists.  This value is stored
 * with the taskq as the lowest id.  It only needs to be recalculated when
 * either the task with the current lowest id completes or is canceled.
 *
 * By blocking until the lowest task id exceeds the passed task id the
 * taskq_wait_outstanding() function can be easily implemented.  Similarly,
 * by blocking until the lowest task id matches the next task id taskq_wait()
 * can be implemented.
 *
 * Callers should be aware that when there are multiple worked threads it
 * is possible for larger task ids to complete before smaller ones.  Also
 * when the taskq contains delay tasks with small task ids callers may
 * block for a considerable length of time waiting for them to expire and
 * execute.
 */
static int
taskq_wait_id_check(taskq_t *tq, taskqid_t id)
{
	int active = 0;
	int rc;
	unsigned long flags;

	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
	rc = (taskq_find(tq, id, &active) == NULL);
	spin_unlock_irqrestore(&tq->tq_lock, flags);

	return (rc);
}

/*
 * The taskq_wait_id() function blocks until the passed task id completes.
 * This does not guarantee that all lower task ids have completed.
 */
void
taskq_wait_id(taskq_t *tq, taskqid_t id)
{
	wait_event(tq->tq_wait_waitq, taskq_wait_id_check(tq, id));
}
EXPORT_SYMBOL(taskq_wait_id);

static int
taskq_wait_outstanding_check(taskq_t *tq, taskqid_t id)
{
	int rc;
	unsigned long flags;

	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
	rc = (id < tq->tq_lowest_id);
	spin_unlock_irqrestore(&tq->tq_lock, flags);

	return (rc);
}

/*
 * The taskq_wait_outstanding() function will block until all tasks with a
 * lower taskqid than the passed 'id' have been completed.  Note that all
 * task id's are assigned monotonically at dispatch time.  Zero may be
 * passed for the id to indicate all tasks dispatch up to this point,
 * but not after, should be waited for.
 */
void
taskq_wait_outstanding(taskq_t *tq, taskqid_t id)
{
	wait_event(tq->tq_wait_waitq,
	    taskq_wait_outstanding_check(tq, id ? id : tq->tq_next_id - 1));
}
EXPORT_SYMBOL(taskq_wait_outstanding);

static int
taskq_wait_check(taskq_t *tq)
{
	int rc;
	unsigned long flags;

	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
	rc = (tq->tq_lowest_id == tq->tq_next_id);
	spin_unlock_irqrestore(&tq->tq_lock, flags);

	return (rc);
}

/*
 * The taskq_wait() function will block until the taskq is empty.
 * This means that if a taskq re-dispatches work to itself taskq_wait()
 * callers will block indefinitely.
 */
void
taskq_wait(taskq_t *tq)
{
	wait_event(tq->tq_wait_waitq, taskq_wait_check(tq));
}
EXPORT_SYMBOL(taskq_wait);

int
taskq_member(taskq_t *tq, kthread_t *t)
{
	return (tq == (taskq_t *)tsd_get_by_thread(taskq_tsd, t));
}
EXPORT_SYMBOL(taskq_member);

/*
 * Cancel an already dispatched task given the task id.  Still pending tasks
 * will be immediately canceled, and if the task is active the function will
 * block until it completes.  Preallocated tasks which are canceled must be
 * freed by the caller.
 */
int
taskq_cancel_id(taskq_t *tq, taskqid_t id)
{
	taskq_ent_t *t;
	int active = 0;
	int rc = ENOENT;
	unsigned long flags;

	ASSERT(tq);

	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
	t = taskq_find(tq, id, &active);
	if (t && !active) {
		list_del_init(&t->tqent_list);
		t->tqent_flags |= TQENT_FLAG_CANCEL;

		/*
		 * When canceling the lowest outstanding task id we
		 * must recalculate the new lowest outstanding id.
		 */
		if (tq->tq_lowest_id == t->tqent_id) {
			tq->tq_lowest_id = taskq_lowest_id(tq);
			ASSERT3S(tq->tq_lowest_id, >, t->tqent_id);
		}

		/*
		 * The task_expire() function takes the tq->tq_lock so drop
		 * drop the lock before synchronously cancelling the timer.
		 */
		if (timer_pending(&t->tqent_timer)) {
			spin_unlock_irqrestore(&tq->tq_lock, flags);
			del_timer_sync(&t->tqent_timer);
			spin_lock_irqsave_nested(&tq->tq_lock, flags,
			    tq->tq_lock_class);
		}

		if (!(t->tqent_flags & TQENT_FLAG_PREALLOC))
			task_done(tq, t);

		rc = 0;
	}
	spin_unlock_irqrestore(&tq->tq_lock, flags);

	if (active) {
		taskq_wait_id(tq, id);
		rc = EBUSY;
	}

	return (rc);
}
EXPORT_SYMBOL(taskq_cancel_id);

static int taskq_thread_spawn(taskq_t *tq);

taskqid_t
taskq_dispatch(taskq_t *tq, task_func_t func, void *arg, uint_t flags)
{
	taskq_ent_t *t;
	taskqid_t rc = 0;
	unsigned long irqflags;

	ASSERT(tq);
	ASSERT(func);

	spin_lock_irqsave_nested(&tq->tq_lock, irqflags, tq->tq_lock_class);

	/* Taskq being destroyed and all tasks drained */
	if (!(tq->tq_flags & TASKQ_ACTIVE))
		goto out;

	/* Do not queue the task unless there is idle thread for it */
	ASSERT(tq->tq_nactive <= tq->tq_nthreads);
	if ((flags & TQ_NOQUEUE) && (tq->tq_nactive == tq->tq_nthreads)) {
		/* Dynamic taskq may be able to spawn another thread */
		if (!(tq->tq_flags & TASKQ_DYNAMIC) || taskq_thread_spawn(tq) == 0)
			goto out;
	}

	if ((t = task_alloc(tq, flags, &irqflags)) == NULL)
		goto out;

	spin_lock(&t->tqent_lock);

	/* Queue to the front of the list to enforce TQ_NOQUEUE semantics */
	if (flags & TQ_NOQUEUE)
		list_add(&t->tqent_list, &tq->tq_prio_list);
	/* Queue to the priority list instead of the pending list */
	else if (flags & TQ_FRONT)
		list_add_tail(&t->tqent_list, &tq->tq_prio_list);
	else
		list_add_tail(&t->tqent_list, &tq->tq_pend_list);

	t->tqent_id = rc = tq->tq_next_id;
	tq->tq_next_id++;
	t->tqent_func = func;
	t->tqent_arg = arg;
	t->tqent_taskq = tq;
	t->tqent_timer.data = 0;
	t->tqent_timer.function = NULL;
	t->tqent_timer.expires = 0;
	t->tqent_birth = jiffies;

	ASSERT(!(t->tqent_flags & TQENT_FLAG_PREALLOC));

	spin_unlock(&t->tqent_lock);

	wake_up(&tq->tq_work_waitq);
out:
	/* Spawn additional taskq threads if required. */
	if (!(flags & TQ_NOQUEUE) && tq->tq_nactive == tq->tq_nthreads)
		(void) taskq_thread_spawn(tq);

	spin_unlock_irqrestore(&tq->tq_lock, irqflags);
	return (rc);
}
EXPORT_SYMBOL(taskq_dispatch);

taskqid_t
taskq_dispatch_delay(taskq_t *tq, task_func_t func, void *arg,
    uint_t flags, clock_t expire_time)
{
	taskqid_t rc = 0;
	taskq_ent_t *t;
	unsigned long irqflags;

	ASSERT(tq);
	ASSERT(func);

	spin_lock_irqsave_nested(&tq->tq_lock, irqflags, tq->tq_lock_class);

	/* Taskq being destroyed and all tasks drained */
	if (!(tq->tq_flags & TASKQ_ACTIVE))
		goto out;

	if ((t = task_alloc(tq, flags, &irqflags)) == NULL)
		goto out;

	spin_lock(&t->tqent_lock);

	/* Queue to the delay list for subsequent execution */
	list_add_tail(&t->tqent_list, &tq->tq_delay_list);

	t->tqent_id = rc = tq->tq_next_id;
	tq->tq_next_id++;
	t->tqent_func = func;
	t->tqent_arg = arg;
	t->tqent_taskq = tq;
	t->tqent_timer.data = (unsigned long)t;
	t->tqent_timer.function = task_expire;
	t->tqent_timer.expires = (unsigned long)expire_time;
	add_timer(&t->tqent_timer);

	ASSERT(!(t->tqent_flags & TQENT_FLAG_PREALLOC));

	spin_unlock(&t->tqent_lock);
out:
	/* Spawn additional taskq threads if required. */
	if (tq->tq_nactive == tq->tq_nthreads)
		(void) taskq_thread_spawn(tq);
	spin_unlock_irqrestore(&tq->tq_lock, irqflags);
	return (rc);
}
EXPORT_SYMBOL(taskq_dispatch_delay);

void
taskq_dispatch_ent(taskq_t *tq, task_func_t func, void *arg, uint_t flags,
    taskq_ent_t *t)
{
	unsigned long irqflags;
	ASSERT(tq);
	ASSERT(func);

	spin_lock_irqsave_nested(&tq->tq_lock, irqflags,
	    tq->tq_lock_class);

	/* Taskq being destroyed and all tasks drained */
	if (!(tq->tq_flags & TASKQ_ACTIVE)) {
		t->tqent_id = 0;
		goto out;
	}

	if ((flags & TQ_NOQUEUE) && (tq->tq_nactive == tq->tq_nthreads)) {
		/* Dynamic taskq may be able to spawn another thread */
		if (!(tq->tq_flags & TASKQ_DYNAMIC) || taskq_thread_spawn(tq) == 0)
			goto out2;
		flags |= TQ_FRONT;
	}

	spin_lock(&t->tqent_lock);

	/*
	 * Mark it as a prealloc'd task.  This is important
	 * to ensure that we don't free it later.
	 */
	t->tqent_flags |= TQENT_FLAG_PREALLOC;

	/* Queue to the priority list instead of the pending list */
	if (flags & TQ_FRONT)
		list_add_tail(&t->tqent_list, &tq->tq_prio_list);
	else
		list_add_tail(&t->tqent_list, &tq->tq_pend_list);

	t->tqent_id = tq->tq_next_id;
	tq->tq_next_id++;
	t->tqent_func = func;
	t->tqent_arg = arg;
	t->tqent_taskq = tq;
	t->tqent_birth = jiffies;

	spin_unlock(&t->tqent_lock);

	wake_up(&tq->tq_work_waitq);
out:
	/* Spawn additional taskq threads if required. */
	if (tq->tq_nactive == tq->tq_nthreads)
		(void) taskq_thread_spawn(tq);
out2:
	spin_unlock_irqrestore(&tq->tq_lock, irqflags);
}
EXPORT_SYMBOL(taskq_dispatch_ent);

int
taskq_empty_ent(taskq_ent_t *t)
{
	return (list_empty(&t->tqent_list));
}
EXPORT_SYMBOL(taskq_empty_ent);

void
taskq_init_ent(taskq_ent_t *t)
{
	spin_lock_init(&t->tqent_lock);
	init_waitqueue_head(&t->tqent_waitq);
	init_timer(&t->tqent_timer);
	INIT_LIST_HEAD(&t->tqent_list);
	t->tqent_id = 0;
	t->tqent_func = NULL;
	t->tqent_arg = NULL;
	t->tqent_flags = 0;
	t->tqent_taskq = NULL;
}
EXPORT_SYMBOL(taskq_init_ent);

/*
 * Return the next pending task, preference is given to tasks on the
 * priority list which were dispatched with TQ_FRONT.
 */
static taskq_ent_t *
taskq_next_ent(taskq_t *tq)
{
	struct list_head *list;

	ASSERT(spin_is_locked(&tq->tq_lock));

	if (!list_empty(&tq->tq_prio_list))
		list = &tq->tq_prio_list;
	else if (!list_empty(&tq->tq_pend_list))
		list = &tq->tq_pend_list;
	else
		return (NULL);

	return (list_entry(list->next, taskq_ent_t, tqent_list));
}

/*
 * Spawns a new thread for the specified taskq.
 */
static void
taskq_thread_spawn_task(void *arg)
{
	taskq_t *tq = (taskq_t *)arg;
	unsigned long flags;

	(void) taskq_thread_create(tq);

	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
	tq->tq_nspawn--;
	spin_unlock_irqrestore(&tq->tq_lock, flags);
}

/*
 * Spawn addition threads for dynamic taskqs (TASKQ_DYNAMIC) the current
 * number of threads is insufficient to handle the pending tasks.  These
 * new threads must be created by the dedicated dynamic_taskq to avoid
 * deadlocks between thread creation and memory reclaim.  The system_taskq
 * which is also a dynamic taskq cannot be safely used for this.
 */
static int
taskq_thread_spawn(taskq_t *tq)
{
	int spawning = 0;

	if (!(tq->tq_flags & TASKQ_DYNAMIC))
		return (0);

	if ((tq->tq_nthreads + tq->tq_nspawn < tq->tq_maxthreads) &&
	    (tq->tq_flags & TASKQ_ACTIVE)) {
		spawning = (++tq->tq_nspawn);
		taskq_dispatch(dynamic_taskq, taskq_thread_spawn_task,
		    tq, TQ_NOSLEEP);
	}

	return (spawning);
}

/*
 * Threads in a dynamic taskq should only exit once it has been completely
 * drained and no other threads are actively servicing tasks.  This prevents
 * threads from being created and destroyed more than is required.
 *
 * The first thread is the thread list is treated as the primary thread.
 * There is nothing special about the primary thread but in order to avoid
 * all the taskq pids from changing we opt to make it long running.
 */
static int
taskq_thread_should_stop(taskq_t *tq, taskq_thread_t *tqt)
{
	ASSERT(spin_is_locked(&tq->tq_lock));

	if (!(tq->tq_flags & TASKQ_DYNAMIC))
		return (0);

	if (list_first_entry(&(tq->tq_thread_list), taskq_thread_t,
	    tqt_thread_list) == tqt)
		return (0);

	return
	    ((tq->tq_nspawn == 0) &&	/* No threads are being spawned */
	    (tq->tq_nactive == 0) &&	/* No threads are handling tasks */
	    (tq->tq_nthreads > 1) &&	/* More than 1 thread is running */
	    (!taskq_next_ent(tq)) &&	/* There are no pending tasks */
	    (spl_taskq_thread_dynamic)); /* Dynamic taskqs are allowed */
}

static int
taskq_thread(void *args)
{
	DECLARE_WAITQUEUE(wait, current);
	sigset_t blocked;
	taskq_thread_t *tqt = args;
	taskq_t *tq;
	taskq_ent_t *t;
	int seq_tasks = 0;
	unsigned long flags;

	ASSERT(tqt);
	ASSERT(tqt->tqt_tq);
	tq = tqt->tqt_tq;
	current->flags |= PF_NOFREEZE;

	(void) spl_fstrans_mark();

	sigfillset(&blocked);
	sigprocmask(SIG_BLOCK, &blocked, NULL);
	flush_signals(current);

	tsd_set(taskq_tsd, tq);
	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);

	/* Immediately exit if more threads than allowed were created. */
	if (tq->tq_nthreads >= tq->tq_maxthreads)
		goto error;

	tq->tq_nthreads++;
	list_add_tail(&tqt->tqt_thread_list, &tq->tq_thread_list);
	wake_up(&tq->tq_wait_waitq);
	set_current_state(TASK_INTERRUPTIBLE);

	while (!kthread_should_stop()) {

		if (list_empty(&tq->tq_pend_list) &&
		    list_empty(&tq->tq_prio_list)) {

			if (taskq_thread_should_stop(tq, tqt)) {
				wake_up_all(&tq->tq_wait_waitq);
				break;
			}

			add_wait_queue_exclusive(&tq->tq_work_waitq, &wait);
			spin_unlock_irqrestore(&tq->tq_lock, flags);

			schedule();
			seq_tasks = 0;

			spin_lock_irqsave_nested(&tq->tq_lock, flags,
			    tq->tq_lock_class);
			remove_wait_queue(&tq->tq_work_waitq, &wait);
		} else {
			__set_current_state(TASK_RUNNING);
		}

		if ((t = taskq_next_ent(tq)) != NULL) {
			list_del_init(&t->tqent_list);

			/*
			 * In order to support recursively dispatching a
			 * preallocated taskq_ent_t, tqent_id must be
			 * stored prior to executing tqent_func.
			 */
			tqt->tqt_id = t->tqent_id;
			tqt->tqt_task = t;

			/*
			 * We must store a copy of the flags prior to
			 * servicing the task (servicing a prealloc'd task
			 * returns the ownership of the tqent back to
			 * the caller of taskq_dispatch). Thus,
			 * tqent_flags _may_ change within the call.
			 */
			tqt->tqt_flags = t->tqent_flags;

			taskq_insert_in_order(tq, tqt);
			tq->tq_nactive++;
			spin_unlock_irqrestore(&tq->tq_lock, flags);

			/* Perform the requested task */
			t->tqent_func(t->tqent_arg);

			spin_lock_irqsave_nested(&tq->tq_lock, flags,
			    tq->tq_lock_class);
			tq->tq_nactive--;
			list_del_init(&tqt->tqt_active_list);
			tqt->tqt_task = NULL;

			/* For prealloc'd tasks, we don't free anything. */
			if (!(tqt->tqt_flags & TQENT_FLAG_PREALLOC))
				task_done(tq, t);

			/*
			 * When the current lowest outstanding taskqid is
			 * done calculate the new lowest outstanding id
			 */
			if (tq->tq_lowest_id == tqt->tqt_id) {
				tq->tq_lowest_id = taskq_lowest_id(tq);
				ASSERT3S(tq->tq_lowest_id, >, tqt->tqt_id);
			}

			/* Spawn additional taskq threads if required. */
			if ((++seq_tasks) > spl_taskq_thread_sequential &&
			    taskq_thread_spawn(tq))
				seq_tasks = 0;

			tqt->tqt_id = 0;
			tqt->tqt_flags = 0;
			wake_up_all(&tq->tq_wait_waitq);
		} else {
			if (taskq_thread_should_stop(tq, tqt))
				break;
		}

		set_current_state(TASK_INTERRUPTIBLE);

	}

	__set_current_state(TASK_RUNNING);
	tq->tq_nthreads--;
	list_del_init(&tqt->tqt_thread_list);
error:
	kmem_free(tqt, sizeof (taskq_thread_t));
	spin_unlock_irqrestore(&tq->tq_lock, flags);

	tsd_set(taskq_tsd, NULL);

	return (0);
}

static taskq_thread_t *
taskq_thread_create(taskq_t *tq)
{
	static int last_used_cpu = 0;
	taskq_thread_t *tqt;

	tqt = kmem_alloc(sizeof (*tqt), KM_PUSHPAGE);
	INIT_LIST_HEAD(&tqt->tqt_thread_list);
	INIT_LIST_HEAD(&tqt->tqt_active_list);
	tqt->tqt_tq = tq;
	tqt->tqt_id = 0;

	tqt->tqt_thread = spl_kthread_create(taskq_thread, tqt,
	    "%s", tq->tq_name);
	if (tqt->tqt_thread == NULL) {
		kmem_free(tqt, sizeof (taskq_thread_t));
		return (NULL);
	}

	if (spl_taskq_thread_bind) {
		last_used_cpu = (last_used_cpu + 1) % num_online_cpus();
		kthread_bind(tqt->tqt_thread, last_used_cpu);
	}

	if (spl_taskq_thread_priority)
		set_user_nice(tqt->tqt_thread, PRIO_TO_NICE(tq->tq_pri));

	wake_up_process(tqt->tqt_thread);

	return (tqt);
}

taskq_t *
taskq_create(const char *name, int nthreads, pri_t pri,
    int minalloc, int maxalloc, uint_t flags)
{
	taskq_t *tq;
	taskq_thread_t *tqt;
	int count = 0, rc = 0, i;
	unsigned long irqflags;

	ASSERT(name != NULL);
	ASSERT(minalloc >= 0);
	ASSERT(maxalloc <= INT_MAX);
	ASSERT(!(flags & (TASKQ_CPR_SAFE))); /* Unsupported */

	/* Scale the number of threads using nthreads as a percentage */
	if (flags & TASKQ_THREADS_CPU_PCT) {
		ASSERT(nthreads <= 100);
		ASSERT(nthreads >= 0);
		nthreads = MIN(nthreads, 100);
		nthreads = MAX(nthreads, 0);
		nthreads = MAX((num_online_cpus() * nthreads) / 100, 1);
	}

	tq = kmem_alloc(sizeof (*tq), KM_PUSHPAGE);
	if (tq == NULL)
		return (NULL);

	spin_lock_init(&tq->tq_lock);
	INIT_LIST_HEAD(&tq->tq_thread_list);
	INIT_LIST_HEAD(&tq->tq_active_list);
	tq->tq_name = strdup(name);
	tq->tq_nactive = 0;
	tq->tq_nthreads = 0;
	tq->tq_nspawn = 0;
	tq->tq_maxthreads = nthreads;
	tq->tq_pri = pri;
	tq->tq_minalloc = minalloc;
	tq->tq_maxalloc = maxalloc;
	tq->tq_nalloc = 0;
	tq->tq_flags = (flags | TASKQ_ACTIVE);
	tq->tq_next_id = 1;
	tq->tq_lowest_id = 1;
	INIT_LIST_HEAD(&tq->tq_free_list);
	INIT_LIST_HEAD(&tq->tq_pend_list);
	INIT_LIST_HEAD(&tq->tq_prio_list);
	INIT_LIST_HEAD(&tq->tq_delay_list);
	init_waitqueue_head(&tq->tq_work_waitq);
	init_waitqueue_head(&tq->tq_wait_waitq);
	tq->tq_lock_class = TQ_LOCK_GENERAL;
	INIT_LIST_HEAD(&tq->tq_taskqs);

	if (flags & TASKQ_PREPOPULATE) {
		spin_lock_irqsave_nested(&tq->tq_lock, irqflags,
		    tq->tq_lock_class);

		for (i = 0; i < minalloc; i++)
			task_done(tq, task_alloc(tq, TQ_PUSHPAGE | TQ_NEW,
			    &irqflags));

		spin_unlock_irqrestore(&tq->tq_lock, irqflags);
	}

	if ((flags & TASKQ_DYNAMIC) && spl_taskq_thread_dynamic)
		nthreads = 1;

	for (i = 0; i < nthreads; i++) {
		tqt = taskq_thread_create(tq);
		if (tqt == NULL)
			rc = 1;
		else
			count++;
	}

	/* Wait for all threads to be started before potential destroy */
	wait_event(tq->tq_wait_waitq, tq->tq_nthreads == count);

	if (rc) {
		taskq_destroy(tq);
		tq = NULL;
	} else {
		down_write(&tq_list_sem);
		tq->tq_instance = taskq_find_by_name(name) + 1;
		list_add_tail(&tq->tq_taskqs, &tq_list);
		up_write(&tq_list_sem);
	}

	return (tq);
}
EXPORT_SYMBOL(taskq_create);

void
taskq_destroy(taskq_t *tq)
{
	struct task_struct *thread;
	taskq_thread_t *tqt;
	taskq_ent_t *t;
	unsigned long flags;

	ASSERT(tq);
	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
	tq->tq_flags &= ~TASKQ_ACTIVE;
	spin_unlock_irqrestore(&tq->tq_lock, flags);

	/*
	 * When TASKQ_ACTIVE is clear new tasks may not be added nor may
	 * new worker threads be spawned for dynamic taskq.
	 */
	if (dynamic_taskq != NULL)
		taskq_wait_outstanding(dynamic_taskq, 0);

	taskq_wait(tq);

	/* remove taskq from global list used by the kstats */
	down_write(&tq_list_sem);
	list_del(&tq->tq_taskqs);
	up_write(&tq_list_sem);

	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);

	/*
	 * Signal each thread to exit and block until it does.  Each thread
	 * is responsible for removing itself from the list and freeing its
	 * taskq_thread_t.  This allows for idle threads to opt to remove
	 * themselves from the taskq.  They can be recreated as needed.
	 */
	while (!list_empty(&tq->tq_thread_list)) {
		tqt = list_entry(tq->tq_thread_list.next,
		    taskq_thread_t, tqt_thread_list);
		thread = tqt->tqt_thread;
		spin_unlock_irqrestore(&tq->tq_lock, flags);

		kthread_stop(thread);

		spin_lock_irqsave_nested(&tq->tq_lock, flags,
		    tq->tq_lock_class);
	}

	while (!list_empty(&tq->tq_free_list)) {
		t = list_entry(tq->tq_free_list.next, taskq_ent_t, tqent_list);

		ASSERT(!(t->tqent_flags & TQENT_FLAG_PREALLOC));

		list_del_init(&t->tqent_list);
		task_free(tq, t);
	}

	ASSERT0(tq->tq_nthreads);
	ASSERT0(tq->tq_nalloc);
	ASSERT0(tq->tq_nspawn);
	ASSERT(list_empty(&tq->tq_thread_list));
	ASSERT(list_empty(&tq->tq_active_list));
	ASSERT(list_empty(&tq->tq_free_list));
	ASSERT(list_empty(&tq->tq_pend_list));
	ASSERT(list_empty(&tq->tq_prio_list));
	ASSERT(list_empty(&tq->tq_delay_list));

	spin_unlock_irqrestore(&tq->tq_lock, flags);

	strfree(tq->tq_name);
	kmem_free(tq, sizeof (taskq_t));
}
EXPORT_SYMBOL(taskq_destroy);


static unsigned int spl_taskq_kick = 0;

/*
 * 2.6.36 API Change
 * module_param_cb is introduced to take kernel_param_ops and
 * module_param_call is marked as obsolete. Also set and get operations
 * were changed to take a 'const struct kernel_param *'.
 */
static int
#ifdef module_param_cb
param_set_taskq_kick(const char *val, const struct kernel_param *kp)
#else
param_set_taskq_kick(const char *val, struct kernel_param *kp)
#endif
{
	int ret;
	taskq_t *tq;
	taskq_ent_t *t;
	unsigned long flags;

	ret = param_set_uint(val, kp);
	if (ret < 0 || !spl_taskq_kick)
		return (ret);
	/* reset value */
	spl_taskq_kick = 0;

	down_read(&tq_list_sem);
	list_for_each_entry(tq, &tq_list, tq_taskqs) {
		spin_lock_irqsave_nested(&tq->tq_lock, flags,
		    tq->tq_lock_class);
		/* Check if the first pending is older than 5 seconds */
		t = taskq_next_ent(tq);
		if (t && time_after(jiffies, t->tqent_birth + 5*HZ)) {
			(void) taskq_thread_spawn(tq);
			printk(KERN_INFO "spl: Kicked taskq %s/%d\n",
			    tq->tq_name, tq->tq_instance);
		}
		spin_unlock_irqrestore(&tq->tq_lock, flags);
	}
	up_read(&tq_list_sem);
	return (ret);
}

#ifdef module_param_cb
static const struct kernel_param_ops param_ops_taskq_kick = {
        .set = param_set_taskq_kick,
        .get = param_get_uint,
};
module_param_cb(spl_taskq_kick, &param_ops_taskq_kick, &spl_taskq_kick, 0644);
#else
module_param_call(spl_taskq_kick, param_set_taskq_kick, param_get_uint,
    &spl_taskq_kick, 0644);
#endif
MODULE_PARM_DESC(spl_taskq_kick,
    "Write nonzero to kick stuck taskqs to spawn more threads");

int
spl_taskq_init(void)
{
	tsd_create(&taskq_tsd, NULL);

	system_taskq = taskq_create("spl_system_taskq", MAX(boot_ncpus, 64),
	    maxclsyspri, boot_ncpus, INT_MAX, TASKQ_PREPOPULATE|TASKQ_DYNAMIC);
	if (system_taskq == NULL)
		return (1);

	dynamic_taskq = taskq_create("spl_dynamic_taskq", 1,
	    maxclsyspri, boot_ncpus, INT_MAX, TASKQ_PREPOPULATE);
	if (dynamic_taskq == NULL) {
		taskq_destroy(system_taskq);
		return (1);
	}

	/*
	 * This is used to annotate tq_lock, so
	 *   taskq_dispatch -> taskq_thread_spawn -> taskq_dispatch
	 * does not trigger a lockdep warning re: possible recursive locking
	 */
	dynamic_taskq->tq_lock_class = TQ_LOCK_DYNAMIC;

	return (0);
}

void
spl_taskq_fini(void)
{
	taskq_destroy(dynamic_taskq);
	dynamic_taskq = NULL;

	taskq_destroy(system_taskq);
	system_taskq = NULL;

	tsd_destroy(&taskq_tsd);
}