xref: /dragonfly/usr.bin/dsynth/build.c (revision 3ea159d2)
1 /*
2  * Copyright (c) 2019-2020 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  *
7  * This code uses concepts and configuration based on 'synth', by
8  * John R. Marino <draco@marino.st>, which was written in ada.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  * 3. Neither the name of The DragonFly Project nor the names of its
21  *    contributors may be used to endorse or promote products derived
22  *    from this software without specific, prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
28  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
30  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
32  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
34  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 #include "dsynth.h"
38 
39 static worker_t WorkerAry[MAXWORKERS];
40 static int BuildInitialized;
41 static int RunningWorkers;
42 int DynamicMaxWorkers;
43 static int FailedWorkers;
44 static long RunningPkgDepSize;
45 static pthread_mutex_t WorkerMutex;
46 static pthread_cond_t WorkerCond;
47 
48 static int build_find_leaves(pkg_t *parent, pkg_t *pkg,
49 			pkg_t ***build_tailp, int *app, int *hasworkp,
50 			int depth, int first, int first_one_only);
51 static int buildCalculateDepiDepth(pkg_t *pkg);
52 static void build_clear_trav(pkg_t *pkg);
53 static void startbuild(pkg_t **build_listp, pkg_t ***build_tailp);
54 static int qsort_depi(const void *pkg1, const void *pkg2);
55 static int qsort_idep(const void *pkg1, const void *pkg2);
56 static void startworker(pkg_t *pkg, worker_t *work);
57 static void cleanworker(worker_t *work);
58 static void waitbuild(int whilematch, int dynamicmax);
59 static void workercomplete(worker_t *work);
60 static void *childBuilderThread(void *arg);
61 static int childInstallPkgDeps(worker_t *work);
62 static size_t childInstallPkgDeps_recurse(FILE *fp, pkglink_t *list,
63 			int undoit, int depth, int first_one_only);
64 static void dophase(worker_t *work, wmsg_t *wmsg,
65 			int wdog, int phaseid, const char *phase);
66 static void phaseReapAll(void);
67 static void phaseTerminateSignal(int sig);
68 static char *buildskipreason(pkglink_t *parent, pkg_t *pkg);
69 static int buildskipcount_dueto(pkg_t *pkg, int mode);
70 static int mptylogpoll(int ptyfd, int fdlog, wmsg_t *wmsg,
71 			time_t *wdog_timep);
72 static void doHook(pkg_t *pkg, const char *id, const char *path, int waitfor);
73 static void childHookRun(bulk_t *bulk);
74 static void adjloadavg(double *dload);
75 static void check_packaged(const char *dbmpath, pkg_t *pkgs);
76 
77 static worker_t *SigWork;
78 static int MasterPtyFd = -1;
79 static int CopyFileFd = -1;
80 static pid_t SigPid;
81 static const char *WorkerFlavorPrt = "";	/* "" or "@flavor" */
82 static DBM *CheckDBM;
83 
84 #define MPTY_FAILED	-2
85 #define MPTY_AGAIN	-1
86 #define MPTY_EOF	0
87 #define MPTY_DATA	1
88 
89 int BuildTotal;
90 int BuildCount;
91 int BuildSkipCount;
92 int BuildIgnoreCount;
93 int BuildFailCount;
94 int BuildSuccessCount;
95 int BuildMissingCount;
96 int BuildMetaCount;
97 
98 /*
99  * Initialize the WorkerAry[]
100  */
101 void
102 DoInitBuild(int slot_override)
103 {
104 	worker_t *work;
105 	struct stat st;
106 	int i;
107 
108 	ddassert(slot_override < 0 || MaxWorkers == 1);
109 
110 	bzero(WorkerAry, MaxWorkers * sizeof(worker_t));
111 	pthread_mutex_init(&WorkerMutex, NULL);
112 
113 	for (i = 0; i < MaxWorkers; ++i) {
114 		work = &WorkerAry[i];
115 		work->index = (slot_override >= 0) ? slot_override : i;
116 		work->state = WORKER_NONE;
117 		asprintf(&work->basedir, "%s/SL%02d", BuildBase, work->index);
118 		pthread_cond_init(&work->cond, NULL);
119 	}
120 	BuildCount = 0;
121 
122 	/*
123 	 * Create required sub-directories. The base directories must already
124 	 * exist as a dsynth configuration safety.
125 	 */
126 	if (stat(RepositoryPath, &st) < 0) {
127 		if (mkdir(RepositoryPath, 0755) < 0)
128 			dfatal("Cannot mkdir %s\n", RepositoryPath);
129 	}
130 
131 	BuildInitialized = 1;
132 
133 	/*
134 	 * slow-start (increases at a rate of 1 per 5 seconds)
135 	 */
136 	if (SlowStartOpt > MaxWorkers)
137 		DynamicMaxWorkers = MaxWorkers;
138 	else if (SlowStartOpt > 0)
139 		DynamicMaxWorkers = SlowStartOpt;
140 	else
141 		DynamicMaxWorkers = MaxWorkers;
142 }
143 
144 /*
145  * Called by the frontend to clean-up any hanging mounts.
146  */
147 void
148 DoCleanBuild(int resetlogs)
149 {
150 	int i;
151 
152 	ddassert(BuildInitialized);
153 
154 	if (resetlogs)
155 		dlogreset();
156 	for (i = 0; i < MaxWorkers; ++i) {
157 		DoWorkerUnmounts(&WorkerAry[i]);
158 	}
159 }
160 
161 void
162 DoBuild(pkg_t *pkgs)
163 {
164 	pkg_t *build_list = NULL;
165 	pkg_t **build_tail = &build_list;
166 	pkg_t *scan;
167 	bulk_t *bulk;
168 	int haswork = 1;
169 	int first = 1;
170 	int newtemplate;
171 	time_t startTime;
172 	time_t t;
173 	int h, m, s;
174 	char *dbmpath;
175 
176 	/*
177 	 * We use our bulk system to run hooks.  This will be for
178 	 * Skipped and Ignored.  Success and Failure are handled by
179 	 * WorkerProcess() which is a separately-exec'd dsynth.
180 	 */
181 	if (UsingHooks)
182 		initbulk(childHookRun, MaxBulk);
183 
184 	/*
185 	 * Count up the packages, not counting dummies
186 	 */
187 	for (scan = pkgs; scan; scan = scan->bnext) {
188 		if ((scan->flags & PKGF_DUMMY) == 0)
189 			++BuildTotal;
190 	}
191 
192 	/*
193 	 * Remove binary package files for dports whos directory
194 	 * has changed.
195 	 */
196 	asprintf(&dbmpath, "%s/ports_crc", BuildBase);
197 	CheckDBM = dbm_open(dbmpath, O_CREAT|O_RDWR, 0644);
198 	check_packaged(dbmpath, pkgs);
199 
200 	doHook(NULL, "hook_run_start", HookRunStart, 1);
201 
202 	/*
203 	 * The pkg and pkg-static binaries are needed.  If already present
204 	 * then assume that the template is also valid, otherwise add to
205 	 * the list and build both.
206 	 */
207 	scan = GetPkgPkg(&pkgs);
208 
209 	/*
210 	 * Create our template.  The template will be missing pkg
211 	 * and pkg-static.
212 	 */
213 	if ((scan->flags & (PKGF_SUCCESS | PKGF_PACKAGED)) == 0) {
214 		/* force a fresh template */
215 		newtemplate = DoCreateTemplate(1);
216 	} else {
217 		newtemplate = DoCreateTemplate(0);
218 	}
219 
220 	/*
221 	 * This will clear the screen and set-up our gui, so sleep
222 	 * a little first in case the user wants to see what was
223 	 * printed before.
224 	 */
225 	sleep(2);
226 	pthread_mutex_lock(&WorkerMutex);
227 	startTime = time(NULL);
228 	RunStatsInit();
229 	RunStatsReset();
230 
231 	/*
232 	 * Build pkg/pkg-static.
233 	 */
234 	if ((scan->flags & (PKGF_SUCCESS | PKGF_PACKAGED)) == 0) {
235 		build_list = scan;
236 		build_tail = &scan->build_next;
237 		startbuild(&build_list, &build_tail);
238 		while (RunningWorkers == 1)
239 			waitbuild(1, 0);
240 
241 		if (scan->flags & PKGF_NOBUILD)
242 			dfatal("Unable to build 'pkg'");
243 		if (scan->flags & PKGF_ERROR)
244 			dfatal("Error building 'pkg'");
245 		if ((scan->flags & PKGF_SUCCESS) == 0)
246 			dfatal("Error building 'pkg'");
247 		newtemplate = 1;
248 	}
249 
250 	/*
251 	 * Install pkg/pkg-static into the template
252 	 */
253 	if (newtemplate) {
254 		char *buf;
255 		int rc;
256 
257 		asprintf(&buf,
258 			 "cd %s/Template; "
259 			 "tar --exclude '+*' --exclude '*/man/*' "
260 			 "-xvzpf %s/%s > /dev/null 2>&1",
261 			 BuildBase,
262 			 RepositoryPath,
263 			 scan->pkgfile);
264 		rc = system(buf);
265 		if (rc)
266 			dfatal("Command failed: %s\n", buf);
267 		freestrp(&buf);
268 	}
269 
270 	/*
271 	 * Calculate depi_depth, the longest chain of dependencies
272 	 * for who depends on me, weighted by powers of two.
273 	 */
274 	for (scan = pkgs; scan; scan = scan->bnext) {
275 		buildCalculateDepiDepth(scan);
276 	}
277 
278 	/*
279 	 * Nominal bulk build sequence
280 	 */
281 	while (haswork) {
282 		haswork = 0;
283 		fflush(stdout);
284 		for (scan = pkgs; scan; scan = scan->bnext) {
285 			ddprintf(0, "SCANLEAVES %08x %s\n",
286 				 scan->flags, scan->portdir);
287 			scan->flags |= PKGF_BUILDLOOP;
288 			/*
289 			 * NOTE: We must still find dependencies if PACKAGED
290 			 *	 to fill in the gaps, as some of them may
291 			 *	 need to be rebuilt.
292 			 */
293 			if (scan->flags & (PKGF_SUCCESS | PKGF_FAILURE |
294 					   PKGF_ERROR)) {
295 #if 0
296 				ddprintf(0, "%s: already built\n",
297 					 scan->portdir);
298 #endif
299 			} else {
300 				int ap = 0;
301 				build_find_leaves(NULL, scan, &build_tail,
302 						  &ap, &haswork, 0, first, 0);
303 				ddprintf(0, "TOPLEVEL %s %08x\n",
304 					 scan->portdir, ap);
305 			}
306 			scan->flags &= ~PKGF_BUILDLOOP;
307 			build_clear_trav(scan);
308 		}
309 		first = 0;
310 		fflush(stdout);
311 		startbuild(&build_list, &build_tail);
312 
313 		if (haswork == 0 && RunningWorkers) {
314 			waitbuild(RunningWorkers, 1);
315 			haswork = 1;
316 		}
317 	}
318 	pthread_mutex_unlock(&WorkerMutex);
319 
320 	/*
321 	 * What is left that cannot be built?  The list really ought to be
322 	 * empty at this point, report anything that remains.
323 	 */
324 	for (scan = pkgs; scan; scan = scan->bnext) {
325 		if (scan->flags & (PKGF_SUCCESS | PKGF_FAILURE))
326 			continue;
327 		dlog(DLOG_ABN, "[XXX] %s lost in the ether [flags=%08x]\n",
328 		     scan->portdir, scan->flags);
329 		++BuildMissingCount;
330 	}
331 
332 	/*
333 	 * Final updates
334 	 */
335 	RunStatsUpdateTop(0);
336 	RunStatsUpdateLogs();
337 	RunStatsSync();
338 	RunStatsDone();
339 
340 	doHook(NULL, "hook_run_end", HookRunEnd, 1);
341 	if (UsingHooks) {
342 		while ((bulk = getbulk()) != NULL)
343 			freebulk(bulk);
344 		donebulk();
345 	}
346 
347 	t = time(NULL) - startTime;
348 	h = t / 3600;
349 	m = t / 60 % 60;
350 	s = t % 60;
351 
352 	if (CheckDBM) {
353 		dbm_close(CheckDBM);
354 		CheckDBM = NULL;
355 	}
356 
357 	dlog(DLOG_ALL|DLOG_STDOUT,
358 		"\n"
359 		"Initial queue size: %d\n"
360 		"    packages built: %d\n"
361 		"           ignored: %d\n"
362 		"           skipped: %d\n"
363 		"            failed: %d\n"
364 		"           missing: %d\n"
365 		"        meta-nodes: %d\n"
366 		"\n"
367 		"Duration: %02d:%02d:%02d\n"
368 		"\n",
369 		BuildTotal,
370 		BuildSuccessCount,
371 		BuildIgnoreCount,
372 		BuildSkipCount,
373 		BuildFailCount,
374 		BuildMissingCount,
375 		BuildMetaCount,
376 		h, m, s);
377 }
378 
379 /*
380  * Traverse the packages (pkg) depends on recursively until we find
381  * a leaf to build or report as unbuildable.  Calculates and assigns a
382  * dependency count.  Returns all parallel-buildable packages.
383  *
384  * (pkg) itself is only added to the list if it is immediately buildable.
385  */
386 static
387 int
388 build_find_leaves(pkg_t *parent, pkg_t *pkg, pkg_t ***build_tailp,
389 		  int *app, int *hasworkp, int depth, int first,
390 		  int first_one_only)
391 {
392 	pkglink_t *link;
393 	pkg_t *scan;
394 	int idep_count = 0;
395 	int apsub;
396 	int dfirst_one_only;
397 	int ndepth;
398 	char *buf;
399 
400 	ndepth = depth + 1;
401 
402 	/*
403 	 * Already on build list, possibly in-progress, tell caller that
404 	 * it is not ready.
405 	 */
406 	ddprintf(ndepth, "sbuild_find_leaves %d %s %08x {\n",
407 		 depth, pkg->portdir, pkg->flags);
408 	if (pkg->flags & PKGF_BUILDLIST) {
409 		ddprintf(ndepth, "} (already on build list)\n");
410 		*app |= PKGF_NOTREADY;
411 		return (pkg->idep_count);
412 	}
413 
414 	/*
415 	 * Check dependencies
416 	 */
417 	PKGLIST_FOREACH(link, &pkg->idepon_list) {
418 		scan = link->pkg;
419 
420 		if (scan == NULL) {
421 			if (first_one_only)
422 				break;
423 			continue;
424 		}
425 		ddprintf(ndepth, "check %s %08x\t", scan->portdir, scan->flags);
426 
427 		/*
428 		 * If this dependency is to a DUMMY node it is a dependency
429 		 * only on the default flavor which is only the first node
430 		 * under this one, not all of them.
431 		 *
432 		 * DUMMY nodes can be marked SUCCESS so the build skips past
433 		 * them, but this doesn't mean that their sub-nodes succeeded.
434 		 * We have to check, so recurse even if it is marked
435 		 * successful.
436 		 *
437 		 * NOTE: The depth is not being for complex dependency type
438 		 *	 tests like it is in childInstallPkgDeps_recurse(),
439 		 *	 so we don't have to hicup it like we do in that
440 		 *	 procedure.
441 		 */
442 		dfirst_one_only = (scan->flags & PKGF_DUMMY) ? 1 : 0;
443 		if (dfirst_one_only)
444 			goto skip_to_flavor;
445 
446 		/*
447 		 * When accounting for a successful build, just bump
448 		 * idep_count by one.  scan->idep_count will heavily
449 		 * overlap packages that we count down multiple branches.
450 		 *
451 		 * We must still recurse through PACKAGED packages as
452 		 * some of their dependencies might be missing.
453 		 */
454 		if (scan->flags & PKGF_SUCCESS) {
455 			ddprintf(0, "SUCCESS - OK\n");
456 			++idep_count;
457 			if (first_one_only)
458 				break;
459 			continue;
460 		}
461 
462 		/*
463 		 * ERROR includes FAILURE, which is set in numerous situations
464 		 * including when NOBUILD state is finally processed.  So
465 		 * check for NOBUILD state first.
466 		 *
467 		 * An ERROR in a sub-package causes a NOBUILD in packages
468 		 * that depend on it.
469 		 */
470 		if (scan->flags & PKGF_NOBUILD) {
471 			ddprintf(0, "NOBUILD - OK "
472 				    "(propagate failure upward)\n");
473 			*app |= PKGF_NOBUILD_S;
474 			if (first_one_only)
475 				break;
476 			continue;
477 		}
478 		if (scan->flags & PKGF_ERROR) {
479 			ddprintf(0, "ERROR - OK (propagate failure upward)\n");
480 			*app |= PKGF_NOBUILD_S;
481 			if (first_one_only)
482 				break;
483 			continue;
484 		}
485 
486 		/*
487 		 * If already on build-list this dependency is not ready.
488 		 */
489 		if (scan->flags & PKGF_BUILDLIST) {
490 			ddprintf(0, " [BUILDLIST]");
491 			*app |= PKGF_NOTREADY;
492 		}
493 
494 		/*
495 		 * If not packaged this dependency is not ready for
496 		 * the caller.
497 		 */
498 		if ((scan->flags & PKGF_PACKAGED) == 0) {
499 			ddprintf(0, " [NOT_PACKAGED]");
500 			*app |= PKGF_NOTREADY;
501 		}
502 
503 		/*
504 		 * Reduce search complexity, if we have already processed
505 		 * scan in the traversal it will either already be on the
506 		 * build list or it will not be buildable.  Either way
507 		 * the parent is not buildable.
508 		 */
509 		if (scan->flags & PKGF_BUILDTRAV) {
510 			ddprintf(0, " [BUILDTRAV]\n");
511 			*app |= PKGF_NOTREADY;
512 			if (first_one_only)
513 				break;
514 			continue;
515 		}
516 skip_to_flavor:
517 
518 		/*
519 		 * Assert on dependency loop
520 		 */
521 		++idep_count;
522 		if (scan->flags & PKGF_BUILDLOOP) {
523 			dfatal("pkg dependency loop %s -> %s",
524 				parent->portdir, scan->portdir);
525 		}
526 
527 		/*
528 		 * NOTE: For debug tabbing purposes we use (ndepth + 1)
529 		 *	 here (i.e. depth + 2) in our iteration.
530 		 */
531 		scan->flags |= PKGF_BUILDLOOP;
532 		apsub = 0;
533 		ddprintf(0, " SUBRECURSION {\n");
534 		idep_count += build_find_leaves(pkg, scan, build_tailp,
535 						&apsub, hasworkp,
536 						ndepth + 1, first,
537 						dfirst_one_only);
538 		scan->flags &= ~PKGF_BUILDLOOP;
539 		*app |= apsub;
540 		if (apsub & PKGF_NOBUILD) {
541 			ddprintf(ndepth, "} (sub-nobuild)\n");
542 		} else if (apsub & PKGF_ERROR) {
543 			ddprintf(ndepth, "} (sub-error)\n");
544 		} else if (apsub & PKGF_NOTREADY) {
545 			ddprintf(ndepth, "} (sub-notready)\n");
546 		} else {
547 			ddprintf(ndepth, "} (sub-ok)\n");
548 		}
549 		if (first_one_only)
550 			break;
551 	}
552 	pkg->idep_count = idep_count;
553 	pkg->flags |= PKGF_BUILDTRAV;
554 
555 	/*
556 	 * Incorporate scan results into pkg state.
557 	 */
558 	if ((pkg->flags & PKGF_NOBUILD) == 0 && (*app & PKGF_NOBUILD)) {
559 		*hasworkp = 1;
560 	} else if ((pkg->flags & PKGF_ERROR) == 0 && (*app & PKGF_ERROR)) {
561 		*hasworkp = 1;
562 	}
563 	pkg->flags |= *app & ~PKGF_NOTREADY;
564 
565 	/*
566 	 * Clear the PACKAGED bit if sub-dependencies aren't clean.
567 	 *
568 	 * NOTE: PKGF_NOTREADY is not stored in pkg->flags, only in *app,
569 	 *	 so incorporate *app to test for it.
570 	 */
571 	if ((pkg->flags & PKGF_PACKAGED) &&
572 	    ((pkg->flags | *app) & (PKGF_NOTREADY|PKGF_ERROR|PKGF_NOBUILD))) {
573 		pkg->flags &= ~PKGF_PACKAGED;
574 		ddassert(pkg->pkgfile);
575 		asprintf(&buf, "%s/%s", RepositoryPath, pkg->pkgfile);
576 		if (OverridePkgDeleteOpt >= 1) {
577 			pkg->flags |= PKGF_PACKAGED;
578 			dlog(DLOG_ALL,
579 			     "[XXX] %s DELETE-PACKAGE %s "
580 			     "(OVERRIDE, NOT DELETED)\n",
581 			     pkg->portdir, buf);
582 		} else if (remove(buf) < 0) {
583 			dlog(DLOG_ALL,
584 			     "[XXX] %s DELETE-PACKAGE %s (failed)\n",
585 			     pkg->portdir, buf);
586 		} else {
587 			dlog(DLOG_ALL,
588 			     "[XXX] %s DELETE-PACKAGE %s "
589 			     "(due to dependencies)\n",
590 			     pkg->portdir, buf);
591 		}
592 		freestrp(&buf);
593 		*hasworkp = 1;
594 	}
595 
596 	/*
597 	 * Set PKGF_NOBUILD_I if there is IGNORE data
598 	 */
599 	if (pkg->ignore) {
600 		pkg->flags |= PKGF_NOBUILD_I;
601 	}
602 
603 	/*
604 	 * Handle propagated flags
605 	 */
606 	if (pkg->flags & PKGF_ERROR) {
607 		/*
608 		 * This can only happen if the ERROR has already been
609 		 * processed and accounted for.
610 		 */
611 		ddprintf(depth, "} (ERROR - %s)\n", pkg->portdir);
612 	} else if (*app & PKGF_NOTREADY) {
613 		/*
614 		 * We don't set PKGF_NOTREADY in the pkg, it is strictly
615 		 * a transient flag propagated via build_find_leaves().
616 		 *
617 		 * Just don't add the package to the list.
618 		 *
619 		 * NOTE: Even if NOBUILD is set (meaning we could list it
620 		 *	 and let startbuild() finish it up as a skip, we
621 		 *	 don't process it to the list because we want to
622 		 *	 process all the dependencies, so someone doing a
623 		 *	 manual build can get more complete information and
624 		 *	 does not have to iterate each failed dependency one
625 		 *	 at a time.
626 		 */
627 		;
628 	} else if (pkg->flags & PKGF_SUCCESS) {
629 		ddprintf(depth, "} (SUCCESS - %s)\n", pkg->portdir);
630 	} else if (pkg->flags & PKGF_DUMMY) {
631 		/*
632 		 * Just mark dummy packages as successful when all of their
633 		 * sub-depends (flavors) complete successfully.  Note that
634 		 * dummy packages are not counted in the total, so do not
635 		 * decrement BuildTotal.
636 		 *
637 		 * Do not propagate *app up for the dummy node or add it to
638 		 * the build list.  The dummy node itself is not an actual
639 		 * dependency.  Packages which depend on the default flavor
640 		 * (aka this dummy node) actually depend on the first flavor
641 		 * under this node.
642 		 *
643 		 * So if there is a generic dependency (i.e. no flavor
644 		 * specified), the upper recursion detects PKGF_DUMMY and
645 		 * traverses through the dummy node to the default flavor
646 		 * without checking the error/nobuild flags on this dummy
647 		 * node.
648 		 */
649 		if (pkg->flags & PKGF_NOBUILD) {
650 			ddprintf(depth, "} (DUMMY/META - IGNORED "
651 				 "- MARK SUCCESS ANYWAY)\n");
652 		} else {
653 			ddprintf(depth, "} (DUMMY/META - SUCCESS)\n");
654 		}
655 		pkg->flags |= PKGF_SUCCESS;
656 		*hasworkp = 1;
657 		if (first) {
658 			dlog(DLOG_ALL | DLOG_FILTER,
659 			     "[XXX] %s META-ALREADY-BUILT\n",
660 			     pkg->portdir);
661 		} else {
662 			dlog(DLOG_SUCC, "[XXX] %s meta-node complete\n",
663 			     pkg->portdir);
664 			RunStatsUpdateCompletion(NULL, DLOG_SUCC, pkg, "", "");
665 			++BuildMetaCount;   /* Only for not built meta nodes */
666 		}
667 	} else if (pkg->flags & PKGF_PACKAGED) {
668 		/*
669 		 * We can just mark the pkg successful.  If this is
670 		 * the first pass, we count this as an initial pruning
671 		 * pass and reduce BuildTotal.
672 		 */
673 		ddprintf(depth, "} (PACKAGED - SUCCESS)\n");
674 		pkg->flags |= PKGF_SUCCESS;
675 		*hasworkp = 1;
676 		if (first) {
677 			dlog(DLOG_ALL | DLOG_FILTER,
678 			     "[XXX] %s Already-Built\n",
679 			     pkg->portdir);
680 			--BuildTotal;
681 		} else {
682 			dlog(DLOG_ABN | DLOG_FILTER,
683 			     "[XXX] %s flags=%08x Packaged Unexpectedly\n",
684 			     pkg->portdir, pkg->flags);
685 			/* ++BuildSuccessTotal; XXX not sure */
686 			goto addlist;
687 		}
688 	} else {
689 		/*
690 		 * All dependencies are successful, queue new work
691 		 * and indicate not-ready to the parent (since our
692 		 * package has to be built).
693 		 *
694 		 * NOTE: The NOBUILD case propagates to here as well
695 		 *	 and is ultimately handled by startbuild().
696 		 */
697 addlist:
698 		*hasworkp = 1;
699 		if (pkg->flags & PKGF_NOBUILD_I)
700 			ddprintf(depth, "} (ADDLIST(IGNORE/BROKEN) - %s)\n",
701 				 pkg->portdir);
702 		else if (pkg->flags & PKGF_NOBUILD)
703 			ddprintf(depth, "} (ADDLIST(NOBUILD) - %s)\n",
704 				 pkg->portdir);
705 		else
706 			ddprintf(depth, "} (ADDLIST - %s)\n", pkg->portdir);
707 		pkg->flags |= PKGF_BUILDLIST;
708 		**build_tailp = pkg;
709 		*build_tailp = &pkg->build_next;
710 		pkg->build_next = NULL;
711 		*app |= PKGF_NOTREADY;
712 	}
713 
714 	return idep_count;
715 }
716 
717 static
718 void
719 build_clear_trav(pkg_t *pkg)
720 {
721 	pkglink_t *link;
722 	pkg_t *scan;
723 
724 	pkg->flags &= ~PKGF_BUILDTRAV;
725 	PKGLIST_FOREACH(link, &pkg->idepon_list) {
726 		scan = link->pkg;
727 		if (scan && (scan->flags & PKGF_BUILDTRAV))
728 			build_clear_trav(scan);
729 	}
730 }
731 
732 /*
733  * Calculate the longest chain of packages that depend on me.  The
734  * long the chain, the more important my package is to build earlier
735  * rather than later.
736  */
737 static int
738 buildCalculateDepiDepth(pkg_t *pkg)
739 {
740 	pkglink_t *link;
741 	pkg_t *scan;
742 	int best_depth = 0;
743 	int res;
744 
745 	if (pkg->depi_depth)
746 		return(pkg->depi_depth + 1);
747 	pkg->flags |= PKGF_BUILDLOOP;
748 	PKGLIST_FOREACH(link, &pkg->deponi_list) {
749 		scan = link->pkg;
750 		if (scan && (scan->flags & PKGF_BUILDLOOP) == 0) {
751 			res = buildCalculateDepiDepth(scan);
752 			if (best_depth < res)
753 				best_depth = res;
754 		}
755 	}
756 	pkg->flags &= ~PKGF_BUILDLOOP;
757 	pkg->depi_depth = best_depth;
758 
759 	return (best_depth + 1);
760 }
761 
762 /*
763  * Take a list of pkg ready to go, sort it, and assign it to worker
764  * slots.  This routine blocks in waitbuild() until it can dispose of
765  * the entire list.
766  *
767  * WorkerMutex is held by the caller.
768  */
769 static
770 void
771 startbuild(pkg_t **build_listp, pkg_t ***build_tailp)
772 {
773 	pkg_t *pkg;
774 	pkg_t **idep_ary;
775 	pkg_t **depi_ary;
776 	int count;
777 	int idep_index;
778 	int depi_index;
779 	int i;
780 	int n;
781 	worker_t *work;
782 	static int IterateWorker;
783 
784 	/*
785 	 * Nothing to do
786 	 */
787 	if (*build_listp == NULL)
788 		return;
789 
790 	/*
791 	 * Sort
792 	 */
793 	count = 0;
794 	for (pkg = *build_listp; pkg; pkg = pkg->build_next)
795 		++count;
796 	idep_ary = calloc(count, sizeof(pkg_t *));
797 	depi_ary = calloc(count, sizeof(pkg_t *));
798 
799 	count = 0;
800 	for (pkg = *build_listp; pkg; pkg = pkg->build_next) {
801 		idep_ary[count] = pkg;
802 		depi_ary[count] = pkg;
803 		++count;
804 	}
805 
806 	/*
807 	 * idep_ary - sorted by #of dependencies this pkg has.
808 	 * depi_ary - sorted by #of other packages that depend on this pkg.
809 	 */
810 	qsort(idep_ary, count, sizeof(pkg_t *), qsort_idep);
811 	qsort(depi_ary, count, sizeof(pkg_t *), qsort_depi);
812 
813 	idep_index = 0;
814 	depi_index = 0;
815 
816 	/*
817 	 * Half the workers build based on the highest depi count,
818 	 * the other half build based on the highest idep count.
819 	 *
820 	 * This is an attempt to get projects which many other projects
821 	 * depend on built first, but to also try to build large projects
822 	 * (which tend to have a lot of dependencies) earlier rather than
823 	 * later so the end of the bulk run doesn't inefficiently build
824 	 * the last few huge projects.
825 	 *
826 	 * Loop until we manage to assign slots to everyone.  We do not
827 	 * wait for build completion.
828 	 *
829 	 * This is the point where we handle DUMMY packages (these are
830 	 * dummy unflavored packages which 'cover' all the flavors for
831 	 * a package).  These are not real packages are marked SUCCESS
832 	 * at this time because their dependencies (the flavors) have all
833 	 * been built.
834 	 */
835 	while (idep_index != count || depi_index != count) {
836 		pkg_t *pkgi;
837 		pkg_t *ipkg;
838 
839 		/*
840 		 * Find candidate to start sorted by depi or idep.
841 		 */
842 		ipkg = NULL;
843 		while (idep_index < count) {
844 			ipkg = idep_ary[idep_index];
845 			if ((ipkg->flags &
846 			     (PKGF_SUCCESS | PKGF_FAILURE |
847 			      PKGF_ERROR | PKGF_RUNNING)) == 0) {
848 				break;
849 			}
850 			ipkg = NULL;
851 			++idep_index;
852 		}
853 
854 		pkgi = NULL;
855 		while (depi_index < count) {
856 			pkgi = depi_ary[depi_index];
857 			if ((pkgi->flags &
858 			     (PKGF_SUCCESS | PKGF_FAILURE |
859 			      PKGF_ERROR | PKGF_RUNNING)) == 0) {
860 				break;
861 			}
862 			pkgi = NULL;
863 			++depi_index;
864 		}
865 
866 		/*
867 		 * ipkg and pkgi must either both be NULL, or both
868 		 * be non-NULL.
869 		 */
870 		if (ipkg == NULL && pkgi == NULL)
871 			break;
872 		ddassert(ipkg && pkgi);
873 
874 		/*
875 		 * Handle the NOBUILD case right here, there's no point
876 		 * queueing it anywhere.
877 		 */
878 		if (ipkg->flags & PKGF_NOBUILD) {
879 			char *reason;
880 			char skipbuf[16];
881 			int scount;
882 
883 			scount = buildskipcount_dueto(ipkg, 1);
884 			buildskipcount_dueto(ipkg, 0);
885 			if (scount) {
886 				snprintf(skipbuf, sizeof(skipbuf), " %d",
887 					 scount);
888 			} else {
889 				skipbuf[0] = 0;
890 			}
891 
892 			ipkg->flags |= PKGF_FAILURE;
893 			ipkg->flags &= ~PKGF_BUILDLIST;
894 
895 			reason = buildskipreason(NULL, ipkg);
896 			if (ipkg->flags & PKGF_NOBUILD_I) {
897 				++BuildIgnoreCount;
898 				dlog(DLOG_IGN,
899 				     "[XXX] %s%s ignored due to %s\n",
900 				     ipkg->portdir, skipbuf, reason);
901 				RunStatsUpdateCompletion(NULL, DLOG_IGN, ipkg,
902 							 reason, skipbuf);
903 				doHook(ipkg, "hook_pkg_ignored",
904 				       HookPkgIgnored, 0);
905 			} else {
906 				++BuildSkipCount;
907 				dlog(DLOG_SKIP,
908 				     "[XXX] %s%s skipped due to %s\n",
909 				     ipkg->portdir, skipbuf, reason);
910 				RunStatsUpdateCompletion(NULL, DLOG_SKIP, ipkg,
911 							 reason, skipbuf);
912 				doHook(ipkg, "hook_pkg_skipped",
913 				       HookPkgSkipped, 0);
914 			}
915 			free(reason);
916 			++BuildCount;
917 			continue;
918 		}
919 		if (pkgi->flags & PKGF_NOBUILD) {
920 			char *reason;
921 			char skipbuf[16];
922 			int scount;
923 
924 			scount = buildskipcount_dueto(pkgi, 1);
925 			buildskipcount_dueto(pkgi, 0);
926 			if (scount) {
927 				snprintf(skipbuf, sizeof(skipbuf), " %d",
928 					 scount);
929 			} else {
930 				skipbuf[0] = 0;
931 			}
932 
933 			pkgi->flags |= PKGF_FAILURE;
934 			pkgi->flags &= ~PKGF_BUILDLIST;
935 
936 			reason = buildskipreason(NULL, pkgi);
937 			if (pkgi->flags & PKGF_NOBUILD_I) {
938 				++BuildIgnoreCount;
939 				dlog(DLOG_IGN, "[XXX] %s%s ignored due to %s\n",
940 				     pkgi->portdir, skipbuf, reason);
941 				RunStatsUpdateCompletion(NULL, DLOG_IGN, pkgi,
942 							 reason, skipbuf);
943 				doHook(pkgi, "hook_pkg_ignored",
944 				       HookPkgIgnored, 0);
945 			} else {
946 				++BuildSkipCount;
947 				dlog(DLOG_SKIP,
948 				     "[XXX] %s%s skipped due to %s\n",
949 				     pkgi->portdir, skipbuf, reason);
950 				RunStatsUpdateCompletion(NULL, DLOG_SKIP, pkgi,
951 							 reason, skipbuf);
952 				doHook(pkgi, "hook_pkg_skipped",
953 				       HookPkgSkipped, 0);
954 			}
955 			free(reason);
956 			++BuildCount;
957 			continue;
958 		}
959 
960 		/*
961 		 * Block while no slots are available.  waitbuild()
962 		 * will clean out any DONE states.
963 		 */
964 		while (RunningWorkers >= DynamicMaxWorkers ||
965 		       RunningWorkers >= MaxWorkers - FailedWorkers) {
966 			waitbuild(RunningWorkers, 1);
967 		}
968 
969 		/*
970 		 * Find an available worker slot, there should be at
971 		 * least one.
972 		 */
973 		for (i = 0; i < MaxWorkers; ++i) {
974 			n = IterateWorker % MaxWorkers;
975 			work = &WorkerAry[n];
976 
977 			if (work->state == WORKER_DONE ||
978 			    work->state == WORKER_FAILED) {
979 				workercomplete(work);
980 			}
981 			if (work->state == WORKER_NONE ||
982 			    work->state == WORKER_IDLE) {
983 				if (n <= MaxWorkers / 2) {
984 					startworker(pkgi, work);
985 				} else {
986 					startworker(ipkg, work);
987 				}
988 				/*RunStatsUpdate(work);*/
989 				break;
990 			}
991 			++IterateWorker;
992 		}
993 		ddassert(i != MaxWorkers);
994 	}
995 	RunStatsSync();
996 
997 	/*
998 	 * We disposed of the whole list
999 	 */
1000 	free(idep_ary);
1001 	free(depi_ary);
1002 	*build_listp = NULL;
1003 	*build_tailp = build_listp;
1004 }
1005 
1006 typedef const pkg_t *pkg_tt;
1007 
1008 static int
1009 qsort_idep(const void *pkg1_arg, const void *pkg2_arg)
1010 {
1011 	const pkg_t *pkg1 = *(const pkg_tt *)pkg1_arg;
1012 	const pkg_t *pkg2 = *(const pkg_tt *)pkg2_arg;
1013 
1014 	return (pkg2->idep_count - pkg1->idep_count);
1015 }
1016 
1017 static int
1018 qsort_depi(const void *pkg1_arg, const void *pkg2_arg)
1019 {
1020 	const pkg_t *pkg1 = *(const pkg_tt *)pkg1_arg;
1021 	const pkg_t *pkg2 = *(const pkg_tt *)pkg2_arg;
1022 
1023 	return ((pkg2->depi_count * pkg2->depi_depth) -
1024 		(pkg1->depi_count * pkg1->depi_depth));
1025 }
1026 
1027 /*
1028  * Frontend starts a pkg up on a worker
1029  *
1030  * WorkerMutex must be held.
1031  */
1032 static void
1033 startworker(pkg_t *pkg, worker_t *work)
1034 {
1035 	switch(work->state) {
1036 	case WORKER_NONE:
1037 		pthread_create(&work->td, NULL, childBuilderThread, work);
1038 		work->state = WORKER_IDLE;
1039 		/* fall through */
1040 	case WORKER_IDLE:
1041 		work->pkg_dep_size =
1042 		childInstallPkgDeps_recurse(NULL, &pkg->idepon_list, 0, 1, 0);
1043 		childInstallPkgDeps_recurse(NULL, &pkg->idepon_list, 1, 1, 0);
1044 		RunningPkgDepSize += work->pkg_dep_size;
1045 
1046 		dlog(DLOG_ALL, "[%03d] START   %s "
1047 			       "##idep=%02d depi=%02d/%02d dep=%-4.2fG\n",
1048 		     work->index, pkg->portdir,
1049 		     pkg->idep_count, pkg->depi_count, pkg->depi_depth,
1050 		     (double)work->pkg_dep_size / (double)ONEGB);
1051 
1052 		cleanworker(work);
1053 		pkg->flags |= PKGF_RUNNING;
1054 		work->pkg = pkg;
1055 		pthread_cond_signal(&work->cond);
1056 		++RunningWorkers;
1057 		/*RunStatsUpdate(work);*/
1058 		break;
1059 	case WORKER_PENDING:
1060 	case WORKER_RUNNING:
1061 	case WORKER_DONE:
1062 	case WORKER_FAILED:
1063 	case WORKER_FROZEN:
1064 	case WORKER_EXITING:
1065 	default:
1066 		dfatal("startworker: [%03d] Unexpected state %d for worker %d",
1067 		       work->index, work->state, work->index);
1068 		break;
1069 	}
1070 }
1071 
1072 static void
1073 cleanworker(worker_t *work)
1074 {
1075 	work->state = WORKER_PENDING;
1076 	work->flags = 0;
1077 	work->accum_error = 0;
1078 	work->start_time = time(NULL);
1079 }
1080 
1081 /*
1082  * Frontend finishes up a completed pkg on a worker.
1083  *
1084  * If the worker is in a FAILED state we clean the pkg out but (for now)
1085  * leave it in its failed state so we can debug.  At this point
1086  * workercomplete() will be called every once in a while on the state
1087  * and we have to deal with the NULL pkg.
1088  *
1089  * WorkerMutex must be held.
1090  */
1091 static void
1092 workercomplete(worker_t *work)
1093 {
1094 	pkg_t *pkg;
1095 	time_t t;
1096 	int h;
1097 	int m;
1098 	int s;
1099 
1100 	/*
1101 	 * Steady state FAILED case.
1102 	 */
1103 	if (work->state == WORKER_FAILED) {
1104 		if (work->pkg == NULL)
1105 			return;
1106 	}
1107 
1108 	t = time(NULL) - work->start_time;
1109 	h = t / 3600;
1110 	m = t / 60 % 60;
1111 	s = t % 60;
1112 
1113 	/*
1114 	 * Reduce total dep size
1115 	 */
1116 	RunningPkgDepSize -= work->pkg_dep_size;
1117 	RunningPkgDepSize -= work->memuse;
1118 	work->pkg_dep_size = 0;
1119 	work->memuse = 0;
1120 
1121 	/*
1122 	 * Process pkg out of the worker
1123 	 */
1124 	pkg = work->pkg;
1125 	if (pkg->flags & (PKGF_ERROR|PKGF_NOBUILD)) {
1126 		char skipbuf[16];
1127 		int scount;
1128 
1129 		pkg->flags |= PKGF_FAILURE;
1130 
1131 		scount = buildskipcount_dueto(pkg, 1);
1132 		buildskipcount_dueto(pkg, 0);
1133 		if (scount) {
1134 			snprintf(skipbuf, sizeof(skipbuf), " %d",
1135 				 scount);
1136 		} else {
1137 			skipbuf[0] = 0;
1138 		}
1139 
1140 		/*
1141 		 * This NOBUILD condition XXX can occur if the package is
1142 		 * not allowed to be built.
1143 		 */
1144 		if (pkg->flags & PKGF_NOBUILD) {
1145 			char *reason;
1146 
1147 			reason = buildskipreason(NULL, pkg);
1148 			if (pkg->flags & PKGF_NOBUILD_I) {
1149 				++BuildIgnoreCount;
1150 				dlog(DLOG_SKIP, "[%03d] IGNORD %s%s - %s\n",
1151 				     work->index, pkg->portdir,
1152 				     skipbuf, reason);
1153 				RunStatsUpdateCompletion(work, DLOG_SKIP, pkg,
1154 							 reason, skipbuf);
1155 				doHook(pkg, "hook_pkg_ignored",
1156 				       HookPkgIgnored, 0);
1157 			} else {
1158 				++BuildSkipCount;
1159 				dlog(DLOG_SKIP, "[%03d] SKIPPD %s%s - %s\n",
1160 				     work->index, pkg->portdir,
1161 				     skipbuf, reason);
1162 				RunStatsUpdateCompletion(work, DLOG_SKIP, pkg,
1163 							 reason, skipbuf);
1164 				doHook(pkg, "hook_pkg_skipped",
1165 				       HookPkgSkipped, 0);
1166 			}
1167 			free(reason);
1168 		} else {
1169 			++BuildFailCount;
1170 			dlog(DLOG_FAIL | DLOG_RED,
1171 			     "[%03d] FAILURE %s%s ##%16.16s %02d:%02d:%02d\n",
1172 			     work->index, pkg->portdir, skipbuf,
1173 			     getphasestr(work->phase),
1174 			     h, m, s);
1175 			RunStatsUpdateCompletion(work, DLOG_FAIL, pkg,
1176 						 skipbuf, "");
1177 			doHook(pkg, "hook_pkg_failure", HookPkgFailure, 0);
1178 		}
1179 	} else {
1180 		if (CheckDBM) {
1181 			datum key;
1182 			datum data;
1183 
1184 			key.dptr = pkg->portdir;
1185 			key.dsize = strlen(pkg->portdir);
1186 			data.dptr = &pkg->crc32;
1187 			data.dsize = sizeof(pkg->crc32);
1188 			dbm_store(CheckDBM, key, data, DBM_REPLACE);
1189 		}
1190 		pkg->flags |= PKGF_SUCCESS;
1191 		++BuildSuccessCount;
1192 		dlog(DLOG_SUCC | DLOG_GRN,
1193 		     "[%03d] SUCCESS %s ##%02d:%02d:%02d\n",
1194 		     work->index, pkg->portdir, h, m, s);
1195 		RunStatsUpdateCompletion(work, DLOG_SUCC, pkg, "", "");
1196 		doHook(pkg, "hook_pkg_success", HookPkgSuccess, 0);
1197 	}
1198 	++BuildCount;
1199 	pkg->flags &= ~PKGF_BUILDLIST;
1200 	pkg->flags &= ~PKGF_RUNNING;
1201 	work->pkg = NULL;
1202 	--RunningWorkers;
1203 
1204 	if (work->state == WORKER_FAILED) {
1205 		dlog(DLOG_ALL, "[%03d] XXX/XXX WORKER IS IN A FAILED STATE\n",
1206 		     work->index);
1207 		++FailedWorkers;
1208 	} else if (work->flags & WORKERF_FREEZE) {
1209 		dlog(DLOG_ALL, "[%03d] FROZEN(DEBUG) %s\n",
1210 		     work->index, pkg->portdir);
1211 		work->state = WORKER_FROZEN;
1212 	} else {
1213 		work->state = WORKER_IDLE;
1214 	}
1215 }
1216 
1217 /*
1218  * Wait for one or more workers to complete.
1219  *
1220  * WorkerMutex must be held.
1221  */
1222 static void
1223 waitbuild(int whilematch, int dynamicmax)
1224 {
1225 	static time_t wblast_time;
1226 	static time_t dmlast_time;
1227 	struct timespec ts;
1228 	worker_t *work;
1229 	time_t t;
1230 	int i;
1231 
1232 	if (whilematch == 0)
1233 		whilematch = 1;
1234 
1235 	while (RunningWorkers == whilematch) {
1236 		for (i = 0; i < MaxWorkers; ++i) {
1237 			work = &WorkerAry[i];
1238 			if (work->state == WORKER_DONE ||
1239 			    work->state == WORKER_FAILED) {
1240 				workercomplete(work);
1241 			} else {
1242 				pthread_cond_signal(&work->cond);
1243 			}
1244 			RunStatsUpdate(work, NULL);
1245 		}
1246 		RunStatsUpdateTop(1);
1247 		RunStatsUpdateLogs();
1248 		RunStatsSync();
1249 		if (RunningWorkers == whilematch) {
1250 			clock_gettime(CLOCK_REALTIME, &ts);
1251 			ts.tv_sec += 1;
1252 			ts.tv_nsec = 0;
1253 			pthread_cond_timedwait(&WorkerCond, &WorkerMutex, &ts);
1254 		}
1255 
1256 		/*
1257 		 * Dynamically reduce MaxWorkers based on the load.  When
1258 		 * the load exceeds 2 x ncpus we reduce the number of workers
1259 		 * up to 75% of MaxWorkers @ (5 x ncpus) load.
1260 		 *
1261 		 * Dynamically reduce MaxWorkers based on swap use, starting
1262 		 * at 10% swap and up to 75% of MaxWorkers at 40% swap.
1263 		 *
1264 		 * NOTE! Generally speaking this allows more workers to be
1265 		 *	 configured which helps in two ways.  First it allows
1266 		 *	 a higher build rate for smaller packages.  Second
1267 		 *	 it allows dsynth to ratchet-down the number of slots
1268 		 *	 when large packages are forcing the load up.
1269 		 *
1270 		 *	 A high load doesn't hurt efficiency, but swap usage
1271 		 *	 due to loading the tmpfs in lots of worker slots up
1272 		 *	 with tons of pkg install's (pre-reqs for a build)
1273 		 *	 does.  Reducing the number of worker slots has a
1274 		 *	 huge beneficial effect on reducing swap use / paging.
1275 		 */
1276 		t = time(NULL);
1277 		if (dynamicmax && (wblast_time == 0 ||
1278 				   (unsigned)(t - wblast_time) >= 5)) {
1279 			double min_load = 1.5 * NumCores;
1280 			double max_load = 5.0 * NumCores;
1281 			double min_swap = 0.10;
1282 			double max_swap = 0.40;
1283 			double dload[3];
1284 			double dswap;
1285 			int max1;
1286 			int max2;
1287 			int max3;
1288 			int max_sel;
1289 			int noswap;
1290 
1291 			wblast_time = t;
1292 
1293 			/*
1294 			 * Cap based on load.  This is back-loaded.
1295 			 */
1296 			getloadavg(dload, 3);
1297 			adjloadavg(dload);
1298 			if (dload[0] < min_load) {
1299 				max1 = MaxWorkers;
1300 			} else if (dload[0] <= max_load) {
1301 				max1 = MaxWorkers -
1302 				       MaxWorkers * 0.75 *
1303 				       (dload[0] - min_load) /
1304 				       (max_load - min_load);
1305 			} else {
1306 				max1 = MaxWorkers * 25 / 100;
1307 			}
1308 
1309 			/*
1310 			 * Cap based on swap use.  This is back-loaded.
1311 			 */
1312 			dswap = getswappct(&noswap);
1313 			if (dswap < min_swap) {
1314 				max2 = MaxWorkers;
1315 			} else if (dswap <= max_swap) {
1316 				max2 = MaxWorkers -
1317 				       MaxWorkers * 0.75 *
1318 				       (dswap - min_swap) /
1319 				       (max_swap - min_swap);
1320 			} else {
1321 				max2 = MaxWorkers * 25 / 100;
1322 			}
1323 
1324 			/*
1325 			 * Cap based on aggregate pkg-dependency memory
1326 			 * use installed in worker slots.  This is
1327 			 * front-loaded.
1328 			 *
1329 			 * Since it can take a while for workers to retire
1330 			 * (to reduce RunningPkgDepSize), just set our
1331 			 * target 1 below the current run count to allow
1332 			 * jobs to retire without being replaced with new
1333 			 * jobs.
1334 			 *
1335 			 * In addition, in order to avoid a paging 'shock',
1336 			 * We enforce a 30 second-per-increment slow-start
1337 			 * once RunningPkgDepSize exceeds 1/2 the target.
1338 			 */
1339 			if (RunningPkgDepSize > PkgDepMemoryTarget) {
1340 				max3 = RunningWorkers - 1;
1341 			} else if (RunningPkgDepSize > PkgDepMemoryTarget / 2) {
1342 				if (dmlast_time == 0 ||
1343 				    (unsigned)(t - dmlast_time) >= 30) {
1344 					dmlast_time = t;
1345 					max3 = RunningWorkers + 1;
1346 				} else {
1347 					max3 = RunningWorkers;
1348 				}
1349 			} else {
1350 				max3 = MaxWorkers;
1351 			}
1352 
1353 			/*
1354 			 * Priority reduction, convert to DynamicMaxWorkers
1355 			 */
1356 			max_sel = max1;
1357 			if (max_sel > max2)
1358 				max_sel = max2;
1359 			if (max_sel > max3)
1360 				max_sel = max3;
1361 
1362 			/*
1363 			 * Restrict to allowed range, and also handle
1364 			 * slow-start.
1365 			 */
1366 			if (max_sel < 1)
1367 				max_sel = 1;
1368 			if (max_sel > DynamicMaxWorkers + 1)
1369 				max_sel = DynamicMaxWorkers + 1;
1370 			if (max_sel > MaxWorkers)
1371 				max_sel = MaxWorkers;
1372 
1373 			/*
1374 			 * Stop waiting if DynamicMaxWorkers is going to
1375 			 * increase.
1376 			 */
1377 			if (DynamicMaxWorkers < max1)
1378 				whilematch = -1;
1379 
1380 			/*
1381 			 * And adjust
1382 			 */
1383 			if (DynamicMaxWorkers != max1) {
1384 				dlog(DLOG_ALL | DLOG_FILTER,
1385 				     "[XXX] Load=%-6.2f(%2d) "
1386 				     "Swap=%-3.2f%%(%2d) "
1387 				     "Mem=%3.2fG(%2d) "
1388 				     "Adjust Workers %d->%d\n",
1389 				     dload[0], max1,
1390 				     dswap * 100.0, max2,
1391 				     RunningPkgDepSize / (double)ONEGB, max3,
1392 				     DynamicMaxWorkers, max_sel);
1393 				DynamicMaxWorkers = max_sel;
1394 			}
1395 		}
1396 	}
1397 }
1398 
1399 
1400 /*
1401  * Worker pthread (WorkerAry)
1402  *
1403  * This thread belongs to the dsynth master process and handled a worker slot.
1404  * (this_thread) -> WORKER fork/exec (WorkerPocess) -> (pty) -> sub-processes.
1405  */
1406 static void *
1407 childBuilderThread(void *arg)
1408 {
1409 	char *envary[1] = { NULL };
1410 	worker_t *work = arg;
1411 	wmsg_t wmsg;
1412 	pkg_t *pkg;
1413 	pid_t pid;
1414 	int status;
1415 	int flags;
1416 	volatile int dowait;
1417 	char slotbuf[8];
1418 	char fdbuf[8];
1419 	char flagsbuf[16];
1420 
1421 	pthread_mutex_lock(&WorkerMutex);
1422 	while (work->terminate == 0) {
1423 		dowait = 1;
1424 
1425 		switch(work->state) {
1426 		case WORKER_IDLE:
1427 			break;
1428 		case WORKER_PENDING:
1429 			/*
1430 			 * Fork the management process for the pkg operation
1431 			 * on this worker slot.
1432 			 *
1433 			 * This process will set up the environment, do the
1434 			 * mounts, will become the reaper, and will process
1435 			 * pipe commands and handle chroot operations.
1436 			 *
1437 			 * NOTE: If SOCK_CLOEXEC is not supported WorkerMutex
1438 			 *	 is sufficient to interlock F_SETFD FD_CLOEXEC
1439 			 *	 operations.
1440 			 */
1441 			ddassert(work->pkg);
1442 			if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
1443 				       PF_UNSPEC, work->fds)) {
1444 				dfatal_errno("socketpair() during worker fork");
1445 			}
1446 			snprintf(slotbuf, sizeof(slotbuf), "%d", work->index);
1447 			snprintf(fdbuf, sizeof(fdbuf), "3");
1448 
1449 			/*
1450 			 * Pass global flags and add-in the DEBUGSTOP if
1451 			 * the package is flagged for debugging.
1452 			 */
1453 			flags = WorkerProcFlags;
1454 			if (work->pkg->flags & PKGF_DEBUGSTOP) {
1455 				flags |= WORKER_PROC_DEBUGSTOP;
1456 			} else {
1457 				flags &= ~WORKER_PROC_DEBUGSTOP;
1458 			}
1459 			snprintf(flagsbuf, sizeof(flagsbuf), "%d", flags);
1460 
1461 			/*
1462 			 * fds[0] - master
1463 			 * fds[1] - slave
1464 			 *
1465 			 * We pass the salve descriptor in fd 3 and close all
1466 			 * other descriptors for security.
1467 			 */
1468 			pthread_mutex_unlock(&WorkerMutex);
1469 			pid = vfork();
1470 			if (pid == 0) {
1471 				close(work->fds[0]);
1472 				dup2(work->fds[1], 3);
1473 				closefrom(4);
1474 				fcntl(3, F_SETFD, 0);
1475 				execle(DSynthExecPath, DSynthExecPath,
1476 				       "-p", Profile,
1477 				       "WORKER", slotbuf, fdbuf,
1478 				       work->pkg->portdir, work->pkg->pkgfile,
1479 				       flagsbuf,
1480 				       NULL, envary);
1481 				write(2, "EXECLE FAILURE\n", 15);
1482 				_exit(1);
1483 			}
1484 			pthread_mutex_lock(&WorkerMutex);
1485 			close(work->fds[1]);
1486 			work->phase = PHASE_PENDING;
1487 			work->lines = 0;
1488 			work->memuse = 0;
1489 			work->pid = pid;
1490 			work->state = WORKER_RUNNING;
1491 			/* fall through */
1492 		case WORKER_RUNNING:
1493 			/*
1494 			 * Poll for status updates, if NULL is returned
1495 			 * and status is non-zero, the communications link
1496 			 * failed unexpectedly.
1497 			 */
1498 			pkg = work->pkg;
1499 			pthread_mutex_unlock(&WorkerMutex);
1500 			status = ipcreadmsg(work->fds[0], &wmsg);
1501 			pthread_mutex_lock(&WorkerMutex);
1502 
1503 			if (status == 0) {
1504 				/*
1505 				 * Normal message, can include normal
1506 				 * termination which changes us over
1507 				 * to another state.
1508 				 */
1509 				dowait = 0;
1510 				switch(wmsg.cmd) {
1511 				case WMSG_CMD_INSTALL_PKGS:
1512 					wmsg.cmd = WMSG_RES_INSTALL_PKGS;
1513 					wmsg.status = childInstallPkgDeps(work);
1514 					pthread_mutex_unlock(&WorkerMutex);
1515 					ipcwritemsg(work->fds[0], &wmsg);
1516 					pthread_mutex_lock(&WorkerMutex);
1517 					break;
1518 				case WMSG_CMD_STATUS_UPDATE:
1519 					work->phase = wmsg.phase;
1520 					work->lines = wmsg.lines;
1521 					if (work->memuse != wmsg.memuse) {
1522 						RunningPkgDepSize +=
1523 						wmsg.memuse - work->memuse;
1524 						work->memuse = wmsg.memuse;
1525 					}
1526 					break;
1527 				case WMSG_CMD_SUCCESS:
1528 					work->flags |= WORKERF_SUCCESS;
1529 					break;
1530 				case WMSG_CMD_FAILURE:
1531 					work->flags |= WORKERF_FAILURE;
1532 					break;
1533 				case WMSG_CMD_FREEZEWORKER:
1534 					work->flags |= WORKERF_FREEZE;
1535 					break;
1536 				default:
1537 					break;
1538 				}
1539 				RunStatsUpdate(work, NULL);
1540 				RunStatsSync();
1541 			} else {
1542 				close(work->fds[0]);
1543 				pthread_mutex_unlock(&WorkerMutex);
1544 				while (waitpid(work->pid, &status, 0) < 0 &&
1545 				       errno == EINTR) {
1546 					;
1547 				}
1548 				pthread_mutex_lock(&WorkerMutex);
1549 
1550 				if (work->flags & WORKERF_SUCCESS) {
1551 					pkg->flags |= PKGF_SUCCESS;
1552 					work->state = WORKER_DONE;
1553 				} else if (work->flags & WORKERF_FAILURE) {
1554 					pkg->flags |= PKGF_FAILURE;
1555 					work->state = WORKER_DONE;
1556 				} else {
1557 					pkg->flags |= PKGF_FAILURE;
1558 					work->state = WORKER_FAILED;
1559 				}
1560 				work->flags |= WORKERF_STATUS_UPDATE;
1561 				pthread_cond_signal(&WorkerCond);
1562 			}
1563 			break;
1564 		case WORKER_DONE:
1565 			/*
1566 			 * pkg remains attached until frontend processes the
1567 			 * completion.  The frontend will then set the state
1568 			 * back to idle.
1569 			 */
1570 			break;
1571 		case WORKER_FAILED:
1572 			/*
1573 			 * A worker failure means that the worker did not
1574 			 * send us a WMSG_CMD_SUCCESS or WMSG_CMD_FAILURE
1575 			 * ipc before terminating.
1576 			 *
1577 			 * We just sit in this state until the front-end
1578 			 * does something about it.
1579 			 */
1580 			break;
1581 		case WORKER_FROZEN:
1582 			/*
1583 			 * A worker getting frozen is debug-related.  We
1584 			 * just sit in this state (likely forever).
1585 			 */
1586 			break;
1587 		default:
1588 			dfatal("worker: [%03d] Unexpected state %d "
1589 			       "for worker %d",
1590 			       work->index, work->state, work->index);
1591 			/* NOT REACHED */
1592 			break;
1593 		}
1594 
1595 		/*
1596 		 * The dsynth frontend will poll us approximately once
1597 		 * a second (its variable).
1598 		 */
1599 		if (dowait)
1600 			pthread_cond_wait(&work->cond, &WorkerMutex);
1601 	}
1602 
1603 	/*
1604 	 * Scrap the comm socket if running, this should cause the worker
1605 	 * process to kill its sub-programs and cleanup.
1606 	 */
1607 	if (work->state == WORKER_RUNNING) {
1608 		pthread_mutex_unlock(&WorkerMutex);
1609 		close(work->fds[0]);
1610 		while (waitpid(work->pid, &status, 0) < 0 &&
1611 		       errno == EINTR);
1612 		pthread_mutex_lock(&WorkerMutex);
1613 	}
1614 
1615 	/*
1616 	 * Final handshake
1617 	 */
1618 	work->state = WORKER_EXITING;
1619 	pthread_cond_signal(&WorkerCond);
1620 	pthread_mutex_unlock(&WorkerMutex);
1621 
1622 	return NULL;
1623 }
1624 
1625 /*
1626  * Install all the binary packages (we have already built them) that
1627  * the current work package depends on, without duplicates, in a script
1628  * which will be run from within the specified work jail.
1629  *
1630  * Locked by WorkerMutex (global)
1631  */
1632 static int
1633 childInstallPkgDeps(worker_t *work)
1634 {
1635 	char *buf;
1636 	FILE *fp;
1637 
1638 	if (PKGLIST_EMPTY(&work->pkg->idepon_list))
1639 		return 0;
1640 
1641 	asprintf(&buf, "%s/tmp/dsynth_install_pkgs", work->basedir);
1642 	fp = fopen(buf, "w");
1643 	ddassert(fp != NULL);
1644 	fprintf(fp, "#!/bin/sh\n");
1645 	fprintf(fp, "#\n");
1646 	fchmod(fileno(fp), 0755);
1647 
1648 	childInstallPkgDeps_recurse(fp, &work->pkg->idepon_list, 0, 1, 0);
1649 	childInstallPkgDeps_recurse(fp, &work->pkg->idepon_list, 1, 1, 0);
1650 	fprintf(fp, "\nexit 0\n");
1651 	fclose(fp);
1652 	freestrp(&buf);
1653 
1654 	return 1;
1655 }
1656 
1657 /*
1658  * Recursive child install dependencies.
1659  *
1660  * first_one_only is only specified if the pkg the list comes from
1661  * is a generic unflavored package that has flavors, telling us to
1662  * dive the first flavor only.
1663  *
1664  * However, in nearly all cases this flag will now be zero because
1665  * this code now dives the first flavor when encountering a dummy node
1666  * and clears nfirst on success.  Hence if you are asking why 'nfirst'
1667  * is set to 1, and then zero, instead of just being removed entirely,
1668  * it is because there might still be an edge case here.
1669  */
1670 static size_t
1671 childInstallPkgDeps_recurse(FILE *fp, pkglink_t *list, int undoit,
1672 			    int depth, int first_one_only)
1673 {
1674 	pkglink_t *link;
1675 	pkg_t *pkg;
1676 	size_t tot = 0;
1677 	int ndepth;
1678 	int nfirst;
1679 
1680 	PKGLIST_FOREACH(link, list) {
1681 		pkg = link->pkg;
1682 
1683 		/*
1684 		 * We don't want to mess up our depth test just below if
1685 		 * a DUMMY node had to be inserted.  The nodes under the
1686 		 * dummy node.
1687 		 *
1688 		 * The elements under a dummy node represent all the flabor,
1689 		 * a dependency that directly references a dummy node only
1690 		 * uses the first flavor (first_one_only / nfirst).
1691 		 */
1692 		ndepth = (pkg->flags & PKGF_DUMMY) ? depth : depth + 1;
1693 		nfirst = (pkg->flags & PKGF_DUMMY) ? 1 : 0;
1694 
1695 		/*
1696 		 * We only need all packages for the top-level dependencies.
1697 		 * The deeper ones only need DEP_TYPE_LIB and DEP_TYPE_RUN
1698 		 * (types greater than DEP_TYPE_BUILD) since they are already
1699 		 * built.
1700 		 */
1701 		if (depth > 1 && link->dep_type <= DEP_TYPE_BUILD) {
1702 			if (first_one_only)
1703 				break;
1704 			continue;
1705 		}
1706 
1707 		/*
1708 		 * If this is a dummy node with no package, the originator
1709 		 * is requesting a flavored package.  We select the default
1710 		 * flavor which we presume is the first one.
1711 		 */
1712 		if (pkg->pkgfile == NULL && (pkg->flags & PKGF_DUMMY)) {
1713 			pkg_t *spkg = pkg->idepon_list.next->pkg;
1714 
1715 			if (spkg) {
1716 				if (fp) {
1717 					fprintf(fp,
1718 						"echo 'UNFLAVORED %s -> use "
1719 						"%s'\n",
1720 						pkg->portdir,
1721 						spkg->portdir);
1722 				}
1723 				pkg = spkg;
1724 				nfirst = 0;
1725 			} else {
1726 				if (fp) {
1727 					fprintf(fp,
1728 						"echo 'CANNOT FIND DEFAULT "
1729 						"FLAVOR FOR %s'\n",
1730 						pkg->portdir);
1731 				}
1732 			}
1733 		}
1734 
1735 		if (undoit) {
1736 			if (pkg->dsynth_install_flg == 1) {
1737 				pkg->dsynth_install_flg = 0;
1738 				tot += childInstallPkgDeps_recurse(fp,
1739 							    &pkg->idepon_list,
1740 							    undoit,
1741 							    ndepth, nfirst);
1742 			}
1743 			if (first_one_only)
1744 				break;
1745 			continue;
1746 		}
1747 
1748 		if (pkg->dsynth_install_flg) {
1749 			if (DebugOpt >= 2 && pkg->pkgfile && fp) {
1750 				fprintf(fp, "echo 'AlreadyHave %s'\n",
1751 					pkg->pkgfile);
1752 			}
1753 			if (first_one_only)
1754 				break;
1755 			continue;
1756 		}
1757 
1758 		tot += childInstallPkgDeps_recurse(fp, &pkg->idepon_list,
1759 						   undoit, ndepth, nfirst);
1760 		if (pkg->dsynth_install_flg) {
1761 			if (first_one_only)
1762 				break;
1763 			continue;
1764 		}
1765 		pkg->dsynth_install_flg = 1;
1766 
1767 		/*
1768 		 * Generate package installation command
1769 		 */
1770 		if (fp && pkg->pkgfile) {
1771 			fprintf(fp, "echo 'Installing /packages/All/%s'\n",
1772 				pkg->pkgfile);
1773 			fprintf(fp, "pkg install -q -U -y /packages/All/%s "
1774 				"|| exit 1\n",
1775 				pkg->pkgfile);
1776 		} else if (fp) {
1777 			fprintf(fp, "echo 'CANNOT FIND PKG FOR %s'\n",
1778 				pkg->portdir);
1779 		}
1780 
1781 		if (pkg->pkgfile) {
1782 			struct stat st;
1783 			char *path;
1784 			char *ptr;
1785 
1786 			asprintf(&path, "%s/%s", RepositoryPath, pkg->pkgfile);
1787 			ptr = strrchr(pkg->pkgfile, '.');
1788 			if (stat(path, &st) == 0) {
1789 				if (strcmp(ptr, ".tar") == 0)
1790 					tot += st.st_size;
1791 				else if (strcmp(ptr, ".tgz") == 0)
1792 					tot += st.st_size * 3;
1793 				else if (strcmp(ptr, ".txz") == 0)
1794 					tot += st.st_size * 5;
1795 				else if (strcmp(ptr, ".tbz") == 0)
1796 					tot += st.st_size * 3;
1797 				else
1798 					tot += st.st_size * 2;
1799 			}
1800 			free(path);
1801 		}
1802 		if (first_one_only)
1803 			break;
1804 	}
1805 	return tot;
1806 }
1807 
1808 /*
1809  * Worker process interactions.
1810  *
1811  * The worker process is responsible for managing the build of a single
1812  * package.  It is exec'd by the master dsynth and only loads the
1813  * configuration.
1814  *
1815  * This process does not run in the chroot.  It will become the reaper for
1816  * all sub-processes and it will enter the chroot to execute various phases.
1817  * It catches SIGINTR, SIGHUP, and SIGPIPE and will iterate, terminate, and
1818  * reap all sub-process upon kill or exit.
1819  *
1820  * The command line forwarded to this function is:
1821  *
1822  *	WORKER slot# socketfd portdir/subdir
1823  *
1824  * TERM=dumb
1825  * USER=root
1826  * HOME=/root
1827  * LANG=C
1828  * SSL_NO_VERIFY_PEER=1
1829  * USE_PACKAGE_DEPENDS_ONLY=1
1830  * PORTSDIR=/xports
1831  * PORT_DBDIR=/options		For ports options
1832  * PACKAGE_BUILDING=yes		Don't build packages that aren't legally
1833  *				buildable for a binary repo.
1834  * PKG_DBDIR=/var/db/pkg
1835  * PKG_CACHEDIR=/var/cache/pkg
1836  * PKG_CREATE_VERBOSE=yes	Ensure periodic output during packaging
1837  * (custom environment)
1838  * PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
1839  * UNAME_s=DragonFly		(example)
1840  * UNAME_v=DragonFly 5.7-SYNTH	(example)
1841  * UNAME_p=x86_64		(example)
1842  * UNAME_m=x86_64		(example)
1843  * UNAME_r=5.7-SYNTH		(example)
1844  * NO_DEPENDS=yes		(conditional based on phase)
1845  * DISTDIR=/distfiles
1846  * WRKDIRPREFIX=/construction
1847  * BATCH=yes
1848  * MAKE_JOBS_NUMBER=n
1849  *
1850  * SETUP:
1851  *	ldconfig -R
1852  *	/usr/local/sbin/pkg-static install /packages/All/<the pkg pkg>
1853  *	/usr/local/sbin/pkg-static install /packages/All/<pkg>
1854  *			(for all dependencies)
1855  *
1856  * PHASES: 		make -C path FLAVOR=flavor <phase>
1857  *	check-sanity
1858  *	pkg-depends
1859  *	fetch-depends
1860  *	fetch
1861  *	checksum
1862  *	extract-depends
1863  *	extract
1864  *	patch-depends
1865  *	patch
1866  *	build-depends
1867  *	lib-depends
1868  *	configure
1869  *	build
1870  *	run-depends
1871  *	stage
1872  *	test		(skipped)
1873  *	check-plist	('dsynth test blahblah' or 'dsynth -D everything' only)
1874  *	package		 e.g. /construction/lang/perl5.28/pkg/perl5-5.28.2.txz
1875  *	install		(skipped)
1876  *	deinstall	(skipped)
1877  */
1878 void
1879 WorkerProcess(int ac, char **av)
1880 {
1881 	wmsg_t wmsg;
1882 	int fd;
1883 	int slot;
1884 	int tmpfd;
1885 	int pkgpkg = 0;
1886 	int status;
1887 	int len;
1888 	int do_install_phase;
1889 	char *portdir;
1890 	char *pkgfile;
1891 	char *flavor;
1892 	char *buf;
1893 	worker_t *work;
1894 	bulk_t *bulk;
1895 	pkg_t pkg;
1896 	buildenv_t *benv;
1897 	FILE *fp;
1898 
1899 	/*
1900 	 * Parse arguments
1901 	 */
1902 	if (ac != 6) {
1903 		dlog(DLOG_ALL, "WORKER PROCESS %d- bad arguments\n", getpid());
1904 		exit(1);
1905 	}
1906 	slot = strtol(av[1], NULL, 0);
1907 	fd = strtol(av[2], NULL, 0);	/* master<->slave messaging */
1908 	portdir = av[3];
1909 	pkgfile = av[4];
1910 	flavor = strchr(portdir, '@');
1911 	if (flavor) {
1912 		*flavor++ = 0;
1913 		asprintf(&buf, "@%s", flavor);
1914 		WorkerFlavorPrt = buf;
1915 		buf = NULL;	/* safety */
1916 	}
1917 	WorkerProcFlags = strtol(av[5], NULL, 0);
1918 
1919 	bzero(&wmsg, sizeof(wmsg));
1920 
1921 	setproctitle("[%02d] WORKER STARTUP  %s%s",
1922 		     slot, portdir, WorkerFlavorPrt);
1923 
1924 	if (strcmp(portdir, "ports-mgmt/pkg") == 0)
1925 		pkgpkg = 1;
1926 
1927 	signal(SIGTERM, phaseTerminateSignal);
1928 	signal(SIGINT, phaseTerminateSignal);
1929 	signal(SIGHUP, phaseTerminateSignal);
1930 
1931 	/*
1932 	 * Set up the environment
1933 	 */
1934 	setenv("TERM", "dumb", 1);
1935 	setenv("USER", "root", 1);
1936 	setenv("HOME", "/root", 1);
1937 	setenv("LANG", "C", 1);
1938 	setenv("SSL_NO_VERIFY_PEER", "1", 1);
1939 
1940 	addbuildenv("USE_PACKAGE_DEPENDS_ONLY", "yes", BENV_MAKECONF);
1941 	addbuildenv("PORTSDIR", "/xports", BENV_MAKECONF);
1942 	addbuildenv("PORT_DBDIR", "/options", BENV_MAKECONF);
1943 	addbuildenv("PKG_DBDIR", "/var/db/pkg", BENV_MAKECONF);
1944 	addbuildenv("PKG_CACHEDIR", "/var/cache/pkg", BENV_MAKECONF);
1945 	addbuildenv("PKG_SUFX", UsePkgSufx, BENV_MAKECONF);
1946 	if (WorkerProcFlags & WORKER_PROC_DEVELOPER)
1947 		addbuildenv("DEVELOPER", "1", BENV_MAKECONF);
1948 
1949 	/*
1950 	 * CCache is a horrible unreliable hack but... leave the
1951 	 * mechanism in-place in case someone has a death wish.
1952 	 */
1953 	if (UseCCache) {
1954 		addbuildenv("WITH_CCACHE_BUILD", "yes", BENV_MAKECONF);
1955 		addbuildenv("CCACHE_DIR", "/ccache", BENV_MAKECONF);
1956 	}
1957 
1958 	addbuildenv("UID", "0", BENV_MAKECONF);
1959 	addbuildenv("ARCH", ArchitectureName, BENV_MAKECONF);
1960 
1961 #ifdef __DragonFly__
1962 	addbuildenv("OPSYS", "DragonFly", BENV_MAKECONF);
1963 	addbuildenv("DFLYVERSION", VersionFromParamHeader, BENV_MAKECONF);
1964 	addbuildenv("OSVERSION", "9999999", BENV_MAKECONF);
1965 #else
1966 #error "Need OS-specific data to generate make.conf"
1967 #endif
1968 
1969 	addbuildenv("OSREL", ReleaseName, BENV_MAKECONF);
1970 	addbuildenv("_OSRELEASE", VersionOnlyName, BENV_MAKECONF);
1971 
1972 	setenv("PATH",
1973 	       "/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin",
1974 	       1);
1975 
1976 	setenv("UNAME_s", OperatingSystemName, 1);
1977 	setenv("UNAME_v", VersionName, 1);
1978 	setenv("UNAME_p", ArchitectureName, 1);
1979 	setenv("UNAME_m", MachineName, 1);
1980 	setenv("UNAME_r", ReleaseName, 1);
1981 
1982 	addbuildenv("DISTDIR", "/distfiles", BENV_MAKECONF);
1983 	addbuildenv("WRKDIRPREFIX", "/construction", BENV_MAKECONF);
1984 	addbuildenv("BATCH", "yes", BENV_MAKECONF);
1985 
1986 	/*
1987 	 * Special consideration
1988 	 *
1989 	 * PACKAGE_BUILDING	- Disallow packaging ports which do not allow
1990 	 *			  for binary distribution.
1991 	 *
1992 	 * PKG_CREATE_VERBOSE	- Ensure periodic output during the packaging
1993 	 *			  process to avoid a watchdog timeout.
1994 	 *
1995 	 */
1996 	addbuildenv("PACKAGE_BUILDING", "yes", BENV_MAKECONF);
1997 	addbuildenv("PKG_CREATE_VERBOSE", "yes", BENV_MAKECONF);
1998 	asprintf(&buf, "%d", MaxJobs);
1999 	addbuildenv("MAKE_JOBS_NUMBER", buf, BENV_MAKECONF);
2000 	freestrp(&buf);
2001 
2002 	if (flavor)
2003 		setenv("FLAVOR", flavor, 1);
2004 
2005 	/*
2006 	 * Become the reaper
2007 	 */
2008 	if (procctl(P_PID, getpid(), PROC_REAP_ACQUIRE, NULL) < 0)
2009 		dfatal_errno("procctl() - Cannot become reaper");
2010 
2011 	/*
2012 	 * Initialize a worker structure
2013 	 */
2014 	DoInitBuild(slot);
2015 
2016 	bzero(&pkg, sizeof(pkg));
2017 	pkg.portdir = portdir;		/* sans flavor */
2018 	pkg.pkgfile = pkgfile;
2019 	if (strchr(portdir, '/'))
2020 		len = strchr(portdir, '/') - portdir;
2021 	else
2022 		len = 0;
2023 
2024 	/*
2025 	 * Setup the logfile
2026 	 */
2027 	asprintf(&pkg.logfile,
2028 		 "%s/%*.*s___%s%s%s.log",
2029 		 LogsPath, len, len, portdir,
2030 		 ((portdir[len] == '/') ? portdir + len + 1 : portdir + len),
2031 		 (flavor ? "@" : ""),
2032 		 (flavor ? flavor : ""));
2033 	tmpfd = open(pkg.logfile, O_RDWR|O_CREAT|O_TRUNC, 0666);
2034 	if (tmpfd >= 0) {
2035 		if (DebugOpt >= 2) {
2036 			dlog(DLOG_ALL, "[%03d] %s LOGFILE %s\n",
2037 			     slot, pkg.portdir, pkg.logfile);
2038 		}
2039 		close(tmpfd);
2040 	} else {
2041 		dlog(DLOG_ALL, "[%03d] LOGFILE %s (create failed)\n",
2042 		     slot, pkg.logfile);
2043 	}
2044 
2045 	/*
2046 	 * Setup the work structure.  Because this is an exec'd sub-process,
2047 	 * there is only one work structure.
2048 	 */
2049 	work = &WorkerAry[0];
2050 	work->flavor = flavor;
2051 	work->fds[0] = fd;
2052 	work->pkg = &pkg;
2053 	work->start_time = time(NULL);
2054 
2055 	/*
2056 	 * Do mounts
2057 	 */
2058 	SigWork = work;
2059 	setproctitle("[%02d] WORKER MOUNTS   %s%s",
2060 		     slot, portdir, WorkerFlavorPrt);
2061 	DoWorkerMounts(work);
2062 
2063 	/*
2064 	 * Generate an /etc/make.conf in the build base
2065 	 */
2066 	asprintf(&buf, "%s/etc/make.conf", work->basedir);
2067 	fp = fopen(buf, "w");
2068 	dassert_errno(fp, "Unable to create %s\n", buf);
2069 	for (benv = BuildEnv; benv; benv = benv->next) {
2070 		if (benv->type & BENV_PKGLIST)
2071 			continue;
2072 		if ((benv->type & BENV_CMDMASK) == BENV_MAKECONF) {
2073 			if (DebugOpt >= 2) {
2074 				dlog(DLOG_ALL, "[%03d] ENV %s=%s\n",
2075 				     slot, benv->label, benv->data);
2076 			}
2077 			fprintf(fp, "%s=%s\n", benv->label, benv->data);
2078 		}
2079 	}
2080 	fclose(fp);
2081 	freestrp(&buf);
2082 
2083 	/*
2084 	 * Set up our hooks
2085 	 */
2086 	if (UsingHooks)
2087 		initbulk(childHookRun, MaxBulk);
2088 
2089 	/*
2090 	 * Start phases
2091 	 */
2092 	wmsg.cmd = WMSG_CMD_INSTALL_PKGS;
2093 	ipcwritemsg(fd, &wmsg);
2094 	status = ipcreadmsg(fd, &wmsg);
2095 	if (status < 0 || wmsg.cmd != WMSG_RES_INSTALL_PKGS)
2096 		dfatal("pkg installation handshake failed");
2097 	do_install_phase = wmsg.status;
2098 
2099 	wmsg.cmd = WMSG_CMD_STATUS_UPDATE;
2100 	wmsg.phase = PHASE_INSTALL_PKGS;
2101 	wmsg.lines = 0;
2102 
2103 	status = ipcwritemsg(fd, &wmsg);
2104 
2105 	if (pkgpkg) {
2106 		dophase(work, &wmsg,
2107 			WDOG5, PHASE_PACKAGE, "package");
2108 	} else {
2109 		if (do_install_phase) {
2110 			dophase(work, &wmsg,
2111 				WDOG4, PHASE_INSTALL_PKGS, "setup");
2112 		}
2113 		dophase(work, &wmsg,
2114 			WDOG2, PHASE_CHECK_SANITY, "check-sanity");
2115 		dophase(work, &wmsg,
2116 			WDOG2, PHASE_PKG_DEPENDS, "pkg-depends");
2117 		dophase(work, &wmsg,
2118 			WDOG7, PHASE_FETCH_DEPENDS, "fetch-depends");
2119 		dophase(work, &wmsg,
2120 			WDOG7, PHASE_FETCH, "fetch");
2121 		dophase(work, &wmsg,
2122 			WDOG2, PHASE_CHECKSUM, "checksum");
2123 		dophase(work, &wmsg,
2124 			WDOG3, PHASE_EXTRACT_DEPENDS, "extract-depends");
2125 		dophase(work, &wmsg,
2126 			WDOG3, PHASE_EXTRACT, "extract");
2127 		dophase(work, &wmsg,
2128 			WDOG2, PHASE_PATCH_DEPENDS, "patch-depends");
2129 		dophase(work, &wmsg,
2130 			WDOG2, PHASE_PATCH, "patch");
2131 		dophase(work, &wmsg,
2132 			WDOG5, PHASE_BUILD_DEPENDS, "build-depends");
2133 		dophase(work, &wmsg,
2134 			WDOG5, PHASE_LIB_DEPENDS, "lib-depends");
2135 		dophase(work, &wmsg,
2136 			WDOG3, PHASE_CONFIGURE, "configure");
2137 		dophase(work, &wmsg,
2138 			WDOG9, PHASE_BUILD, "build");
2139 		dophase(work, &wmsg,
2140 			WDOG5, PHASE_RUN_DEPENDS, "run-depends");
2141 		dophase(work, &wmsg,
2142 			WDOG5, PHASE_STAGE, "stage");
2143 #if 0
2144 		dophase(work, &wmsg,
2145 			WDOG5, PHASE_TEST, "test");
2146 #endif
2147 		if (WorkerProcFlags & WORKER_PROC_CHECK_PLIST) {
2148 			dophase(work, &wmsg,
2149 				WDOG1, PHASE_CHECK_PLIST, "check-plist");
2150 		}
2151 		dophase(work, &wmsg,
2152 			WDOG5, PHASE_PACKAGE, "package");
2153 
2154 		if (WorkerProcFlags & WORKER_PROC_INSTALL) {
2155 			dophase(work, &wmsg,
2156 			    WDOG5, PHASE_INSTALL, "install");
2157 		}
2158 
2159 		if (WorkerProcFlags & WORKER_PROC_DEINSTALL) {
2160 			dophase(work, &wmsg,
2161 			    WDOG5, PHASE_DEINSTALL, "deinstall");
2162 		}
2163 	}
2164 
2165 	if (MasterPtyFd >= 0) {
2166 		close(MasterPtyFd);
2167 		MasterPtyFd = -1;
2168 	}
2169 
2170 	setproctitle("[%02d] WORKER CLEANUP  %s%s",
2171 		     slot, portdir, WorkerFlavorPrt);
2172 
2173 	/*
2174 	 * Copy the package to the repo.
2175 	 */
2176 	if (work->accum_error == 0) {
2177 		char *b1;
2178 		char *b2;
2179 
2180 		asprintf(&b1, "%s/construction/%s/pkg/%s",
2181 			 work->basedir, pkg.portdir, pkg.pkgfile);
2182 		asprintf(&b2, "%s/%s", RepositoryPath, pkg.pkgfile);
2183 		if (copyfile(b1, b2)) {
2184 			++work->accum_error;
2185 			dlog(DLOG_ALL, "[%03d] %s Unable to copy %s to %s\n",
2186 			     work->index, pkg.portdir, b1, b2);
2187 		}
2188 		free(b1);
2189 		free(b2);
2190 	}
2191 
2192 	/*
2193 	 * Unmount, unless we are in DebugStopMode.
2194 	 */
2195 	if ((WorkerProcFlags & WORKER_PROC_DEBUGSTOP) == 0)
2196 		DoWorkerUnmounts(work);
2197 
2198 	/*
2199 	 * Send completion status to master dsynth worker thread.
2200 	 */
2201 	if (work->accum_error) {
2202 		wmsg.cmd = WMSG_CMD_FAILURE;
2203 	} else {
2204 		wmsg.cmd = WMSG_CMD_SUCCESS;
2205 	}
2206 	ipcwritemsg(fd, &wmsg);
2207 	if (WorkerProcFlags & WORKER_PROC_DEBUGSTOP) {
2208 		wmsg.cmd = WMSG_CMD_FREEZEWORKER;
2209 		ipcwritemsg(fd, &wmsg);
2210 	}
2211 	if (UsingHooks) {
2212 		while ((bulk = getbulk()) != NULL)
2213 			freebulk(bulk);
2214 		donebulk();
2215 	}
2216 }
2217 
2218 static void
2219 dophase(worker_t *work, wmsg_t *wmsg, int wdog, int phaseid, const char *phase)
2220 {
2221 	pkg_t *pkg = work->pkg;
2222 	char buf[1024];
2223 	pid_t pid;
2224 	int status;
2225 	int ms;
2226 	pid_t wpid;
2227 	int wpid_reaped;
2228 	int fdlog;
2229 	time_t start_time;
2230 	time_t last_time;
2231 	time_t next_time;
2232 	time_t wdog_time;
2233 	FILE *fp;
2234 
2235 	if (work->accum_error)
2236 		return;
2237 	setproctitle("[%02d] WORKER %-8.8s %s%s",
2238 		     work->index, phase, pkg->portdir, WorkerFlavorPrt);
2239 	wmsg->phase = phaseid;
2240 	if (ipcwritemsg(work->fds[0], wmsg) < 0) {
2241 		dlog(DLOG_ALL, "[%03d] %s Lost Communication with dsynth, "
2242 		     "aborting worker\n",
2243 		     work->index, pkg->portdir);
2244 		++work->accum_error;
2245 		return;
2246 	}
2247 
2248 	/*
2249 	 * Execute the port make command in chroot on a pty.
2250 	 */
2251 	fflush(stdout);
2252 	fflush(stderr);
2253 	if (MasterPtyFd >= 0) {
2254 		int slavefd;
2255 
2256 		/*
2257 		 * NOTE: We can't open the slave in the child because the
2258 		 *	 master may race a disconnection test.  If we open
2259 		 *	 it in the parent our close() will flush any pending
2260 		 *	 output not read by the master (which is the same
2261 		 *	 parent process) and deadlock.
2262 		 *
2263 		 *	 Solve this by hand-shaking the slave tty to give
2264 		 *	 the master time to close its slavefd (after this
2265 		 *	 section).
2266 		 *
2267 		 *	 Leave the tty defaults intact, which also likely
2268 		 *	 means it will be in line-buffered mode, so handshake
2269 		 *	 with a full line.
2270 		 *
2271 		 * TODO: Our handshake probably echos back to the master pty
2272 		 *	 due to tty echo, and ends up in the log, so just
2273 		 *	 pass through a newline.
2274 		 */
2275 		slavefd = open(ptsname(MasterPtyFd), O_RDWR);
2276 		dassert_errno(slavefd >= 0, "Cannot open slave pty");
2277 
2278 		/*
2279 		 * Now do the fork.
2280 		 */
2281 		pid = fork();
2282 		if (pid == 0) {
2283 			login_tty(slavefd);
2284 			/* login_tty() closes slavefd */
2285 		} else {
2286 			close(slavefd);
2287 		}
2288 	} else {
2289 		/*
2290 		 * Initial MasterPtyFd for the slot, just use forkpty().
2291 		 */
2292 		pid = forkpty(&MasterPtyFd, NULL, NULL, NULL);
2293 	}
2294 
2295 	/*
2296 	 * The slave must make sure the master has time to close slavefd
2297 	 * in the re-use case before going its merry way.  The master needs
2298 	 * to set terminal modes and the window as well.
2299 	 */
2300 	if (pid == 0) {
2301 		/*
2302 		 * Slave nices itself and waits for handshake
2303 		 */
2304 		char ttybuf[2];
2305 
2306 		/*
2307 		 * Self-nice to be nice (ignore any error)
2308 		 */
2309 		if (NiceOpt)
2310 			setpriority(PRIO_PROCESS, 0, NiceOpt);
2311 
2312 		read(0, ttybuf, 1);
2313 	} else {
2314 		/*
2315 		 * We are going through a pty, so set the tty modes to
2316 		 * Set tty modes so we do not get ^M's in the log files.
2317 		 *
2318 		 * This isn't fatal if it doesn't work.  Remember that
2319 		 * our output goes through the pty to the management
2320 		 * process which will log it.
2321 		 */
2322 		struct termios tio;
2323 		struct winsize win;
2324 
2325 		if (tcgetattr(MasterPtyFd, &tio) == 0) {
2326 			tio.c_oflag |= OPOST | ONOCR;
2327 			tio.c_oflag &= ~(OCRNL | ONLCR);
2328 			tio.c_iflag |= ICRNL;
2329 			tio.c_iflag &= ~(INLCR | IGNCR);
2330 			if (tcsetattr(MasterPtyFd, TCSANOW, &tio)) {
2331 				printf("tcsetattr failed: %s\n",
2332 				       strerror(errno));
2333 			}
2334 
2335 			/*
2336 			 * Give the tty a non-zero columns field.
2337 			 * This fixes at least one port (textproc/po4a)
2338 			 */
2339 			if (ioctl(MasterPtyFd, TIOCGWINSZ, &win) == 0) {
2340 				win.ws_col = 80;
2341 				ioctl(MasterPtyFd, TIOCSWINSZ, &win);
2342 			} else {
2343 				printf("TIOCGWINSZ failed: %s\n",
2344 				       strerror(errno));
2345 			}
2346 
2347 		} else {
2348 			printf("tcgetattr failed: %s\n", strerror(errno));
2349 		}
2350 
2351 		/*
2352 		 * Master issues handshake
2353 		 */
2354 		write(MasterPtyFd, "\n", 1);
2355 	}
2356 
2357 	if (pid == 0) {
2358 		/*
2359 		 * Additional phase-specific environment variables
2360 		 *
2361 		 * - Do not try to process missing depends outside of the
2362 		 *   depends phases.  Also relies on USE_PACKAGE_DEPENDS_ONLY
2363 		 *   in the make.conf.
2364 		 */
2365 		switch(phaseid) {
2366 		case PHASE_CHECK_SANITY:
2367 		case PHASE_FETCH:
2368 		case PHASE_CHECKSUM:
2369 		case PHASE_EXTRACT:
2370 		case PHASE_PATCH:
2371 		case PHASE_CONFIGURE:
2372 		case PHASE_STAGE:
2373 		case PHASE_TEST:
2374 		case PHASE_CHECK_PLIST:
2375 		case PHASE_INSTALL:
2376 		case PHASE_DEINSTALL:
2377 			break;
2378 		case PHASE_PKG_DEPENDS:
2379 		case PHASE_FETCH_DEPENDS:
2380 		case PHASE_EXTRACT_DEPENDS:
2381 		case PHASE_PATCH_DEPENDS:
2382 		case PHASE_BUILD_DEPENDS:
2383 		case PHASE_LIB_DEPENDS:
2384 		case PHASE_RUN_DEPENDS:
2385 			break;
2386 		default:
2387 			setenv("NO_DEPENDS", "1", 1);
2388 			break;
2389 		}
2390 
2391 		/*
2392 		 * Clean-up, chdir, and chroot.
2393 		 */
2394 		closefrom(3);
2395 		if (chdir(work->basedir) < 0)
2396 			dfatal_errno("chdir in phase initialization");
2397 		if (chroot(work->basedir) < 0)
2398 			dfatal_errno("chroot in phase initialization");
2399 
2400 		/*
2401 		 * We have a choice here on how to handle stdin (fd 0).
2402 		 * We can leave it connected to the pty in which case
2403 		 * the build will just block if it tries to ask a
2404 		 * question (and the watchdog will kill it, eventually),
2405 		 * or we can try to EOF the pty, or we can attach /dev/null
2406 		 * to descriptor 0.
2407 		 */
2408 		if (NullStdinOpt) {
2409 			int fd;
2410 
2411 			fd = open("/dev/null", O_RDWR);
2412 			dassert_errno(fd >= 0, "cannot open /dev/null");
2413 			if (fd != 0) {
2414 				dup2(fd, 0);
2415 				close(fd);
2416 			}
2417 		}
2418 
2419 		/*
2420 		 * Execute the appropriate command.
2421 		 */
2422 		switch(phaseid) {
2423 		case PHASE_INSTALL_PKGS:
2424 			snprintf(buf, sizeof(buf), "/tmp/dsynth_install_pkgs");
2425 			execl(buf, buf, NULL);
2426 			break;
2427 		default:
2428 			snprintf(buf, sizeof(buf), "/xports/%s", pkg->portdir);
2429 			execl(MAKE_BINARY, MAKE_BINARY, "-C", buf, phase, NULL);
2430 			break;
2431 		}
2432 		_exit(1);
2433 	}
2434 	fcntl(MasterPtyFd, F_SETFL, O_NONBLOCK);
2435 
2436 	if (pid < 0) {
2437 		dlog(DLOG_ALL, "[%03d] %s Fork Failed: %s\n",
2438 		     work->index, pkg->logfile, strerror(errno));
2439 		++work->accum_error;
2440 		return;
2441 	}
2442 
2443 	SigPid = pid;
2444 
2445 	fdlog = open(pkg->logfile, O_RDWR|O_CREAT|O_APPEND, 0644);
2446 	if (fdlog < 0) {
2447 		dlog(DLOG_ALL, "[%03d] %s Cannot open logfile '%s': %s\n",
2448 		     work->index, pkg->portdir,
2449 		     pkg->logfile, strerror(errno));
2450 	}
2451 
2452 	snprintf(buf, sizeof(buf),
2453 		 "----------------------------------------"
2454 		 "---------------------------------------\n"
2455 		 "-- Phase: %s\n"
2456 		 "----------------------------------------"
2457 		 "---------------------------------------\n",
2458 		 phase);
2459 	write(fdlog, buf, strlen(buf));
2460 
2461 	start_time = time(NULL);
2462 	last_time = start_time;
2463 	wdog_time = start_time;
2464 	wpid_reaped = 0;
2465 
2466 	status = 0;
2467 	for (;;) {
2468 		ms = mptylogpoll(MasterPtyFd, fdlog, wmsg, &wdog_time);
2469 		if (ms == MPTY_FAILED) {
2470 			dlog(DLOG_ALL,
2471 			     "[%03d] %s lost pty in phase %s, terminating\n",
2472 			     work->index, pkg->portdir, phase);
2473 			break;
2474 		}
2475 		if (ms == MPTY_EOF)
2476 			break;
2477 
2478 		/*
2479 		 * Generally speaking update status once a second.
2480 		 * This also allows us to detect if the management
2481 		 * dsynth process has gone away.
2482 		 */
2483 		next_time = time(NULL);
2484 		if (next_time != last_time) {
2485 			double dload[3];
2486 			double dv;
2487 			int wdog_scaled;
2488 
2489 			/*
2490 			 * Send status update to the worker management thread
2491 			 * in the master dsynth process.  Remember, *WE* are
2492 			 * the worker management process sub-fork.
2493 			 */
2494 			if (ipcwritemsg(work->fds[0], wmsg) < 0)
2495 				break;
2496 			last_time = next_time;
2497 
2498 			/*
2499 			 * Watchdog scaling
2500 			 */
2501 			getloadavg(dload, 3);
2502 			adjloadavg(dload);
2503 			dv = dload[2] / NumCores;
2504 			if (dv < (double)NumCores) {
2505 				wdog_scaled = wdog;
2506 			} else {
2507 				if (dv > 4.0 * NumCores)
2508 					dv = 4.0 * NumCores;
2509 				wdog_scaled = wdog * dv / NumCores;
2510 			}
2511 
2512 			/*
2513 			 * Watchdog
2514 			 */
2515 			if (next_time - wdog_time >= wdog_scaled * 60) {
2516 				snprintf(buf, sizeof(buf),
2517 					 "\n--------\n"
2518 					 "WATCHDOG TIMEOUT FOR %s in %s "
2519 					 "after %d minutes\n"
2520 					 "Killing pid %d\n"
2521 					 "--------\n",
2522 					 pkg->portdir, phase, wdog_scaled, pid);
2523 				if (fdlog >= 0)
2524 					write(fdlog, buf, strlen(buf));
2525 				dlog(DLOG_ALL,
2526 				     "[%03d] %s WATCHDOG TIMEOUT in %s "
2527 				     "after %d minutes (%d min scaled)\n",
2528 				     work->index, pkg->portdir, phase,
2529 				     wdog, wdog_scaled);
2530 				kill(pid, SIGKILL);
2531 				++work->accum_error;
2532 				break;
2533 			}
2534 		}
2535 
2536 		/*
2537 		 * Check process exit.  Normally the pty will EOF
2538 		 * but if background processes remain we need to
2539 		 * check here to see if our primary exec is done,
2540 		 * so we can break out and reap those processes.
2541 		 *
2542 		 * Generally reap any other processes we have inherited
2543 		 * while we are here.
2544 		 */
2545 		do {
2546 			wpid = wait3(&status, WNOHANG, NULL);
2547 		} while (wpid > 0 && wpid != pid);
2548 		if (wpid == pid && WIFEXITED(status)) {
2549 			wpid_reaped = 1;
2550 			break;
2551 		}
2552 	}
2553 
2554 	next_time = time(NULL);
2555 
2556 	setproctitle("[%02d] WORKER EXITREAP %s%s",
2557 		     work->index, pkg->portdir, WorkerFlavorPrt);
2558 
2559 	/*
2560 	 * We usually get here due to a mpty EOF, but not always as there
2561 	 * could be persistent processes still holding the slave.  Finish
2562 	 * up getting the exit status for the main process we are waiting
2563 	 * on and clean out any data left on the MasterPtyFd (as it could
2564 	 * be blocking the exit).
2565 	 */
2566 	while (wpid_reaped == 0) {
2567 		(void)mptylogpoll(MasterPtyFd, fdlog, wmsg, &wdog_time);
2568 		wpid = waitpid(pid, &status, WNOHANG);
2569 		if (wpid == pid && WIFEXITED(status)) {
2570 			wpid_reaped = 1;
2571 			break;
2572 		}
2573 		if (wpid < 0 && errno != EINTR) {
2574 			break;
2575 		}
2576 
2577 		/*
2578 		 * Safety.  The normal phase waits until the fork/exec'd
2579 		 * pid finishes, causing a pty EOF on exit (the slave
2580 		 * descriptor is closed by the kernel on exit so the
2581 		 * process should already have exited).
2582 		 *
2583 		 * However, it is also possible to get here if the pty fails
2584 		 * for some reason.  In this case, make sure that the process
2585 		 * is killed.
2586 		 */
2587 		kill(pid, SIGKILL);
2588 	}
2589 
2590 	/*
2591 	 * Clean out anything left on the pty but don't wait around
2592 	 * because there could be background processes preventing the
2593 	 * slave side from closing.
2594 	 */
2595 	while (mptylogpoll(MasterPtyFd, fdlog, wmsg, &wdog_time) == MPTY_DATA)
2596 		;
2597 
2598 	/*
2599 	 * Report on the exit condition.  If the pid was somehow lost
2600 	 * (probably due to someone gdb'ing the process), assume an error.
2601 	 */
2602 	if (wpid_reaped) {
2603 		if (WEXITSTATUS(status)) {
2604 			dlog(DLOG_ALL | DLOG_FILTER,
2605 			     "[%03d] %s Build phase '%s' failed exit %d\n",
2606 			     work->index, pkg->portdir, phase,
2607 			     WEXITSTATUS(status));
2608 			++work->accum_error;
2609 		}
2610 	} else {
2611 		dlog(DLOG_ALL, "[%03d] %s Build phase '%s' failed - lost pid\n",
2612 		     work->index, pkg->portdir, phase);
2613 		++work->accum_error;
2614 	}
2615 
2616 	/*
2617 	 * Kill any processes still running (sometimes processes end up in
2618 	 * the background during a dports build), and clean up any other
2619 	 * children that we have inherited.
2620 	 */
2621 	phaseReapAll();
2622 
2623 	/*
2624 	 * After the extraction phase add the space used by /construction
2625 	 * to the memory use.  This helps us reduce the amount of paging
2626 	 * we do due to extremely large package extractions (languages,
2627 	 * chromium, etc).
2628 	 *
2629 	 * (dsynth already estimated the space used by the package deps
2630 	 * up front, but this will help us further).
2631 	 */
2632 	if (work->accum_error == 0 && phaseid == PHASE_EXTRACT) {
2633 		struct statfs sfs;
2634 		char *b1;
2635 
2636 		asprintf(&b1, "%s/construction", work->basedir);
2637 		if (statfs(b1, &sfs) == 0) {
2638 			wmsg->memuse = (sfs.f_blocks - sfs.f_bfree) *
2639 				       sfs.f_bsize;
2640 			ipcwritemsg(work->fds[0], wmsg);
2641 		}
2642 	}
2643 
2644 	/*
2645 	 * Update log
2646 	 */
2647 	if (fdlog >= 0) {
2648 		struct stat st;
2649 		int h;
2650 		int m;
2651 		int s;
2652 
2653 		last_time = next_time - start_time;
2654 		s = last_time % 60;
2655 		m = last_time / 60 % 60;
2656 		h = last_time / 3600;
2657 
2658 		fp = fdopen(fdlog, "a");
2659 		if (fp == NULL) {
2660 			dlog(DLOG_ALL, "[%03d] %s Cannot fdopen fdlog: %s %d\n",
2661 			     work->index, pkg->portdir,
2662 			     strerror(errno), fstat(fdlog, &st));
2663 			close(fdlog);
2664 			goto skip;
2665 		}
2666 
2667 		fprintf(fp, "\n");
2668 		if (work->accum_error) {
2669 			fprintf(fp, "FAILED %02d:%02d:%02d\n", h, m, s);
2670 		} else {
2671 			if (phaseid == PHASE_EXTRACT && wmsg->memuse) {
2672 				fprintf(fp, "Extracted Memory Use: %6.2fM\n",
2673 					wmsg->memuse / (1024.0 * 1024.0));
2674 			}
2675 			fprintf(fp, "SUCCEEDED %02d:%02d:%02d\n", h, m, s);
2676 		}
2677 		last_time = next_time - work->start_time;
2678 		s = last_time % 60;
2679 		m = last_time / 60 % 60;
2680 		h = last_time / 3600;
2681 		if (phaseid == PHASE_PACKAGE) {
2682 			fprintf(fp, "TOTAL TIME %02d:%02d:%02d\n", h, m, s);
2683 		}
2684 		fprintf(fp, "\n");
2685 		fclose(fp);
2686 skip:
2687 		;
2688 	}
2689 
2690 }
2691 
2692 static void
2693 phaseReapAll(void)
2694 {
2695 	struct reaper_status rs;
2696 	int status;
2697 
2698 	while (procctl(P_PID, getpid(), PROC_REAP_STATUS, &rs) == 0) {
2699 		if ((rs.flags & PROC_REAP_ACQUIRE) == 0)
2700 			break;
2701 		if (rs.pid_head < 0)
2702 			break;
2703 		if (kill(rs.pid_head, SIGKILL) == 0) {
2704 			while (waitpid(rs.pid_head, &status, 0) < 0)
2705 				;
2706 		}
2707 	}
2708 	while (wait3(&status, 0, NULL) > 0)
2709 		;
2710 }
2711 
2712 static void
2713 phaseTerminateSignal(int sig __unused)
2714 {
2715 	if (CopyFileFd >= 0)
2716 		close(CopyFileFd);
2717 	if (MasterPtyFd >= 0)
2718 		close(MasterPtyFd);
2719 	if (SigPid > 1)
2720 		kill(SigPid, SIGKILL);
2721 	phaseReapAll();
2722 	if (SigWork)
2723 		DoWorkerUnmounts(SigWork);
2724 	exit(1);
2725 }
2726 
2727 static
2728 char *
2729 buildskipreason(pkglink_t *parent, pkg_t *pkg)
2730 {
2731 	pkglink_t *link;
2732 	pkg_t *scan;
2733 	char *reason = NULL;
2734 	char *ptr;
2735 	size_t tot;
2736 	size_t len;
2737 	pkglink_t stack;
2738 
2739 	if ((pkg->flags & PKGF_NOBUILD_I) && pkg->ignore)
2740 		asprintf(&reason, "%s ", pkg->ignore);
2741 
2742 	tot = 0;
2743 	PKGLIST_FOREACH(link, &pkg->idepon_list) {
2744 #if 0
2745 		if (link->dep_type > DEP_TYPE_BUILD)
2746 			continue;
2747 #endif
2748 		scan = link->pkg;
2749 		if (scan == NULL)
2750 			continue;
2751 		if ((scan->flags & (PKGF_ERROR | PKGF_NOBUILD)) == 0)
2752 			continue;
2753 		if (scan->flags & PKGF_NOBUILD) {
2754 			stack.pkg = scan;
2755 			stack.next = parent;
2756 			ptr = buildskipreason(&stack, scan);
2757 			len = strlen(scan->portdir) + strlen(ptr) + 8;
2758 			reason = realloc(reason, tot + len);
2759 			snprintf(reason + tot, len, "%s->%s",
2760 				 scan->portdir, ptr);
2761 			free(ptr);
2762 		} else {
2763 			len = strlen(scan->portdir) + 8;
2764 			reason = realloc(reason, tot + len);
2765 			snprintf(reason + tot, len, "%s", scan->portdir);
2766 		}
2767 
2768 		/*
2769 		 * Don't try to print the entire graph
2770 		 */
2771 		if (parent)
2772 			break;
2773 		tot += strlen(reason + tot);
2774 		reason[tot++] = ' ';
2775 		reason[tot] = 0;
2776 	}
2777 	return (reason);
2778 }
2779 
2780 /*
2781  * Count number of packages that would be skipped due to the
2782  * specified package having failed.
2783  *
2784  * Call with mode 1 to count, and mode 0 to clear the
2785  * cumulative rscan flag (used to de-duplicate the count).
2786  *
2787  * Must be serialized.
2788  */
2789 static int
2790 buildskipcount_dueto(pkg_t *pkg, int mode)
2791 {
2792 	pkglink_t *link;
2793 	pkg_t *scan;
2794 	int total;
2795 
2796 	total = 0;
2797 	PKGLIST_FOREACH(link, &pkg->deponi_list) {
2798 		scan = link->pkg;
2799 		if (scan == NULL || scan->rscan == mode)
2800 			continue;
2801 		scan->rscan = mode;
2802 		++total;
2803 		total += buildskipcount_dueto(scan, mode);
2804 	}
2805 	return total;
2806 }
2807 
2808 /*
2809  * The master ptyfd is in non-blocking mode.  Drain up to 1024 bytes
2810  * and update wmsg->lines and *wdog_timep as appropriate.
2811  *
2812  * This function will poll, stalling up to 1 second.
2813  */
2814 static int
2815 mptylogpoll(int ptyfd, int fdlog, wmsg_t *wmsg, time_t *wdog_timep)
2816 {
2817 	struct pollfd pfd;
2818 	char buf[1024];
2819 	ssize_t r;
2820 
2821 	pfd.fd = ptyfd;
2822 	pfd.events = POLLIN;
2823 	pfd.revents = 0;
2824 
2825 	poll(&pfd, 1, 1000);
2826 	if (pfd.revents) {
2827 		r = read(ptyfd, buf, sizeof(buf));
2828 		if (r > 0) {
2829 			*wdog_timep = time(NULL);
2830 			if (r > 0 && fdlog >= 0)
2831 				write(fdlog, buf, r);
2832 			while (--r >= 0) {
2833 				if (buf[r] == '\n')
2834 					++wmsg->lines;
2835 			}
2836 			return MPTY_DATA;
2837 		} else if (r < 0) {
2838 			if (errno != EINTR && errno != EAGAIN)
2839 				return MPTY_FAILED;
2840 			return MPTY_AGAIN;
2841 		} else if (r == 0) {
2842 			return MPTY_EOF;
2843 		}
2844 	}
2845 	return MPTY_AGAIN;
2846 }
2847 
2848 /*
2849  * Copy a (package) file from (src) to (dst), use an intermediate file and
2850  * rename to ensure that interruption does not leave us with a corrupt
2851  * package file.
2852  *
2853  * This is called by the WORKER process.
2854  *
2855  * (dsynth management thread -> WORKER process -> sub-processes)
2856  */
2857 #define COPYBLKSIZE	32768
2858 
2859 int
2860 copyfile(char *src, char *dst)
2861 {
2862 	char *tmp;
2863 	char *buf;
2864 	int fd1;
2865 	int fd2;
2866 	int error = 0;
2867 	int mask;
2868 	ssize_t r;
2869 
2870 	asprintf(&tmp, "%s.new", dst);
2871 	buf = malloc(COPYBLKSIZE);
2872 
2873 	mask = sigsetmask(sigmask(SIGTERM)|sigmask(SIGINT)|sigmask(SIGHUP));
2874 	fd1 = open(src, O_RDONLY|O_CLOEXEC);
2875 	fd2 = open(tmp, O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0644);
2876 	CopyFileFd = fd1;
2877 	sigsetmask(mask);
2878 	while ((r = read(fd1, buf, COPYBLKSIZE)) > 0) {
2879 		if (write(fd2, buf, r) != r)
2880 			error = 1;
2881 	}
2882 	if (r < 0)
2883 		error = 1;
2884 	mask = sigsetmask(sigmask(SIGTERM)|sigmask(SIGINT)|sigmask(SIGHUP));
2885 	CopyFileFd = -1;
2886 	close(fd1);
2887 	close(fd2);
2888 	sigsetmask(mask);
2889 	if (error) {
2890 		remove(tmp);
2891 	} else {
2892 		if (rename(tmp, dst)) {
2893 			error = 1;
2894 			remove(tmp);
2895 		}
2896 	}
2897 
2898 	freestrp(&buf);
2899 	freestrp(&tmp);
2900 
2901 	return error;
2902 }
2903 
2904 /*
2905  * doHook()
2906  *
2907  * primary process (threaded) - run_start, run_end, pkg_ignored, pkg_skipped
2908  * worker process  (threaded) - pkg_sucess, pkg_failure
2909  *
2910  * If waitfor is non-zero this hook will be serialized.
2911  */
2912 static void
2913 doHook(pkg_t *pkg, const char *id, const char *path, int waitfor)
2914 {
2915 	if (path == NULL)
2916 		return;
2917 	while (waitfor && getbulk() != NULL)
2918 		;
2919 	if (pkg)
2920 		queuebulk(pkg->portdir, id, path, pkg->pkgfile);
2921 	else
2922 		queuebulk(NULL, id, path, NULL);
2923 	while (waitfor && getbulk() != NULL)
2924 		;
2925 }
2926 
2927 /*
2928  * Execute hook (backend)
2929  *
2930  * s1 - portdir
2931  * s2 - id
2932  * s3 - script path
2933  * s4 - pkgfile		(if applicable)
2934  */
2935 static void
2936 childHookRun(bulk_t *bulk)
2937 {
2938 	const char *cav[MAXCAC];
2939 	buildenv_t benv[MAXCAC];
2940 	char buf1[128];
2941 	char buf2[128];
2942 	char buf3[128];
2943 	char buf4[128];
2944 	FILE *fp;
2945 	char *ptr;
2946 	size_t len;
2947 	pid_t pid;
2948 	int cac;
2949 	int bi;
2950 
2951 	cac = 0;
2952 	bi = 0;
2953 	bzero(benv, sizeof(benv));
2954 
2955 	cav[cac++] = bulk->s3;
2956 
2957 	benv[bi].label = "PROFILE";
2958 	benv[bi].data = Profile;
2959 	++bi;
2960 
2961 	benv[bi].label = "DIR_PACKAGES";
2962 	benv[bi].data = PackagesPath;
2963 	++bi;
2964 
2965 	benv[bi].label = "DIR_REPOSITORY";
2966 	benv[bi].data = RepositoryPath;
2967 	++bi;
2968 
2969 	benv[bi].label = "DIR_PORTS";
2970 	benv[bi].data = DPortsPath;
2971 	++bi;
2972 
2973 	benv[bi].label = "DIR_OPTIONS";
2974 	benv[bi].data = OptionsPath;
2975 	++bi;
2976 
2977 	benv[bi].label = "DIR_DISTFILES";
2978 	benv[bi].data = DistFilesPath;
2979 	++bi;
2980 
2981 	benv[bi].label = "DIR_LOGS";
2982 	benv[bi].data = LogsPath;
2983 	++bi;
2984 
2985 	benv[bi].label = "DIR_BUILDBASE";
2986 	benv[bi].data = BuildBase;
2987 	++bi;
2988 
2989 	if (strcmp(bulk->s2, "hook_run_start") == 0) {
2990 		snprintf(buf1, sizeof(buf1), "%d", BuildTotal);
2991 		benv[bi].label = "PORTS_QUEUED";
2992 		benv[bi].data = buf1;
2993 		++bi;
2994 	} else if (strcmp(bulk->s2, "hook_run_end") == 0) {
2995 		snprintf(buf1, sizeof(buf1), "%d", BuildSuccessCount);
2996 		benv[bi].label = "PORTS_BUILT";
2997 		benv[bi].data = buf1;
2998 		++bi;
2999 		snprintf(buf2, sizeof(buf2), "%d", BuildFailCount);
3000 		benv[bi].label = "PORTS_FAILED";
3001 		benv[bi].data = buf2;
3002 		++bi;
3003 		snprintf(buf3, sizeof(buf3), "%d", BuildIgnoreCount);
3004 		benv[bi].label = "PORTS_IGNORED";
3005 		benv[bi].data = buf3;
3006 		++bi;
3007 		snprintf(buf4, sizeof(buf4), "%d", BuildSkipCount);
3008 		benv[bi].label = "PORTS_SKIPPED";
3009 		benv[bi].data = buf4;
3010 		++bi;
3011 	} else {
3012 		/*
3013 		 * success, failure, ignored, skipped
3014 		 */
3015 		benv[bi].label = "RESULT";
3016 		if (strcmp(bulk->s2, "hook_pkg_success") == 0) {
3017 			benv[bi].data = "success";
3018 		} else if (strcmp(bulk->s2, "hook_pkg_failure") == 0) {
3019 			benv[bi].data = "failure";
3020 		} else if (strcmp(bulk->s2, "hook_pkg_ignored") == 0) {
3021 			benv[bi].data = "ignored";
3022 		} else if (strcmp(bulk->s2, "hook_pkg_skipped") == 0) {
3023 			benv[bi].data = "skipped";
3024 		} else {
3025 			dfatal("Unknown hook id: %s", bulk->s2);
3026 			/* NOT REACHED */
3027 		}
3028 		++bi;
3029 
3030 		/*
3031 		 * For compatibility with synth:
3032 		 *
3033 		 * ORIGIN does not include any @flavor, thus it is suitable
3034 		 * for finding the actual port directory/subdirectory.
3035 		 *
3036 		 * FLAVOR is set to ORIGIN if there is no flavor, otherwise
3037 		 * it is set to only the flavor sans the '@'.
3038 		 */
3039 		if ((ptr = strchr(bulk->s1, '@')) != NULL) {
3040 			snprintf(buf1, sizeof(buf1), "%*.*s",
3041 				 (int)(ptr - bulk->s1),
3042 				 (int)(ptr - bulk->s1),
3043 				 bulk->s1);
3044 			benv[bi].label = "ORIGIN";
3045 			benv[bi].data = buf1;
3046 			++bi;
3047 			benv[bi].label = "FLAVOR";
3048 			benv[bi].data = ptr + 1;
3049 			++bi;
3050 		} else {
3051 			benv[bi].label = "ORIGIN";
3052 			benv[bi].data = bulk->s1;
3053 			++bi;
3054 			benv[bi].label = "FLAVOR";
3055 			benv[bi].data = bulk->s1;
3056 			++bi;
3057 		}
3058 		benv[bi].label = "PKGNAME";
3059 		benv[bi].data = bulk->s4;
3060 		++bi;
3061 	}
3062 
3063 	benv[bi].label = NULL;
3064 	benv[bi].data = NULL;
3065 
3066 	fp = dexec_open(bulk->s1, cav, cac, &pid, benv, 0, 0);
3067 	while ((ptr = fgetln(fp, &len)) != NULL)
3068 		;
3069 
3070 	if (dexec_close(fp, pid)) {
3071 		dlog(DLOG_ALL,
3072 		     "[XXX] %s SCRIPT %s (%s)\n",
3073 		     bulk->s1, bulk->s2, bulk->s3);
3074 	}
3075 }
3076 
3077 /*
3078  * Adjusts dload[0] by adding in t_pw (processes waiting on page-fault).
3079  * We don't want load reductions due to e.g. thrashing to cause dsynth
3080  * to increase the dynamic limit because it thinks the load is low.
3081  *
3082  * This has a desirable property.  If the system pager cannot keep up
3083  * with process demand t_pw will spike while loadavg will only drop
3084  * slowly, resulting in a high adjusted load calculation that causes
3085  * dsynth to quickly clamp-down the limit.  If the condition alleviates,
3086  * the limit will then rise slowly again, possibly even before existing
3087  * jobs are retired to meet the clamp-down from the original spike.
3088  */
3089 static void
3090 adjloadavg(double *dload)
3091 {
3092 #if defined(__DragonFly__)
3093 	struct vmtotal total;
3094 	size_t size;
3095 
3096 	size = sizeof(total);
3097 	if (sysctlbyname("vm.vmtotal", &total, &size, NULL, 0) == 0) {
3098 		dload[0] += (double)total.t_pw;
3099 	}
3100 #else
3101 	dload[0] += 0.0;	/* just avoid compiler 'unused' warnings */
3102 #endif
3103 }
3104 
3105 /*
3106  * Check if the ports directory contents has changed and force a
3107  * package to be rebuilt if it has by clearing the PACKAGED bit.
3108  */
3109 static
3110 void
3111 check_packaged(const char *dbmpath, pkg_t *pkgs)
3112 {
3113 	pkg_t *scan;
3114 	datum key;
3115 	datum data;
3116 	char *buf;
3117 
3118 	if (CheckDBM == NULL) {
3119 		dlog(DLOG_ABN, "[XXX] Unable to open/create dbm %s\n", dbmpath);
3120 		return;
3121 	}
3122 	for (scan = pkgs; scan; scan = scan->bnext) {
3123 		if ((scan->flags & PKGF_PACKAGED) == 0)
3124 			continue;
3125 		key.dptr = scan->portdir;
3126 		key.dsize = strlen(scan->portdir);
3127 		data = dbm_fetch(CheckDBM, key);
3128 		if (data.dptr && data.dsize == sizeof(uint32_t) &&
3129 		    *(uint32_t *)data.dptr != scan->crc32) {
3130 			scan->flags &= ~PKGF_PACKAGED;
3131 			asprintf(&buf, "%s/%s", RepositoryPath, scan->pkgfile);
3132 			if (OverridePkgDeleteOpt >= 2) {
3133 				scan->flags |= PKGF_PACKAGED;
3134 				dlog(DLOG_ALL,
3135 				     "[XXX] %s DELETE-PACKAGE %s "
3136 				     "(port content changed CRC %08x/%08x "
3137 				     "OVERRIDE, NOT DELETED)\n",
3138 				     scan->portdir, buf,
3139 				     *(uint32_t *)data.dptr, scan->crc32);
3140 			} else if (remove(buf) < 0) {
3141 				dlog(DLOG_ALL,
3142 				     "[XXX] %s DELETE-PACKAGE %s (failed)\n",
3143 				     scan->portdir, buf);
3144 			} else {
3145 				dlog(DLOG_ALL,
3146 				     "[XXX] %s DELETE-PACKAGE %s "
3147 				     "(port content changed CRC %08x/%08x)\n",
3148 				     scan->portdir, buf,
3149 				     *(uint32_t *)data.dptr, scan->crc32);
3150 			}
3151 			freestrp(&buf);
3152 		} else if (data.dptr == NULL) {
3153 			data.dptr = &scan->crc32;
3154 			data.dsize = sizeof(scan->crc32);
3155 			dbm_store(CheckDBM, key, data, DBM_REPLACE);
3156 		}
3157 	}
3158 }
3159