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