xref: /dragonfly/sys/vfs/hammer2/hammer2_admin.c (revision 631c21f2)
1 /*
2  * Copyright (c) 2015-2018 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@dragonflybsd.org>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 /*
35  * This module implements the hammer2 helper thread API, including
36  * the frontend/backend XOP API.
37  */
38 #include "hammer2.h"
39 
40 #define H2XOPDESCRIPTOR(label)					\
41 	hammer2_xop_desc_t hammer2_##label##_desc = {		\
42 		.storage_func = hammer2_xop_##label,		\
43 		.id = #label					\
44 	}
45 
46 H2XOPDESCRIPTOR(ipcluster);
47 H2XOPDESCRIPTOR(readdir);
48 H2XOPDESCRIPTOR(nresolve);
49 H2XOPDESCRIPTOR(unlink);
50 H2XOPDESCRIPTOR(nrename);
51 H2XOPDESCRIPTOR(scanlhc);
52 H2XOPDESCRIPTOR(scanall);
53 H2XOPDESCRIPTOR(lookup);
54 H2XOPDESCRIPTOR(delete);
55 H2XOPDESCRIPTOR(inode_mkdirent);
56 H2XOPDESCRIPTOR(inode_create);
57 H2XOPDESCRIPTOR(inode_create_det);
58 H2XOPDESCRIPTOR(inode_create_ins);
59 H2XOPDESCRIPTOR(inode_destroy);
60 H2XOPDESCRIPTOR(inode_chain_sync);
61 H2XOPDESCRIPTOR(inode_unlinkall);
62 H2XOPDESCRIPTOR(inode_connect);
63 H2XOPDESCRIPTOR(inode_flush);
64 H2XOPDESCRIPTOR(strategy_read);
65 H2XOPDESCRIPTOR(strategy_write);
66 
67 /*
68  * Set flags and wakeup any waiters.
69  *
70  * WARNING! During teardown (thr) can disappear the instant our cmpset
71  *	    succeeds.
72  */
73 void
74 hammer2_thr_signal(hammer2_thread_t *thr, uint32_t flags)
75 {
76 	uint32_t oflags;
77 	uint32_t nflags;
78 
79 	for (;;) {
80 		oflags = thr->flags;
81 		cpu_ccfence();
82 		nflags = (oflags | flags) & ~HAMMER2_THREAD_WAITING;
83 
84 		if (oflags & HAMMER2_THREAD_WAITING) {
85 			if (atomic_cmpset_int(&thr->flags, oflags, nflags)) {
86 				wakeup(&thr->flags);
87 				break;
88 			}
89 		} else {
90 			if (atomic_cmpset_int(&thr->flags, oflags, nflags))
91 				break;
92 		}
93 	}
94 }
95 
96 /*
97  * Set and clear flags and wakeup any waiters.
98  *
99  * WARNING! During teardown (thr) can disappear the instant our cmpset
100  *	    succeeds.
101  */
102 void
103 hammer2_thr_signal2(hammer2_thread_t *thr, uint32_t posflags, uint32_t negflags)
104 {
105 	uint32_t oflags;
106 	uint32_t nflags;
107 
108 	for (;;) {
109 		oflags = thr->flags;
110 		cpu_ccfence();
111 		nflags = (oflags | posflags) &
112 			~(negflags | HAMMER2_THREAD_WAITING);
113 		if (oflags & HAMMER2_THREAD_WAITING) {
114 			if (atomic_cmpset_int(&thr->flags, oflags, nflags)) {
115 				wakeup(&thr->flags);
116 				break;
117 			}
118 		} else {
119 			if (atomic_cmpset_int(&thr->flags, oflags, nflags))
120 				break;
121 		}
122 	}
123 }
124 
125 /*
126  * Wait until all the bits in flags are set.
127  *
128  * WARNING! During teardown (thr) can disappear the instant our cmpset
129  *	    succeeds.
130  */
131 void
132 hammer2_thr_wait(hammer2_thread_t *thr, uint32_t flags)
133 {
134 	uint32_t oflags;
135 	uint32_t nflags;
136 
137 	for (;;) {
138 		oflags = thr->flags;
139 		cpu_ccfence();
140 		if ((oflags & flags) == flags)
141 			break;
142 		nflags = oflags | HAMMER2_THREAD_WAITING;
143 		tsleep_interlock(&thr->flags, 0);
144 		if (atomic_cmpset_int(&thr->flags, oflags, nflags)) {
145 			tsleep(&thr->flags, PINTERLOCKED, "h2twait", hz*60);
146 		}
147 	}
148 }
149 
150 /*
151  * Wait until any of the bits in flags are set, with timeout.
152  *
153  * WARNING! During teardown (thr) can disappear the instant our cmpset
154  *	    succeeds.
155  */
156 int
157 hammer2_thr_wait_any(hammer2_thread_t *thr, uint32_t flags, int timo)
158 {
159 	uint32_t oflags;
160 	uint32_t nflags;
161 	int error;
162 
163 	error = 0;
164 	for (;;) {
165 		oflags = thr->flags;
166 		cpu_ccfence();
167 		if (oflags & flags)
168 			break;
169 		nflags = oflags | HAMMER2_THREAD_WAITING;
170 		tsleep_interlock(&thr->flags, 0);
171 		if (atomic_cmpset_int(&thr->flags, oflags, nflags)) {
172 			error = tsleep(&thr->flags, PINTERLOCKED,
173 				       "h2twait", timo);
174 		}
175 		if (error == ETIMEDOUT) {
176 			error = HAMMER2_ERROR_ETIMEDOUT;
177 			break;
178 		}
179 	}
180 	return error;
181 }
182 
183 /*
184  * Wait until the bits in flags are clear.
185  *
186  * WARNING! During teardown (thr) can disappear the instant our cmpset
187  *	    succeeds.
188  */
189 void
190 hammer2_thr_wait_neg(hammer2_thread_t *thr, uint32_t flags)
191 {
192 	uint32_t oflags;
193 	uint32_t nflags;
194 
195 	for (;;) {
196 		oflags = thr->flags;
197 		cpu_ccfence();
198 		if ((oflags & flags) == 0)
199 			break;
200 		nflags = oflags | HAMMER2_THREAD_WAITING;
201 		tsleep_interlock(&thr->flags, 0);
202 		if (atomic_cmpset_int(&thr->flags, oflags, nflags)) {
203 			tsleep(&thr->flags, PINTERLOCKED, "h2twait", hz*60);
204 		}
205 	}
206 }
207 
208 /*
209  * Initialize the supplied thread structure, starting the specified
210  * thread.
211  *
212  * NOTE: thr structure can be retained across mounts and unmounts for this
213  *	 pmp, so make sure the flags are in a sane state.
214  */
215 void
216 hammer2_thr_create(hammer2_thread_t *thr, hammer2_pfs_t *pmp,
217 		   hammer2_dev_t *hmp,
218 		   const char *id, int clindex, int repidx,
219 		   void (*func)(void *arg))
220 {
221 	thr->pmp = pmp;		/* xop helpers */
222 	thr->hmp = hmp;		/* bulkfree */
223 	thr->clindex = clindex;
224 	thr->repidx = repidx;
225 	TAILQ_INIT(&thr->xopq);
226 	atomic_clear_int(&thr->flags, HAMMER2_THREAD_STOP |
227 				      HAMMER2_THREAD_STOPPED |
228 				      HAMMER2_THREAD_FREEZE |
229 				      HAMMER2_THREAD_FROZEN);
230 	if (thr->scratch == NULL)
231 		thr->scratch = kmalloc(MAXPHYS, M_HAMMER2, M_WAITOK | M_ZERO);
232 	if (repidx >= 0) {
233 		lwkt_create(func, thr, &thr->td, NULL, 0, repidx % ncpus,
234 			    "%s-%s.%02d", id, pmp->pfs_names[clindex], repidx);
235 	} else if (pmp) {
236 		lwkt_create(func, thr, &thr->td, NULL, 0, -1,
237 			    "%s-%s", id, pmp->pfs_names[clindex]);
238 	} else {
239 		lwkt_create(func, thr, &thr->td, NULL, 0, -1, "%s", id);
240 	}
241 }
242 
243 /*
244  * Terminate a thread.  This function will silently return if the thread
245  * was never initialized or has already been deleted.
246  *
247  * This is accomplished by setting the STOP flag and waiting for the td
248  * structure to become NULL.
249  */
250 void
251 hammer2_thr_delete(hammer2_thread_t *thr)
252 {
253 	if (thr->td == NULL)
254 		return;
255 	hammer2_thr_signal(thr, HAMMER2_THREAD_STOP);
256 	hammer2_thr_wait(thr, HAMMER2_THREAD_STOPPED);
257 	thr->pmp = NULL;
258 	if (thr->scratch) {
259 		kfree(thr->scratch, M_HAMMER2);
260 		thr->scratch = NULL;
261 	}
262 	KKASSERT(TAILQ_EMPTY(&thr->xopq));
263 }
264 
265 /*
266  * Asynchronous remaster request.  Ask the synchronization thread to
267  * start over soon (as if it were frozen and unfrozen, but without waiting).
268  * The thread always recalculates mastership relationships when restarting.
269  */
270 void
271 hammer2_thr_remaster(hammer2_thread_t *thr)
272 {
273 	if (thr->td == NULL)
274 		return;
275 	hammer2_thr_signal(thr, HAMMER2_THREAD_REMASTER);
276 }
277 
278 void
279 hammer2_thr_freeze_async(hammer2_thread_t *thr)
280 {
281 	hammer2_thr_signal(thr, HAMMER2_THREAD_FREEZE);
282 }
283 
284 void
285 hammer2_thr_freeze(hammer2_thread_t *thr)
286 {
287 	if (thr->td == NULL)
288 		return;
289 	hammer2_thr_signal(thr, HAMMER2_THREAD_FREEZE);
290 	hammer2_thr_wait(thr, HAMMER2_THREAD_FROZEN);
291 }
292 
293 void
294 hammer2_thr_unfreeze(hammer2_thread_t *thr)
295 {
296 	if (thr->td == NULL)
297 		return;
298 	hammer2_thr_signal(thr, HAMMER2_THREAD_UNFREEZE);
299 	hammer2_thr_wait_neg(thr, HAMMER2_THREAD_FROZEN);
300 }
301 
302 int
303 hammer2_thr_break(hammer2_thread_t *thr)
304 {
305 	if (thr->flags & (HAMMER2_THREAD_STOP |
306 			  HAMMER2_THREAD_REMASTER |
307 			  HAMMER2_THREAD_FREEZE)) {
308 		return 1;
309 	}
310 	return 0;
311 }
312 
313 /****************************************************************************
314  *			    HAMMER2 XOPS API	 			    *
315  ****************************************************************************/
316 
317 /*
318  * Allocate a XOP request.
319  *
320  * Once allocated a XOP request can be started, collected, and retired,
321  * and can be retired early if desired.
322  *
323  * NOTE: Fifo indices might not be zero but ri == wi on objcache_get().
324  */
325 void *
326 hammer2_xop_alloc(hammer2_inode_t *ip, int flags)
327 {
328 	hammer2_xop_t *xop;
329 
330 	xop = objcache_get(cache_xops, M_WAITOK);
331 	KKASSERT(xop->head.cluster.array[0].chain == NULL);
332 
333 	xop->head.ip1 = ip;
334 	xop->head.desc = NULL;
335 	xop->head.flags = flags;
336 	xop->head.state = 0;
337 	xop->head.error = 0;
338 	xop->head.collect_key = 0;
339 	xop->head.focus_dio = NULL;
340 
341 	if (flags & HAMMER2_XOP_MODIFYING)
342 		xop->head.mtid = hammer2_trans_sub(ip->pmp);
343 	else
344 		xop->head.mtid = 0;
345 
346 	xop->head.cluster.nchains = ip->cluster.nchains;
347 	xop->head.cluster.pmp = ip->pmp;
348 	xop->head.cluster.flags = HAMMER2_CLUSTER_LOCKED;
349 
350 	/*
351 	 * run_mask - Active thread (or frontend) associated with XOP
352 	 */
353 	xop->head.run_mask = HAMMER2_XOPMASK_VOP;
354 
355 	hammer2_inode_ref(ip);
356 
357 	return xop;
358 }
359 
360 void
361 hammer2_xop_setname(hammer2_xop_head_t *xop, const char *name, size_t name_len)
362 {
363 	xop->name1 = kmalloc(name_len + 1, M_HAMMER2, M_WAITOK | M_ZERO);
364 	xop->name1_len = name_len;
365 	bcopy(name, xop->name1, name_len);
366 }
367 
368 void
369 hammer2_xop_setname2(hammer2_xop_head_t *xop, const char *name, size_t name_len)
370 {
371 	xop->name2 = kmalloc(name_len + 1, M_HAMMER2, M_WAITOK | M_ZERO);
372 	xop->name2_len = name_len;
373 	bcopy(name, xop->name2, name_len);
374 }
375 
376 size_t
377 hammer2_xop_setname_inum(hammer2_xop_head_t *xop, hammer2_key_t inum)
378 {
379 	const size_t name_len = 18;
380 
381 	xop->name1 = kmalloc(name_len + 1, M_HAMMER2, M_WAITOK | M_ZERO);
382 	xop->name1_len = name_len;
383 	ksnprintf(xop->name1, name_len + 1, "0x%016jx", (intmax_t)inum);
384 
385 	return name_len;
386 }
387 
388 
389 void
390 hammer2_xop_setip2(hammer2_xop_head_t *xop, hammer2_inode_t *ip2)
391 {
392 	xop->ip2 = ip2;
393 	hammer2_inode_ref(ip2);
394 }
395 
396 void
397 hammer2_xop_setip3(hammer2_xop_head_t *xop, hammer2_inode_t *ip3)
398 {
399 	xop->ip3 = ip3;
400 	hammer2_inode_ref(ip3);
401 }
402 
403 void
404 hammer2_xop_setip4(hammer2_xop_head_t *xop, hammer2_inode_t *ip4)
405 {
406 	xop->ip4 = ip4;
407 	hammer2_inode_ref(ip4);
408 }
409 
410 void
411 hammer2_xop_reinit(hammer2_xop_head_t *xop)
412 {
413 	xop->state = 0;
414 	xop->error = 0;
415 	xop->collect_key = 0;
416 	xop->run_mask = HAMMER2_XOPMASK_VOP;
417 }
418 
419 /*
420  * A mounted PFS needs Xops threads to support frontend operations.
421  */
422 void
423 hammer2_xop_helper_create(hammer2_pfs_t *pmp)
424 {
425 	int i;
426 	int j;
427 
428 	lockmgr(&pmp->lock, LK_EXCLUSIVE);
429 	pmp->has_xop_threads = 1;
430 
431 	pmp->xop_groups = kmalloc(hammer2_xopgroups *
432 				  sizeof(hammer2_xop_group_t),
433 				  M_HAMMER2, M_WAITOK | M_ZERO);
434 	for (i = 0; i < pmp->iroot->cluster.nchains; ++i) {
435 		for (j = 0; j < hammer2_xopgroups; ++j) {
436 			if (pmp->xop_groups[j].thrs[i].td)
437 				continue;
438 			hammer2_thr_create(&pmp->xop_groups[j].thrs[i],
439 					   pmp, NULL,
440 					   "h2xop", i, j,
441 					   hammer2_primary_xops_thread);
442 		}
443 	}
444 	lockmgr(&pmp->lock, LK_RELEASE);
445 }
446 
447 void
448 hammer2_xop_helper_cleanup(hammer2_pfs_t *pmp)
449 {
450 	int i;
451 	int j;
452 
453 	if (pmp->xop_groups == NULL) {
454 		KKASSERT(pmp->has_xop_threads == 0);
455 		return;
456 	}
457 
458 	for (i = 0; i < pmp->pfs_nmasters; ++i) {
459 		for (j = 0; j < hammer2_xopgroups; ++j) {
460 			if (pmp->xop_groups[j].thrs[i].td)
461 				hammer2_thr_delete(&pmp->xop_groups[j].thrs[i]);
462 		}
463 	}
464 	pmp->has_xop_threads = 0;
465 	kfree(pmp->xop_groups, M_HAMMER2);
466 	pmp->xop_groups = NULL;
467 }
468 
469 /*
470  * Start a XOP request, queueing it to all nodes in the cluster to
471  * execute the cluster op.
472  *
473  * XXX optimize single-target case.
474  */
475 void
476 hammer2_xop_start_except(hammer2_xop_head_t *xop, hammer2_xop_desc_t *desc,
477 			 int notidx)
478 {
479 	hammer2_inode_t *ip1;
480 	hammer2_pfs_t *pmp;
481 	hammer2_thread_t *thr;
482 	int i;
483 	int ng;
484 	int nchains;
485 
486 	ip1 = xop->ip1;
487 	pmp = ip1->pmp;
488 	if (pmp->has_xop_threads == 0)
489 		hammer2_xop_helper_create(pmp);
490 
491 	/*
492 	 * The intent of the XOP sequencer is to ensure that ops on the same
493 	 * inode execute in the same order.  This is necessary when issuing
494 	 * modifying operations to multiple targets because some targets might
495 	 * get behind and the frontend is allowed to complete the moment a
496 	 * quorum of targets succeed.
497 	 *
498 	 * Strategy operations:
499 	 *
500 	 *	(1) Must be segregated from non-strategy operations to
501 	 *	    avoid a deadlock.  A vfsync and a bread/bwrite can
502 	 *	    deadlock the vfsync's buffer list scan.
503 	 *
504 	 *	(2) Reads are separated from writes to avoid write stalls
505 	 *	    from excessively intefering with reads.  Reads are allowed
506 	 *	    to wander across multiple worker threads for potential
507 	 *	    single-file concurrency improvements.
508 	 *
509 	 *	(3) Writes are serialized to a single worker thread (for any
510 	 *	    given inode) in order to try to improve block allocation
511 	 *	    sequentiality and to reduce lock contention.
512 	 *
513 	 * TODO - RENAME fails here because it is potentially modifying
514 	 *	  three different inodes, but we triple-lock the inodes
515 	 *	  involved so it shouldn't create a sequencing schism.
516 	 */
517 	if (xop->flags & HAMMER2_XOP_STRATEGY) {
518 		hammer2_xop_strategy_t *xopst;
519 
520 		xopst = &((hammer2_xop_t *)xop)->xop_strategy;
521 		ng = mycpu->gd_cpuid % (hammer2_xopgroups >> 1);
522 #if 0
523 		hammer2_off_t off;
524 		int cdr;
525 
526 		ng = (int)(hammer2_icrc32(&xop->ip1, sizeof(xop->ip1)));
527 		if (desc == &hammer2_strategy_read_desc) {
528 			off = xopst->lbase / HAMMER2_PBUFSIZE;
529 			cdr = hammer2_cluster_data_read;
530 			/* sysctl race, load into var */
531 			cpu_ccfence();
532 			if (cdr)
533 				off /= cdr;
534 			ng ^= hammer2_icrc32(&off, sizeof(off)) &
535 			      (hammer2_worker_rmask << 1);
536 			ng |= 1;
537 		} else {
538 #if 0
539 			off = xopst->lbase >> 21;
540 			ng ^= hammer2_icrc32(&off, sizeof(off)) & 3;
541 #endif
542 			ng &= ~1;
543 		}
544 		ng = ng % (hammer2_xopgroups >> 1);
545 		ng += (hammer2_xopgroups >> 1);
546 #endif
547 	} else {
548 		ng = (int)(hammer2_icrc32(&xop->ip1, sizeof(xop->ip1)));
549 		ng = (unsigned int)ng % (hammer2_xopgroups >> 1);
550 	}
551 	xop->desc = desc;
552 
553 	/*
554 	 * The instant xop is queued another thread can pick it off.  In the
555 	 * case of asynchronous ops, another thread might even finish and
556 	 * deallocate it.
557 	 */
558 	hammer2_spin_ex(&pmp->xop_spin);
559 	nchains = ip1->cluster.nchains;
560 	for (i = 0; i < nchains; ++i) {
561 		/*
562 		 * XXX ip1->cluster.array* not stable here.  This temporary
563 		 *     hack fixes basic issues in target XOPs which need to
564 		 *     obtain a starting chain from the inode but does not
565 		 *     address possible races against inode updates which
566 		 *     might NULL-out a chain.
567 		 */
568 		if (i != notidx && ip1->cluster.array[i].chain) {
569 			thr = &pmp->xop_groups[ng].thrs[i];
570 			atomic_set_64(&xop->run_mask, 1LLU << i);
571 			atomic_set_64(&xop->chk_mask, 1LLU << i);
572 			xop->collect[i].thr = thr;
573 			TAILQ_INSERT_TAIL(&thr->xopq, xop, collect[i].entry);
574 		}
575 	}
576 	hammer2_spin_unex(&pmp->xop_spin);
577 	/* xop can become invalid at this point */
578 
579 	/*
580 	 * Each thread has its own xopq
581 	 */
582 	for (i = 0; i < nchains; ++i) {
583 		if (i != notidx) {
584 			thr = &pmp->xop_groups[ng].thrs[i];
585 			hammer2_thr_signal(thr, HAMMER2_THREAD_XOPQ);
586 		}
587 	}
588 }
589 
590 void
591 hammer2_xop_start(hammer2_xop_head_t *xop, hammer2_xop_desc_t *desc)
592 {
593 	hammer2_xop_start_except(xop, desc, -1);
594 }
595 
596 /*
597  * Retire a XOP.  Used by both the VOP frontend and by the XOP backend.
598  */
599 void
600 hammer2_xop_retire(hammer2_xop_head_t *xop, uint64_t mask)
601 {
602 	hammer2_chain_t *chain;
603 	uint64_t nmask;
604 	int i;
605 
606 	/*
607 	 * Remove the frontend collector or remove a backend feeder.
608 	 *
609 	 * When removing the frontend we must wakeup any backend feeders
610 	 * who are waiting for FIFO space.
611 	 *
612 	 * When removing the last backend feeder we must wakeup any waiting
613 	 * frontend.
614 	 */
615 	KKASSERT(xop->run_mask & mask);
616 	nmask = atomic_fetchadd_64(&xop->run_mask,
617 				   -mask + HAMMER2_XOPMASK_FEED);
618 
619 	/*
620 	 * More than one entity left
621 	 */
622 	if ((nmask & HAMMER2_XOPMASK_ALLDONE) != mask) {
623 		/*
624 		 * Frontend terminating, wakeup any backends waiting on
625 		 * fifo full.
626 		 *
627 		 * NOTE!!! The xop can get ripped out from under us at
628 		 *	   this point, so do not reference it again.
629 		 *	   The wakeup(xop) doesn't touch the xop and
630 		 *	   is ok.
631 		 */
632 		if (mask == HAMMER2_XOPMASK_VOP) {
633 			if (nmask & HAMMER2_XOPMASK_FIFOW)
634 				wakeup(xop);
635 		}
636 
637 		/*
638 		 * Wakeup frontend if the last backend is terminating.
639 		 */
640 		nmask -= mask;
641 		if ((nmask & HAMMER2_XOPMASK_ALLDONE) == HAMMER2_XOPMASK_VOP) {
642 			if (nmask & HAMMER2_XOPMASK_WAIT)
643 				wakeup(xop);
644 		}
645 
646 		return;
647 	}
648 	/* else nobody else left, we can ignore FIFOW */
649 
650 	/*
651 	 * All collectors are gone, we can cleanup and dispose of the XOP.
652 	 * Note that this can wind up being a frontend OR a backend.
653 	 * Pending chains are locked shared and not owned by any thread.
654 	 *
655 	 * Cleanup the collection cluster.
656 	 */
657 	for (i = 0; i < xop->cluster.nchains; ++i) {
658 		xop->cluster.array[i].flags = 0;
659 		chain = xop->cluster.array[i].chain;
660 		if (chain) {
661 			xop->cluster.array[i].chain = NULL;
662 			hammer2_chain_drop_unhold(chain);
663 		}
664 	}
665 
666 	/*
667 	 * Cleanup the fifos.  Since we are the only entity left on this
668 	 * xop we don't have to worry about fifo flow control, and one
669 	 * lfence() will do the job.
670 	 */
671 	cpu_lfence();
672 	mask = xop->chk_mask;
673 	for (i = 0; mask && i < HAMMER2_MAXCLUSTER; ++i) {
674 		hammer2_xop_fifo_t *fifo = &xop->collect[i];
675 		while (fifo->ri != fifo->wi) {
676 			chain = fifo->array[fifo->ri & HAMMER2_XOPFIFO_MASK];
677 			if (chain)
678 				hammer2_chain_drop_unhold(chain);
679 			++fifo->ri;
680 		}
681 		mask &= ~(1U << i);
682 	}
683 
684 	/*
685 	 * The inode is only held at this point, simply drop it.
686 	 */
687 	if (xop->ip1) {
688 		hammer2_inode_drop(xop->ip1);
689 		xop->ip1 = NULL;
690 	}
691 	if (xop->ip2) {
692 		hammer2_inode_drop(xop->ip2);
693 		xop->ip2 = NULL;
694 	}
695 	if (xop->ip3) {
696 		hammer2_inode_drop(xop->ip3);
697 		xop->ip3 = NULL;
698 	}
699 	if (xop->ip4) {
700 		hammer2_inode_drop(xop->ip4);
701 		xop->ip4 = NULL;
702 	}
703 	if (xop->name1) {
704 		kfree(xop->name1, M_HAMMER2);
705 		xop->name1 = NULL;
706 		xop->name1_len = 0;
707 	}
708 	if (xop->name2) {
709 		kfree(xop->name2, M_HAMMER2);
710 		xop->name2 = NULL;
711 		xop->name2_len = 0;
712 	}
713 
714 	objcache_put(cache_xops, xop);
715 }
716 
717 /*
718  * (Backend) Returns non-zero if the frontend is still attached.
719  */
720 int
721 hammer2_xop_active(hammer2_xop_head_t *xop)
722 {
723 	if (xop->run_mask & HAMMER2_XOPMASK_VOP)
724 		return 1;
725 	else
726 		return 0;
727 }
728 
729 /*
730  * (Backend) Feed chain data through the cluster validator and back to
731  * the frontend.  Chains are fed from multiple nodes concurrently
732  * and pipelined via per-node FIFOs in the XOP.
733  *
734  * The chain must be locked (either shared or exclusive).  The caller may
735  * unlock and drop the chain on return.  This function will add an extra
736  * ref and hold the chain's data for the pass-back.
737  *
738  * No xop lock is needed because we are only manipulating fields under
739  * our direct control.
740  *
741  * Returns 0 on success and a hammer2 error code if sync is permanently
742  * lost.  The caller retains a ref on the chain but by convention
743  * the lock is typically inherited by the xop (caller loses lock).
744  *
745  * Returns non-zero on error.  In this situation the caller retains a
746  * ref on the chain but loses the lock (we unlock here).
747  */
748 int
749 hammer2_xop_feed(hammer2_xop_head_t *xop, hammer2_chain_t *chain,
750 		 int clindex, int error)
751 {
752 	hammer2_xop_fifo_t *fifo;
753 	uint64_t mask;
754 
755 	/*
756 	 * Early termination (typicaly of xop_readir)
757 	 */
758 	if (hammer2_xop_active(xop) == 0) {
759 		error = HAMMER2_ERROR_ABORTED;
760 		goto done;
761 	}
762 
763 	/*
764 	 * Multi-threaded entry into the XOP collector.  We own the
765 	 * fifo->wi for our clindex.
766 	 */
767 	fifo = &xop->collect[clindex];
768 
769 	if (fifo->ri == fifo->wi - HAMMER2_XOPFIFO)
770 		lwkt_yield();
771 	while (fifo->ri == fifo->wi - HAMMER2_XOPFIFO) {
772 		atomic_set_int(&fifo->flags, HAMMER2_XOP_FIFO_STALL);
773 		mask = xop->run_mask;
774 		if ((mask & HAMMER2_XOPMASK_VOP) == 0) {
775 			error = HAMMER2_ERROR_ABORTED;
776 			goto done;
777 		}
778 		tsleep_interlock(xop, 0);
779 		if (atomic_cmpset_64(&xop->run_mask, mask,
780 				     mask | HAMMER2_XOPMASK_FIFOW)) {
781 			if (fifo->ri == fifo->wi - HAMMER2_XOPFIFO) {
782 				tsleep(xop, PINTERLOCKED, "h2feed", hz*60);
783 			}
784 		}
785 		/* retry */
786 	}
787 	atomic_clear_int(&fifo->flags, HAMMER2_XOP_FIFO_STALL);
788 	if (chain)
789 		hammer2_chain_ref_hold(chain);
790 	if (error == 0 && chain)
791 		error = chain->error;
792 	fifo->errors[fifo->wi & HAMMER2_XOPFIFO_MASK] = error;
793 	fifo->array[fifo->wi & HAMMER2_XOPFIFO_MASK] = chain;
794 	cpu_sfence();
795 	++fifo->wi;
796 
797 	mask = atomic_fetchadd_64(&xop->run_mask, HAMMER2_XOPMASK_FEED);
798 	if (mask & HAMMER2_XOPMASK_WAIT) {
799 		atomic_clear_64(&xop->run_mask, HAMMER2_XOPMASK_WAIT);
800 		wakeup(xop);
801 	}
802 	error = 0;
803 
804 	/*
805 	 * Cleanup.  If an error occurred we eat the lock.  If no error
806 	 * occurred the fifo inherits the lock and gains an additional ref.
807 	 *
808 	 * The caller's ref remains in both cases.
809 	 */
810 done:
811 	return error;
812 }
813 
814 /*
815  * (Frontend) collect a response from a running cluster op.
816  *
817  * Responses are fed from all appropriate nodes concurrently
818  * and collected into a cohesive response >= collect_key.
819  *
820  * The collector will return the instant quorum or other requirements
821  * are met, even if some nodes get behind or become non-responsive.
822  *
823  * HAMMER2_XOP_COLLECT_NOWAIT	- Used to 'poll' a completed collection,
824  *				  usually called synchronously from the
825  *				  node XOPs for the strategy code to
826  *				  fake the frontend collection and complete
827  *				  the BIO as soon as possible.
828  *
829  * HAMMER2_XOP_SYNCHRONIZER	- Reqeuest synchronization with a particular
830  *				  cluster index, prevents looping when that
831  *				  index is out of sync so caller can act on
832  *				  the out of sync element.  ESRCH and EDEADLK
833  *				  can be returned if this flag is specified.
834  *
835  * Returns 0 on success plus a filled out xop->cluster structure.
836  * Return ENOENT on normal termination.
837  * Otherwise return an error.
838  *
839  * WARNING! If the xop returns a cluster with a non-NULL focus, note that
840  *	    none of the chains in the cluster (or the focus) are either
841  *	    locked or I/O synchronized with the cpu.  hammer2_xop_gdata()
842  *	    and hammer2_xop_pdata() must be used to safely access the focus
843  *	    chain's content.
844  *
845  *	    The frontend can make certain assumptions based on higher-level
846  *	    locking done by the frontend, but data integrity absolutely
847  *	    requires using the gdata/pdata API.
848  */
849 int
850 hammer2_xop_collect(hammer2_xop_head_t *xop, int flags)
851 {
852 	hammer2_xop_fifo_t *fifo;
853 	hammer2_chain_t *chain;
854 	hammer2_key_t lokey;
855 	uint64_t mask;
856 	int error;
857 	int keynull;
858 	int adv;		/* advance the element */
859 	int i;
860 
861 loop:
862 	/*
863 	 * First loop tries to advance pieces of the cluster which
864 	 * are out of sync.
865 	 */
866 	lokey = HAMMER2_KEY_MAX;
867 	keynull = HAMMER2_CHECK_NULL;
868 	mask = xop->run_mask;
869 	cpu_lfence();
870 
871 	for (i = 0; i < xop->cluster.nchains; ++i) {
872 		chain = xop->cluster.array[i].chain;
873 		if (chain == NULL) {
874 			adv = 1;
875 		} else if (chain->bref.key < xop->collect_key) {
876 			adv = 1;
877 		} else {
878 			keynull &= ~HAMMER2_CHECK_NULL;
879 			if (lokey > chain->bref.key)
880 				lokey = chain->bref.key;
881 			adv = 0;
882 		}
883 		if (adv == 0)
884 			continue;
885 
886 		/*
887 		 * Advance element if possible, advanced element may be NULL.
888 		 */
889 		if (chain)
890 			hammer2_chain_drop_unhold(chain);
891 
892 		fifo = &xop->collect[i];
893 		if (fifo->ri != fifo->wi) {
894 			cpu_lfence();
895 			chain = fifo->array[fifo->ri & HAMMER2_XOPFIFO_MASK];
896 			error = fifo->errors[fifo->ri & HAMMER2_XOPFIFO_MASK];
897 			++fifo->ri;
898 			xop->cluster.array[i].chain = chain;
899 			xop->cluster.array[i].error = error;
900 			if (chain == NULL) {
901 				/* XXX */
902 				xop->cluster.array[i].flags |=
903 							HAMMER2_CITEM_NULL;
904 			}
905 			if (fifo->wi - fifo->ri <= HAMMER2_XOPFIFO / 2) {
906 				if (fifo->flags & HAMMER2_XOP_FIFO_STALL) {
907 					atomic_clear_int(&fifo->flags,
908 						    HAMMER2_XOP_FIFO_STALL);
909 					wakeup(xop);
910 					lwkt_yield();
911 				}
912 			}
913 			--i;		/* loop on same index */
914 		} else {
915 			/*
916 			 * Retain CITEM_NULL flag.  If set just repeat EOF.
917 			 * If not, the NULL,0 combination indicates an
918 			 * operation in-progress.
919 			 */
920 			xop->cluster.array[i].chain = NULL;
921 			/* retain any CITEM_NULL setting */
922 		}
923 	}
924 
925 	/*
926 	 * Determine whether the lowest collected key meets clustering
927 	 * requirements.  Returns:
928 	 *
929 	 * 0	 	 - key valid, cluster can be returned.
930 	 *
931 	 * ENOENT	 - normal end of scan, return ENOENT.
932 	 *
933 	 * ESRCH	 - sufficient elements collected, quorum agreement
934 	 *		   that lokey is not a valid element and should be
935 	 *		   skipped.
936 	 *
937 	 * EDEADLK	 - sufficient elements collected, no quorum agreement
938 	 *		   (and no agreement possible).  In this situation a
939 	 *		   repair is needed, for now we loop.
940 	 *
941 	 * EINPROGRESS	 - insufficient elements collected to resolve, wait
942 	 *		   for event and loop.
943 	 */
944 	if ((flags & HAMMER2_XOP_COLLECT_WAITALL) &&
945 	    (mask & HAMMER2_XOPMASK_ALLDONE) != HAMMER2_XOPMASK_VOP) {
946 		error = HAMMER2_ERROR_EINPROGRESS;
947 	} else {
948 		error = hammer2_cluster_check(&xop->cluster, lokey, keynull);
949 	}
950 	if (error == HAMMER2_ERROR_EINPROGRESS) {
951 		if (flags & HAMMER2_XOP_COLLECT_NOWAIT)
952 			goto done;
953 		tsleep_interlock(xop, 0);
954 		if (atomic_cmpset_64(&xop->run_mask,
955 				     mask, mask | HAMMER2_XOPMASK_WAIT)) {
956 			tsleep(xop, PINTERLOCKED, "h2coll", hz*60);
957 		}
958 		goto loop;
959 	}
960 	if (error == HAMMER2_ERROR_ESRCH) {
961 		if (lokey != HAMMER2_KEY_MAX) {
962 			xop->collect_key = lokey + 1;
963 			goto loop;
964 		}
965 		error = HAMMER2_ERROR_ENOENT;
966 	}
967 	if (error == HAMMER2_ERROR_EDEADLK) {
968 		kprintf("hammer2: no quorum possible lokey %016jx\n",
969 			lokey);
970 		if (lokey != HAMMER2_KEY_MAX) {
971 			xop->collect_key = lokey + 1;
972 			goto loop;
973 		}
974 		error = HAMMER2_ERROR_ENOENT;
975 	}
976 	if (lokey == HAMMER2_KEY_MAX)
977 		xop->collect_key = lokey;
978 	else
979 		xop->collect_key = lokey + 1;
980 done:
981 	return error;
982 }
983 
984 /*
985  * N x M processing threads are available to handle XOPs, N per cluster
986  * index x M cluster nodes.
987  *
988  * Locate and return the next runnable xop, or NULL if no xops are
989  * present or none of the xops are currently runnable (for various reasons).
990  * The xop is left on the queue and serves to block other dependent xops
991  * from being run.
992  *
993  * Dependent xops will not be returned.
994  *
995  * Sets HAMMER2_XOP_FIFO_RUN on the returned xop or returns NULL.
996  *
997  * NOTE! Xops run concurrently for each cluster index.
998  */
999 #define XOP_HASH_SIZE	16
1000 #define XOP_HASH_MASK	(XOP_HASH_SIZE - 1)
1001 
1002 static __inline
1003 int
1004 xop_testhash(hammer2_thread_t *thr, hammer2_inode_t *ip, uint32_t *hash)
1005 {
1006 	uint32_t mask;
1007 	int hv;
1008 
1009 	hv = (int)((uintptr_t)ip + (uintptr_t)thr) / sizeof(hammer2_inode_t);
1010 	mask = 1U << (hv & 31);
1011 	hv >>= 5;
1012 
1013 	return ((int)(hash[hv & XOP_HASH_MASK] & mask));
1014 }
1015 
1016 static __inline
1017 void
1018 xop_sethash(hammer2_thread_t *thr, hammer2_inode_t *ip, uint32_t *hash)
1019 {
1020 	uint32_t mask;
1021 	int hv;
1022 
1023 	hv = (int)((uintptr_t)ip + (uintptr_t)thr) / sizeof(hammer2_inode_t);
1024 	mask = 1U << (hv & 31);
1025 	hv >>= 5;
1026 
1027 	hash[hv & XOP_HASH_MASK] |= mask;
1028 }
1029 
1030 static
1031 hammer2_xop_head_t *
1032 hammer2_xop_next(hammer2_thread_t *thr)
1033 {
1034 	hammer2_pfs_t *pmp = thr->pmp;
1035 	int clindex = thr->clindex;
1036 	uint32_t hash[XOP_HASH_SIZE] = { 0 };
1037 	hammer2_xop_head_t *xop;
1038 
1039 	hammer2_spin_ex(&pmp->xop_spin);
1040 	TAILQ_FOREACH(xop, &thr->xopq, collect[clindex].entry) {
1041 		/*
1042 		 * Check dependency
1043 		 */
1044 		if (xop_testhash(thr, xop->ip1, hash) ||
1045 		    (xop->ip2 && xop_testhash(thr, xop->ip2, hash)) ||
1046 		    (xop->ip3 && xop_testhash(thr, xop->ip3, hash)) ||
1047 		    (xop->ip4 && xop_testhash(thr, xop->ip4, hash)))
1048 		{
1049 			continue;
1050 		}
1051 		xop_sethash(thr, xop->ip1, hash);
1052 		if (xop->ip2)
1053 			xop_sethash(thr, xop->ip2, hash);
1054 		if (xop->ip3)
1055 			xop_sethash(thr, xop->ip3, hash);
1056 		if (xop->ip4)
1057 			xop_sethash(thr, xop->ip4, hash);
1058 
1059 		/*
1060 		 * Check already running
1061 		 */
1062 		if (xop->collect[clindex].flags & HAMMER2_XOP_FIFO_RUN)
1063 			continue;
1064 
1065 		/*
1066 		 * Found a good one, return it.
1067 		 */
1068 		atomic_set_int(&xop->collect[clindex].flags,
1069 			       HAMMER2_XOP_FIFO_RUN);
1070 		break;
1071 	}
1072 	hammer2_spin_unex(&pmp->xop_spin);
1073 
1074 	return xop;
1075 }
1076 
1077 /*
1078  * Remove the completed XOP from the queue, clear HAMMER2_XOP_FIFO_RUN.
1079  *
1080  * NOTE! Xops run concurrently for each cluster index.
1081  */
1082 static
1083 void
1084 hammer2_xop_dequeue(hammer2_thread_t *thr, hammer2_xop_head_t *xop)
1085 {
1086 	hammer2_pfs_t *pmp = thr->pmp;
1087 	int clindex = thr->clindex;
1088 
1089 	hammer2_spin_ex(&pmp->xop_spin);
1090 	TAILQ_REMOVE(&thr->xopq, xop, collect[clindex].entry);
1091 	atomic_clear_int(&xop->collect[clindex].flags,
1092 			 HAMMER2_XOP_FIFO_RUN);
1093 	hammer2_spin_unex(&pmp->xop_spin);
1094 	if (TAILQ_FIRST(&thr->xopq))
1095 		hammer2_thr_signal(thr, HAMMER2_THREAD_XOPQ);
1096 }
1097 
1098 /*
1099  * Primary management thread for xops support.  Each node has several such
1100  * threads which replicate front-end operations on cluster nodes.
1101  *
1102  * XOPS thread node operations, allowing the function to focus on a single
1103  * node in the cluster after validating the operation with the cluster.
1104  * This is primarily what prevents dead or stalled nodes from stalling
1105  * the front-end.
1106  */
1107 void
1108 hammer2_primary_xops_thread(void *arg)
1109 {
1110 	hammer2_thread_t *thr = arg;
1111 	hammer2_pfs_t *pmp;
1112 	hammer2_xop_head_t *xop;
1113 	uint64_t mask;
1114 	uint32_t flags;
1115 	uint32_t nflags;
1116 	hammer2_xop_desc_t *last_desc = NULL;
1117 
1118 	pmp = thr->pmp;
1119 	/*xgrp = &pmp->xop_groups[thr->repidx]; not needed */
1120 	mask = 1LLU << thr->clindex;
1121 
1122 	for (;;) {
1123 		flags = thr->flags;
1124 
1125 		/*
1126 		 * Handle stop request
1127 		 */
1128 		if (flags & HAMMER2_THREAD_STOP)
1129 			break;
1130 
1131 		/*
1132 		 * Handle freeze request
1133 		 */
1134 		if (flags & HAMMER2_THREAD_FREEZE) {
1135 			hammer2_thr_signal2(thr, HAMMER2_THREAD_FROZEN,
1136 						 HAMMER2_THREAD_FREEZE);
1137 			continue;
1138 		}
1139 
1140 		if (flags & HAMMER2_THREAD_UNFREEZE) {
1141 			hammer2_thr_signal2(thr, 0,
1142 						 HAMMER2_THREAD_FROZEN |
1143 						 HAMMER2_THREAD_UNFREEZE);
1144 			continue;
1145 		}
1146 
1147 		/*
1148 		 * Force idle if frozen until unfrozen or stopped.
1149 		 */
1150 		if (flags & HAMMER2_THREAD_FROZEN) {
1151 			hammer2_thr_wait_any(thr,
1152 					     HAMMER2_THREAD_UNFREEZE |
1153 					     HAMMER2_THREAD_STOP,
1154 					     0);
1155 			continue;
1156 		}
1157 
1158 		/*
1159 		 * Reset state on REMASTER request
1160 		 */
1161 		if (flags & HAMMER2_THREAD_REMASTER) {
1162 			hammer2_thr_signal2(thr, 0, HAMMER2_THREAD_REMASTER);
1163 			/* reset state here */
1164 			continue;
1165 		}
1166 
1167 		/*
1168 		 * Process requests.  Each request can be multi-queued.
1169 		 *
1170 		 * If we get behind and the frontend VOP is no longer active,
1171 		 * we retire the request without processing it.  The callback
1172 		 * may also abort processing if the frontend VOP becomes
1173 		 * inactive.
1174 		 */
1175 		if (flags & HAMMER2_THREAD_XOPQ) {
1176 			nflags = flags & ~HAMMER2_THREAD_XOPQ;
1177 			if (!atomic_cmpset_int(&thr->flags, flags, nflags))
1178 				continue;
1179 			flags = nflags;
1180 			/* fall through */
1181 		}
1182 		while ((xop = hammer2_xop_next(thr)) != NULL) {
1183 			if (hammer2_xop_active(xop)) {
1184 				last_desc = xop->desc;
1185 				xop->desc->storage_func((hammer2_xop_t *)xop,
1186 							thr->scratch,
1187 							thr->clindex);
1188 				hammer2_xop_dequeue(thr, xop);
1189 				hammer2_xop_retire(xop, mask);
1190 			} else {
1191 				last_desc = xop->desc;
1192 				hammer2_xop_feed(xop, NULL, thr->clindex,
1193 						 ECONNABORTED);
1194 				hammer2_xop_dequeue(thr, xop);
1195 				hammer2_xop_retire(xop, mask);
1196 			}
1197 		}
1198 
1199 		/*
1200 		 * Wait for event, interlock using THREAD_WAITING and
1201 		 * THREAD_SIGNAL.
1202 		 *
1203 		 * For robustness poll on a 30-second interval, but nominally
1204 		 * expect to be woken up.
1205 		 */
1206 		nflags = flags | HAMMER2_THREAD_WAITING;
1207 
1208 		tsleep_interlock(&thr->flags, 0);
1209 		if (atomic_cmpset_int(&thr->flags, flags, nflags)) {
1210 			tsleep(&thr->flags, PINTERLOCKED, "h2idle", hz*30);
1211 		}
1212 	}
1213 
1214 #if 0
1215 	/*
1216 	 * Cleanup / termination
1217 	 */
1218 	while ((xop = TAILQ_FIRST(&thr->xopq)) != NULL) {
1219 		kprintf("hammer2_thread: aborting xop %s\n", xop->desc->id);
1220 		TAILQ_REMOVE(&thr->xopq, xop,
1221 			     collect[thr->clindex].entry);
1222 		hammer2_xop_retire(xop, mask);
1223 	}
1224 #endif
1225 	thr->td = NULL;
1226 	hammer2_thr_signal(thr, HAMMER2_THREAD_STOPPED);
1227 	/* thr structure can go invalid after this point */
1228 }
1229