int nfsd_setuser(struct svc_rqst *rqstp, struct svc_export *exp)
{
	struct group_info *rqgi;
	struct group_info *gi;
	struct cred *new;
	int i;
	int flags = nfsexp_flags(rqstp, exp);

	/* discard any old override before preparing the new set */
	revert_creds(get_cred(current_real_cred()));
	new = prepare_creds();
	if (!new)
		return -ENOMEM;

	#ifdef CONFIG_CREDP
	iee_set_cred_fsuid(new,rqstp->rq_cred.cr_uid);
	iee_set_cred_fsgid(new,rqstp->rq_cred.cr_gid);
	#else
	new->fsuid = rqstp->rq_cred.cr_uid;
	new->fsgid = rqstp->rq_cred.cr_gid;
	#endif

	rqgi = rqstp->rq_cred.cr_group_info;

	if (flags & NFSEXP_ALLSQUASH) {
		#ifdef CONFIG_CREDP
		iee_set_cred_fsuid(new,exp->ex_anon_uid);
		iee_set_cred_fsgid(new,exp->ex_anon_gid);
		#else
		new->fsuid = exp->ex_anon_uid;
		new->fsgid = exp->ex_anon_gid;
		#endif
		gi = groups_alloc(0);
		if (!gi)
			goto oom;
	} else if (flags & NFSEXP_ROOTSQUASH) {
		if (uid_eq(new->fsuid, GLOBAL_ROOT_UID))
			#ifdef CONFIG_CREDP
			iee_set_cred_fsuid(new,exp->ex_anon_uid);
			#else
			new->fsuid = exp->ex_anon_uid;
			#endif
		if (gid_eq(new->fsgid, GLOBAL_ROOT_GID))
			#ifdef CONFIG_CREDP
			iee_set_cred_fsgid(new,exp->ex_anon_gid);
			#else
			new->fsgid = exp->ex_anon_gid;
			#endif

		gi = groups_alloc(rqgi->ngroups);
		if (!gi)
			goto oom;

		for (i = 0; i < rqgi->ngroups; i++) {
			if (gid_eq(GLOBAL_ROOT_GID, rqgi->gid[i]))
				gi->gid[i] = exp->ex_anon_gid;
			else
				gi->gid[i] = rqgi->gid[i];
		}

		/* Each thread allocates its own gi, no race */
		groups_sort(gi);
	} else {
		gi = get_group_info(rqgi);
	}

	if (uid_eq(new->fsuid, INVALID_UID))
		#ifdef CONFIG_CREDP
		iee_set_cred_fsuid(new,exp->ex_anon_uid);
		#else
		new->fsuid = exp->ex_anon_uid;
		#endif
	if (gid_eq(new->fsgid, INVALID_GID))
		#ifdef CONFIG_CREDP
		iee_set_cred_fsgid(new,exp->ex_anon_gid);
		#else
		new->fsgid = exp->ex_anon_gid;
		#endif

	set_groups(new, gi);
	put_group_info(gi);

	if (!uid_eq(new->fsuid, GLOBAL_ROOT_UID))
		#ifdef CONFIG_CREDP
		iee_set_cred_cap_effective(new,cap_drop_nfsd_set(new->cap_effective));
		#else
		new->cap_effective = cap_drop_nfsd_set(new->cap_effective);
		#endif
	else
		#ifdef CONFIG_CREDP
		iee_set_cred_cap_effective(new,cap_raise_nfsd_set(new->cap_effective,
							new->cap_permitted));
		#else
		new->cap_effective = cap_raise_nfsd_set(new->cap_effective,
							new->cap_permitted);
		#endif
	put_cred(override_creds(new));
	put_cred(new);
	return 0;

oom:
	abort_creds(new);
	return -ENOMEM;
}
