2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (C) 2009 Gabor Kovesdan <gabor@FreeBSD.org>
5 * Copyright (C) 2012 Oleg Moskalenko <mom040267@gmail.com>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
35 #include <sys/types.h>
36 #include <sys/queue.h>
40 #if defined(SORT_THREADS)
43 #include <semaphore.h>
53 #include "radixsort.h"
55 unsigned long long free_memory = 1000000;
56 unsigned long long available_free_memory = 1000000;
60 const char *tmpdir = "/var/tmp";
61 const char *compress_program;
63 size_t max_open_files = 16;
66 * How much space we read from file at once
68 #define READ_CHUNK (4096)
71 * File reader structure
75 struct reader_buffer rb;
78 unsigned char *buffer;
79 unsigned char *mmapaddr;
80 unsigned char *mmapptr;
90 * Structure to be used in file merge process.
94 struct file_reader *fr;
95 struct sort_list_item *si; /* current top line */
100 * List elements of "cleanable" files list.
102 struct CLEANABLE_FILE
105 LIST_ENTRY(CLEANABLE_FILE) files;
109 * List header of "cleanable" files list.
111 static LIST_HEAD(CLEANABLE_FILES,CLEANABLE_FILE) tmp_files;
114 * Semaphore to protect the tmp file list.
115 * We use semaphore here because it is signal-safe, according to POSIX.
116 * And semaphore does not require pthread library.
118 static sem_t tmp_files_sem;
120 static void mt_sort(struct sort_list *list,
121 int (*sort_func)(void *, size_t, size_t,
122 int (*)(const void *, const void *)), const char* fn);
125 * Init tmp files list
131 LIST_INIT(&tmp_files);
132 sem_init(&tmp_files_sem, 0, 1);
136 * Save name of a tmp file for signal cleanup
139 tmp_file_atexit(const char *tmp_file)
143 sem_wait(&tmp_files_sem);
144 struct CLEANABLE_FILE *item =
145 sort_malloc(sizeof(struct CLEANABLE_FILE));
146 item->fn = sort_strdup(tmp_file);
147 LIST_INSERT_HEAD(&tmp_files, item, files);
148 sem_post(&tmp_files_sem);
156 clear_tmp_files(void)
158 struct CLEANABLE_FILE *item;
160 sem_wait(&tmp_files_sem);
161 LIST_FOREACH(item,&tmp_files,files) {
162 if ((item) && (item->fn))
165 sem_post(&tmp_files_sem);
169 * Check whether a file is a temporary file
172 file_is_tmp(const char* fn)
174 struct CLEANABLE_FILE *item;
178 sem_wait(&tmp_files_sem);
179 LIST_FOREACH(item,&tmp_files,files) {
180 if ((item) && (item->fn))
181 if (strcmp(item->fn, fn) == 0) {
186 sem_post(&tmp_files_sem);
193 * Generate new temporary file name
196 new_tmp_file_name(void)
198 static size_t tfcounter = 0;
199 static const char *fn = ".bsdsort.";
203 sz = strlen(tmpdir) + 1 + strlen(fn) + 32 + 1;
204 ret = sort_malloc(sz);
206 sprintf(ret, "%s/%s%d.%lu", tmpdir, fn, (int) getpid(), (unsigned long)(tfcounter++));
207 tmp_file_atexit(ret);
212 * Initialize file list
215 file_list_init(struct file_list *fl, bool tmp)
227 * Add a file name to the list
230 file_list_add(struct file_list *fl, const char *fn, bool allocate)
234 if (fl->count >= fl->sz || (fl->fns == NULL)) {
235 fl->sz = (fl->sz) * 2 + 1;
236 fl->fns = sort_realloc(fl->fns, fl->sz *
239 fl->fns[fl->count] = allocate ? sort_strdup(fn) : fn;
245 * Populate file list from array of file names
248 file_list_populate(struct file_list *fl, int argc, char **argv, bool allocate)
254 for (i = 0; i < argc; i++)
255 file_list_add(fl, argv[i], allocate);
260 * Clean file list data and delete the files,
261 * if this is a list of temporary files
264 file_list_clean(struct file_list *fl)
271 for (i = 0; i < fl->count; i++) {
275 sort_free(fl->fns[i]);
292 sort_list_init(struct sort_list *l)
298 l->memsize = sizeof(struct sort_list);
304 * Add string to sort list
307 sort_list_add(struct sort_list *l, struct bwstring *str)
311 size_t indx = l->count;
313 if ((l->list == NULL) || (indx >= l->size)) {
314 size_t newsize = (l->size + 1) + 1024;
316 l->list = sort_realloc(l->list,
317 sizeof(struct sort_list_item*) * newsize);
318 l->memsize += (newsize - l->size) *
319 sizeof(struct sort_list_item*);
322 l->list[indx] = sort_list_item_alloc();
323 sort_list_item_set(l->list[indx], str);
324 l->memsize += sort_list_item_size(l->list[indx]);
330 * Clean sort list data
333 sort_list_clean(struct sort_list *l)
340 for (i = 0; i < l->count; i++) {
341 struct sort_list_item *item;
346 sort_list_item_clean(item);
356 l->memsize = sizeof(struct sort_list);
361 * Write sort list to file
364 sort_list_dump(struct sort_list *l, const char *fn)
370 f = openfile(fn, "w");
376 if (!(sort_opts_vals.uflag)) {
377 for (i = 0; i < l->count; ++i)
378 bwsfwrite(l->list[i]->str, f,
379 sort_opts_vals.zflag);
381 struct sort_list_item *last_printed_item = NULL;
382 struct sort_list_item *item;
383 for (i = 0; i < l->count; ++i) {
385 if ((last_printed_item == NULL) ||
386 list_coll(&last_printed_item, &item)) {
387 bwsfwrite(item->str, f, sort_opts_vals.zflag);
388 last_printed_item = item;
399 * Checks if the given file is sorted. Stops at the first disorder,
400 * prints the disordered line and returns 1.
403 check(const char *fn)
405 struct bwstring *s1, *s2, *s1disorder, *s2disorder;
406 struct file_reader *fr;
407 struct keys_array *ka1, *ka2;
409 size_t pos, posdisorder;
411 s1 = s2 = s1disorder = s2disorder = NULL;
414 fr = file_reader_init(fn);
425 s1 = file_reader_readline(fr);
429 ka1 = keys_array_alloc();
432 s2 = file_reader_readline(fr);
436 ka2 = keys_array_alloc();
442 bwsprintf(stdout, s2, "s1=<", ">");
443 bwsprintf(stdout, s1, "s2=<", ">");
445 int cmp = key_coll(ka2, ka1, 0);
447 printf("; cmp1=%d", cmp);
449 if (!cmp && sort_opts_vals.complex_sort &&
450 !(sort_opts_vals.uflag) && !(sort_opts_vals.sflag)) {
451 cmp = top_level_str_coll(s2, s1);
453 printf("; cmp2=%d", cmp);
458 if ((sort_opts_vals.uflag && (cmp <= 0)) || (cmp < 0)) {
459 if (!(sort_opts_vals.csilentflag)) {
460 s2disorder = bwsdup(s2);
463 s1disorder = bwsdup(s1);
471 clean_keys_array(s1, ka1);
479 s2 = file_reader_readline(fr);
483 ka2 = keys_array_alloc();
489 clean_keys_array(s1, ka1);
497 clean_keys_array(s2, ka2);
504 if ((fn == NULL) || (*fn == 0) || (strcmp(fn, "-") == 0)) {
506 s2 = file_reader_readline(fr);
513 file_reader_free(fr);
516 bws_disorder_warnx(s2disorder, fn, posdisorder);
518 bws_disorder_warnx(s1disorder, fn, posdisorder);
519 if (s1disorder != s2disorder)
534 * Opens a file. If the given filename is "-", stdout will be
538 openfile(const char *fn, const char *mode)
542 if (strcmp(fn, "-") == 0) {
543 return ((mode && mode[0] == 'r') ? stdin : stdout);
545 mode_t orig_file_mask = 0;
546 int is_tmp = file_is_tmp(fn);
548 if (is_tmp && (mode[0] == 'w'))
549 orig_file_mask = umask(S_IWGRP | S_IWOTH |
552 if (is_tmp && (compress_program != NULL)) {
556 cmdsz = strlen(fn) + 128;
557 cmd = sort_malloc(cmdsz);
562 snprintf(cmd, cmdsz - 1, "cat %s | %s -d",
563 fn, compress_program);
564 else if (mode[0] == 'w')
565 snprintf(cmd, cmdsz - 1, "%s > %s",
566 compress_program, fn);
568 err(2, "%s", getstr(7));
570 if ((file = popen(cmd, mode)) == NULL)
576 if ((file = fopen(fn, mode)) == NULL)
579 if (is_tmp && (mode[0] == 'w'))
580 umask(orig_file_mask);
590 closefile(FILE *f, const char *fn)
594 } else if (f == stdin) {
596 } else if (f == stdout) {
599 if (file_is_tmp(fn) && compress_program != NULL) {
608 * Reads a file into the internal buffer.
611 file_reader_init(const char *fsrc)
613 struct file_reader *ret;
618 ret = sort_malloc(sizeof(struct file_reader));
619 memset(ret, 0, sizeof(struct file_reader));
622 if (sort_opts_vals.zflag)
625 ret->fname = sort_strdup(fsrc);
627 if (strcmp(fsrc, "-") && (compress_program == NULL) && use_mmap) {
630 struct stat stat_buf;
635 flags = MAP_NOCORE | MAP_NOSYNC;
637 fd = open(fsrc, O_RDONLY);
641 if (fstat(fd, &stat_buf) < 0) {
646 sz = stat_buf.st_size;
648 #if defined(MAP_PREFAULT_READ)
649 flags |= MAP_PREFAULT_READ;
652 addr = mmap(NULL, sz, PROT_READ, flags, fd, 0);
653 if (addr == MAP_FAILED) {
659 ret->mmapaddr = addr;
661 ret->mmapptr = ret->mmapaddr;
666 if (ret->mmapaddr == NULL) {
667 ret->file = openfile(fsrc, "r");
668 if (ret->file == NULL)
671 if (strcmp(fsrc, "-")) {
672 ret->cbsz = READ_CHUNK;
673 ret->buffer = sort_malloc(ret->cbsz);
677 ret->bsz = fread(ret->buffer, 1, ret->cbsz, ret->file);
679 if (ferror(ret->file))
689 file_reader_readline(struct file_reader *fr)
691 struct bwstring *ret = NULL;
694 unsigned char *mmapend;
696 mmapend = fr->mmapaddr + fr->mmapsize;
697 if (fr->mmapptr >= mmapend)
700 unsigned char *strend;
703 sz = mmapend - fr->mmapptr;
704 strend = memchr(fr->mmapptr, fr->elsymb, sz);
706 if (strend == NULL) {
707 ret = bwscsbdup(fr->mmapptr, sz);
708 fr->mmapptr = mmapend;
710 ret = bwscsbdup(fr->mmapptr, strend -
712 fr->mmapptr = strend + 1;
716 } else if (fr->file != stdin) {
717 unsigned char *strend;
718 size_t bsz1, remsz, search_start;
724 if (fr->bsz > fr->strbeg)
725 remsz = fr->bsz - fr->strbeg;
727 /* line read cycle */
729 if (remsz > search_start)
730 strend = memchr(fr->buffer + fr->strbeg +
731 search_start, fr->elsymb, remsz -
741 if (fr->bsz != fr->cbsz)
743 err(2, "File read software error 1");
745 if (remsz > (READ_CHUNK >> 1)) {
746 search_start = fr->cbsz - fr->strbeg;
747 fr->cbsz += READ_CHUNK;
748 fr->buffer = sort_realloc(fr->buffer,
750 bsz1 = fread(fr->buffer + fr->bsz, 1,
751 READ_CHUNK, fr->file);
753 if (ferror(fr->file))
760 if (remsz > 0 && fr->strbeg>0)
761 bcopy(fr->buffer + fr->strbeg,
765 search_start = remsz;
766 bsz1 = fread(fr->buffer + remsz, 1,
767 fr->cbsz - remsz, fr->file);
769 if (ferror(fr->file))
773 fr->bsz = remsz + bsz1;
779 strend = fr->buffer + fr->bsz;
781 if ((fr->buffer + fr->strbeg <= strend) &&
782 (fr->strbeg < fr->bsz) && (remsz>0))
783 ret = bwscsbdup(fr->buffer + fr->strbeg, strend -
784 fr->buffer - fr->strbeg);
786 fr->strbeg = (strend - fr->buffer) + 1;
791 ret = bwsfgetln(fr->file, &len, sort_opts_vals.zflag,
799 file_reader_clean(struct file_reader *fr)
804 munmap(fr->mmapaddr, fr->mmapsize);
810 sort_free(fr->buffer);
813 if (fr->file != stdin)
814 closefile(fr->file, fr->fname);
817 sort_free(fr->fname);
819 memset(fr, 0, sizeof(struct file_reader));
824 file_reader_free(struct file_reader *fr)
828 file_reader_clean(fr);
834 procfile(const char *fsrc, struct sort_list *list, struct file_list *fl)
836 struct file_reader *fr;
838 fr = file_reader_init(fsrc);
842 /* file browse cycle */
844 struct bwstring *bws;
846 bws = file_reader_readline(fr);
851 sort_list_add(list, bws);
853 if (list->memsize >= available_free_memory) {
856 fn = new_tmp_file_name();
857 sort_list_to_file(list, fn);
858 file_list_add(fl, fn, false);
859 sort_list_clean(list);
863 file_reader_free(fr);
869 * Compare file headers. Files with EOF always go to the end of the list.
872 file_header_cmp(struct file_header *f1, struct file_header *f2)
878 if (f1->fr == NULL) {
879 return ((f2->fr == NULL) ? 0 : +1);
880 } else if (f2->fr == NULL)
885 ret = list_coll(&(f1->si), &(f2->si));
887 return ((f1->file_pos < f2->file_pos) ? -1 : +1);
894 * Allocate and init file header structure
897 file_header_init(struct file_header **fh, const char *fn, size_t file_pos)
901 struct bwstring *line;
903 *fh = sort_malloc(sizeof(struct file_header));
904 (*fh)->file_pos = file_pos;
905 (*fh)->fr = file_reader_init(fn);
906 if ((*fh)->fr == NULL) {
908 err(2, "%s", getstr(8));
910 line = file_reader_readline((*fh)->fr);
912 file_reader_free((*fh)->fr);
916 (*fh)->si = sort_list_item_alloc();
917 sort_list_item_set((*fh)->si, line);
926 file_header_close(struct file_header **fh)
931 file_reader_free((*fh)->fr);
935 sort_list_item_clean((*fh)->si);
936 sort_free((*fh)->si);
945 * Swap two array elements
948 file_header_swap(struct file_header **fh, size_t i1, size_t i2)
950 struct file_header *tmp;
957 /* heap algorithm ==>> */
960 * See heap sort algorithm
961 * "Raises" last element to its right place
964 file_header_heap_swim(struct file_header **fh, size_t indx)
970 parent_index = (indx - 1) >> 1;
972 if (file_header_cmp(fh[indx], fh[parent_index]) < 0) {
973 /* swap child and parent and continue */
974 file_header_swap(fh, indx, parent_index);
975 file_header_heap_swim(fh, parent_index);
981 * Sink the top element to its correct position
984 file_header_heap_sink(struct file_header **fh, size_t indx, size_t size)
986 size_t left_child_index;
987 size_t right_child_index;
989 left_child_index = indx + indx + 1;
990 right_child_index = left_child_index + 1;
992 if (left_child_index < size) {
993 size_t min_child_index;
995 min_child_index = left_child_index;
997 if ((right_child_index < size) &&
998 (file_header_cmp(fh[left_child_index],
999 fh[right_child_index]) > 0))
1000 min_child_index = right_child_index;
1001 if (file_header_cmp(fh[indx], fh[min_child_index]) > 0) {
1002 file_header_swap(fh, indx, min_child_index);
1003 file_header_heap_sink(fh, min_child_index, size);
1008 /* <<== heap algorithm */
1011 * Adds element to the "left" end
1014 file_header_list_rearrange_from_header(struct file_header **fh, size_t size)
1017 file_header_heap_sink(fh, 0, size);
1021 * Adds element to the "right" end
1024 file_header_list_push(struct file_header *f, struct file_header **fh, size_t size)
1028 file_header_heap_swim(fh, size - 1);
1033 struct bwstring *str;
1037 * Prints the current line of the file
1040 file_header_print(struct file_header *fh, FILE *f_out, struct last_printed *lp)
1043 if (fh && fh->fr && f_out && fh->si && fh->si->str) {
1044 if (sort_opts_vals.uflag) {
1045 if ((lp->str == NULL) || (str_list_coll(lp->str, &(fh->si)))) {
1046 bwsfwrite(fh->si->str, f_out, sort_opts_vals.zflag);
1049 lp->str = bwsdup(fh->si->str);
1052 bwsfwrite(fh->si->str, f_out, sort_opts_vals.zflag);
1060 file_header_read_next(struct file_header *fh)
1064 struct bwstring *tmp;
1066 tmp = file_reader_readline(fh->fr);
1068 file_reader_free(fh->fr);
1071 sort_list_item_clean(fh->si);
1077 fh->si = sort_list_item_alloc();
1078 sort_list_item_set(fh->si, tmp);
1084 * Merge array of "files headers"
1087 file_headers_merge(size_t fnum, struct file_header **fh, FILE *f_out)
1089 struct last_printed lp;
1092 memset(&lp, 0, sizeof(lp));
1095 * construct the initial sort structure
1097 for (i = 0; i < fnum; i++)
1098 file_header_list_push(fh[i], fh, i);
1100 while (fh[0]->fr) { /* unfinished files are always in front */
1101 /* output the smallest line: */
1102 file_header_print(fh[0], f_out, &lp);
1103 /* read a new line, if possible: */
1104 file_header_read_next(fh[0]);
1105 /* re-arrange the list: */
1106 file_header_list_rearrange_from_header(fh, fnum);
1114 * Merges the given files into the output file, which can be
1118 merge_files_array(size_t argc, const char **argv, const char *fn_out)
1121 if (argv && fn_out) {
1122 struct file_header **fh;
1126 f_out = openfile(fn_out, "w");
1131 fh = sort_malloc((argc + 1) * sizeof(struct file_header *));
1133 for (i = 0; i < argc; i++)
1134 file_header_init(fh + i, argv[i], (size_t) i);
1136 file_headers_merge(argc, fh, f_out);
1138 for (i = 0; i < argc; i++)
1139 file_header_close(fh + i);
1143 closefile(f_out, fn_out);
1148 * Shrinks the file list until its size smaller than max number of opened files
1151 shrink_file_list(struct file_list *fl)
1154 if ((fl == NULL) || (size_t) (fl->count) < max_open_files)
1157 struct file_list new_fl;
1160 file_list_init(&new_fl, true);
1161 while (indx < fl->count) {
1165 num = fl->count - indx;
1166 fnew = new_tmp_file_name();
1168 if ((size_t) num >= max_open_files)
1169 num = max_open_files - 1;
1170 merge_files_array(num, fl->fns + indx, fnew);
1174 for (i = 0; i < num; i++)
1175 unlink(fl->fns[indx + i]);
1177 file_list_add(&new_fl, fnew, false);
1180 fl->tmp = false; /* already taken care of */
1181 file_list_clean(fl);
1183 fl->count = new_fl.count;
1184 fl->fns = new_fl.fns;
1186 fl->tmp = new_fl.tmp;
1193 * Merge list of files
1196 merge_files(struct file_list *fl, const char *fn_out)
1200 while (shrink_file_list(fl));
1202 merge_files_array(fl->count, fl->fns, fn_out);
1207 get_sort_method_name(int sm)
1210 if (sm == SORT_MERGESORT)
1212 else if (sort_opts_vals.sort_method == SORT_RADIXSORT)
1214 else if (sort_opts_vals.sort_method == SORT_HEAPSORT)
1223 static int sort_qsort(void *list, size_t count, size_t elem_size,
1224 int (*cmp_func)(const void *, const void *))
1227 qsort(list, count, elem_size, cmp_func);
1232 * Sort list of lines and writes it to the file
1235 sort_list_to_file(struct sort_list *list, const char *outfile)
1237 struct sort_mods *sm = &(keys[0].sm);
1239 if (!(sm->Mflag) && !(sm->Rflag) && !(sm->Vflag) &&
1240 !(sm->gflag) && !(sm->hflag) && !(sm->nflag)) {
1241 if ((sort_opts_vals.sort_method == SORT_DEFAULT) && byte_sort)
1242 sort_opts_vals.sort_method = SORT_RADIXSORT;
1244 } else if (sort_opts_vals.sort_method == SORT_RADIXSORT)
1245 err(2, "%s", getstr(9));
1248 * to handle stable sort and the unique cases in the
1249 * right order, we need stable basic algorithm
1251 if (sort_opts_vals.sflag) {
1252 switch (sort_opts_vals.sort_method){
1253 case SORT_MERGESORT:
1255 case SORT_RADIXSORT:
1258 sort_opts_vals.sort_method = SORT_MERGESORT;
1261 errx(2, "%s", getstr(10));
1265 if (sort_opts_vals.sort_method == SORT_DEFAULT)
1266 sort_opts_vals.sort_method = DEFAULT_SORT_ALGORITHM;
1269 printf("sort_method=%s\n",
1270 get_sort_method_name(sort_opts_vals.sort_method));
1272 switch (sort_opts_vals.sort_method){
1273 case SORT_RADIXSORT:
1274 rxsort(list->list, list->count);
1275 sort_list_dump(list, outfile);
1277 case SORT_MERGESORT:
1278 mt_sort(list, mergesort, outfile);
1281 mt_sort(list, heapsort, outfile);
1284 mt_sort(list, sort_qsort, outfile);
1287 mt_sort(list, DEFAULT_SORT_FUNC, outfile);
1292 /******************* MT SORT ************************/
1294 #if defined(SORT_THREADS)
1295 /* semaphore to count threads */
1298 /* current system sort function */
1299 static int (*g_sort_func)(void *, size_t, size_t,
1300 int(*)(const void *, const void *));
1303 * Sort cycle thread (in multi-threaded mode)
1306 mt_sort_thread(void* arg)
1308 struct sort_list *list = arg;
1310 g_sort_func(list->list, list->count, sizeof(struct sort_list_item *),
1311 (int(*)(const void *, const void *)) list_coll);
1319 * Compare sub-lists. Empty sub-lists always go to the end of the list.
1322 sub_list_cmp(struct sort_list *l1, struct sort_list *l2)
1328 if (l1->count == 0) {
1329 return ((l2->count == 0) ? 0 : +1);
1330 } else if (l2->count == 0) {
1335 ret = list_coll(&(l1->list[0]), &(l2->list[0]));
1337 return ((l1->sub_list_pos < l2->sub_list_pos) ?
1345 * Swap two array elements
1348 sub_list_swap(struct sort_list **sl, size_t i1, size_t i2)
1350 struct sort_list *tmp;
1357 /* heap algorithm ==>> */
1360 * See heap sort algorithm
1361 * "Raises" last element to its right place
1364 sub_list_swim(struct sort_list **sl, size_t indx)
1368 size_t parent_index;
1370 parent_index = (indx - 1) >> 1;
1372 if (sub_list_cmp(sl[indx], sl[parent_index]) < 0) {
1373 /* swap child and parent and continue */
1374 sub_list_swap(sl, indx, parent_index);
1375 sub_list_swim(sl, parent_index);
1381 * Sink the top element to its correct position
1384 sub_list_sink(struct sort_list **sl, size_t indx, size_t size)
1386 size_t left_child_index;
1387 size_t right_child_index;
1389 left_child_index = indx + indx + 1;
1390 right_child_index = left_child_index + 1;
1392 if (left_child_index < size) {
1393 size_t min_child_index;
1395 min_child_index = left_child_index;
1397 if ((right_child_index < size) &&
1398 (sub_list_cmp(sl[left_child_index],
1399 sl[right_child_index]) > 0))
1400 min_child_index = right_child_index;
1401 if (sub_list_cmp(sl[indx], sl[min_child_index]) > 0) {
1402 sub_list_swap(sl, indx, min_child_index);
1403 sub_list_sink(sl, min_child_index, size);
1408 /* <<== heap algorithm */
1411 * Adds element to the "right" end
1414 sub_list_push(struct sort_list *s, struct sort_list **sl, size_t size)
1418 sub_list_swim(sl, size - 1);
1421 struct last_printed_item
1423 struct sort_list_item *item;
1427 * Prints the current line of the file
1430 sub_list_header_print(struct sort_list *sl, FILE *f_out,
1431 struct last_printed_item *lp)
1434 if (sl && sl->count && f_out && sl->list[0]->str) {
1435 if (sort_opts_vals.uflag) {
1436 if ((lp->item == NULL) || (list_coll(&(lp->item),
1438 bwsfwrite(sl->list[0]->str, f_out,
1439 sort_opts_vals.zflag);
1440 lp->item = sl->list[0];
1443 bwsfwrite(sl->list[0]->str, f_out,
1444 sort_opts_vals.zflag);
1452 sub_list_next(struct sort_list *sl)
1455 if (sl && sl->count) {
1462 * Merge sub-lists to a file
1465 merge_sub_lists(struct sort_list **sl, size_t n, FILE* f_out)
1467 struct last_printed_item lp;
1470 memset(&lp,0,sizeof(lp));
1472 /* construct the initial list: */
1473 for (i = 0; i < n; i++)
1474 sub_list_push(sl[i], sl, i);
1476 while (sl[0]->count) { /* unfinished lists are always in front */
1477 /* output the smallest line: */
1478 sub_list_header_print(sl[0], f_out, &lp);
1479 /* move to a new line, if possible: */
1480 sub_list_next(sl[0]);
1481 /* re-arrange the list: */
1482 sub_list_sink(sl, 0, n);
1487 * Merge sub-lists to a file
1490 merge_list_parts(struct sort_list **parts, size_t n, const char *fn)
1494 f_out = openfile(fn,"w");
1496 merge_sub_lists(parts, n, f_out);
1498 closefile(f_out, fn);
1501 #endif /* defined(SORT_THREADS) */
1503 * Multi-threaded sort algorithm "driver"
1506 mt_sort(struct sort_list *list,
1507 int(*sort_func)(void *, size_t, size_t, int(*)(const void *, const void *)),
1510 #if defined(SORT_THREADS)
1511 if (nthreads < 2 || list->count < MT_SORT_THRESHOLD) {
1512 size_t nthreads_save = nthreads;
1515 /* if single thread or small data, do simple sort */
1516 sort_func(list->list, list->count,
1517 sizeof(struct sort_list_item *),
1518 (int(*)(const void *, const void *)) list_coll);
1519 sort_list_dump(list, fn);
1520 #if defined(SORT_THREADS)
1521 nthreads = nthreads_save;
1523 /* multi-threaded sort */
1524 struct sort_list **parts;
1525 size_t avgsize, cstart, i;
1527 /* array of sub-lists */
1528 parts = sort_malloc(sizeof(struct sort_list*) * nthreads);
1530 avgsize = list->count / nthreads;
1532 /* set global system sort function */
1533 g_sort_func = sort_func;
1536 for (i = 0; i < nthreads; ++i) {
1539 parts[i] = sort_malloc(sizeof(struct sort_list));
1540 parts[i]->list = list->list + cstart;
1541 parts[i]->memsize = 0;
1542 parts[i]->sub_list_pos = i;
1544 sz = (i == nthreads - 1) ? list->count - cstart :
1547 parts[i]->count = sz;
1549 parts[i]->size = parts[i]->count;
1554 /* init threads counting semaphore */
1555 sem_init(&mtsem, 0, 0);
1558 for (i = 0; i < nthreads; ++i) {
1560 pthread_attr_t attr;
1562 pthread_attr_init(&attr);
1563 pthread_attr_setdetachstate(&attr, PTHREAD_DETACHED);
1566 int res = pthread_create(&pth, &attr,
1567 mt_sort_thread, parts[i]);
1571 if (errno == EAGAIN) {
1578 pthread_attr_destroy(&attr);
1581 /* wait for threads completion */
1582 for (i = 0; i < nthreads; ++i) {
1585 /* destroy the semaphore - we do not need it anymore */
1586 sem_destroy(&mtsem);
1588 /* merge sorted sub-lists to the file */
1589 merge_list_parts(parts, nthreads, fn);
1591 /* free sub-lists data */
1592 for (i = 0; i < nthreads; ++i) {
1593 sort_free(parts[i]);
1597 #endif /* defined(SORT_THREADS) */