1570af302Sopenharmony_ci#include "stdio_impl.h"
2570af302Sopenharmony_ci#include "pthread_impl.h"
3570af302Sopenharmony_ci#include <limits.h>
4570af302Sopenharmony_ci
5570af302Sopenharmony_civoid __do_orphaned_stdio_locks()
6570af302Sopenharmony_ci{
7570af302Sopenharmony_ci	FILE *f;
8570af302Sopenharmony_ci	for (f=__pthread_self()->stdio_locks; f; f=f->next_locked)
9570af302Sopenharmony_ci		a_store(&f->lock, 0x40000000);
10570af302Sopenharmony_ci}
11570af302Sopenharmony_ci
12570af302Sopenharmony_civoid __unlist_locked_file(FILE *f)
13570af302Sopenharmony_ci{
14570af302Sopenharmony_ci	if (f->lockcount) {
15570af302Sopenharmony_ci		if (f->next_locked) f->next_locked->prev_locked = f->prev_locked;
16570af302Sopenharmony_ci		if (f->prev_locked) f->prev_locked->next_locked = f->next_locked;
17570af302Sopenharmony_ci		else __pthread_self()->stdio_locks = f->next_locked;
18570af302Sopenharmony_ci	}
19570af302Sopenharmony_ci}
20570af302Sopenharmony_ci
21570af302Sopenharmony_civoid __register_locked_file(FILE *f, pthread_t self)
22570af302Sopenharmony_ci{
23570af302Sopenharmony_ci	f->lockcount = 1;
24570af302Sopenharmony_ci	f->prev_locked = 0;
25570af302Sopenharmony_ci	f->next_locked = self->stdio_locks;
26570af302Sopenharmony_ci	if (f->next_locked) f->next_locked->prev_locked = f;
27570af302Sopenharmony_ci	self->stdio_locks = f;
28570af302Sopenharmony_ci}
29570af302Sopenharmony_ci
30570af302Sopenharmony_ciint ftrylockfile(FILE *f)
31570af302Sopenharmony_ci{
32570af302Sopenharmony_ci	pthread_t self = __pthread_self();
33570af302Sopenharmony_ci	int tid = self->tid;
34570af302Sopenharmony_ci	int owner = f->lock;
35570af302Sopenharmony_ci	if ((owner & ~MAYBE_WAITERS) == tid) {
36570af302Sopenharmony_ci		if (f->lockcount == LONG_MAX)
37570af302Sopenharmony_ci			return -1;
38570af302Sopenharmony_ci		f->lockcount++;
39570af302Sopenharmony_ci		return 0;
40570af302Sopenharmony_ci	}
41570af302Sopenharmony_ci	if (owner < 0) f->lock = owner = 0;
42570af302Sopenharmony_ci	if (owner || a_cas(&f->lock, 0, tid))
43570af302Sopenharmony_ci		return -1;
44570af302Sopenharmony_ci	__register_locked_file(f, self);
45570af302Sopenharmony_ci	return 0;
46570af302Sopenharmony_ci}
47