From 776276d5c7e67356a880f3e31076d32cdc1c1882 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Tue, 10 Nov 2026 11:29:58 +0300 Subject: publish --- src/card.h | 15 ++ src/cuda.cu | 157 ++++++++++++ src/file-scanner.c | 301 ++++++++++++++++++++++ src/file-scanner.h | 42 ++++ src/multi-threaded.c | 339 +++++++++++++++++++++++++ src/partition.c | 134 ++++++++++ src/sandbox.c | 55 ++++ src/scanner.c | 137 ++++++++++ src/scanner.h | 29 +++ src/single-threaded.c | 262 +++++++++++++++++++ src/string-view.h | 16 ++ src/super-computer.c | 672 +++++++++++++++++++++++++++++++++++++++++++++++++ src/transaction-heap.c | 60 +++++ src/transaction-heap.h | 18 ++ src/transaction.h | 26 ++ src/user.h | 22 ++ src/utils.c | 91 +++++++ src/utils.h | 95 +++++++ 18 files changed, 2471 insertions(+) create mode 100644 src/card.h create mode 100644 src/cuda.cu create mode 100644 src/file-scanner.c create mode 100644 src/file-scanner.h create mode 100644 src/multi-threaded.c create mode 100644 src/partition.c create mode 100644 src/sandbox.c create mode 100644 src/scanner.c create mode 100644 src/scanner.h create mode 100644 src/single-threaded.c create mode 100644 src/string-view.h create mode 100644 src/super-computer.c create mode 100644 src/transaction-heap.c create mode 100644 src/transaction-heap.h create mode 100644 src/transaction.h create mode 100644 src/user.h create mode 100644 src/utils.c create mode 100644 src/utils.h (limited to 'src') diff --git a/src/card.h b/src/card.h new file mode 100644 index 0000000..b92add5 --- /dev/null +++ b/src/card.h @@ -0,0 +1,15 @@ +// card.h +#ifndef INCLUDED_CARD_H +#define INCLUDED_CARD_H + +typedef uint16_t card_id_t; + +struct card { + union { + card_id_t key; + card_id_t id; + }; +}; + +#endif // INCLUDED_CARD_H +// card.h ends here diff --git a/src/cuda.cu b/src/cuda.cu new file mode 100644 index 0000000..fb59c57 --- /dev/null +++ b/src/cuda.cu @@ -0,0 +1,157 @@ +// cuda.cu -*- C++ -*- +#include +#include +#include +#include +#include +#include "utils.h" + +// #define K 100 + +extern "C" int +process_transactions (uint64_t *h_keys, float *h_vals, size_t count) +{ + // CUresult cuerr = cuInit(0); + // if (cuerr != CUDA_SUCCESS) { + // DEBUG ("cuInit: %d\n", cuerr); + // return 0; + // } + + cudaError_t err; + // int device_count = 0; + // err = cudaGetDeviceCount (&device_count); + // if (err != cudaSuccess) { + // DEBUG ("cudaGetDeviceCount: %s", cudaGetErrorString (err)); + // return 0; + // } + // printf ("CUDA Device Count: %d\n", device_count); + + // if (device_count == 0) { + // printf("ERROR: No CUDA devices found!\n"); + // return 0; + // } + + // cudaSetDevice (0); + + uint64_t *d_in_keys = nullptr, *d_out_keys = nullptr; + float *d_in_vals = nullptr, *d_out_vals = nullptr; + + cudaMalloc (&d_in_keys, count*sizeof (*d_in_keys)); + cudaMalloc (&d_in_vals, count*sizeof (*d_in_vals)); + + cudaMemcpy (d_in_keys, h_keys, count*sizeof (*h_keys), cudaMemcpyHostToDevice); + cudaMemcpy (d_in_vals, h_vals, count*sizeof (*h_vals), cudaMemcpyHostToDevice); + + cudaMalloc (&d_out_keys, count*sizeof (*d_out_keys)); + cudaMalloc (&d_out_vals, count*sizeof (*d_out_vals)); + + void *d_temp = nullptr; + size_t temp_size = 0; + err = cub::DeviceRadixSort::SortPairs (d_temp, temp_size, + d_in_keys, d_out_keys, + d_in_vals, d_out_vals, count); + // if (err != cudaSuccess) { + // DEBUG ("SortPairs: %s", cudaGetErrorString (err)); + // return 0; + // } + cudaMalloc (&d_temp, temp_size); + err = cub::DeviceRadixSort::SortPairs (d_temp, temp_size, + d_in_keys, d_out_keys, + d_in_vals, d_out_vals, count); + // if (err != cudaSuccess) { + // DEBUG ("SortPairs: %s", cudaGetErrorString (err)); + // return 0; + // } + cudaFree (d_in_keys); + cudaFree (d_in_vals); + cudaFree (d_temp); + + uint64_t *d_unique_keys = nullptr; + float *d_unique_vals = nullptr; + int *d_unique_count = nullptr; + cudaMalloc (&d_unique_keys, count*sizeof (*d_unique_keys)); + cudaMalloc (&d_unique_vals, count*sizeof (*d_unique_vals)); + cudaMalloc (&d_unique_count, sizeof (*d_unique_count)); + d_temp = nullptr; + temp_size = 0; + err = cub::DeviceReduce::ReduceByKey (d_temp, temp_size, + d_out_keys, + d_unique_keys, + d_out_vals, + d_unique_vals, + d_unique_count, cub::Sum (), count); + // if (err != cudaSuccess) { + // DEBUG ("SortPairs: %s", cudaGetErrorString (err)); + // return 0; + // } + cudaMalloc (&d_temp, temp_size); + err = cub::DeviceReduce::ReduceByKey (d_temp, temp_size, + d_out_keys, + d_unique_keys, + d_out_vals, + d_unique_vals, + d_unique_count, cub::Sum (), count); + // if (err != cudaSuccess) { + // DEBUG ("SortPairs: %s", cudaGetErrorString (err)); + // return 0; + // } + cudaFree (d_out_keys); + cudaFree (d_out_vals); + cudaFree (d_temp); + + int h_unique_count; + cudaMemcpy (&h_unique_count, d_unique_count, + sizeof (h_unique_count), cudaMemcpyDeviceToHost); + cudaFree (d_unique_count); + + cudaMemcpy (h_keys, d_unique_keys, h_unique_count*sizeof (*h_keys), cudaMemcpyDeviceToHost); + cudaMemcpy (h_vals, d_unique_vals, h_unique_count*sizeof (*h_vals), cudaMemcpyDeviceToHost); + + cudaFree (d_unique_keys); + cudaFree (d_unique_vals); + + return h_unique_count; + + // requires cuda 13... +#if 0 + if (h_unique_count <= K) { + cudaMemcpy (h_keys, d_unique_keys, + h_unique_count*sizeof (*h_keys), cudaMemcpyDeviceToHost); + cudaFree (d_unique_keys); + + cudaMemcpy (h_vals, d_unique_vals, + h_unique_count*sizeof (*h_vals), cudaMemcpyDeviceToHost); + cudaFree (d_unique_vals); + + return h_unique_count; + } + + uint64_t *d_top_keys = nullptr; + float *d_top_vals = nullptr; + cudaMalloc (&d_top_keys, K*sizeof (*d_unique_keys)); + cudaMalloc (&d_top_vals, K*sizeof (*d_unique_vals)); + d_temp = nullptr; + temp_size = 0; + cub::DeviceTopK::MaxPairs (d_temp, temp_size, + d_unique_vals, d_top_vals, + d_unique_keys, d_top_keys, + h_unique_count, K, env); + cudaMalloc (&d_temp, temp_size); + cub::DeviceTopK::MaxPairs (d_temp, temp_size, + d_unique_vals, d_top_vals, + d_unique_keys, d_top_keys, + h_unique_count, K); + cudaFree (d_unique_keys); + cudaFree (d_unique_vals); + cudaFree (d_temp); + + cudaMemcpy (h_keys, d_top_keys, K*sizeof (*h_keys), cudaMemcpyDeviceToHost); + cudaMemcpy (h_vals, d_top_vals, K*sizeof (*h_vals), cudaMemcpyDeviceToHost); + + cudaFree (d_top_keys); + cudaFree (d_top_vals); + + return K; +#endif +} +// cuda.cu ends here diff --git a/src/file-scanner.c b/src/file-scanner.c new file mode 100644 index 0000000..6ae217a --- /dev/null +++ b/src/file-scanner.c @@ -0,0 +1,301 @@ +#define _GNU_SOURCE +#include +#include + +#include "file-scanner.h" +#include "utils.h" + +void +file_scanner__init (struct file_scanner *fs, int fd) +{ + union { + int i; + void *p; + } ret; + + ASSERT (fs != NULL); + ASSERT (fd >= 0); + + fs->to_mark_as_scanned = 0; + + fs->input_fd = fd; // Open with O_DIRECT? + ret.i = posix_fadvise (fs->input_fd, 0, 0, POSIX_FADV_SEQUENTIAL); + ASSERT (ret.i == 0); + + struct stat st; + ret.i = fstat (fs->input_fd, &st); + ASSERT (ret.i == 0); + ASSERT (st.st_size > 0); + fs->input_size = st.st_size; + + // Create backing memory (can't be virtual in order to double map) + fs->memfd = memfd_create ("file-scanner", 0); // TODO(cmmm): gen UID from fs + ASSERT (fs->memfd != -1); + ret.i = ftruncate (fs->memfd, RING_SIZE*READ_SIZE); + ASSERT (ret.i == 0); + + // Reserve contiguous virtual memory region for double mapping memfd + fs->buffer = mmap (NULL, 2*RING_SIZE*READ_SIZE, PROT_NONE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + ASSERT (fs->buffer != MAP_FAILED); + + // Double map buffer (to cleanly handle wraparound) + ret.p = mmap (fs->buffer, RING_SIZE*READ_SIZE, + PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fs->memfd, 0); + ASSERT (ret.p != MAP_FAILED); + ret.p = mmap (fs->buffer + RING_SIZE*READ_SIZE, RING_SIZE*READ_SIZE, + PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fs->memfd, 0); + ASSERT (ret.p != MAP_FAILED); + + ret.i = io_uring_queue_init (IO_URING_SIZE, &fs->io_uring, 0); + ASSERT (ret.i == 0); + + struct iovec iov[RING_SIZE]; + for (int i = 0; i < RING_SIZE; ++i) { + iov[i].iov_base = fs->buffer + i*READ_SIZE; + iov[i].iov_len = READ_SIZE; + } + io_uring_register_buffers (&fs->io_uring, iov, RING_SIZE); + io_uring_register_files (&fs->io_uring, &fs->input_fd, 1); + + fs->scanner.cursor = fs->buffer; + fs->scanner.end = fs->buffer; // NOTE(cmmm): haven't read anything yet + + // Fill io_uring queue + size_t read_size = MIN (4 << 10, // Start with reading a single page + fs->input_size - fs->input_submitted); + fs->input_scanned = 0; + fs->input_submitted = 0; + int submitted; + for (submitted = 0; submitted < IO_URING_SIZE;) { + // Getting a submission queue entry (SQE) + struct io_uring_sqe *sqe = io_uring_get_sqe (&fs->io_uring); + ASSERT (sqe != NULL); + submitted += 1; + + // Prepare a read + // printf ("prepared: %lu @ %lu\n", read_size, fs->input_submitted); + io_uring_prep_read_fixed (sqe, 0, fs->buffer + fs->input_submitted, + read_size, fs->input_submitted, + fs->input_submitted/READ_SIZE); + sqe->flags |= IOSQE_FIXED_FILE; + fs->input_submitted += read_size; + io_uring_sqe_set_data64 (sqe, fs->input_submitted); + + if (fs->input_submitted == RING_SIZE*READ_SIZE || + fs->input_submitted == fs->input_size) + break; + if (read_size > fs->input_size - fs->input_submitted) + read_size = fs->input_size - fs->input_submitted; // For last read + else if (read_size < READ_SIZE && fs->input_submitted != read_size) + read_size *= 2; // Ramp-up + } + + // Submit SQEs to the kernel + ret.i = io_uring_submit (&fs->io_uring); + ASSERT_MSG (ret.i == submitted, "io_uring_submit: %s", strerror (-ret.i)); +} + +// void +// file_scanner__reinit (struct file_scanner *fs, int fd) +// { + // union { + // int i; + // void *p; + // } ret; + + // ASSERT (fs); + // ASSERT (fd >= 0); + + // fs->input_fd = fd; // Open with O_DIRECT? + // posix_fadvise (fs->input_fd, 0, 0, POSIX_FADV_SEQUENTIAL); + + // struct stat st; + // ret = fstat (fs->input_fd, &st); + // ASSERT (ret.i != -1); + // fs->input_bytes_to_submit = st.st_size; + + // fs->scanner.begin = fs->buffer; + // fs->scanner.end = fs->buffer; // NOTE(cmmm): Haven't read anything yet + + // // Reset io_uring queues + // memset (&fs->io_uring.sq, 0, sizeof (fs->io_uring.sq)); + // memset (&fs->io_uring.cq, 0, sizeof (fs->io_uring.cq)); + // io_uring_cq_advance (&fs->io_uring, fs->io_uring.cq.ring_tail); + + // // Fill io_uring submission queue + // size_t read_size = 4 << 10; // Start with reading a single page + // size_t bytes_submitted = 0; + // for (int enqueued = 0; enqueued < IO_URING_SIZE; ++enqueued) { + // // Getting a submission queue entry (SQE) + // struct io_uring_sqe *sqe = io_uring_get_sqe (&fs->io_uring); + // ASSERT (sqe != NULL); + + // // Prepare a read + // io_uring_prep_read ( + // sqe, fs->input_fd, fs->buffer + bytes_submitted, read_size, bytes_submitted); + // io_uring_sqe_set_data (sqe, bytes_submitted); + // bytes_submitted += read_size; + // fs->input_bytes_to_submit -= read_size; + // if (fs->input_bytes_to_submit == 0) + // break; + // if (fs->input_bytes_to_submit < read_size) + // read_size = fs->input_bytes_to_submit; // For last read + // else if (read_size < RING_SIZE && bytes_submitted != read_size) + // read_size *= 2; // Ramp-up + // } + + // // Submit SQEs to the kernel + // ret = io_uring_submit (&fs->io_uring); + // ASSERT (ret == 0); +// } + +void +file_scanner__deinit (struct file_scanner *fs) +{ + ASSERT (fs != NULL); + + io_uring_queue_exit (&fs->io_uring); + + munmap (fs->buffer + RING_SIZE*READ_SIZE, RING_SIZE*READ_SIZE); + munmap (fs->buffer, RING_SIZE*READ_SIZE); + + close (fs->memfd); +} + +static void +mark_scanned (struct file_scanner *fs, size_t offset) +{ + if (offset == 0) return; + + ASSERT (fs != NULL); + ASSERT (fs->input_scanned + offset <= fs->input_submitted); + + int buffers_to_read = (fs->input_scanned + offset)/READ_SIZE - + (fs->input_scanned )/READ_SIZE; + + fs->input_scanned += offset; + + // printf ("Reading %d buffers (scanned %lu)\n", buffers_to_read, offset); + if (!buffers_to_read) return; + for (int i = 0; i < buffers_to_read; ++i) { + // Getting a submission queue entry (SQE) + struct io_uring_sqe *sqe = io_uring_get_sqe (&fs->io_uring); + ASSERT (sqe != NULL); + + // Prepare a read + size_t read_size = MIN (READ_SIZE, fs->input_size - fs->input_submitted); + io_uring_prep_read_fixed (sqe, 0, &fs->buffer[fs->input_submitted % + (RING_SIZE*READ_SIZE)], + read_size, fs->input_submitted, + fs->input_submitted/READ_SIZE % RING_SIZE); + sqe->flags |= IOSQE_FIXED_FILE; + fs->input_submitted += read_size; + io_uring_sqe_set_data64 (sqe, fs->input_submitted); + } + + // submit SQEs to the kernel + int ret = io_uring_submit (&fs->io_uring); + ASSERT_MSG (ret == buffers_to_read, "io_uring_submit: %s", strerror (-ret)); +} + +void +wrap_scanner (struct file_scanner *fs) +{ + if (fs->scanner.cursor - fs->buffer < RING_SIZE*READ_SIZE) + return; + + fs->scanner.end = fs->scanner.cursor; + fs->scanner.cursor -= RING_SIZE*READ_SIZE; +} + +void +file_scanner__skip_until (struct file_scanner *fs, char c) +{ + ASSERT (fs != NULL); + + mark_scanned (fs, fs->to_mark_as_scanned); + fs->to_mark_as_scanned = 0; + + do { + wrap_scanner (fs); + const char *begin = fs->scanner.cursor; + scanner__skip_until (&fs->scanner, c); + // printf ("%s %p %p %p\n", __func__, fs->buffer, fs->scanner.cursor, fs->scanner.end); + mark_scanned (fs, fs->scanner.cursor - begin); + } while ( scanner__reached_end (&fs->scanner) && + !file_scanner__reached_end (fs)); +} + +struct string_view +file_scanner__get_until (struct file_scanner *fs, char c) +{ + ASSERT (fs != NULL); + + mark_scanned (fs, fs->to_mark_as_scanned); + fs->to_mark_as_scanned = 0; + wrap_scanner (fs); + + struct string_view sv = { .begin = fs->scanner.cursor }; + do { + scanner__skip_until (&fs->scanner, c); + // printf ("%s %p %p %p\n", __func__, fs->buffer, fs->scanner.cursor, fs->scanner.end); + } while ( scanner__reached_end (&fs->scanner) && + !file_scanner__reached_end (fs)); + + sv.end = fs->scanner.cursor; + fs->to_mark_as_scanned = sv.end - sv.begin; + + return sv; +} + +// TODO(cmmm): Could potentially be used to skip reads, has to be +// implemented differently +void +file_scanner__skip_n (struct file_scanner *fs, size_t n) +{ + ASSERT (fs != NULL); + + mark_scanned (fs, fs->to_mark_as_scanned); + fs->to_mark_as_scanned = 0; + + do { + wrap_scanner (fs); + const char *begin = fs->scanner.cursor; + scanner__skip_n (&fs->scanner, n); + // printf ("%s %p %p %p\n", __func__, fs->buffer, fs->scanner.cursor, fs->scanner.end); + size_t skipped = fs->scanner.cursor - begin; + n -= skipped; + mark_scanned (fs, skipped); + if (n == 0) break; + } while ( scanner__reached_end (&fs->scanner) && + !file_scanner__reached_end (fs)); +} + +bool +file_scanner__reached_end (struct file_scanner *fs) +{ + ASSERT (fs != NULL); + + mark_scanned (fs, fs->to_mark_as_scanned); + + if (!scanner__reached_end (&fs->scanner)) return false; + if (fs->input_scanned == fs->input_size) return true; + + // Wait for completion + struct io_uring_cqe *cqe; + int ret = io_uring_wait_cqe (&fs->io_uring, &cqe); + ASSERT (ret == 0); + ASSERT (cqe->res != -1); + ASSERT (cqe->res != 0); + + int res = cqe->res; + size_t end = io_uring_cqe_get_data64 (cqe); + io_uring_cqe_seen (&fs->io_uring, cqe); + + // printf ("res: %d, end: %lu\n", res, end); + fs->scanner.end = fs->buffer + end % (RING_SIZE*READ_SIZE) + (RING_SIZE*READ_SIZE); + // printf ("%s %p %p %p\n", __func__, fs->buffer, fs->scanner.cursor, fs->scanner.end); + + return false; +} diff --git a/src/file-scanner.h b/src/file-scanner.h new file mode 100644 index 0000000..494bff2 --- /dev/null +++ b/src/file-scanner.h @@ -0,0 +1,42 @@ +#ifndef INCLUDED_FILE_SCANNER_H +#define INCLUDED_FILE_SCANNER_H + +#include + +#include "scanner.h" + +#define READ_SIZE (128 << 10) +#define RING_SIZE 4 +#define IO_URING_SIZE 16 // 4K 4K 8K 16K 32K 64K 128K 128K 128K + +struct file_scanner { + struct scanner scanner; + size_t to_mark_as_scanned; + size_t input_size; + size_t input_submitted; + size_t input_scanned; + int input_fd; + int memfd; + enum file_scanner__state { + FILE_SCANNER__STATE__NO_END, + FILE_SCANNER__STATE__READ_END, + FILE_SCANNER__STATE__REACHED_END, + } state; + struct io_uring io_uring; + char *buffer; +}; + +void file_scanner__init (struct file_scanner *, int fd); +void file_scanner__deinit (struct file_scanner *); +bool file_scanner__reached_end (struct file_scanner *); +void file_scanner__skip_until (struct file_scanner *, char); +void file_scanner__skip_over (struct file_scanner *, char); +void file_scanner__skip_until_one_of (struct file_scanner *, char *); +void file_scanner__skip_n (struct file_scanner *, size_t); +struct string_view file_scanner__get_until (struct file_scanner *, char); +struct string_view file_scanner__get_until_one_of (struct file_scanner *, char *); +struct string_view file_scanner__get_n (struct file_scanner *, size_t); +uint64_t file_scanner__get_uint64 (struct file_scanner *); +int64_t file_scanner__get_int64 (struct file_scanner *); + +#endif // INCLUDED_FILE_SCANNER_H diff --git a/src/multi-threaded.c b/src/multi-threaded.c new file mode 100644 index 0000000..ecdda68 --- /dev/null +++ b/src/multi-threaded.c @@ -0,0 +1,339 @@ +// multi-threaded.c +#include +#include +#include +#include +#include +#include +#include +#include + +#include "string-view.h" +#include "scanner.h" +#include "utils.h" +#include "card.h" +#include "user.h" +#include "transaction.h" +#include "transaction-heap.h" +#include "stb_ds.h" + +unsigned int hash (register const char *str, register size_t len); +extern const char *wordlist[]; + +int max_threads; + +void +read_filtered_cards_and_users (const char *filename, + struct card **cards, struct user **users) +{ + MEASURE_SCOPE (); + + ASSERT (filename); + ASSERT (cards); + ASSERT (users); + + int fd = open (filename, O_RDONLY); + ASSERT_MSG (fd != -1, "open %s: %s", filename, strerror (errno)); + struct string_view sv = mmap_whole (fd); + + struct scanner sc; + scanner__init (&sc, sv); + + // skip header: id, client_id, card_brand, card_type, card_number, + // expires, cvv, has_chip, num_cards_issued, credit_limit, + // acct_open_date, year_pin_last_changed, card_on_dark_web + scanner__skip_over (&sc, '\n'); + while (!scanner__reached_end (&sc)) { + struct card card; + struct user user; + + card.id = scanner__get_uint64 (&sc); + + scanner__skip_n (&sc, 1); + + user.id = scanner__get_uint64 (&sc); + + scanner__skip_over (&sc, '$'); + + uint64_t credit_limit = scanner__get_uint64 (&sc); + scanner__skip_over (&sc, '\n'); + + if (credit_limit < 12000) + continue; + + hmputs (*cards, card); + + if (hmgetp_null (*users, user.key) == NULL) + hmputs (*users, user); + } + + munmap ((char *) sv.begin, sv.end - sv.begin); + close (fd); +} + +void +read_user_per_capita_incomes (const char *filename, struct user *users) +{ + MEASURE_SCOPE (); + + ASSERT (filename); + ASSERT (users); + + int fd = open (filename, O_RDONLY); + ASSERT_MSG (fd != -1, "open %s: %s", filename, strerror (errno)); + struct string_view sv = mmap_whole (fd); + + struct scanner sc; + scanner__init (&sc, sv); + + // skip header: id, current_age, retirement_age, birth_year, + // birth_month, gender, address, latitude, longitude, + // per_capita_income, yearly_income, total_debt, credit_score, + // num_credit_cards + scanner__skip_over (&sc, '\n'); + + while (!scanner__reached_end (&sc)) { + client_id_t id = scanner__get_uint64 (&sc); + struct user *user = hmgetp_null (users, id); + if (user == NULL) { + scanner__skip_over (&sc, '\n'); + continue; + } + + scanner__skip_over (&sc, '$'); + + user->normalizer = .12/scanner__get_uint64 (&sc); + + scanner__skip_over (&sc, '\n'); + } + + munmap ((char *) sv.begin, sv.end - sv.begin); + close (fd); +} + +void +scanner__skip_current_month (struct scanner *sc) +{ + scanner__skip_over (sc, '\n'); + + uint16_t current_year_month; + scanner__skip_over (sc, ','); + current_year_month = scanner__get_uint64 (sc) << 4; scanner__skip_n (sc, 1); + current_year_month |= scanner__get_uint64 (sc); + + const char *line; + uint16_t year_month; + do { + scanner__skip_over (sc, '\n'); + line = sc->cursor; + scanner__skip_over (sc, ','); + year_month = scanner__get_uint64 (sc) << 4; scanner__skip_n (sc, 1); + year_month |= scanner__get_uint64 (sc); + } while (year_month == current_year_month); + + sc->cursor = line; +} + +void +split_transaction_scanner (struct scanner *sc, int block, int blocks) +{ + struct scanner tmp = *sc; + + size_t bytes_total = tmp.end - tmp.cursor; + size_t bytes_per_block = bytes_total/blocks; + + if (block > 0) { + sc->cursor += block*bytes_per_block; + scanner__skip_current_month (sc); + } else { + // skip header: id, date, client_id, card_id, amount, use_chip, + // merchant_id, merchant_city, merchant_state, zip, mcc, errors + scanner__skip_over (sc, '\n'); + } + + if (block < blocks - 1) { + tmp.cursor += (block + 1)*bytes_per_block; + scanner__skip_current_month (&tmp); + sc->end = tmp.cursor; + } +} + +void +scan_filtered_and_reduced_transactions (struct scanner *sc, + struct transaction **transactions, + struct card *cards) +{ + while (!scanner__reached_end (sc)) { + union transaction_key transaction_key; + + scanner__skip_over (sc, ','); + + transaction_key.year_month = scanner__get_uint64 (sc) << 4; + scanner__skip_n (sc, 1); + transaction_key.year_month |= scanner__get_uint64 (sc); + + scanner__skip_over (sc, ','); + + transaction_key.client_id = scanner__get_uint64 (sc); + + scanner__skip_n (sc, 1); + + card_id_t card_id = scanner__get_uint64 (sc); + if (hmgetp_null (cards, card_id) == NULL) { + scanner__skip_over (sc, '\n'); + continue; + } + + scanner__skip_n (sc, 2); + + int64_t amount = 100*scanner__get_int64 (sc); + scanner__skip_n (sc, 1); + int sign = amount >= 0 ? 1 : -1; + amount += sign*scanner__get_uint64 (sc); + + scanner__skip_n (sc, 1); + scanner__skip_over (sc, ','); + scanner__skip_over (sc, ','); + + struct string_view sv = scanner__get_until (sc, ','); + transaction_key.merchant_city_id = hash (sv.begin, STRING_VIEW__LENGTH (sv)); + + scanner__skip_over (sc, '\n'); + + struct transaction *transaction = + hmgetp_null (*transactions, transaction_key); + if (transaction == NULL) + hmput (*transactions, transaction_key, amount); + else transaction->sum += amount; + } +} + +void +read_filtered_and_reduced_transactions (const char *filename, + struct transaction **transactions, + struct card *cards) +{ + MEASURE_SCOPE (); + + ASSERT (filename); + ASSERT (transactions); + ASSERT (cards); + + int fd = open (filename, O_RDONLY); + ASSERT_MSG (fd != -1, "open %s: %s", filename, strerror (errno)); + struct string_view sv = mmap_whole (fd); + +#pragma omp parallel + { + int tid = omp_get_thread_num (); + struct scanner sc; + scanner__init (&sc, sv); + split_transaction_scanner (&sc, tid, max_threads); + scan_filtered_and_reduced_transactions (&sc, &transactions[tid], cards); + } + + munmap ((char *) sv.begin, sv.end - sv.begin); + close (fd); +} + +void +normalize_transaction_sums (struct transaction **transactions, + struct user *users) +{ + MEASURE_SCOPE (); + + ASSERT (transactions); + ASSERT (users); + +#pragma omp parallel + { + int tid = omp_get_thread_num (); + ptrdiff_t tempvar; + for (size_t i = 0; i < hmlenu (transactions[tid]); ++i) { + struct transaction *transaction = &transactions[tid][i]; + float normalizer = hmgetp_ts (users, transaction->key.client_id, tempvar)->normalizer; + transaction->normalized = transaction->sum*normalizer; + } + } +} + +int +compare_transactions (const void *lhs, const void *rhs) +{ + const struct transaction *lhs_transaction = lhs; + const struct transaction *rhs_transaction = rhs; + + float lhs_normalized = lhs_transaction->normalized; + float rhs_normalized = rhs_transaction->normalized; + + return (lhs_normalized < rhs_normalized) - (lhs_normalized > rhs_normalized); +} + +void +extract_top_normalized_transaction_sums (struct transaction **transactions, + struct transaction_heap *heap) +{ + MEASURE_SCOPE (); + + ASSERT (transactions); + ASSERT (heap); + + for (int i = 0; i < max_threads; ++i) { + for (size_t j = 0; j < hmlenu (transactions[i]); ++j) + transaction_heap__push (heap, transactions[i][j]); + } + + qsort (heap->array, heap->count, sizeof (*heap->array), compare_transactions); +} + +void +print_top_transactions (struct transaction_heap *heap) +{ + MEASURE_SCOPE (); + + printf (" i client_id normalized_spending year_month city\n"); + for (int i = 0; i < heap->count; ++i) { + printf ("%2d %4hu %6.2f %hu-%02hu %s\n", i, + heap->array[i].key.client_id, + heap->array[i].normalized, + heap->array[i].key.year_month >> 4, + heap->array[i].key.year_month & ((1 << 4) - 1), + wordlist[heap->array[i].key.merchant_city_id]); + } +} + +size_t +get_transaction_count (struct transaction **transactions) +{ + size_t count = 0; + + for (int i = 0; i < max_threads; ++i) + count += hmlenu (transactions[i]); + + return count; +} + +int +main (void) +{ + MEASURE_SCOPE (); + + max_threads = omp_get_max_threads (); + + struct card *cards = NULL; + struct user *users = NULL; + struct transaction **transactions = calloc (max_threads, sizeof (*transactions)); + struct transaction_heap top_transactions = {0}; + + read_filtered_cards_and_users ("res/cards_data.csv", &cards, &users); + read_filtered_and_reduced_transactions ("res/transactions_data.csv", + transactions, cards); + read_user_per_capita_incomes ("res/users_data.csv", users); + normalize_transaction_sums (transactions, users); + extract_top_normalized_transaction_sums (transactions, &top_transactions); + printf ("Top %d out of %lu:\n", top_transactions.count, get_transaction_count (transactions)); + print_top_transactions (&top_transactions); + + return EXIT_SUCCESS; +} +// multi-threaded.c ends here diff --git a/src/partition.c b/src/partition.c new file mode 100644 index 0000000..529f1ac --- /dev/null +++ b/src/partition.c @@ -0,0 +1,134 @@ +#include +#include + +#define RATIO (66/33.) + +struct sizes { + size_t cpu; + size_t gpu; + size_t tail; +}; + +struct partition { + size_t offset; + size_t size; +}; + +struct sizes +get_sizes (size_t size, int node_count__cpu, int node_count__gpu, int thread_count) +{ + int thread_count__cpu = thread_count*node_count__cpu + (thread_count - 1)*node_count__gpu; + int thread_count__gpu = node_count__gpu; + + double weight__cpu = thread_count__cpu*RATIO; + double weight__gpu = thread_count__gpu; + + double ratio__cpu = weight__cpu/(weight__cpu + weight__gpu); + + struct sizes sizes; + + size_t size__cpus = size * ratio__cpu; + size_t size__gpus = size - size__cpus; + sizes.cpu = (thread_count__cpu > 0) ? size__cpus/thread_count__cpu : 0; + sizes.gpu = (thread_count__gpu > 0) ? size__gpus/thread_count__gpu : 0; + sizes.tail = size - (thread_count__cpu*sizes.cpu + thread_count__gpu*sizes.gpu); + + return sizes; +} + +struct partition +partition_node (struct sizes sizes, int node_count__cpu, int node_count__gpu, + int thread_count, int node_rank) +{ + struct partition partition; + + if (node_rank < node_count__cpu) { // CPU NODE + partition.size = thread_count*sizes.cpu; + partition.offset = node_rank*partition.size; + } else { // GPU NODE + partition.size = (thread_count - 1)*sizes.cpu + sizes.gpu; + partition.offset = node_count__cpu*thread_count*sizes.cpu + (node_rank - node_count__cpu)*partition.size; + } + + if (node_rank + 1 == node_count__cpu + node_count__gpu) + partition.size += sizes.tail; + + return partition; +} + +struct partition +partition_thread (struct partition partition, struct sizes sizes, bool cpu, bool tail, + int thread_count, int thread) +{ + if (cpu) { + partition.size = sizes.cpu; + partition.offset += thread*partition.size; + } else { + if (thread == 0) { + partition.size = sizes.gpu; + } else { + partition.size = sizes.cpu; + partition.offset += sizes.gpu + (thread - 1)*partition.size; + } + } + + if (tail) + partition.size += sizes.tail; + + return partition; +} + +void +test (size_t size, int node_count__cpu, int node_count__gpu, int thread_count) +{ + printf ("%lu %d %d %d\n", size, node_count__cpu, node_count__gpu, thread_count); + + int node_count = node_count__cpu + node_count__gpu; + for (int n = 0; n < node_count; ++n) { + struct sizes sizes = get_sizes (size, node_count__cpu, node_count__gpu, thread_count); + struct partition pn = partition_node (sizes, node_count__cpu, node_count__gpu, thread_count, n); + printf ("[%d/%d] %10lu %10lu %10lu\n", n + 1, node_count, + pn.offset, pn.offset + pn.size, pn.size); + for (int t = 0; t < thread_count; ++t) { + struct partition pt = partition_thread (pn, sizes, n < node_count__cpu, + n + 1 == node_count__cpu + node_count__gpu && + t + 1 == thread_count, thread_count, t); + printf ("[%d/%d] [%d/%d] %10lu %10lu %10lu\n", n + 1, node_count, t + 1, thread_count, + pt.offset, pt.offset + pt.size, pt.size); + } + } +} + +int +main (int argc, char *argv[]) +{ + test (1024, 2, 0, 4); putchar ('\n'); + test (1024, 0, 2, 4); putchar ('\n'); + + test (1024, 1, 1, 1); putchar ('\n'); + test (1024, 1, 1, 2); putchar ('\n'); + test (1024, 1, 1, 8); putchar ('\n'); + + test (1024, 2, 2, 1); putchar ('\n'); + test (1024, 2, 2, 2); putchar ('\n'); + test (1024, 2, 2, 3); putchar ('\n'); + test (1024, 2, 2, 8); putchar ('\n'); + + test (1024, 4, 1, 8); putchar ('\n'); + test (1024, 1, 4, 8); putchar ('\n'); + + test (1000, 2, 2, 3); putchar ('\n'); + test (1000, 3, 1, 4); putchar ('\n'); + test (1000, 1, 3, 4); putchar ('\n'); + + test (7, 2, 2, 4); putchar ('\n'); + test (3, 2, 2, 4); putchar ('\n'); + test (1, 2, 2, 4); putchar ('\n'); + + test (0, 2, 2, 4); putchar ('\n'); + + test (1ULL<<20, 2, 2, 2); putchar ('\n'); + test (1ULL<<32, 2, 2, 4); putchar ('\n'); + + return EXIT_SUCCESS; +} diff --git a/src/sandbox.c b/src/sandbox.c new file mode 100644 index 0000000..957d318 --- /dev/null +++ b/src/sandbox.c @@ -0,0 +1,55 @@ +#include +#include +#include +#include +#include + +#include "utils.h" +#include "file-scanner.h" + +int +main (void) +{ + // const char *filename = "./res/users_data.csv"; + const char *filename = "./res/transactions_data.csv"; + int fd = open (filename, O_RDONLY); + + if (0) { + MEASURE_SCOPE ("mmap"); + struct string_view sv = mmap_whole (fd); + struct scanner sc; + scanner__init (&sc, sv); + while (!scanner__reached_end (&sc)) { + static size_t i = 0; + struct string_view sv = scanner__get_until (&sc, '\n'); + sc.cursor += 1; + // if (i > 13300000) + // printf ("%s:%lu: " STRING_VIEW__FMT "\n", filename, ++i, STRING_VIEW__FMTA (sv)); + i += 1; + if (i > 13300000) break; + } + munmap (&sv.begin, STRING_VIEW__LENGTH (sv)); + } + + if (1) { + MEASURE_SCOPE ("io_uring"); + struct file_scanner fs; + file_scanner__init (&fs, fd); + while (!file_scanner__reached_end (&fs)) { + static size_t i = 0; + struct string_view sv = file_scanner__get_until (&fs, '\n'); + file_scanner__skip_n (&fs, 1); + // if (i > 13300000) + // printf ("%s:%lu: %lX/%lX/%lX " STRING_VIEW__FMT "\n", filename, i, + // fs.input_scanned, fs.input_submitted, fs.input_size, + // STRING_VIEW__FMTA (sv)); + i += 1; + if (i > 13300000) break; + } + file_scanner__deinit (&fs); + } + + close (fd); + + return EXIT_SUCCESS; +} diff --git a/src/scanner.c b/src/scanner.c new file mode 100644 index 0000000..8326eee --- /dev/null +++ b/src/scanner.c @@ -0,0 +1,137 @@ +// scanner.c +#include +#include + +#include "utils.h" +#include "scanner.h" + +void +scanner__init (struct scanner *self, struct string_view sv) +{ + ASSERT (sv.begin <= sv.end); + + self->cursor = sv.begin; + self->end = sv.end; +} + +void +mmap_wholescanner__skip_until (struct scanner *self, char c) +{ + ASSERT (self->cursor <= self->end); + + char *p = memchr (self->cursor, c, self->end - self->cursor); + self->cursor = p ? p : self->end; +} + +void +scanner__skip_over (struct scanner *self, char c) +{ + scanner__skip_until (self, c); + if (!scanner__reached_end (self)) + self->cursor += 1; +} + +struct string_view +scanner__get_until (struct scanner *self, char c) +{ + ASSERT (self->cursor <= self->end); + + struct string_view sv; + + sv.begin = self->cursor; + scanner__skip_until (self, c); + sv.end = self->cursor; + + return sv; +} + +void +scanner__skip_until_one_of (struct scanner *self, char *str) +{ + ASSERT (self->cursor <= self->end); + + while (self->cursor != self->end && strchr (str, *self->cursor) == NULL) + self->cursor += 1; +} + +struct string_view +scanner__get_until_one_of (struct scanner *self, char *str) +{ + ASSERT (self->cursor <= self->end); + + struct string_view sv; + + sv.begin = self->cursor; + scanner__skip_until_one_of (self, str); + sv.end = self->cursor; + + return sv; +} + +void +scanner__skip_n (struct scanner *self, size_t n) +{ + ASSERT (self->cursor <= self->end); + + self->cursor += n; + if (self->cursor > self->end) + self->cursor = self->end; +} + +struct string_view +scanner__get_n (struct scanner *self, size_t n) +{ + ASSERT (self->cursor <= self->end); + + struct string_view sv; + + sv.begin = self->cursor; + scanner__skip_n (self, n); + sv.end = self->cursor; + + return sv; +} + +uint64_t +scanner__get_uint64 (struct scanner *self) +{ + ASSERT (self->cursor <= self->end); + + uint64_t val = 0; + while ((unsigned) *self->cursor - '0' < 10) { + val *= 10; + val += *self->cursor - '0'; + self->cursor += 1; + ASSERT (self->cursor < self->end); + } + + ASSERT (self->cursor <= self->end); + + return val; +} + +int64_t +scanner__get_int64 (struct scanner *self) +{ + ASSERT (self->cursor <= self->end); + + int64_t negative = 1; + if (*self->cursor == '-') { + negative = -1; + self->cursor += 1; + } + int64_t val = scanner__get_uint64 (self); + + ASSERT (self->cursor <= self->end); + + return negative*val; +} + +bool +scanner__reached_end (struct scanner *self) +{ + ASSERT (self->cursor <= self->end); + + return self->cursor == self->end; +} +// scanner.c ends here diff --git a/src/scanner.h b/src/scanner.h new file mode 100644 index 0000000..22c2c41 --- /dev/null +++ b/src/scanner.h @@ -0,0 +1,29 @@ +// scanner.h +#ifndef INCLUDED_SCANNER_H +#define INCLUDED_SCANNER_H + +#include +#include +#include + +#include "string-view.h" + +struct scanner { + const char *cursor; + const char *end; +}; + +void scanner__init (struct scanner *, struct string_view); +void scanner__skip_until (struct scanner *, char); +void scanner__skip_over (struct scanner *, char); +void scanner__skip_until_one_of (struct scanner *, char *); +void scanner__skip_n (struct scanner *, size_t); +struct string_view scanner__get_until (struct scanner *, char); +struct string_view scanner__get_until_one_of (struct scanner *, char *); +struct string_view scanner__get_n (struct scanner *, size_t); +uint64_t scanner__get_uint64 (struct scanner *); +int64_t scanner__get_int64 (struct scanner *); +bool scanner__reached_end (struct scanner *); + +#endif // INCLUDED_SCANNER_H +// scanner.h ends here diff --git a/src/single-threaded.c b/src/single-threaded.c new file mode 100644 index 0000000..6f2b159 --- /dev/null +++ b/src/single-threaded.c @@ -0,0 +1,262 @@ +// single-threaded.c +#include +#include +#include +#include +#include +#include +#include + +#include "string-view.h" +#include "scanner.h" +#include "utils.h" +#include "card.h" +#include "user.h" +#include "transaction.h" +#include "transaction-heap.h" +#include "stb_ds.h" + +unsigned int hash (register const char *str, register size_t len); +extern const char *wordlist[]; + +void +read_filtered_cards_and_users (const char *filename, + struct card **cards, struct user **users) +{ + MEASURE_SCOPE (); + + ASSERT (filename); + ASSERT (cards); + ASSERT (users); + + int fd = open (filename, O_RDONLY); + ASSERT_MSG (fd != -1, "open %s: %s", filename, strerror (errno)); + struct string_view sv = mmap_whole (fd); + + struct scanner sc; + scanner__init (&sc, sv); + + // skip header: id, client_id, card_brand, card_type, card_number, + // expires, cvv, has_chip, num_cards_issued, credit_limit, + // acct_open_date, year_pin_last_changed, card_on_dark_web + scanner__skip_over (&sc, '\n'); + while (!scanner__reached_end (&sc)) { + struct card card; + struct user user; + + card.id = scanner__get_uint64 (&sc); + + scanner__skip_n (&sc, 1); + + user.id = scanner__get_uint64 (&sc); + + scanner__skip_over (&sc, '$'); + + uint64_t credit_limit = scanner__get_uint64 (&sc); + scanner__skip_over (&sc, '\n'); + + if (credit_limit < 12000) + continue; + + hmputs (*cards, card); + + if (hmgetp_null (*users, user.key) == NULL) + hmputs (*users, user); + } + + munmap ((char *) sv.begin, sv.end - sv.begin); + close (fd); +} + +void +read_user_per_capita_incomes (const char *filename, struct user *users) +{ + MEASURE_SCOPE (); + + ASSERT (filename); + ASSERT (users); + + int fd = open (filename, O_RDONLY); + ASSERT_MSG (fd != -1, "open %s: %s", filename, strerror (errno)); + struct string_view sv = mmap_whole (fd); + + struct scanner sc; + scanner__init (&sc, sv); + + // skip header: id, current_age, retirement_age, birth_year, + // birth_month, gender, address, latitude, longitude, + // per_capita_income, yearly_income, total_debt, credit_score, + // num_credit_cards + scanner__skip_over (&sc, '\n'); + + while (!scanner__reached_end (&sc)) { + client_id_t id = scanner__get_uint64 (&sc); + struct user *user = hmgetp_null (users, id); + if (user == NULL) { + scanner__skip_over (&sc, '\n'); + continue; + } + + scanner__skip_over (&sc, '$'); + + user->normalizer = 0.12/scanner__get_uint64 (&sc); + + scanner__skip_over (&sc, '\n'); + } + + munmap ((char *) sv.begin, sv.end - sv.begin); + close (fd); +} + +void +read_filtered_and_reduced_transactions (const char *filename, + struct transaction **transactions, + struct card *cards) +{ + MEASURE_SCOPE (); + + ASSERT (filename); + ASSERT (transactions); + ASSERT (cards); + + int fd = open (filename, O_RDONLY); + ASSERT_MSG (fd != -1, "open %s: %s", filename, strerror (errno)); + struct string_view sv = mmap_whole (fd); + + struct scanner sc; + scanner__init (&sc, sv); + + // skip header: id, date, client_id, card_id, amount, use_chip, + // merchant_id, merchant_city, merchant_state, zip, mcc, errors + scanner__skip_over (&sc, '\n'); + while (!scanner__reached_end (&sc)) { + union transaction_key transaction_key; + + scanner__skip_over (&sc, ','); + + transaction_key.year_month = scanner__get_uint64 (&sc) << 4; + scanner__skip_n (&sc, 1); + transaction_key.year_month |= scanner__get_uint64 (&sc); + + scanner__skip_over (&sc, ','); + + transaction_key.client_id = scanner__get_uint64 (&sc); + + scanner__skip_n (&sc, 1); + + card_id_t card_id = scanner__get_uint64 (&sc); + if (hmgetp_null (cards, card_id) == NULL) { + scanner__skip_over (&sc, '\n'); + continue; + } + + scanner__skip_n (&sc, 2); + + int64_t amount = 100*scanner__get_int64 (&sc); + scanner__skip_n (&sc, 1); + int sign = amount >= 0 ? 1 : -1; + amount += sign*scanner__get_uint64 (&sc); + + scanner__skip_n (&sc, 1); + scanner__skip_over (&sc, ','); + scanner__skip_over (&sc, ','); + + struct string_view sv = scanner__get_until (&sc, ','); + transaction_key.merchant_city_id = hash (sv.begin, STRING_VIEW__LENGTH (sv)); + + scanner__skip_over (&sc, '\n'); + + struct transaction *transaction = hmgetp_null (*transactions, + transaction_key); + if (transaction == NULL) + hmput (*transactions, transaction_key, amount); + else transaction->sum += amount; + } + + munmap ((char *) sv.begin, sv.end - sv.begin); + close (fd); +} + +void +normalize_transaction_sums (struct transaction *transactions, + struct user *users, size_t count) +{ + MEASURE_SCOPE ("%lu transactions", count); + + ASSERT (transactions); + ASSERT (users); + + for (size_t i = 0; i < count; ++i) { + struct transaction *transaction = &transactions[i]; + float normalizer = hmgets (users, transaction->key.client_id).normalizer; + transaction->normalized = transaction->sum*normalizer; + } +} + +int +compare_transactions (const void *lhs, const void *rhs) +{ + const struct transaction *lhs_transaction = lhs; + const struct transaction *rhs_transaction = rhs; + + float lhs_normalized = lhs_transaction->normalized; + float rhs_normalized = rhs_transaction->normalized; + + return (lhs_normalized < rhs_normalized) - (lhs_normalized > rhs_normalized); +} + +void +extract_top_normalized_transaction_sums (struct transaction *transactions, + size_t count, struct transaction_heap *heap) +{ + MEASURE_SCOPE ("(~10x faster then full sort)"); + + ASSERT (transactions); + ASSERT (heap); + + for (size_t i = 0; i < count; ++i) + transaction_heap__push (heap, transactions[i]); + + qsort (heap->array, heap->count, sizeof (*heap->array), compare_transactions); +} + +void +print_top_transactions (struct transaction_heap *heap) +{ + MEASURE_SCOPE (); + + printf (" i client_id normalized_spending year_month city\n"); + for (int i = 0; i < heap->count; ++i) { + printf ("%2d %4hu %6.2f %hu-%02hu %s\n", i, + heap->array[i].key.client_id, + heap->array[i].normalized, + heap->array[i].key.year_month >> 4, + heap->array[i].key.year_month & ((1 << 4) - 1), + wordlist[heap->array[i].key.merchant_city_id]); + } +} + +int +main (void) +{ + MEASURE_SCOPE (); + + struct card *cards = NULL; + struct user *users = NULL; + struct transaction *transactions = NULL; + struct transaction_heap top_transactions = {0}; + + read_filtered_cards_and_users ("res/cards_data.csv", &cards, &users); + read_filtered_and_reduced_transactions ("res/transactions_data.csv", + &transactions, cards); + size_t transaction_count = hmlenu (transactions); + read_user_per_capita_incomes ("res/users_data.csv", users); + normalize_transaction_sums (transactions, users, transaction_count); + extract_top_normalized_transaction_sums (transactions, transaction_count, + &top_transactions); + printf ("Top %d out of %lu:\n", top_transactions.count, transaction_count); + print_top_transactions (&top_transactions); + + return EXIT_SUCCESS; +} +// single-threaded.c ends here diff --git a/src/string-view.h b/src/string-view.h new file mode 100644 index 0000000..3ebebc0 --- /dev/null +++ b/src/string-view.h @@ -0,0 +1,16 @@ +// string-view.h +#ifndef INCLUDED_STRING_VIEW_H +#define INCLUDED_STRING_VIEW_H + +#define STRING_VIEW__LENGTH(SV) ((SV).end - (SV).begin) + +#define STRING_VIEW__FMT "%.*s" +#define STRING_VIEW__FMTA(SV) (int) STRING_VIEW__LENGTH (SV), (SV).begin + +struct string_view { + const char *begin; + const char *end; +}; + +#endif // INCLUDED_STRING_VIEW_H +// string-view.h ends here diff --git a/src/super-computer.c b/src/super-computer.c new file mode 100644 index 0000000..78453b6 --- /dev/null +++ b/src/super-computer.c @@ -0,0 +1,672 @@ +// super-computer.c +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "utils.h" +#include "string-view.h" +#include "scanner.h" +#include "stb_ds.h" +#include "card.h" +#include "user.h" +#include "transaction.h" +#include "transaction-heap.h" + +#define RATIO__CPU_GPU (70/30.) + +unsigned int hash (register const char *str, register size_t len); +extern const char *wordlist[]; +const char *mpi_strerror (int errorcode) +{ + static char string[MPI_MAX_ERROR_STRING]; + MPI_Error_string (errorcode, string, NULL); + return string; +} + +void +die (const char *fmt, ...) +{ + va_list ap; + + va_start (ap, fmt); + vfprintf (stderr, fmt, ap); + va_end (ap); + + exit (EXIT_FAILURE); +} + +#define DIE(FMT, ...) \ + die (__FILE__ ":" TO_STRING (__LINE__) ": %s: die: " FMT, \ + __func__ __VA_OPT__ (,) __VA_ARGS__) + +int node_count__cpu; +int node_count__gpu; +int world_size; +int world_rank; +char processor_name[MPI_MAX_PROCESSOR_NAME]; +int name_len; +int max_threads; +bool has_gpu; + +void +mpi_init (int *argc, char ***argv) +{ + int err = MPI_Init (argc, argv); + if (err) DIE ("MPI_Init: %s", mpi_strerror (err)); +} + +int +mpi_world_size (void) +{ + int world_size; + int err = MPI_Comm_size (MPI_COMM_WORLD, &world_size); + if (err) DIE ("MPI_Comm_size: %s", mpi_strerror (err)); + return world_size; +} + +int +mpi_world_rank (void) +{ + int world_rank; + int err = MPI_Comm_rank (MPI_COMM_WORLD, &world_rank); + if (err) DIE ("MPI_Comm_rank: %s", mpi_strerror (err)); + return world_rank; +} + +void +mpi_get_processor_name (char processor_name[MPI_MAX_PROCESSOR_NAME], + int *name_len) +{ + int err = MPI_Get_processor_name (processor_name, name_len); + if (err) DIE ("MPI_Get_processor_name: %s", mpi_strerror (err)); +} + +void +mpi_send (const void *buf, int count, MPI_Datatype datatype, int dest) +{ + int err = MPI_Send (buf, count, datatype, dest, 0, MPI_COMM_WORLD); + if (err) DIE ("MPI_Send: %s", mpi_strerror (err)); +} + +void +mpi_recv (void *buf, int count, MPI_Datatype datatype, int source) +{ + int err = MPI_Recv (buf, count, datatype, source, 0, + MPI_COMM_WORLD, MPI_STATUS_IGNORE); + if (err) DIE ("MPI_Recv: %s", mpi_strerror (err)); +} + +void +mpi_finalize (void) +{ + int err = MPI_Finalize (); + if (err) DIE ("MPI_Finalize: %s", mpi_strerror (err)); +} + +void +send_top (struct transaction_heap *top, int dest) +{ + mpi_send (&top->count, 1, MPI_UINT8_T, dest); + mpi_send (top->array, 2*top->count, MPI_UINT64_T, dest); +} + +void +recv_top (struct transaction_heap *top, int source) +{ + struct transaction_heap other; + + mpi_recv (&other.count, 1, MPI_UINT8_T, source); + mpi_recv (other.array, 2*other.count, MPI_UINT64_T, source); + + for (int i = 0; i < other.count; ++i) + transaction_heap__push (top, other.array[i]); +} + +void +process_cards (const char *filename, struct card **cards, struct user **users) +{ + MEASURE_SCOPE ("[%d/%d]", world_rank + 1, world_size); + + ASSERT (filename); + ASSERT (cards); + ASSERT (users); + + int fd = open (filename, O_RDONLY); + ASSERT_MSG (fd != -1, "open %s: %s", filename, strerror (errno)); + struct string_view sv = mmap_whole (fd); + + struct scanner sc; + scanner__init (&sc, sv); + + // skip header: id, client_id, card_brand, card_type, card_number, + // expires, cvv, has_chip, num_cards_issued, credit_limit, + // acct_open_date, year_pin_last_changed, card_on_dark_web + scanner__skip_over (&sc, '\n'); + while (!scanner__reached_end (&sc)) { + struct card card; + struct user user; + + card.id = scanner__get_uint64 (&sc); + + scanner__skip_n (&sc, 1); + + user.id = scanner__get_uint64 (&sc); + + scanner__skip_over (&sc, '$'); + + uint64_t credit_limit = scanner__get_uint64 (&sc); + scanner__skip_over (&sc, '\n'); + + if (credit_limit < 12000) + continue; + + hmputs (*cards, card); + + if (hmgetp_null (*users, user.key) == NULL) + hmputs (*users, user); + } + + munmap ((char *) sv.begin, sv.end - sv.begin); + close (fd); +} + +void +process_users (const char *filename, struct user *users) +{ + MEASURE_SCOPE ("[%d/%d]", world_rank + 1, world_size); + + ASSERT (filename); + ASSERT (users); + + int fd = open (filename, O_RDONLY); + ASSERT_MSG (fd != -1, "open %s: %s", filename, strerror (errno)); + struct string_view sv = mmap_whole (fd); + + struct scanner sc; + scanner__init (&sc, sv); + + // skip header: id, current_age, retirement_age, birth_year, + // birth_month, gender, address, latitude, longitude, + // per_capita_income, yearly_income, total_debt, credit_score, + // num_credit_cards + scanner__skip_over (&sc, '\n'); + + while (!scanner__reached_end (&sc)) { + client_id_t id = scanner__get_uint64 (&sc); + struct user *user = hmgetp_null (users, id); + if (user == NULL) { + scanner__skip_over (&sc, '\n'); + continue; + } + + scanner__skip_over (&sc, '$'); + + user->normalizer = 0.12/scanner__get_uint64 (&sc); // 12 months, cents->dollars + scanner__skip_over (&sc, '\n'); + } + + munmap ((char *) sv.begin, sv.end - sv.begin); + close (fd); +} + +void +scanner__skip_current_month (struct scanner *sc) +{ + scanner__skip_over (sc, '\n'); + if (sc->cursor == sc->end) return; + + uint16_t current_year_month; + scanner__skip_over (sc, ','); + current_year_month = scanner__get_uint64 (sc) << 4; scanner__skip_n (sc, 1); + current_year_month |= scanner__get_uint64 (sc); + + const char *line; + uint16_t year_month; + do { + scanner__skip_over (sc, '\n'); + line = sc->cursor; + scanner__skip_over (sc, ','); + year_month = scanner__get_uint64 (sc) << 4; scanner__skip_n (sc, 1); + year_month |= scanner__get_uint64 (sc); + } while (year_month == current_year_month); + + sc->cursor = line; +} + +void +split_transaction_scanner (struct scanner *sc, int block, int blocks) +{ + struct scanner tmp = *sc; + + size_t bytes_total = tmp.end - tmp.cursor; + size_t bytes_per_block = bytes_total/blocks; + + if (block > 0) { + sc->cursor += block*bytes_per_block; + scanner__skip_current_month (sc); + } else { + // skip header: id, date, client_id, card_id, amount, use_chip, + // merchant_id, merchant_city, merchant_state, zip, mcc, errors + scanner__skip_over (sc, '\n'); + } + + if (block < blocks - 1) { + tmp.cursor += (block + 1)*bytes_per_block; + scanner__skip_current_month (&tmp); + sc->end = tmp.cursor; + } +} + +void +process_transactions__cpu (struct scanner *sc, + struct transaction_heap *top_transactions, + struct card *cards, struct user *users) +{ + MEASURE_SCOPE ("[%d/%d]", world_rank + 1, world_size); + + ASSERT (sc != NULL); + ASSERT (top_transactions != NULL); + ASSERT (cards != NULL); + ASSERT (users != NULL); + + struct transaction *transactions = NULL; + + // Parse, aggregate, reduce + while (!scanner__reached_end (sc)) { + union transaction_key key; + + scanner__skip_over (sc, ','); + + key.year_month = scanner__get_uint64 (sc) << 4; + scanner__skip_n (sc, 1); + key.year_month |= scanner__get_uint64 (sc); + + scanner__skip_over (sc, ','); + + key.client_id = scanner__get_uint64 (sc); + + scanner__skip_n (sc, 1); + + card_id_t card_id = scanner__get_uint64 (sc); + if (hmgetp_null (cards, card_id) == NULL) { + scanner__skip_over (sc, '\n'); + continue; + } + + scanner__skip_n (sc, 2); + + int64_t amount = 100*scanner__get_int64 (sc); + scanner__skip_n (sc, 1); + int sign = amount >= 0 ? 1 : -1; + amount += sign*scanner__get_uint64 (sc); + + scanner__skip_n (sc, 1); + scanner__skip_over (sc, ','); + scanner__skip_over (sc, ','); + + struct string_view sv = scanner__get_until (sc, ','); + key.merchant_city_id = hash (sv.begin, STRING_VIEW__LENGTH (sv)); + + scanner__skip_over (sc, '\n'); + + struct transaction *transaction = + hmgetp_null (transactions, key); + if (transaction == NULL) + hmput (transactions, key, amount); + else transaction->sum += amount; + } + + // Normalize + ptrdiff_t tempvar; + for (size_t i = 0; i < hmlenu (transactions); ++i) { + struct transaction *transaction = &transactions[i]; + float normalizer = hmgetp_ts (users, transaction->key.client_id, tempvar)->normalizer; + transaction->normalized = transaction->sum*normalizer; + } + + // Exctract top + for (size_t i = 0; i < hmlenu (transactions); ++i) + transaction_heap__push (top_transactions, transactions[i]); + + hmfree (transactions); +} + +void +process_transactions__gpu (struct scanner *sc, + struct transaction_heap *top_transactions, + struct card *cards, struct user *users) +{ + MEASURE_SCOPE ("[%d/%d]", world_rank + 1, world_size); + + ASSERT (sc != NULL); + ASSERT (top_transactions != NULL); + ASSERT (cards != NULL); + ASSERT (users != NULL); + + uint64_t *keys = NULL; + float *vals = NULL; + ptrdiff_t tempvar; + while (!scanner__reached_end (sc)) { + union transaction_key key; + + scanner__skip_over (sc, ','); + + key.year_month = scanner__get_uint64 (sc) << 4; + scanner__skip_n (sc, 1); + key.year_month |= scanner__get_uint64 (sc); + + scanner__skip_over (sc, ','); + + key.client_id = scanner__get_uint64 (sc); + + scanner__skip_n (sc, 1); + + card_id_t card_id = scanner__get_uint64 (sc); + if (hmgetp_null (cards, card_id) == NULL) { + scanner__skip_over (sc, '\n'); + continue; + } + + scanner__skip_n (sc, 2); + + int64_t amount = 100*scanner__get_int64 (sc); + scanner__skip_n (sc, 1); + int sign = amount >= 0 ? 1 : -1; + amount += sign*scanner__get_uint64 (sc); + + scanner__skip_n (sc, 1); + scanner__skip_over (sc, ','); + scanner__skip_over (sc, ','); + + struct string_view sv = scanner__get_until (sc, ','); + key.merchant_city_id = hash (sv.begin, STRING_VIEW__LENGTH (sv)); + + scanner__skip_over (sc, '\n'); + + float normalizer = hmgetp_ts (users, key.client_id, tempvar)->normalizer; + arrput (keys, key.packed); + arrput (vals, amount*normalizer); + } + + void *handle = dlopen ("./cuda.so", RTLD_LAZY); + if (handle == NULL) + DIE ("dlopen: %s", dlerror ()); + + int (*cuda_process_transactions) (uint64_t *keys, float *vals, size_t) = + dlsym (handle, "process_transactions"); + if (cuda_process_transactions == NULL) + DIE ("dlsym: %s", dlerror ()); + + int count = cuda_process_transactions (keys, vals, arrlenu (keys)); + + if (dlclose (handle)) + DIE ("dlclose: %s", dlerror ()); + + for (int i = 0; i < count; ++i) { + transaction_heap__push (top_transactions, (struct transaction) { + .key.packed = keys[i], + .normalized = vals[i], + }); + } + + arrfree (keys); + arrfree (vals); +} + +struct sizes { + size_t cpu; + size_t gpu; + size_t tail; +}; + +struct partition { + size_t offset; + size_t size; +}; + +struct sizes +get_sizes (size_t size) +{ + int thread_count__cpu = ((max_threads - 0)*node_count__cpu + + (max_threads - 1)*node_count__gpu); + int thread_count__gpu = node_count__gpu; + + double weight__cpu = thread_count__cpu*RATIO__CPU_GPU; + double weight__gpu = thread_count__gpu; + + double ratio__cpu = weight__cpu/(weight__cpu + weight__gpu); + + struct sizes sizes; + + size_t size__cpus = size * ratio__cpu; + size_t size__gpus = size - size__cpus; + sizes.cpu = (thread_count__cpu > 0) ? size__cpus/thread_count__cpu : 0; + sizes.gpu = (thread_count__gpu > 0) ? size__gpus/thread_count__gpu : 0; + sizes.tail = size - (thread_count__cpu*sizes.cpu + + thread_count__gpu*sizes.gpu); + + return sizes; +} + +struct partition +partition_node (struct sizes sizes, int node_rank) +{ + struct partition partition; + + if (node_rank < node_count__cpu) { // CPU NODE + partition.size = max_threads*sizes.cpu; + partition.offset = node_rank*partition.size; + } else { // GPU NODE + partition.size = (max_threads - 1)*sizes.cpu + sizes.gpu; + partition.offset = (node_count__cpu*max_threads*sizes.cpu + + (node_rank - node_count__cpu)*partition.size); + } + + if (node_rank + 1 == node_count__cpu + node_count__gpu) + partition.size += sizes.tail; + + return partition; +} + +struct partition +partition_thread (struct partition partition, struct sizes sizes, + int node_rank, int thread) +{ + if (node_rank < node_count__cpu) { + partition.size = sizes.cpu; + partition.offset += thread*partition.size; + } else { + if (thread == 0) { + partition.size = sizes.gpu; + } else { + partition.size = sizes.cpu; + partition.offset += sizes.gpu + (thread - 1)*partition.size; + } + } + + if (node_rank + 1 == node_count__cpu + node_count__gpu && thread + 1 == max_threads) + partition.size += sizes.tail; + + return partition; +} + +void +align_scanner (struct scanner *sc, const char *base, + struct partition partition, bool last) +{ + sc->cursor = base + partition.offset; + + struct scanner tmp = *sc; + + if (partition.offset > 0) + scanner__skip_current_month (sc); + + if (!last) { + tmp.cursor += partition.size; + scanner__skip_current_month (&tmp); + sc->end = tmp.cursor; + } +} + +void +process_transactions (const char *filename, + struct transaction_heap *top_transactions, + struct card *cards, struct user *users) +{ + MEASURE_SCOPE ("[%d/%d]", world_rank + 1, world_size); + + ASSERT (filename); + ASSERT (top_transactions); + ASSERT (cards); + ASSERT (users); + + int fd = open (filename, O_RDONLY); + ASSERT_MSG (fd != -1, "open %s: %s", filename, strerror (errno)); + + struct stat st; + int ret = fstat (fd, &st); + ASSERT_MSG (ret != -1, "fstat: %s", strerror (errno)); + ASSERT (S_ISREG (st.st_mode)); + + struct sizes sizes = get_sizes (st.st_size); + + struct partition node_partition = partition_node (sizes, world_rank); + + off_t page_align = node_partition.offset % 4096; + struct string_view sv = + mmap_n_from (fd, // mmap till end + st.st_size - node_partition.offset + page_align, + 0 + node_partition.offset - page_align); + + struct transaction_heap top_transactions_other = {0}; +#pragma omp parallel + { + int tid = omp_get_thread_num (); + struct partition thread_partition = + partition_thread (node_partition, sizes, world_rank, tid); + struct scanner sc; + scanner__init (&sc, sv); + sc.cursor += page_align; + align_scanner (&sc, sc.cursor - node_partition.offset, thread_partition, + world_rank == world_size - 1 && tid == max_threads - 1); + + if (world_rank == 0 && tid == 0) + scanner__skip_over (&sc, '\n'); + + printf ("[%d/%d] [%d/%d] Data split: 0x%06lx 0x%06lx %7luK %p %p %p\n", + world_rank + 1, world_size, tid + 1, max_threads, + (sc.cursor - (sv.begin + page_align) + node_partition.offset) >> 10, + (sc.end - (sv.begin + page_align) + node_partition.offset) >> 10, + (sc.end - sc.cursor) >> 10, + sc.cursor, sc.end, sv.end); + + if (tid == 0) { + if (has_gpu) process_transactions__gpu (&sc, top_transactions, cards, users); + else process_transactions__cpu (&sc, top_transactions, cards, users); + } else process_transactions__cpu (&sc, &top_transactions_other, cards, users); + } + + munmap ((char *) sv.begin, sv.end - sv.begin); + close (fd); + + // Aggregate + for (int i = 0; i < top_transactions_other.count; ++i) + transaction_heap__push (top_transactions, top_transactions_other.array[i]); +} + +int +compare_transactions (const void *lhs, const void *rhs) +{ + const struct transaction *lhs_transaction = lhs; + const struct transaction *rhs_transaction = rhs; + + float lhs_normalized = lhs_transaction->normalized; + float rhs_normalized = rhs_transaction->normalized; + + return (lhs_normalized < rhs_normalized) - (lhs_normalized > rhs_normalized); +} + +void +sort_top (struct transaction_heap *top) +{ + MEASURE_SCOPE (); + ASSERT (top != NULL); + + qsort (top->array, top->count, sizeof (*top->array), compare_transactions); +} + +void +print_top (const struct transaction_heap *top) +{ + MEASURE_SCOPE (); + ASSERT (top != NULL); + + printf (" i client_id normalized_spending year_month city\n"); + for (int i = 0; i < top->count; ++i) { + printf ("%2d %4hu %6.2f %hu-%02hu %s\n", i, + top->array[i].key.client_id, + top->array[i].normalized, + top->array[i].key.year_month >> 4, + top->array[i].key.year_month & ((1 << 4) - 1), + wordlist[top->array[i].key.merchant_city_id]); + } +} + +int +main (int argc, char *argv[]) +{ + mpi_init (&argc, &argv); + + if (argc != 3) + return 1; + + const char *progname = *argv++; + node_count__cpu = atoi (*argv++); + node_count__gpu = atoi (*argv++); + + UNUSED (progname); + + world_size = mpi_world_size (); + world_rank = mpi_world_rank (); + mpi_get_processor_name (processor_name, &name_len); + max_threads = omp_get_max_threads (); + has_gpu = world_rank >= node_count__cpu; + + MEASURE_SCOPE ("[%d/%d]", world_rank + 1, world_size); + + printf ("Hello from processor %s, rank %d out of %d processors (%d threads, %s GPU)\n", + processor_name, world_rank, world_size, + max_threads, has_gpu ? "Has" : "Doesn't have"); + + struct card *cards = NULL; + struct user *users = NULL; + struct transaction_heap top_transactions = {0}; + + // TODO(cmmm): all threads read their part, then the host shares with others + process_cards ("res/cards_data.csv", &cards, &users); + process_users ("res/users_data.csv", users); + + process_transactions ("res/transactions_data.csv", + &top_transactions, cards, users); + if (world_rank > 0) { + send_top (&top_transactions, 0); + } else { + for (int i = 1; i < world_size; ++i) + recv_top (&top_transactions, i); + sort_top (&top_transactions); + print_top (&top_transactions); + } + + mpi_finalize (); +} +// super-computer.c ends here diff --git a/src/transaction-heap.c b/src/transaction-heap.c new file mode 100644 index 0000000..038b634 --- /dev/null +++ b/src/transaction-heap.c @@ -0,0 +1,60 @@ +// transaction-heap.c +#include "transaction-heap.h" +#include "utils.h" + +void +transaction_heap__pop (struct transaction_heap *heap) +{ + ASSERT (heap != NULL); + ASSERT (heap->count > 0); + + heap->array[0] = heap->array[--heap->count]; + + int current = 0; + loop: { + int left = 2*current + 1; + int right = 2*current + 2; + int smallest = current; + + if (left < heap->count && + heap->array[left].normalized < heap->array[smallest].normalized) { + smallest = left; + } + if (right < heap->count && + heap->array[right].normalized < heap->array[smallest].normalized) { + smallest = right; + } + + if (smallest != current) { + struct transaction temp = heap->array[current]; + heap->array[current] = heap->array[smallest]; + heap->array[smallest] = temp; + current = smallest; + goto loop; + } + } +} + +void +transaction_heap__push (struct transaction_heap *heap, struct transaction value) +{ + ASSERT (heap != NULL); + + if (heap->count > 0 && value.normalized < heap->array[0].normalized) + return; + + if (heap->count == ARRAY_LENGTH (heap->array)) + transaction_heap__pop (heap); + + heap->array[heap->count++] = value; + // bottom up, parent = (current - 1)/2 + for (int current = heap->count - 1; + current > 0 && + heap->array[(current - 1)/2].normalized > heap->array[current].normalized; + current = (current - 1)/2) { + struct transaction temp = heap->array[(current - 1)/2]; + heap->array[(current - 1)/2] = heap->array[current]; + heap->array[current] = temp; + } +} +// transaction-heap.c ends here diff --git a/src/transaction-heap.h b/src/transaction-heap.h new file mode 100644 index 0000000..43eeea3 --- /dev/null +++ b/src/transaction-heap.h @@ -0,0 +1,18 @@ +// transaction-heap.h +#ifndef INCLUDED_TRANSACTION_HEAP_H +#define INCLUDED_TRANSACTION_HEAP_H + +#include + +#include "transaction.h" + +struct transaction_heap { + struct transaction array[100]; + int count; +}; + +void transaction_heap__pop (struct transaction_heap *); +void transaction_heap__push (struct transaction_heap *, struct transaction); + +#endif // INCLUDED_TRANSACTION_HEAP_H +// transaction-heap.h ends here diff --git a/src/transaction.h b/src/transaction.h new file mode 100644 index 0000000..709b242 --- /dev/null +++ b/src/transaction.h @@ -0,0 +1,26 @@ +// transaction.h +#ifndef INCLUDED_TRANSACTION_H +#define INCLUDED_TRANSACTION_H + +#include + +typedef uint32_t merchant_city_id_t; + +struct transaction { + union transaction_key { + uint64_t packed; + struct { + uint32_t merchant_city_id; + uint16_t client_id; + uint16_t year_month; // year << 4 + month + }; + } key; + union { + int32_t value; + int32_t sum; + float normalized; + }; +}; + +#endif // INCLUDED_TRANSACTION_H +// transaction.h ends here diff --git a/src/user.h b/src/user.h new file mode 100644 index 0000000..d52b763 --- /dev/null +++ b/src/user.h @@ -0,0 +1,22 @@ +// user.h +#ifndef INCLUDED_USER_H +#define INCLUDED_USER_H + +#include + +typedef uint16_t client_id_t; + +struct user { + union { + client_id_t key; + client_id_t id; + }; + union { + uint32_t value; + uint32_t per_capita_income; + float normalizer; + }; +}; + +#endif // INCLUDED_USER_H +// user.h ends here diff --git a/src/utils.c b/src/utils.c new file mode 100644 index 0000000..ea4b936 --- /dev/null +++ b/src/utils.c @@ -0,0 +1,91 @@ +// utils.c +#include +#include +#include +#include +#include +#include +#include + +#include "utils.h" + +struct string_view +mmap_whole (int fd) +{ + struct string_view sv; + + struct stat st; + int ret = fstat (fd, &st); + UNUSED (ret); + ASSERT_MSG (ret != -1, "fstat: %s", strerror (errno)); + ASSERT (S_ISREG (st.st_mode)); + + posix_fadvise (fd, 0, st.st_size, POSIX_FADV_SEQUENTIAL | + POSIX_FADV_WILLNEED | + POSIX_FADV_NOREUSE); + + sv.begin = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE | + MAP_POPULATE | + MAP_NONBLOCK, fd, 0); + ASSERT_MSG (sv.begin != MAP_FAILED, "mmap: %s", strerror (errno)); + posix_madvise ((void *) sv.begin, st.st_size, MADV_HUGEPAGE | MADV_WILLNEED); + + sv.end = sv.begin + st.st_size; + + return sv; +} + +struct string_view +mmap_n_from (int fd, size_t n, off_t offset) +{ + struct string_view sv; + + posix_fadvise (fd, offset, n, POSIX_FADV_SEQUENTIAL | + POSIX_FADV_WILLNEED | + POSIX_FADV_NOREUSE); + + sv.begin = mmap (NULL, n, PROT_READ, MAP_PRIVATE | + MAP_POPULATE | + MAP_NONBLOCK, fd, offset); + ASSERT_MSG (sv.begin != MAP_FAILED, "mmap: %s", strerror (errno)); + posix_madvise ((void *) sv.begin, n, MADV_HUGEPAGE | MADV_WILLNEED); + + sv.end = sv.begin + n; + + return sv; +} + +int +vasprintf (char **str, const char *fmt, va_list args) +{ + int size = 0; + va_list tmpa; + + va_copy (tmpa, args); + size = vsnprintf (NULL, 0, fmt, tmpa); + va_end (tmpa); + + if (size < 0) + return -1; + + *str = (char *) malloc (size + 1); + if (NULL == *str) + return -1; + + size = vsprintf (*str, fmt, args); + return size; +} + +int +asprintf (char **str, const char *fmt, ...) +{ + int size = 0; + va_list args; + + va_start (args, fmt); + size = vasprintf (str, fmt, args); + va_end (args); + + return size; +} +// utils.c ends here diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..d8e7dda --- /dev/null +++ b/src/utils.h @@ -0,0 +1,95 @@ +// utils.h +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include +#include +#include +#include + +#include "string-view.h" + +#define NOP() do {} while (0) + +#define ARRAY_LENGTH(ARR) (sizeof (ARR)/sizeof (*(ARR))) + +#ifndef NDEBUG +#include +#define ASSERT assert +#else +#define ASSERT(...) NOP () +#endif + +#define UNUSED(EXP) ((void) EXP) + +#define FALLTHROUGH __attribute__ ((__fallthrough__)) + +#define STRINGIFY(ARG) #ARG +#define TO_STRING(ARG) STRINGIFY (ARG) + +#ifndef NDEBUG +#define DEBUG(FMT, ...) \ + fprintf (stderr, __FILE__ ":" TO_STRING (__LINE__) ": %s: " FMT "\n", \ + __func__ __VA_OPT__ (,) __VA_ARGS__) +#else +#define DEBUG(...) NOP () +#endif + +#ifndef NDEBUG +#define ASSERT_MSG(EXP, FMT, ...) do if (!(EXP)) { \ + DEBUG (FMT __VA_OPT__ (,) __VA_ARGS__); \ + exit (EXIT_FAILURE); \ + } while (0) +#else +#define ASSERT_MSG(EXP, FMT, ...) NOP () +#endif + +#define MEASURE(FMT, ...) \ + for (struct timespec __ts0, __ts1, *__once = NULL; \ + clock_gettime (CLOCK_MONOTONIC, &__ts0), !__once; \ + clock_gettime (CLOCK_MONOTONIC, &__ts1), \ + fprintf (stderr, __FILE__ ":" TO_STRING (__LINE__) \ + ": %s: " FMT " %.6fs\n", __func__, \ + __VA_ARGS__ __VA_OPT__ (,) \ + (__ts1.tv_sec - __ts0.tv_sec ) + \ + (__ts1.tv_nsec - __ts0.tv_nsec) / 1e9), \ + __once += 1) + +#define MIN(A, B) ((A) <= (B) ? (A) : (B)) + +struct timer_scope { + char *fmt; + struct timespec start; +}; + +static void +timer_end (struct timer_scope *t) +{ + struct timespec end; + clock_gettime (CLOCK_MONOTONIC, &end); + + double s = ((end.tv_sec - t->start.tv_sec) + + (end.tv_nsec - t->start.tv_nsec)/1e9); + + fprintf (stderr, t->fmt, s); + if (t->fmt[strlen (t->fmt) - 1] != ' ') + putc (' ', stderr); + fprintf (stderr, "took %.6fs\n", s); + free (t->fmt); +} + +#define MEASURE_SCOPE(FMT, ...) \ + __attribute__ ((cleanup (timer_end))) struct timer_scope __ts; \ + asprintf (&__ts.fmt, \ + __FILE__ ":" TO_STRING (__LINE__) ": %s: " FMT, \ + __func__ __VA_OPT__ (,) __VA_ARGS__); \ + clock_gettime (CLOCK_MONOTONIC, &__ts.start) + +struct string_view mmap_whole (int fd); +struct string_view mmap_n_from (int fd, size_t n, off_t offset); + +int asprintf (char **str, const char *fmt, ...); + +#endif // INCLUDED_UTILS_H +// utils.h ends here -- cgit v1.3.1