1 /*-
2  * Copyright (c) 1997, 2020 Oracle and/or its affiliates.  All rights reserved.
3  *
4  * See the file EXAMPLES-LICENSE for license information.
5  *
6  * ex_tpcb--
7  *
8  *   This example is an early transaction processing benchmark that simulates bank
9  *   transfers from one account to another. The program is first run in an initialization
10  *   mode which loads the data. Subsequent runs in one or more processes perform a
11  *   workload. This program implements a basic TPC/B driver program. To create the TPC/B
12  *   database, run with the -i(init) flag. The number of records with which to populate the
13  *   account, history, branch, and teller tables is specified by the a, s, b, and t flags
14  *   respectively. To run a TPC/B test, use the n flag to indicate a number of transactions
15  *   to run.
16  *
17  *   The program requires two invocations, both taking in integer identifier as an argument.
18  *   This identifier allows for multiple sets of databases to be used within the same
19  *   environment. The first is to initialize the databases, the second is to run the program
20  *   on those databases.
21  *
22  *   After the transaction message is printed, the program closes the environment and exits.
23  *
24  * Options:
25  *    -a	set the number of accounts per teller
26  *    -b	set the number of branches
27  *    -c	set the cache size in bytes
28  *    -f	fast I/O mode: no txn sync
29  *    -h	set the home directory
30  *    -i	initialize the environment and load databases
31  *    -n	set the number of transactions
32  *    -S	set the random number seed
33  *    -s	set the number of history records
34  *    -t	set the number of bank tellers
35  *    -v	print verbose messages during processing
36  *
37  * $Id$
38  */
39 
40 #include <sys/types.h>
41 
42 #include <errno.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <time.h>
46 
47 #define	NS_PER_MS	1000000		/* Nanoseconds in a millisecond */
48 #define	NS_PER_US	1000		/* Nanoseconds in a microsecond */
49 #ifdef _WIN32
50 #include <sys/timeb.h>
51 #include <winsock2.h>
52 extern int getopt(int, char * const *, const char *);
53 /* Implement a basic high res timer with a POSIX interface for Windows. */
gettimeofday(struct timeval * tv,struct timezone * tz)54 int gettimeofday(struct timeval *tv, struct timezone *tz)
55 {
56 	struct _timeb now;
57 	_ftime(&now);
58 	tv->tv_sec = (long)now.time;
59 	tv->tv_usec = now.millitm * NS_PER_US;
60 	return (0);
61 }
62 #else
63 #include <unistd.h>
64 #include <sys/time.h>
65 #endif
66 
67 #include <db.h>
68 
69 typedef enum { ACCOUNT, BRANCH, TELLER } FTYPE;
70 
71 DB_ENV	 *db_init __P((const char *, const char *, int, u_int32_t));
72 int	  hpopulate __P((DB *, int, int, int, int));
73 int	  populate __P((DB *, u_int32_t, u_int32_t, int, const char *));
74 u_int32_t random_id __P((FTYPE, int, int, int));
75 u_int32_t random_int __P((u_int32_t, u_int32_t));
76 int	  tp_populate __P((DB_ENV *, int, int, int, int, int));
77 int	  tp_run __P((DB_ENV *, int, int, int, int, int));
78 int	  tp_txn __P((DB_ENV *, DB *, DB *, DB *, DB *, int, int, int, int));
79 
80 int	  invarg __P((const char *, int, const char *));
81 int	  main __P((int, char *[]));
82 int	  usage __P((const char *));
83 
84 #define	TELLERS_PER_BRANCH	10
85 #define	ACCOUNTS_PER_TELLER	10000
86 #define	HISTORY_PER_BRANCH	2592000
87 
88 /*
89  * The default configuration that adheres to TPCB scaling rules requires
90  * nearly 3 GB of space. To avoid requiring that much space for testing,
91  * we set the parameters much lower. If you want to run a valid 10 TPS
92  * configuration, define VALID_SCALING.
93  */
94 #ifdef	VALID_SCALING
95 #define	ACCOUNTS	 1000000
96 #define	BRANCHES	      10
97 #define	TELLERS		     100
98 #define	HISTORY		25920000
99 #endif
100 
101 #ifdef	TINY
102 #define	ACCOUNTS	    1000
103 #define	BRANCHES	      10
104 #define	TELLERS		     100
105 #define	HISTORY		   10000
106 #endif
107 
108 #ifdef	VERY_TINY
109 #define	ACCOUNTS	     500
110 #define	BRANCHES	      10
111 #define	TELLERS		      50
112 #define	HISTORY		    5000
113 #endif
114 
115 #if !defined(VALID_SCALING) && !defined(TINY) && !defined(VERY_TINY)
116 #define	ACCOUNTS	  100000
117 #define	BRANCHES	      10
118 #define	TELLERS		     100
119 #define	HISTORY		  259200
120 #endif
121 
122 #define	HISTORY_LEN	    100
123 #define	RECLEN		    100
124 #define	BEGID		1000000
125 
126 typedef struct _defrec {
127 	u_int32_t	id;
128 	u_int32_t	balance;
129 	u_int8_t	pad[RECLEN - sizeof(u_int32_t) - sizeof(u_int32_t)];
130 } defrec;
131 
132 typedef struct _histrec {
133 	u_int32_t	aid;
134 	u_int32_t	bid;
135 	u_int32_t	tid;
136 	u_int32_t	amount;
137 	u_int8_t	pad[RECLEN - 4 * sizeof(u_int32_t)];
138 } histrec;
139 
140 char *progname = "ex_tpcb";			/* Program name. */
141 
142 int
main(argc,argv)143 main(argc, argv)
144 	int argc;
145 	char *argv[];
146 {
147 	extern char *optarg;    /* argument associated with option */
148 	extern int optind;      /* index into parent argv vector */
149 	DB_ENV *dbenv;          /* The environment handle. */
150 	int accounts;           /* The account variable. */
151 	int branches;           /* The branch variable. */
152 	int seed;               /* The random number seed variable. */
153 	int tellers;            /* The teller variable. */
154 	int history;            /* The history record variable. */
155 	int ch;                 /* The current command line option char. */
156 	int iflag;              /* The initialization flag. */
157 	int mpool;              /* Memory pool variable. */
158 	int ntxns;              /* The number of transactions. */
159 	int ret;                /* Return code from call into Berkeley DB. */
160 	int txn_no_sync;        /* Transaction no synchronization flag. */
161 	int verbose;            /* Verbose message flag. */
162 	const char *home;       /* Home directory constant. */
163 
164 	home = "TESTDIR";
165 	accounts = branches = history = tellers = 0;
166 	iflag = mpool = ntxns = txn_no_sync = verbose = 0;
167 	seed = (int)time(NULL);
168 	/* Parse the command line arguments */
169 	while ((ch = getopt(argc, argv, "a:b:c:fh:in:S:s:t:v")) != EOF)
170 		switch (ch) {
171 		case 'a':			/* Set the number of accounts per teller. */
172 			if ((accounts = atoi(optarg)) <= 0)
173 				return (invarg(progname, ch, optarg));
174 			break;
175 		case 'b':			/* Set the number of branches. */
176 			if ((branches = atoi(optarg)) <= 0)
177 				return (invarg(progname, ch, optarg));
178 			break;
179 		case 'c':			/* Set the cache size in bytes. */
180 			if ((mpool = atoi(optarg)) <= 0)
181 				return (invarg(progname, ch, optarg));
182 			break;
183 		case 'f':			/* Fast I/O mode: no txn sync. */
184 			txn_no_sync = 1;
185 			break;
186 		case 'h':			/* Set the home directory. */
187 			home = optarg;
188 			break;
189 		case 'i':			/* Initialize the environment and load databases. */
190 			iflag = 1;
191 			break;
192 		case 'n':			/* Set the number of transactions */
193 			if ((ntxns = atoi(optarg)) <= 0)
194 				return (invarg(progname, ch, optarg));
195 			break;
196 		case 'S':			/* Set the random number seed. */
197 			if ((seed = atoi(optarg)) <= 0)
198 				return (invarg(progname, ch, optarg));
199 			break;
200 		case 's':			/* Set the number of history records */
201 			if ((history = atoi(optarg)) <= 0)
202 				return (invarg(progname, ch, optarg));
203 			break;
204 		case 't':			/* Set the number of bank tellers. */
205 			if ((tellers = atoi(optarg)) <= 0)
206 				return (invarg(progname, ch, optarg));
207 			break;
208 		case 'v':			/* Print verbose messages during processing. */
209 			verbose = 1;
210 			break;
211 		case '?':
212 		default:
213 			return (usage(progname));
214 		}
215 	argc -= optind;
216 	argv += optind;
217 
218 	srand((u_int)seed);
219 
220 	/* Initialize the database environment. */
221 	if ((dbenv = db_init(home,
222 	    progname, mpool, txn_no_sync ? DB_TXN_NOSYNC : 0)) == NULL)
223 		return (EXIT_FAILURE);
224 
225 	accounts = accounts == 0 ? ACCOUNTS : accounts;
226 	branches = branches == 0 ? BRANCHES : branches;
227 	tellers = tellers == 0 ? TELLERS : tellers;
228 	history = history == 0 ? HISTORY : history;
229 
230 	if (verbose)
231 		printf("%ld Accounts, %ld Branches, %ld Tellers, %ld History\n",
232 		    (long)accounts, (long)branches,
233 		    (long)tellers, (long)history);
234 
235 	if (iflag) {
236 		if (ntxns != 0)
237 			return (usage(progname));
238 		tp_populate(dbenv,
239 		    accounts, branches, history, tellers, verbose);
240 	} else {
241 		if (ntxns == 0)
242 			return (usage(progname));
243 		tp_run(dbenv, ntxns, accounts, branches, tellers, verbose);
244 	}
245 
246 	if ((ret = dbenv->close(dbenv, 0)) != 0) {
247 		fprintf(stderr, "%s: dbenv->close failed: %s\n",
248 		    progname, db_strerror(ret));
249 		return (EXIT_FAILURE);
250 	}
251 
252 	return (EXIT_SUCCESS);
253 }
254 
255 /*
256  * invarg --
257  *	Describe invalid command line argument, then exit.
258  *
259  * Parameters:
260  *   progname        program name
261  *   arg             argument variable
262  *   str             invalid input string
263  */
264 int
invarg(progname,arg,str)265 invarg(progname, arg, str)
266 	const char *progname;
267 	int arg;
268 	const char *str;
269 {
270 	(void)fprintf(stderr,
271 	    "%s: invalid argument for -%c: %s\n", progname, arg, str);
272 	return (EXIT_FAILURE);
273 }
274 
275 /*
276  * usage --
277  *	Describe this program's command line options, then exit.
278  *
279  * Parameters:
280  *  progname        program name
281  */
282 int
usage(progname)283 usage(progname)
284 	const char *progname;
285 {
286 	const char *a1, *a2;
287 
288 	a1 = "[-fv] [-a accounts] [-b branches]\n";
289 	a2 = "\t[-c cache_size] [-h home] [-S seed] [-s history] [-t tellers]";
290 	(void)fprintf(stderr, "usage: %s -i %s %s\n", progname, a1, a2);
291 	(void)fprintf(stderr,
292 	    "       %s -n transactions %s %s\n", progname, a1, a2);
293 	return (EXIT_FAILURE);
294 }
295 
296 /*
297  * db_init --
298  *	Initialize the environment.
299  *
300  * Parameters:
301  *    home        home directory
302  *    prefix      an error output stream
303  *    cachesize   cache size of the database environment
304  *    flags       environment open flag
305  */
306 DB_ENV *
db_init(home,prefix,cachesize,flags)307 db_init(home, prefix, cachesize, flags)
308 	const char *home, *prefix;
309 	int cachesize;
310 	u_int32_t flags;
311 {
312 	DB_ENV *dbenv;            /* Database environment handle. */
313 	u_int32_t local_flags;    /* Local flags to open environment. */
314 	int ret;                  /* Return code. */
315 
316 	/* Create the environment object. */
317 	if ((ret = db_env_create(&dbenv, 0)) != 0) {
318 		fprintf(stderr,
319 		    "%s: db_env_create: %s\n", progname, db_strerror(ret));
320 		return (NULL);
321 	}
322 
323 	/*
324 	 * Prefix any error messages with the name of this program and a ':'.
325 	 * Setting the errfile to stderr is not necessary, since that is the
326 	 * default; it is provided here as a placeholder showing where one
327 	 * could direct error messages to an application-specific log file.
328 	 */
329 	dbenv->set_errfile(dbenv, stderr);
330 	dbenv->set_errpfx(dbenv, prefix);
331 
332 	/* Use the default deadlock detector. */
333 	(void)dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT);
334 	/* Set the cache size. */
335 	(void)dbenv->set_cachesize(dbenv, 0,
336 	    cachesize == 0 ? 4 * 1024 * 1024 : (u_int32_t)cachesize, 0);
337 
338 	/*
339 	 * If -f option is specified, do not synchronize on transaction
340 	 * commit. This reduces the durability of the database but improves
341 	 * transaction throughput.
342 	 */
343 	if (flags & (DB_TXN_NOSYNC))
344 		(void)dbenv->set_flags(dbenv, DB_TXN_NOSYNC, 1);
345 	flags &= ~(DB_TXN_NOSYNC);
346 
347 	/* Open a transactional environment. */
348 	local_flags = flags | DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG |
349 	    DB_INIT_MPOOL | DB_INIT_TXN;
350 	/* Open environment with local flags. */
351 	if ((ret = dbenv->open(dbenv, home, local_flags, 0)) != 0) {
352 		dbenv->err(dbenv, ret, "DB_ENV->open: %s", home);
353 		(void)dbenv->close(dbenv, 0);
354 		return (NULL);
355 	}
356 	return (dbenv);
357 }
358 
359 /*
360  * tp_populate --
361  *        Initialize the database to the specified number of accounts, branches,
362  * history records, and tellers.
363  *
364  * Parameters:
365  *    env        environment handle
366  *    accounts   account variable to specify
367  *    branches   branch variable to specify
368  *    history    history record
369  *    tellers    teller variable to specify
370  *    verbose    verbose message
371  */
372 int
tp_populate(env,accounts,branches,history,tellers,verbose)373 tp_populate(env, accounts, branches, history, tellers, verbose)
374 	DB_ENV *env;
375 	int accounts, branches, history, tellers, verbose;
376 {
377 	DB *dbp;                  /* The database handle. */
378 	u_int32_t balance;        /* Balance of account. */
379 	u_int32_t idnum;          /* Number of transaction identifier. */
380 	u_int32_t oflags;         /* Open flag for the database. */
381 	u_int32_t end_anum;       /* End number of accounts. */
382 	u_int32_t end_bnum;       /* End number of branches. */
383 	u_int32_t end_tnum;       /* End number of tellers. */
384 	u_int32_t start_anum;     /* Start number of accounts. */
385 	u_int32_t start_bnum;     /* Start number of branches. */
386 	u_int32_t start_tnum;     /* Start number of tellers. */
387 	int ret;                  /* Return code. */
388 
389 	idnum = BEGID;
390 	balance = 500000;
391 	oflags = DB_CREATE;
392 
393 	/* Create the database object for accounts. */
394 	if ((ret = db_create(&dbp, env, 0)) != 0) {
395 		env->err(env, ret, "db_create");
396 		return (1);
397 	}
398 	/* Set the estimated final size of the account database. */
399 	(void)dbp->set_h_nelem(dbp, (u_int32_t)accounts);
400 
401 	/* Create the account database with the hash access method. */
402 	if ((ret = dbp->open(dbp, NULL, "account", NULL,
403 	    DB_HASH, oflags, 0644)) != 0) {
404 		env->err(env, ret, "DB->open: account");
405 		return (1);
406 	}
407 
408 	/* Populate the account database. */
409 	start_anum = idnum;
410 	populate(dbp, idnum, balance, accounts, "account");
411 	idnum += accounts;
412 	end_anum = idnum - 1;
413 	/* Close the account database. */
414 	if ((ret = dbp->close(dbp, 0)) != 0) {
415 		env->err(env, ret, "DB->close: account");
416 		return (1);
417 	}
418 	if (verbose)
419 		printf("Populated accounts: %ld - %ld\n",
420 		    (long)start_anum, (long)end_anum);
421 
422 	/*
423 	 * Since the number of branches is very small, we want to use very
424 	 * small pages and only 1 key per page, i.e., key-locking instead
425 	 * of page locking.
426 	 */
427 	if ((ret = db_create(&dbp, env, 0)) != 0) {
428 		env->err(env, ret, "db_create");
429 		return (1);
430 	}
431 	/* Set the fill factor to be 1, allowing approximately 1 key per bucket. */
432 	(void)dbp->set_h_ffactor(dbp, 1);
433 	/* Set the estimated final size of the branch database. */
434 	(void)dbp->set_h_nelem(dbp, (u_int32_t)branches);
435 	/* Use a small page size to reduce the number of keys per page. */
436 	(void)dbp->set_pagesize(dbp, 512);
437 	/* Open the branch database with the hash access method. */
438 	if ((ret = dbp->open(dbp, NULL, "branch", NULL,
439 	    DB_HASH, oflags, 0644)) != 0) {
440 		env->err(env, ret, "DB->open: branch");
441 		return (1);
442 	}
443 
444 	/* Populate the branch database. */
445 	start_bnum = idnum;
446 	populate(dbp, idnum, balance, branches, "branch");
447 	idnum += branches;
448 	end_bnum = idnum - 1;
449 	if ((ret = dbp->close(dbp, 0)) != 0) {
450 		env->err(env, ret, "DB->close: branch");
451 		return (1);
452 	}
453 	if (verbose)
454 		printf("Populated branches: %ld - %ld\n",
455 		    (long)start_bnum, (long)end_bnum);
456 
457 	/*
458 	 * In the case of tellers, we also want small pages, but we'll let
459 	 * the fill factor dynamically adjust itself.
460 	 */
461 	if ((ret = db_create(&dbp, env, 0)) != 0) {
462 		env->err(env, ret, "db_create");
463 		return (1);
464 	}
465 	/* Set the fill factor to 0 to allow it dynamically adjust itself. */
466 	(void)dbp->set_h_ffactor(dbp, 0);
467 	/* Set the estimated final size of the teller database. */
468 	(void)dbp->set_h_nelem(dbp, (u_int32_t)tellers);
469 	/* Use a small page size. */
470 	(void)dbp->set_pagesize(dbp, 512);
471 	/* Open the teller database with the hash access method. */
472 	if ((ret = dbp->open(dbp, NULL, "teller", NULL,
473 	    DB_HASH, oflags, 0644)) != 0) {
474 		env->err(env, ret, "DB->open: teller");
475 		return (1);
476 	}
477 
478 	/* Populate the teller database. */
479 	start_tnum = idnum;
480 	populate(dbp, idnum, balance, tellers, "teller");
481 	idnum += tellers;
482 	end_tnum = idnum - 1;
483 	if ((ret = dbp->close(dbp, 0)) != 0) {
484 		env->err(env, ret, "DB->close: teller");
485 		return (1);
486 	}
487 	if (verbose)
488 		printf("Populated tellers: %ld - %ld\n",
489 		    (long)start_tnum, (long)end_tnum);
490 
491 	if ((ret = db_create(&dbp, env, 0)) != 0) {
492 		env->err(env, ret, "db_create");
493 		return (1);
494 	}
495 	/* Set the record length of history records. */
496 	(void)dbp->set_re_len(dbp, HISTORY_LEN);
497 	/* Open the history database with the recno access method. */
498 	if ((ret = dbp->open(dbp, NULL, "history", NULL,
499 	    DB_RECNO, oflags, 0644)) != 0) {
500 		env->err(env, ret, "DB->open: history");
501 		return (1);
502 	}
503 
504 	/* Populate the history records. */
505 	hpopulate(dbp, history, accounts, branches, tellers);
506 	if ((ret = dbp->close(dbp, 0)) != 0) {
507 		env->err(env, ret, "DB->close: history");
508 		return (1);
509 	}
510 	return (0);
511 }
512 
513 /*
514  * populate --
515  *        Initialize the database to the specified value according to the file type.
516  *
517  * Parameters:
518  *    dbp        database handle
519  *    start_id   start position
520  *    balance    the balance of account
521  *    nrecs      number of records
522  *    msg        error message
523  */
524 int
populate(dbp,start_id,balance,nrecs,msg)525 populate(dbp, start_id, balance, nrecs, msg)
526 	DB *dbp;
527 	u_int32_t start_id, balance;
528 	int nrecs;
529 	const char *msg;
530 {
531 	DBT kdbt;         /* The key value of the database. */
532 	DBT ddbt;         /* The data value of the database. */
533 	defrec drec;      /* database record. */
534 	int i;            /* Variable to indicate the position of the record. */
535 	int ret;          /* Return code. */
536 
537 	/* Set the key to be record's id, and data to be the entire record. */
538 	kdbt.flags = 0;
539 	kdbt.data = &drec.id;
540 	kdbt.size = sizeof(u_int32_t);
541 	ddbt.flags = 0;
542 	ddbt.data = &drec;
543 	ddbt.size = sizeof(drec);
544 	memset(&drec.pad[0], 1, sizeof(drec.pad));
545 
546 	/* Insert records. */
547 	for (i = 0; i < nrecs; i++) {
548 		drec.id = start_id + (u_int32_t)i;
549 		drec.balance = balance;
550 		if ((ret =
551 		    (dbp->put)(dbp, NULL, &kdbt, &ddbt, DB_NOOVERWRITE)) != 0) {
552 			dbp->err(dbp,
553 			    ret, "Failure initializing %s file\n", msg);
554 			return (1);
555 		}
556 	}
557 	return (0);
558 }
559 
560 /*
561  * hpopulate --
562  *        Initialize the database to the specified number of history records.
563  *
564  * Parameters:
565  *    dbp        database handle
566  *    history    history record variable
567  *    accounts   account variable to specify
568  *    branches   branch variable to specify
569  *    tellers    teller variable to specify
570  */
571 int
hpopulate(dbp,history,accounts,branches,tellers)572 hpopulate(dbp, history, accounts, branches, tellers)
573 	DB *dbp;
574 	int history, accounts, branches, tellers;
575 {
576 	DBT kdbt;         /* The key value of the database. */
577 	DBT ddbt;         /* The data value of the database. */
578 	histrec hrec;     /* History record. */
579 	db_recno_t key;   /* The record number variable of the transaction database. */
580 	int i;            /* variable to indicate the position of history record. */
581 	int ret;          /* Return code. */
582 
583 	/*
584 	 * The key must be a record number. Set the data to be the entire
585 	 * history record.
586 	 */
587 	memset(&kdbt, 0, sizeof(kdbt));
588 	memset(&ddbt, 0, sizeof(ddbt));
589 	ddbt.data = &hrec;
590 	ddbt.size = sizeof(hrec);
591 	kdbt.data = &key;
592 	kdbt.size = sizeof(key);
593 	memset(&hrec.pad[0], 1, sizeof(hrec.pad));
594 	hrec.amount = 10;
595 
596 	/* Insert history records. */
597 	for (i = 1; i <= history; i++) {
598 		hrec.aid = random_id(ACCOUNT, accounts, branches, tellers);
599 		hrec.bid = random_id(BRANCH, accounts, branches, tellers);
600 		hrec.tid = random_id(TELLER, accounts, branches, tellers);
601 		if ((ret = dbp->put(dbp, NULL, &kdbt, &ddbt, DB_APPEND)) != 0) {
602 			dbp->err(dbp, ret, "dbp->put");
603 			return (1);
604 		}
605 	}
606 	return (0);
607 }
608 
609 /*
610  * random_int --
611  *        function to generate random integer within the range
612  *
613  * Parameters:
614  *    lo    the low bound of the range
615  *    hi    the high bound of the range
616  */
617 u_int32_t
random_int(lo,hi)618 random_int(lo, hi)
619 	u_int32_t lo, hi;
620 {
621 	u_int32_t ret;          /* Return code. */
622 	int t;                  /* random integer. */
623 
624 #ifndef RAND_MAX
625 #define	RAND_MAX	0x7fffffff
626 #endif
627 	t = rand();
628 	ret = (u_int32_t)(((double)t / ((double)(RAND_MAX) + 1)) *
629 	    (hi - lo + 1));
630 	ret += lo;
631 	return (ret);
632 }
633 
634 /*
635  * random_int --
636  *        function to generate transaction identifier.
637  *
638  * Parameters:
639  *    type        the file type
640  *    accounts    the account variable
641  *    branches    the branch variable
642  *    tellers      the teller variable
643  */
644 u_int32_t
random_id(type,accounts,branches,tellers)645 random_id(type, accounts, branches, tellers)
646 	FTYPE type;
647 	int accounts, branches, tellers;
648 {
649 	u_int32_t min;        /* The minimum value of the transaction identifier. */
650 	u_int32_t max;        /* The maximum value of the transaction identifier. */
651 	u_int32_t num;        /* The range between the minimum value and maximum value. */
652 
653 	max = min = BEGID;
654 	num = accounts;
655 	switch (type) {
656 	case TELLER:
657 		min += branches;
658 		num = tellers;
659 		/* FALLTHROUGH */
660 	case BRANCH:
661 		if (type == BRANCH)
662 			num = branches;
663 		min += accounts;
664 		/* FALLTHROUGH */
665 	case ACCOUNT:
666 		max = min + num - 1;
667 	}
668 	return (random_int(min, max));
669 }
670 
671 /*
672  * tp_run --
673  *        function to run the transaction.
674  *
675  * Parameters:
676  *    dbenv        the database environment handle
677  *    n            the number of transactions
678  *    accounts     the account variable
679  *    branches     the branch variable
680  *    tellers      the teller variable
681  *    verbose      verbose message
682  */
683 int
tp_run(dbenv,n,accounts,branches,tellers,verbose)684 tp_run(dbenv, n, accounts, branches, tellers, verbose)
685 	DB_ENV *dbenv;
686 	int n, accounts, branches, tellers, verbose;
687 {
688 	DB *adb;          /* The accounts database. */
689 	DB *bdb;          /* The branches database. */
690 	DB *hdb;          /* The history record database. */
691 	DB *tdb;          /* The tellers database. */
692 	int failed;       /* Transaction running fail flag. */
693 	int ret;          /* Return code. */
694 	int txns;         /* Number of transactions. */
695 	struct timeval start_tv;        /* Time variable to store the start time. */
696 	struct timeval end_tv;          /* Time variable to store the end time. */
697 	double start_time;              /* Start time variable. */
698 	double end_time;                /* End time varialbe. */
699 
700 	adb = bdb = hdb = tdb = NULL;
701 
702 	/*
703 	 * Open the database files.
704 	 */
705 	if ((ret = db_create(&adb, dbenv, 0)) != 0) {
706 		dbenv->err(dbenv, ret, "db_create");
707 		goto err;
708 	}
709 	if ((ret = adb->open(adb, NULL, "account", NULL, DB_UNKNOWN,
710 	    DB_AUTO_COMMIT, 0)) != 0) {
711 		dbenv->err(dbenv, ret, "DB->open: account");
712 		goto err;
713 	}
714 	if ((ret = db_create(&bdb, dbenv, 0)) != 0) {
715 		dbenv->err(dbenv, ret, "db_create");
716 		goto err;
717 	}
718 	if ((ret = bdb->open(bdb, NULL, "branch", NULL, DB_UNKNOWN,
719 	    DB_AUTO_COMMIT, 0)) != 0) {
720 		dbenv->err(dbenv, ret, "DB->open: branch");
721 		goto err;
722 	}
723 	if ((ret = db_create(&hdb, dbenv, 0)) != 0) {
724 		dbenv->err(dbenv, ret, "db_create");
725 		goto err;
726 	}
727 	if ((ret = hdb->open(hdb, NULL, "history", NULL, DB_UNKNOWN,
728 	    DB_AUTO_COMMIT, 0)) != 0) {
729 		dbenv->err(dbenv, ret, "DB->open: history");
730 		goto err;
731 	}
732 	if ((ret = db_create(&tdb, dbenv, 0)) != 0) {
733 		dbenv->err(dbenv, ret, "db_create");
734 		goto err;
735 	}
736 	if ((ret = tdb->open(tdb, NULL, "teller", NULL, DB_UNKNOWN,
737 	    DB_AUTO_COMMIT, 0)) != 0) {
738 		dbenv->err(dbenv, ret, "DB->open: teller");
739 		goto err;
740 	}
741 
742 	/* Get the start time. */
743 	(void)gettimeofday(&start_tv, NULL);
744 
745 	/* Run n transactions. */
746 	for (txns = n, failed = 0; n-- > 0;)
747 		if ((ret = tp_txn(dbenv, adb, bdb, tdb, hdb,
748 		    accounts, branches, tellers, verbose)) != 0)
749 			++failed;
750 
751 	/* Get the end time. */
752 	(void)gettimeofday(&end_tv, NULL);
753 
754 	start_time = start_tv.tv_sec + ((start_tv.tv_usec + 0.0)/NS_PER_MS);
755 	end_time = end_tv.tv_sec + ((end_tv.tv_usec + 0.0)/NS_PER_MS);
756 	if (end_time == start_time)
757 		end_time += 1/NS_PER_MS;
758 
759 	/* Print the result. */
760 	printf("%s: %d txns: %d failed, %.3f sec, %.2f TPS\n", progname,
761 	    txns, failed, (end_time - start_time),
762 	    (txns - failed) / (double)(end_time - start_time));
763 
764 	/* Close databases. */
765 err:	if (adb != NULL)
766 		(void)adb->close(adb, 0);
767 	if (bdb != NULL)
768 		(void)bdb->close(bdb, 0);
769 	if (tdb != NULL)
770 		(void)tdb->close(tdb, 0);
771 	if (hdb != NULL)
772 		(void)hdb->close(hdb, 0);
773 	return (ret == 0 ? 0 : 1);
774 }
775 
776 /*
777  * tp_txn --
778  *        function to run one single specified transaction.
779  *
780  * Parameters:
781  *    dbenv        the database environment handle
782  *    adb          the accounts database
783  *    bdb          the branches database
784  *    tdb          the tellers database
785  *    hdb          the history record database
786  *    accounts     the account variable
787  *    branches     the branch variable
788  *    tellers      the teller variable
789  *    verbose      verbose message
790  */
791 int
tp_txn(dbenv,adb,bdb,tdb,hdb,accounts,branches,tellers,verbose)792 tp_txn(dbenv, adb, bdb, tdb, hdb, accounts, branches, tellers, verbose)
793 	DB_ENV *dbenv;
794 	DB *adb, *bdb, *tdb, *hdb;
795 	int accounts, branches, tellers, verbose;
796 {
797 	DBC *acurs;        /* The accounts database cursor. */
798 	DBC *bcurs;        /* The branches database cursor. */
799 	DBC *tcurs;        /* The tellers database cursor. */
800 	DBT d_dbt;         /* The data value of the database. */
801 	DBT d_histdbt;     /* The data value of the history record database. */
802 	DBT k_dbt;         /* The key value of the database. */
803 	DBT k_histdbt;     /* The key value of the history record database. */
804 	DB_TXN *t;         /* The transaction handle. */
805 	db_recno_t key;    /* The record number variable of the transaction database. */
806 	defrec rec;        /* The record variable. */
807 	histrec hrec;      /* The history record. */
808 	int account;       /* The account variable. */
809 	int branch;        /* The branch variable. */
810 	int teller;        /* The teller variable. */
811 	int ret;           /* Return code. */
812 
813 	t = NULL;
814 	acurs = bcurs = tcurs = NULL;
815 
816 	/*
817 	 * !!!
818 	 * This is sample code -- we could move a lot of this into the driver
819 	 * to make it faster.
820 	 */
821 	account = random_id(ACCOUNT, accounts, branches, tellers);
822 	branch = random_id(BRANCH, accounts, branches, tellers);
823 	teller = random_id(TELLER, accounts, branches, tellers);
824 
825 	/* Initialize history key/data pairs. */
826 	memset(&d_histdbt, 0, sizeof(d_histdbt));
827 
828 	memset(&k_histdbt, 0, sizeof(k_histdbt));
829 	k_histdbt.data = &key;
830 	k_histdbt.size = sizeof(key);
831 
832 	/* Initialize database key/data pairs. */
833 	memset(&k_dbt, 0, sizeof(k_dbt));
834 	k_dbt.size = sizeof(int);
835 
836 	memset(&d_dbt, 0, sizeof(d_dbt));
837 	d_dbt.flags = DB_DBT_USERMEM;
838 	d_dbt.data = &rec;
839 	d_dbt.ulen = sizeof(rec);
840 
841 	hrec.aid = account;
842 	hrec.bid = branch;
843 	hrec.tid = teller;
844 	hrec.amount = 10;
845 	/* Request 0 bytes since we're just positioning. */
846 	d_histdbt.flags = DB_DBT_PARTIAL;
847 
848 	/*
849 	 * START PER-TRANSACTION TIMING.
850 	 *
851 	 * Technically, TPCB requires a limit on response time, you only get
852 	 * to count transactions that complete within 2 seconds.  That's not
853 	 * an issue for this sample application -- regardless, here's where
854 	 * the transaction begins.
855 	 */
856 	if (dbenv->txn_begin(dbenv, NULL, &t, 0) != 0)
857 		goto err;
858 
859 	/* Create transactional cursors for account, branch and teller databases. */
860 	if (adb->cursor(adb, t, &acurs, 0) != 0 ||
861 	    bdb->cursor(bdb, t, &bcurs, 0) != 0 ||
862 	    tdb->cursor(tdb, t, &tcurs, 0) != 0)
863 		goto err;
864 
865 	/* Read and update one account record */
866 	k_dbt.data = &account;
867 	if (acurs->get(acurs, &k_dbt, &d_dbt, DB_SET) != 0)
868 		goto err;
869 	rec.balance += 10;
870 	if (acurs->put(acurs, &k_dbt, &d_dbt, DB_CURRENT) != 0)
871 		goto err;
872 
873 	/* Read and update one branch record */
874 	k_dbt.data = &branch;
875 	if (bcurs->get(bcurs, &k_dbt, &d_dbt, DB_SET) != 0)
876 		goto err;
877 	rec.balance += 10;
878 	if (bcurs->put(bcurs, &k_dbt, &d_dbt, DB_CURRENT) != 0)
879 		goto err;
880 
881 	/* Read and update one teller record */
882 	k_dbt.data = &teller;
883 	if (tcurs->get(tcurs, &k_dbt, &d_dbt, DB_SET) != 0)
884 		goto err;
885 	rec.balance += 10;
886 	if (tcurs->put(tcurs, &k_dbt, &d_dbt, DB_CURRENT) != 0)
887 		goto err;
888 
889 	/* Add one history record */
890 	d_histdbt.flags = 0;
891 	d_histdbt.data = &hrec;
892 	d_histdbt.ulen = sizeof(hrec);
893 	if (hdb->put(hdb, t, &k_histdbt, &d_histdbt, DB_APPEND) != 0)
894 		goto err;
895 
896 	/* Close all cursors. */
897 	if (acurs->close(acurs) != 0 || bcurs->close(bcurs) != 0 ||
898 	    tcurs->close(tcurs) != 0)
899 		goto err;
900 	/* Commit the transaction. */
901 	ret = t->commit(t, 0);
902 	t = NULL;
903 	if (ret != 0)
904 		goto err;
905 	/* END PER-TRANSACTION TIMING. */
906 
907 	return (0);
908 
909 err:	if (acurs != NULL)
910 		(void)acurs->close(acurs);
911 	if (bcurs != NULL)
912 		(void)bcurs->close(bcurs);
913 	if (tcurs != NULL)
914 		(void)tcurs->close(tcurs);
915 	if (t != NULL)
916 		(void)t->abort(t);
917 
918 	if (verbose)
919 		printf("Transaction A=%ld B=%ld T=%ld failed\n",
920 		    (long)account, (long)branch, (long)teller);
921 	return (-1);
922 }
923