xref: /titanic_50/usr/src/tools/ctf/cvt/ctfmerge.c (revision b249c65cf0a7400e86a36ddab5c3fce085809859)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * Given several files containing CTF data, merge and uniquify that data into
30  * a single CTF section in an output file.
31  *
32  * Merges can proceed independently.  As such, we perform the merges in parallel
33  * using a worker thread model.  A given glob of CTF data (either all of the CTF
34  * data from a single input file, or the result of one or more merges) can only
35  * be involved in a single merge at any given time, so the process decreases in
36  * parallelism, especially towards the end, as more and more files are
37  * consolidated, finally resulting in a single merge of two large CTF graphs.
38  * Unfortunately, the last merge is also the slowest, as the two graphs being
39  * merged are each the product of merges of half of the input files.
40  *
41  * The algorithm consists of two phases, described in detail below.  The first
42  * phase entails the merging of CTF data in groups of eight.  The second phase
43  * takes the results of Phase I, and merges them two at a time.  This disparity
44  * is due to an observation that the merge time increases at least quadratically
45  * with the size of the CTF data being merged.  As such, merges of CTF graphs
46  * newly read from input files are much faster than merges of CTF graphs that
47  * are themselves the results of prior merges.
48  *
49  * A further complication is the need to ensure the repeatability of CTF merges.
50  * That is, a merge should produce the same output every time, given the same
51  * input.  In both phases, this consistency requirement is met by imposing an
52  * ordering on the merge process, thus ensuring that a given set of input files
53  * are merged in the same order every time.
54  *
55  *   Phase I
56  *
57  *   The main thread reads the input files one by one, transforming the CTF
58  *   data they contain into tdata structures.  When a given file has been read
59  *   and parsed, it is placed on the work queue for retrieval by worker threads.
60  *
61  *   Central to Phase I is the Work In Progress (wip) array, which is used to
62  *   merge batches of files in a predictable order.  Files are read by the main
63  *   thread, and are merged into wip array elements in round-robin order.  When
64  *   the number of files merged into a given array slot equals the batch size,
65  *   the merged CTF graph in that array is added to the done slot in order by
66  *   array slot.
67  *
68  *   For example, consider a case where we have five input files, a batch size
69  *   of two, a wip array size of two, and two worker threads (T1 and T2).
70  *
71  *    1. The wip array elements are assigned initial batch numbers 0 and 1.
72  *    2. T1 reads an input file from the input queue (wq_queue).  This is the
73  *       first input file, so it is placed into wip[0].  The second file is
74  *       similarly read and placed into wip[1].  The wip array slots now contain
75  *       one file each (wip_nmerged == 1).
76  *    3. T1 reads the third input file, which it merges into wip[0].  The
77  *       number of files in wip[0] is equal to the batch size.
78  *    4. T2 reads the fourth input file, which it merges into wip[1].  wip[1]
79  *       is now full too.
80  *    5. T2 attempts to place the contents of wip[1] on the done queue
81  *       (wq_done_queue), but it can't, since the batch ID for wip[1] is 1.
82  *       Batch 0 needs to be on the done queue before batch 1 can be added, so
83  *       T2 blocks on wip[1]'s cv.
84  *    6. T1 attempts to place the contents of wip[0] on the done queue, and
85  *       succeeds, updating wq_lastdonebatch to 0.  It clears wip[0], and sets
86  *       its batch ID to 2.  T1 then signals wip[1]'s cv to awaken T2.
87  *    7. T2 wakes up, notices that wq_lastdonebatch is 0, which means that
88  *       batch 1 can now be added.  It adds wip[1] to the done queue, clears
89  *       wip[1], and sets its batch ID to 3.  It signals wip[0]'s cv, and
90  *       restarts.
91  *
92  *   The above process continues until all input files have been consumed.  At
93  *   this point, a pair of barriers are used to allow a single thread to move
94  *   any partial batches from the wip array to the done array in batch ID order.
95  *   When this is complete, wq_done_queue is moved to wq_queue, and Phase II
96  *   begins.
97  *
98  *	Locking Semantics (Phase I)
99  *
100  *	The input queue (wq_queue) and the done queue (wq_done_queue) are
101  *	protected by separate mutexes - wq_queue_lock and wq_done_queue.  wip
102  *	array slots are protected by their own mutexes, which must be grabbed
103  *	before releasing the input queue lock.  The wip array lock is dropped
104  *	when the thread restarts the loop.  If the array slot was full, the
105  *	array lock will be held while the slot contents are added to the done
106  *	queue.  The done queue lock is used to protect the wip slot cv's.
107  *
108  *	The pow number is protected by the queue lock.  The master batch ID
109  *	and last completed batch (wq_lastdonebatch) counters are protected *in
110  *	Phase I* by the done queue lock.
111  *
112  *   Phase II
113  *
114  *   When Phase II begins, the queue consists of the merged batches from the
115  *   first phase.  Assume we have five batches:
116  *
117  *	Q:	a b c d e
118  *
119  *   Using the same batch ID mechanism we used in Phase I, but without the wip
120  *   array, worker threads remove two entries at a time from the beginning of
121  *   the queue.  These two entries are merged, and are added back to the tail
122  *   of the queue, as follows:
123  *
124  *	Q:	a b c d e	# start
125  *	Q:	c d e ab	# a, b removed, merged, added to end
126  *	Q:	e ab cd		# c, d removed, merged, added to end
127  *	Q:	cd eab		# e, ab removed, merged, added to end
128  *	Q:	cdeab		# cd, eab removed, merged, added to end
129  *
130  *   When one entry remains on the queue, with no merges outstanding, Phase II
131  *   finishes.  We pre-determine the stopping point by pre-calculating the
132  *   number of nodes that will appear on the list.  In the example above, the
133  *   number (wq_ninqueue) is 9.  When ninqueue is 1, we conclude Phase II by
134  *   signaling the main thread via wq_done_cv.
135  *
136  *	Locking Semantics (Phase II)
137  *
138  *	The queue (wq_queue), ninqueue, and the master batch ID and last
139  *	completed batch counters are protected by wq_queue_lock.  The done
140  *	queue and corresponding lock are unused in Phase II as is the wip array.
141  *
142  *   Uniquification
143  *
144  *   We want the CTF data that goes into a given module to be as small as
145  *   possible.  For example, we don't want it to contain any type data that may
146  *   be present in another common module.  As such, after creating the master
147  *   tdata_t for a given module, we can, if requested by the user, uniquify it
148  *   against the tdata_t from another module (genunix in the case of the SunOS
149  *   kernel).  We perform a merge between the tdata_t for this module and the
150  *   tdata_t from genunix.  Nodes found in this module that are not present in
151  *   genunix are added to a third tdata_t - the uniquified tdata_t.
152  *
153  *   Additive Merges
154  *
155  *   In some cases, for example if we are issuing a new version of a common
156  *   module in a patch, we need to make sure that the CTF data already present
157  *   in that module does not change.  Changes to this data would void the CTF
158  *   data in any module that uniquified against the common module.  To preserve
159  *   the existing data, we can perform what is known as an additive merge.  In
160  *   this case, a final uniquification is performed against the CTF data in the
161  *   previous version of the module.  The result will be the placement of new
162  *   and changed data after the existing data, thus preserving the existing type
163  *   ID space.
164  *
165  *   Saving the result
166  *
167  *   When the merges are complete, the resulting tdata_t is placed into the
168  *   output file, replacing the .SUNW_ctf section (if any) already in that file.
169  *
170  * The person who changes the merging thread code in this file without updating
171  * this comment will not live to see the stock hit five.
172  */
173 
174 #include <stdio.h>
175 #include <stdlib.h>
176 #include <unistd.h>
177 #include <pthread.h>
178 #include <assert.h>
179 #include <synch.h>
180 #include <signal.h>
181 #include <libgen.h>
182 #include <string.h>
183 #include <errno.h>
184 #include <alloca.h>
185 #include <sys/param.h>
186 #include <sys/types.h>
187 #include <sys/mman.h>
188 #include <sys/sysconf.h>
189 
190 #include "ctf_headers.h"
191 #include "ctftools.h"
192 #include "ctfmerge.h"
193 #include "traverse.h"
194 #include "memory.h"
195 #include "fifo.h"
196 #include "barrier.h"
197 
198 #pragma init(bigheap)
199 
200 #define	MERGE_PHASE1_BATCH_SIZE		8
201 #define	MERGE_PHASE1_MAX_SLOTS		5
202 #define	MERGE_INPUT_THROTTLE_LEN	10
203 
204 const char *progname;
205 static char *outfile = NULL;
206 static char *tmpname = NULL;
207 static int dynsym;
208 int debug_level = DEBUG_LEVEL;
209 static size_t maxpgsize = 0x400000;
210 
211 
212 void
213 usage(void)
214 {
215 	(void) fprintf(stderr,
216 	    "Usage: %s [-fgstv] -l label | -L labelenv -o outfile file ...\n"
217 	    "       %s [-fgstv] -l label | -L labelenv -o outfile -d uniqfile\n"
218 	    "       %*s [-g] [-D uniqlabel] file ...\n"
219 	    "       %s [-fgstv] -l label | -L labelenv -o outfile -w withfile "
220 	    "file ...\n"
221 	    "       %s [-g] -c srcfile destfile\n"
222 	    "\n"
223 	    "  Note: if -L labelenv is specified and labelenv is not set in\n"
224 	    "  the environment, a default value is used.\n",
225 	    progname, progname, strlen(progname), " ",
226 	    progname, progname);
227 }
228 
229 static void
230 bigheap(void)
231 {
232 	size_t big, *size;
233 	int sizes;
234 	struct memcntl_mha mha;
235 
236 	/*
237 	 * First, get the available pagesizes.
238 	 */
239 	if ((sizes = getpagesizes(NULL, 0)) == -1)
240 		return;
241 
242 	if (sizes == 1 || (size = alloca(sizeof (size_t) * sizes)) == NULL)
243 		return;
244 
245 	if (getpagesizes(size, sizes) == -1)
246 		return;
247 
248 	while (size[sizes - 1] > maxpgsize)
249 		sizes--;
250 
251 	/* set big to the largest allowed page size */
252 	big = size[sizes - 1];
253 	if (big & (big - 1)) {
254 		/*
255 		 * The largest page size is not a power of two for some
256 		 * inexplicable reason; return.
257 		 */
258 		return;
259 	}
260 
261 	/*
262 	 * Now, align our break to the largest page size.
263 	 */
264 	if (brk((void *)((((uintptr_t)sbrk(0) - 1) & ~(big - 1)) + big)) != 0)
265 		return;
266 
267 	/*
268 	 * set the preferred page size for the heap
269 	 */
270 	mha.mha_cmd = MHA_MAPSIZE_BSSBRK;
271 	mha.mha_flags = 0;
272 	mha.mha_pagesize = big;
273 
274 	(void) memcntl(NULL, 0, MC_HAT_ADVISE, (caddr_t)&mha, 0, 0);
275 }
276 
277 static void
278 finalize_phase_one(workqueue_t *wq)
279 {
280 	int startslot, i;
281 
282 	/*
283 	 * wip slots are cleared out only when maxbatchsz td's have been merged
284 	 * into them.  We're not guaranteed that the number of files we're
285 	 * merging is a multiple of maxbatchsz, so there will be some partial
286 	 * groups in the wip array.  Move them to the done queue in batch ID
287 	 * order, starting with the slot containing the next batch that would
288 	 * have been placed on the done queue, followed by the others.
289 	 * One thread will be doing this while the others wait at the barrier
290 	 * back in worker_thread(), so we don't need to worry about pesky things
291 	 * like locks.
292 	 */
293 
294 	for (startslot = -1, i = 0; i < wq->wq_nwipslots; i++) {
295 		if (wq->wq_wip[i].wip_batchid == wq->wq_lastdonebatch + 1) {
296 			startslot = i;
297 			break;
298 		}
299 	}
300 
301 	assert(startslot != -1);
302 
303 	for (i = startslot; i < startslot + wq->wq_nwipslots; i++) {
304 		int slotnum = i % wq->wq_nwipslots;
305 		wip_t *wipslot = &wq->wq_wip[slotnum];
306 
307 		if (wipslot->wip_td != NULL) {
308 			debug(2, "clearing slot %d (%d) (saving %d)\n",
309 			    slotnum, i, wipslot->wip_nmerged);
310 		} else
311 			debug(2, "clearing slot %d (%d)\n", slotnum, i);
312 
313 		if (wipslot->wip_td != NULL) {
314 			fifo_add(wq->wq_donequeue, wipslot->wip_td);
315 			wq->wq_wip[slotnum].wip_td = NULL;
316 		}
317 	}
318 
319 	wq->wq_lastdonebatch = wq->wq_next_batchid++;
320 
321 	debug(2, "phase one done: donequeue has %d items\n",
322 	    fifo_len(wq->wq_donequeue));
323 }
324 
325 static void
326 init_phase_two(workqueue_t *wq)
327 {
328 	int num;
329 
330 	/*
331 	 * We're going to continually merge the first two entries on the queue,
332 	 * placing the result on the end, until there's nothing left to merge.
333 	 * At that point, everything will have been merged into one.  The
334 	 * initial value of ninqueue needs to be equal to the total number of
335 	 * entries that will show up on the queue, both at the start of the
336 	 * phase and as generated by merges during the phase.
337 	 */
338 	wq->wq_ninqueue = num = fifo_len(wq->wq_donequeue);
339 	while (num != 1) {
340 		wq->wq_ninqueue += num / 2;
341 		num = num / 2 + num % 2;
342 	}
343 
344 	/*
345 	 * Move the done queue to the work queue.  We won't be using the done
346 	 * queue in phase 2.
347 	 */
348 	assert(fifo_len(wq->wq_queue) == 0);
349 	fifo_free(wq->wq_queue, NULL);
350 	wq->wq_queue = wq->wq_donequeue;
351 }
352 
353 static void
354 wip_save_work(workqueue_t *wq, wip_t *slot, int slotnum)
355 {
356 	pthread_mutex_lock(&wq->wq_donequeue_lock);
357 
358 	while (wq->wq_lastdonebatch + 1 < slot->wip_batchid)
359 		pthread_cond_wait(&slot->wip_cv, &wq->wq_donequeue_lock);
360 	assert(wq->wq_lastdonebatch + 1 == slot->wip_batchid);
361 
362 	fifo_add(wq->wq_donequeue, slot->wip_td);
363 	wq->wq_lastdonebatch++;
364 	pthread_cond_signal(&wq->wq_wip[(slotnum + 1) %
365 	    wq->wq_nwipslots].wip_cv);
366 
367 	/* reset the slot for next use */
368 	slot->wip_td = NULL;
369 	slot->wip_batchid = wq->wq_next_batchid++;
370 
371 	pthread_mutex_unlock(&wq->wq_donequeue_lock);
372 }
373 
374 static void
375 wip_add_work(wip_t *slot, tdata_t *pow)
376 {
377 	if (slot->wip_td == NULL) {
378 		slot->wip_td = pow;
379 		slot->wip_nmerged = 1;
380 	} else {
381 		debug(2, "%d: merging %p into %p\n", pthread_self(),
382 		    (void *)pow, (void *)slot->wip_td);
383 
384 		merge_into_master(pow, slot->wip_td, NULL, 0);
385 		tdata_free(pow);
386 
387 		slot->wip_nmerged++;
388 	}
389 }
390 
391 static void
392 worker_runphase1(workqueue_t *wq)
393 {
394 	wip_t *wipslot;
395 	tdata_t *pow;
396 	int wipslotnum, pownum;
397 
398 	for (;;) {
399 		pthread_mutex_lock(&wq->wq_queue_lock);
400 
401 		while (fifo_empty(wq->wq_queue)) {
402 			if (wq->wq_nomorefiles == 1) {
403 				pthread_cond_broadcast(&wq->wq_work_avail);
404 				pthread_mutex_unlock(&wq->wq_queue_lock);
405 
406 				/* on to phase 2 ... */
407 				return;
408 			}
409 
410 			pthread_cond_wait(&wq->wq_work_avail,
411 			    &wq->wq_queue_lock);
412 		}
413 
414 		/* there's work to be done! */
415 		pow = fifo_remove(wq->wq_queue);
416 		pownum = wq->wq_nextpownum++;
417 		pthread_cond_broadcast(&wq->wq_work_removed);
418 
419 		assert(pow != NULL);
420 
421 		/* merge it into the right slot */
422 		wipslotnum = pownum % wq->wq_nwipslots;
423 		wipslot = &wq->wq_wip[wipslotnum];
424 
425 		pthread_mutex_lock(&wipslot->wip_lock);
426 
427 		pthread_mutex_unlock(&wq->wq_queue_lock);
428 
429 		wip_add_work(wipslot, pow);
430 
431 		if (wipslot->wip_nmerged == wq->wq_maxbatchsz)
432 			wip_save_work(wq, wipslot, wipslotnum);
433 
434 		pthread_mutex_unlock(&wipslot->wip_lock);
435 	}
436 }
437 
438 static void
439 worker_runphase2(workqueue_t *wq)
440 {
441 	tdata_t *pow1, *pow2;
442 	int batchid;
443 
444 	for (;;) {
445 		pthread_mutex_lock(&wq->wq_queue_lock);
446 
447 		if (wq->wq_ninqueue == 1) {
448 			pthread_cond_broadcast(&wq->wq_work_avail);
449 			pthread_mutex_unlock(&wq->wq_queue_lock);
450 
451 			debug(2, "%d: entering p2 completion barrier\n",
452 			    pthread_self());
453 			if (barrier_wait(&wq->wq_bar1)) {
454 				pthread_mutex_lock(&wq->wq_queue_lock);
455 				wq->wq_alldone = 1;
456 				pthread_cond_signal(&wq->wq_alldone_cv);
457 				pthread_mutex_unlock(&wq->wq_queue_lock);
458 			}
459 
460 			return;
461 		}
462 
463 		if (fifo_len(wq->wq_queue) < 2) {
464 			pthread_cond_wait(&wq->wq_work_avail,
465 			    &wq->wq_queue_lock);
466 			pthread_mutex_unlock(&wq->wq_queue_lock);
467 			continue;
468 		}
469 
470 		/* there's work to be done! */
471 		pow1 = fifo_remove(wq->wq_queue);
472 		pow2 = fifo_remove(wq->wq_queue);
473 		wq->wq_ninqueue -= 2;
474 
475 		batchid = wq->wq_next_batchid++;
476 
477 		pthread_mutex_unlock(&wq->wq_queue_lock);
478 
479 		debug(2, "%d: merging %p into %p\n", pthread_self(),
480 		    (void *)pow1, (void *)pow2);
481 		merge_into_master(pow1, pow2, NULL, 0);
482 		tdata_free(pow1);
483 
484 		/*
485 		 * merging is complete.  place at the tail of the queue in
486 		 * proper order.
487 		 */
488 		pthread_mutex_lock(&wq->wq_queue_lock);
489 		while (wq->wq_lastdonebatch + 1 != batchid) {
490 			pthread_cond_wait(&wq->wq_done_cv,
491 			    &wq->wq_queue_lock);
492 		}
493 
494 		wq->wq_lastdonebatch = batchid;
495 
496 		fifo_add(wq->wq_queue, pow2);
497 		debug(2, "%d: added %p to queue, len now %d, ninqueue %d\n",
498 		    pthread_self(), (void *)pow2, fifo_len(wq->wq_queue),
499 		    wq->wq_ninqueue);
500 		pthread_cond_broadcast(&wq->wq_done_cv);
501 		pthread_cond_signal(&wq->wq_work_avail);
502 		pthread_mutex_unlock(&wq->wq_queue_lock);
503 	}
504 }
505 
506 /*
507  * Main loop for worker threads.
508  */
509 static void
510 worker_thread(workqueue_t *wq)
511 {
512 	worker_runphase1(wq);
513 
514 	debug(2, "%d: entering first barrier\n", pthread_self());
515 
516 	if (barrier_wait(&wq->wq_bar1)) {
517 
518 		debug(2, "%d: doing work in first barrier\n", pthread_self());
519 
520 		finalize_phase_one(wq);
521 
522 		init_phase_two(wq);
523 
524 		debug(2, "%d: ninqueue is %d, %d on queue\n", pthread_self(),
525 		    wq->wq_ninqueue, fifo_len(wq->wq_queue));
526 	}
527 
528 	debug(2, "%d: entering second barrier\n", pthread_self());
529 
530 	(void) barrier_wait(&wq->wq_bar2);
531 
532 	debug(2, "%d: phase 1 complete\n", pthread_self());
533 
534 	worker_runphase2(wq);
535 }
536 
537 /*
538  * Pass a tdata_t tree, built from an input file, off to the work queue for
539  * consumption by worker threads.
540  */
541 static int
542 merge_ctf_cb(tdata_t *td, char *name, void *arg)
543 {
544 	workqueue_t *wq = arg;
545 
546 	debug(3, "Adding tdata %p for processing\n", (void *)td);
547 
548 	pthread_mutex_lock(&wq->wq_queue_lock);
549 	while (fifo_len(wq->wq_queue) > wq->wq_ithrottle) {
550 		debug(2, "Throttling input (len = %d, throttle = %d)\n",
551 		    fifo_len(wq->wq_queue), wq->wq_ithrottle);
552 		pthread_cond_wait(&wq->wq_work_removed, &wq->wq_queue_lock);
553 	}
554 
555 	fifo_add(wq->wq_queue, td);
556 	debug(1, "Thread %d announcing %s\n", pthread_self(), name);
557 	pthread_cond_broadcast(&wq->wq_work_avail);
558 	pthread_mutex_unlock(&wq->wq_queue_lock);
559 
560 	return (1);
561 }
562 
563 /*
564  * This program is intended to be invoked from a Makefile, as part of the build.
565  * As such, in the event of a failure or user-initiated interrupt (^C), we need
566  * to ensure that a subsequent re-make will cause ctfmerge to be executed again.
567  * Unfortunately, ctfmerge will usually be invoked directly after (and as part
568  * of the same Makefile rule as) a link, and will operate on the linked file
569  * in place.  If we merely exit upon receipt of a SIGINT, a subsequent make
570  * will notice that the *linked* file is newer than the object files, and thus
571  * will not reinvoke ctfmerge.  The only way to ensure that a subsequent make
572  * reinvokes ctfmerge, is to remove the file to which we are adding CTF
573  * data (confusingly named the output file).  This means that the link will need
574  * to happen again, but links are generally fast, and we can't allow the merge
575  * to be skipped.
576  *
577  * Another possibility would be to block SIGINT entirely - to always run to
578  * completion.  The run time of ctfmerge can, however, be measured in minutes
579  * in some cases, so this is not a valid option.
580  */
581 static void
582 handle_sig(int sig)
583 {
584 	terminate("Caught signal %d - exiting\n", sig);
585 }
586 
587 static void
588 terminate_cleanup(void)
589 {
590 	int dounlink = getenv("CTFMERGE_TERMINATE_NO_UNLINK") ? 0 : 1;
591 
592 	if (tmpname != NULL && dounlink)
593 		unlink(tmpname);
594 
595 	if (outfile == NULL)
596 		return;
597 
598 	if (dounlink) {
599 		fprintf(stderr, "Removing %s\n", outfile);
600 		unlink(outfile);
601 	}
602 }
603 
604 static void
605 copy_ctf_data(char *srcfile, char *destfile, int keep_stabs)
606 {
607 	tdata_t *srctd;
608 
609 	if (read_ctf(&srcfile, 1, NULL, read_ctf_save_cb, &srctd, 1) == 0)
610 		terminate("No CTF data found in source file %s\n", srcfile);
611 
612 	tmpname = mktmpname(destfile, ".ctf");
613 	write_ctf(srctd, destfile, tmpname, CTF_COMPRESS | keep_stabs);
614 	if (rename(tmpname, destfile) != 0) {
615 		terminate("Couldn't rename temp file %s to %s", tmpname,
616 		    destfile);
617 	}
618 	free(tmpname);
619 	tdata_free(srctd);
620 }
621 
622 static void
623 wq_init(workqueue_t *wq, int nfiles)
624 {
625 	int throttle, nslots, i;
626 
627 	if (getenv("CTFMERGE_MAX_SLOTS"))
628 		nslots = atoi(getenv("CTFMERGE_MAX_SLOTS"));
629 	else
630 		nslots = MERGE_PHASE1_MAX_SLOTS;
631 
632 	if (getenv("CTFMERGE_PHASE1_BATCH_SIZE"))
633 		wq->wq_maxbatchsz = atoi(getenv("CTFMERGE_PHASE1_BATCH_SIZE"));
634 	else
635 		wq->wq_maxbatchsz = MERGE_PHASE1_BATCH_SIZE;
636 
637 	nslots = MIN(nslots, (nfiles + wq->wq_maxbatchsz - 1) /
638 	    wq->wq_maxbatchsz);
639 
640 	wq->wq_wip = xcalloc(sizeof (wip_t) * nslots);
641 	wq->wq_nwipslots = nslots;
642 	wq->wq_nthreads = MIN(sysconf(_SC_NPROCESSORS_ONLN) * 3 / 2, nslots);
643 	wq->wq_thread = xmalloc(sizeof (pthread_t) * wq->wq_nthreads);
644 
645 	if (getenv("CTFMERGE_INPUT_THROTTLE"))
646 		throttle = atoi(getenv("CTFMERGE_INPUT_THROTTLE"));
647 	else
648 		throttle = MERGE_INPUT_THROTTLE_LEN;
649 	wq->wq_ithrottle = throttle * wq->wq_nthreads;
650 
651 	debug(1, "Using %d slots, %d threads\n", wq->wq_nwipslots,
652 	    wq->wq_nthreads);
653 
654 	wq->wq_next_batchid = 0;
655 
656 	for (i = 0; i < nslots; i++) {
657 		pthread_mutex_init(&wq->wq_wip[i].wip_lock, NULL);
658 		wq->wq_wip[i].wip_batchid = wq->wq_next_batchid++;
659 	}
660 
661 	pthread_mutex_init(&wq->wq_queue_lock, NULL);
662 	wq->wq_queue = fifo_new();
663 	pthread_cond_init(&wq->wq_work_avail, NULL);
664 	pthread_cond_init(&wq->wq_work_removed, NULL);
665 	wq->wq_ninqueue = nfiles;
666 	wq->wq_nextpownum = 0;
667 
668 	pthread_mutex_init(&wq->wq_donequeue_lock, NULL);
669 	wq->wq_donequeue = fifo_new();
670 	wq->wq_lastdonebatch = -1;
671 
672 	pthread_cond_init(&wq->wq_done_cv, NULL);
673 
674 	pthread_cond_init(&wq->wq_alldone_cv, NULL);
675 	wq->wq_alldone = 0;
676 
677 	barrier_init(&wq->wq_bar1, wq->wq_nthreads);
678 	barrier_init(&wq->wq_bar2, wq->wq_nthreads);
679 
680 	wq->wq_nomorefiles = 0;
681 }
682 
683 static void
684 start_threads(workqueue_t *wq)
685 {
686 	sigset_t sets;
687 	int i;
688 
689 	sigemptyset(&sets);
690 	sigaddset(&sets, SIGINT);
691 	sigaddset(&sets, SIGQUIT);
692 	sigaddset(&sets, SIGTERM);
693 	pthread_sigmask(SIG_BLOCK, &sets, NULL);
694 
695 	for (i = 0; i < wq->wq_nthreads; i++) {
696 		pthread_create(&wq->wq_thread[i], NULL,
697 		    (void *(*)(void *))worker_thread, wq);
698 	}
699 
700 	sigset(SIGINT, handle_sig);
701 	sigset(SIGQUIT, handle_sig);
702 	sigset(SIGTERM, handle_sig);
703 	pthread_sigmask(SIG_UNBLOCK, &sets, NULL);
704 }
705 
706 static void
707 join_threads(workqueue_t *wq)
708 {
709 	int i;
710 
711 	for (i = 0; i < wq->wq_nthreads; i++) {
712 		pthread_join(wq->wq_thread[i], NULL);
713 	}
714 }
715 
716 static int
717 strcompare(const void *p1, const void *p2)
718 {
719 	char *s1 = *((char **)p1);
720 	char *s2 = *((char **)p2);
721 
722 	return (strcmp(s1, s2));
723 }
724 
725 /*
726  * Core work queue structure; passed to worker threads on thread creation
727  * as the main point of coordination.  Allocate as a static structure; we
728  * could have put this into a local variable in main, but passing a pointer
729  * into your stack to another thread is fragile at best and leads to some
730  * hard-to-debug failure modes.
731  */
732 static workqueue_t wq;
733 
734 int
735 main(int argc, char **argv)
736 {
737 	tdata_t *mstrtd, *savetd;
738 	char *uniqfile = NULL, *uniqlabel = NULL;
739 	char *withfile = NULL;
740 	char *label = NULL;
741 	char **ifiles, **tifiles;
742 	int verbose = 0, docopy = 0;
743 	int write_fuzzy_match = 0;
744 	int keep_stabs = 0;
745 	int require_ctf = 0;
746 	int nifiles, nielems;
747 	int c, i, idx, tidx, err;
748 
749 	progname = basename(argv[0]);
750 
751 	if (getenv("CTFMERGE_DEBUG_LEVEL"))
752 		debug_level = atoi(getenv("CTFMERGE_DEBUG_LEVEL"));
753 
754 	err = 0;
755 	while ((c = getopt(argc, argv, ":cd:D:fgl:L:o:tvw:s")) != EOF) {
756 		switch (c) {
757 		case 'c':
758 			docopy = 1;
759 			break;
760 		case 'd':
761 			/* Uniquify against `uniqfile' */
762 			uniqfile = optarg;
763 			break;
764 		case 'D':
765 			/* Uniquify against label `uniqlabel' in `uniqfile' */
766 			uniqlabel = optarg;
767 			break;
768 		case 'f':
769 			write_fuzzy_match = CTF_FUZZY_MATCH;
770 			break;
771 		case 'g':
772 			keep_stabs = CTF_KEEP_STABS;
773 			break;
774 		case 'l':
775 			/* Label merged types with `label' */
776 			label = optarg;
777 			break;
778 		case 'L':
779 			/* Label merged types with getenv(`label`) */
780 			if ((label = getenv(optarg)) == NULL)
781 				label = CTF_DEFAULT_LABEL;
782 			break;
783 		case 'o':
784 			/* Place merged types in CTF section in `outfile' */
785 			outfile = optarg;
786 			break;
787 		case 't':
788 			/* Insist *all* object files built from C have CTF */
789 			require_ctf = 1;
790 			break;
791 		case 'v':
792 			/* More debugging information */
793 			verbose = 1;
794 			break;
795 		case 'w':
796 			/* Additive merge with data from `withfile' */
797 			withfile = optarg;
798 			break;
799 		case 's':
800 			/* use the dynsym rather than the symtab */
801 			dynsym = CTF_USE_DYNSYM;
802 			break;
803 		default:
804 			usage();
805 			exit(2);
806 		}
807 	}
808 
809 	/* Validate arguments */
810 	if (docopy) {
811 		if (uniqfile != NULL || uniqlabel != NULL || label != NULL ||
812 		    outfile != NULL || withfile != NULL || dynsym != 0)
813 			err++;
814 
815 		if (argc - optind != 2)
816 			err++;
817 	} else {
818 		if (uniqfile != NULL && withfile != NULL)
819 			err++;
820 
821 		if (uniqlabel != NULL && uniqfile == NULL)
822 			err++;
823 
824 		if (outfile == NULL || label == NULL)
825 			err++;
826 
827 		if (argc - optind == 0)
828 			err++;
829 	}
830 
831 	if (err) {
832 		usage();
833 		exit(2);
834 	}
835 
836 	if (getenv("STRIPSTABS_KEEP_STABS") != NULL)
837 		keep_stabs = CTF_KEEP_STABS;
838 
839 	if (uniqfile && access(uniqfile, R_OK) != 0) {
840 		warning("Uniquification file %s couldn't be opened and "
841 		    "will be ignored.\n", uniqfile);
842 		uniqfile = NULL;
843 	}
844 	if (withfile && access(withfile, R_OK) != 0) {
845 		warning("With file %s couldn't be opened and will be "
846 		    "ignored.\n", withfile);
847 		withfile = NULL;
848 	}
849 	if (outfile && access(outfile, R_OK|W_OK) != 0)
850 		terminate("Cannot open output file %s for r/w", outfile);
851 
852 	/*
853 	 * This is ugly, but we don't want to have to have a separate tool
854 	 * (yet) just for copying an ELF section with our specific requirements,
855 	 * so we shoe-horn a copier into ctfmerge.
856 	 */
857 	if (docopy) {
858 		copy_ctf_data(argv[optind], argv[optind + 1], keep_stabs);
859 
860 		exit(0);
861 	}
862 
863 	set_terminate_cleanup(terminate_cleanup);
864 
865 	/* Sort the input files and strip out duplicates */
866 	nifiles = argc - optind;
867 	ifiles = xmalloc(sizeof (char *) * nifiles);
868 	tifiles = xmalloc(sizeof (char *) * nifiles);
869 
870 	for (i = 0; i < nifiles; i++)
871 		tifiles[i] = argv[optind + i];
872 	qsort(tifiles, nifiles, sizeof (char *), (int (*)())strcompare);
873 
874 	ifiles[0] = tifiles[0];
875 	for (idx = 0, tidx = 1; tidx < nifiles; tidx++) {
876 		if (strcmp(ifiles[idx], tifiles[tidx]) != 0)
877 			ifiles[++idx] = tifiles[tidx];
878 	}
879 	nifiles = idx + 1;
880 
881 	/* Make sure they all exist */
882 	if ((nielems = count_files(ifiles, nifiles)) < 0)
883 		terminate("Some input files were inaccessible\n");
884 
885 	/* Prepare for the merge */
886 	wq_init(&wq, nielems);
887 
888 	start_threads(&wq);
889 
890 	/*
891 	 * Start the merge
892 	 *
893 	 * We're reading everything from each of the object files, so we
894 	 * don't need to specify labels.
895 	 */
896 	if (read_ctf(ifiles, nifiles, NULL, merge_ctf_cb,
897 	    &wq, require_ctf) == 0) {
898 		/*
899 		 * If we're verifying that C files have CTF, it's safe to
900 		 * assume that in this case, we're building only from assembly
901 		 * inputs.
902 		 */
903 		if (require_ctf)
904 			exit(0);
905 		terminate("No ctf sections found to merge\n");
906 	}
907 
908 	pthread_mutex_lock(&wq.wq_queue_lock);
909 	wq.wq_nomorefiles = 1;
910 	pthread_cond_broadcast(&wq.wq_work_avail);
911 	pthread_mutex_unlock(&wq.wq_queue_lock);
912 
913 	pthread_mutex_lock(&wq.wq_queue_lock);
914 	while (wq.wq_alldone == 0)
915 		pthread_cond_wait(&wq.wq_alldone_cv, &wq.wq_queue_lock);
916 	pthread_mutex_unlock(&wq.wq_queue_lock);
917 
918 	join_threads(&wq);
919 
920 	/*
921 	 * All requested files have been merged, with the resulting tree in
922 	 * mstrtd.  savetd is the tree that will be placed into the output file.
923 	 *
924 	 * Regardless of whether we're doing a normal uniquification or an
925 	 * additive merge, we need a type tree that has been uniquified
926 	 * against uniqfile or withfile, as appropriate.
927 	 *
928 	 * If we're doing a uniquification, we stuff the resulting tree into
929 	 * outfile.  Otherwise, we add the tree to the tree already in withfile.
930 	 */
931 	assert(fifo_len(wq.wq_queue) == 1);
932 	mstrtd = fifo_remove(wq.wq_queue);
933 
934 	if (verbose || debug_level) {
935 		debug(2, "Statistics for td %p\n", (void *)mstrtd);
936 
937 		iidesc_stats(mstrtd->td_iihash);
938 	}
939 
940 	if (uniqfile != NULL || withfile != NULL) {
941 		char *reffile, *reflabel = NULL;
942 		tdata_t *reftd;
943 
944 		if (uniqfile != NULL) {
945 			reffile = uniqfile;
946 			reflabel = uniqlabel;
947 		} else
948 			reffile = withfile;
949 
950 		if (read_ctf(&reffile, 1, reflabel, read_ctf_save_cb,
951 		    &reftd, require_ctf) == 0) {
952 			terminate("No CTF data found in reference file %s\n",
953 			    reffile);
954 		}
955 
956 		savetd = tdata_new();
957 
958 		if (CTF_TYPE_ISCHILD(reftd->td_nextid))
959 			terminate("No room for additional types in master\n");
960 
961 		savetd->td_nextid = withfile ? reftd->td_nextid :
962 		    CTF_INDEX_TO_TYPE(1, TRUE);
963 		merge_into_master(mstrtd, reftd, savetd, 0);
964 
965 		tdata_label_add(savetd, label, CTF_LABEL_LASTIDX);
966 
967 		if (withfile) {
968 			/*
969 			 * savetd holds the new data to be added to the withfile
970 			 */
971 			tdata_t *withtd = reftd;
972 
973 			tdata_merge(withtd, savetd);
974 
975 			savetd = withtd;
976 		} else {
977 			char uniqname[MAXPATHLEN];
978 			labelent_t *parle;
979 
980 			parle = tdata_label_top(reftd);
981 
982 			savetd->td_parlabel = xstrdup(parle->le_name);
983 
984 			strncpy(uniqname, reffile, sizeof (uniqname));
985 			uniqname[MAXPATHLEN - 1] = '\0';
986 			savetd->td_parname = xstrdup(basename(uniqname));
987 		}
988 
989 	} else {
990 		/*
991 		 * No post processing.  Write the merged tree as-is into the
992 		 * output file.
993 		 */
994 		tdata_label_free(mstrtd);
995 		tdata_label_add(mstrtd, label, CTF_LABEL_LASTIDX);
996 
997 		savetd = mstrtd;
998 	}
999 
1000 	tmpname = mktmpname(outfile, ".ctf");
1001 	write_ctf(savetd, outfile, tmpname,
1002 	    CTF_COMPRESS | write_fuzzy_match | dynsym | keep_stabs);
1003 	if (rename(tmpname, outfile) != 0)
1004 		terminate("Couldn't rename output temp file %s", tmpname);
1005 	free(tmpname);
1006 
1007 	return (0);
1008 }
1009