diff mbox series

libgomp: Add omp_{s,g}et_device_{num_teams,teams_thread_limit}

Message ID 1d223ea4-1058-4deb-8d3e-85bdd9a18d5f@baylibre.com
State New
Headers show
Series libgomp: Add omp_{s,g}et_device_{num_teams,teams_thread_limit} | expand

Commit Message

Tobias Burnus Nov. 4, 2026, 1:27 a.m. UTC
While looking at something else, I noticed the pointless copy back
of device ICV values at the end of the target region - and as data
copying is expensive, I removed it.

While being there, I also added the 6.0 API routines - which turned
out to be useful as three testcases use 5.1 API routines to change
those ICVs on the device side - which was never valid. However, due
to the new API routines, the test cases could be made valid, which
was before not possible!

When writing the documentation, I noticed some @ref missing and
that omp_set_device_num did not state that 0 is permitted, which
is fixed as well.

Any comments before I commit this later today (Wednesday)?

Tobias

Comments

Tobias Burnus Nov. 4, 2026, 1:57 a.m. UTC | #1
Next try – with the proper patch!

This time with the pristine patch (unchanged to previous attempt, except 
for removed unrelated gcc/ changes)

Tobias Burnus wrote:
> While looking at something else, I noticed the pointless copy back
> of device ICV values at the end of the target region - and as data
> copying is expensive, I removed it.
>
> While being there, I also added the 6.0 API routines - which turned
> out to be useful as three testcases use 5.1 API routines to change
> those ICVs on the device side - which was never valid. However, due
> to the new API routines, the test cases could be made valid, which
> was before not possible!
>
> When writing the documentation, I noticed some @ref missing and
> that omp_set_device_num did not state that 0 is permitted, which
> is fixed as well.
>
> Any comments before I commit this later today (Wednesday)? 
Tobias
Tobias Burnus Nov. 4, 2026, 8:37 a.m. UTC | #2
Now committed as r17-5916-g00513d11fb2b5a
with some follow-up tweaks to the .texi file (see interdiff
attachment) and some typo/wording fixes in the commit message.

Tobias

Tobias Burnus wrote:
> Next try – with the proper patch!
>
> This time with the pristine patch (unchanged to previous attempt, 
> except for removed unrelated gcc/ changes)
>
> Tobias Burnus wrote:
>> While looking at something else, I noticed the pointless copy back
>> of device ICV values at the end of the target region - and as data
>> copying is expensive, I removed it.
>>
>> While being there, I also added the 6.0 API routines - which turned
>> out to be useful as three testcases use 5.1 API routines to change
>> those ICVs on the device side - which was never valid. However, due
>> to the new API routines, the test cases could be made valid, which
>> was before not possible!
>>
>> When writing the documentation, I noticed some @ref missing and
>> that omp_set_device_num did not state that 0 is permitted, which
>> is fixed as well.
>>
>> Any comments before I commit this later today (Wednesday)? 
> Tobias
diff mbox series

Patch

libgomp: Add omp_{s,g}et_device_{num_teams,teams_thread_limit}

Add the four OpenMP 6.0 API routines.

Avoid pointless copy back of device ICV at the end of GOMP_target_ext
as the host-used dvice ICV variables are not changable from the
device side.
This requires to change the omp_set_{num_teams,teams_thread_limit}
(added in 5.1) to the new API function in three tests, which did
so nontheless.

Also fix documentation for omp_set_num_teams (zero is permitted).

gcc/ChangeLog:

	* omp-general.cc (omp_runtime_api_procname): Add
	omp_{s,g}et_device_{num_teams,teams_thread_limit}.

libgomp/ChangeLog:

	* icv-device.c (omp_set_teams_thread_limit): Add comment.
	* libgomp.map (OMP_6.0): Add
	omp_{s,g}et_device_{num_teams,teams_thread_limit}.
	* libgomp.texi: Add some more @refs related to new new routines.
	(Device Information Routines): Document new routines.
	(6.0 Impl. Status): Mark them as implemented.
	* omp.h.in: Add prototypes for them.
	* omp_lib.f90.in: Add iterface for them.
	* omp_lib.h.in: Likewise.
	* target.c (gomp_get_offload_icv_item): Add usage comment.
	(gomp_copy_back_icvs): Return gomp_offload_icvs instead of void.
	(gomp_copy_icvs_to_device): New.
	(GOMP_target_ext): Remove gomp_copy_back_icvs.
	(omp_set_device_num_teams, omp_get_device_num_teams,
	omp_set_device_teams_thread_limit,
	omp_get_device_teams_thread_limit): New.
	* testsuite/libgomp.c-c++-common/icv-5.c: Change from invalid ICV
	setting on the device to setting it on the host.
	* testsuite/libgomp.c-c++-common/icv-6.c: Likewise.
	* testsuite/libgomp.fortran/icv-6.f90: Likewise.
	* testsuite/libgomp.c-c++-common/omp-device-num-teams-thread-limit-1.c:
	New test.
	* testsuite/libgomp.fortran/omp-device-num-teams-thread-limit-1.f90:
	New test.

 gcc/fortran/openmp.cc                              |   2 +-
 gcc/fortran/trans-openmp.cc                        | 227 +++++++++++++++++----
 gcc/gimplify.cc                                    |   6 +
 gcc/omp-general.cc                                 |   4 +
 .../gfortran.dg/gomp/spatial-dimensions-1.f90      |   2 +-
 .../gfortran.dg/gomp/spatial-dimensions-4.f90      |  27 ++-
 .../gfortran.dg/gomp/spatial-dimensions-5.f90      |  12 +-
 libgomp/icv-device.c                               |   3 +
 libgomp/libgomp.map                                |   4 +
 libgomp/libgomp.texi                               | 178 ++++++++++++++--
 libgomp/omp.h.in                                   |   4 +
 libgomp/omp_lib.f90.in                             |  35 ++++
 libgomp/omp_lib.h.in                               |  36 ++++
 libgomp/target.c                                   | 148 +++++++++++++-
 libgomp/testsuite/libgomp.c-c++-common/icv-5.c     |  18 +-
 libgomp/testsuite/libgomp.c-c++-common/icv-6.c     |  18 +-
 .../omp-device-num-teams-thread-limit-1.c          | 193 ++++++++++++++++++
 libgomp/testsuite/libgomp.fortran/icv-6.f90        |  26 ++-
 .../omp-device-num-teams-thread-limit-1.f90        | 194 ++++++++++++++++++
 19 files changed, 1055 insertions(+), 82 deletions(-)

diff --git a/gcc/fortran/openmp.cc b/gcc/fortran/openmp.cc
index ba7f3c5ea24..670e4af1399 100644
--- a/gcc/fortran/openmp.cc
+++ b/gcc/fortran/openmp.cc
@@ -5995,7 +5995,7 @@  cleanup:
   (omp_mask (OMP_CLAUSE_NUM_TEAMS) | OMP_CLAUSE_THREAD_LIMIT		\
    | OMP_CLAUSE_DEFAULT | OMP_CLAUSE_PRIVATE | OMP_CLAUSE_FIRSTPRIVATE	\
    | OMP_CLAUSE_SHARED | OMP_CLAUSE_REDUCTION | OMP_CLAUSE_ALLOCATE	\
-   | OMP_CLAUSE_MESSAGE)
+   | OMP_CLAUSE_MESSAGE | OMP_CLAUSE_DYN_GROUPPRIVATE)
 #define OMP_DISTRIBUTE_CLAUSES \
   (omp_mask (OMP_CLAUSE_PRIVATE) | OMP_CLAUSE_FIRSTPRIVATE		\
    | OMP_CLAUSE_LASTPRIVATE | OMP_CLAUSE_COLLAPSE | OMP_CLAUSE_DIST_SCHEDULE \
diff --git a/gcc/fortran/trans-openmp.cc b/gcc/fortran/trans-openmp.cc
index bee9fd608ec..ae6d3d290f4 100644
--- a/gcc/fortran/trans-openmp.cc
+++ b/gcc/fortran/trans-openmp.cc
@@ -6016,9 +6016,19 @@  gfc_trans_omp_clauses (stmtblock_t *block, gfc_omp_clauses *clauses,
 			       gfc_convert_expr_to_tree (block, el->expr),
 			       num_teams);
       c = build_omp_clause (gfc_get_location (&where), OMP_CLAUSE_NUM_TEAMS);
-      OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (c) = NULL_TREE;
-      OMP_CLAUSE_NUM_TEAMS_UPPER_EXPR (c) = nreverse (num_teams);
-      OMP_CLAUSE_NUM_TEAMS_DIMS (c) = clauses->num_teams_dims;
+      if (clauses->num_teams_dims)
+	{
+	  OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (c) = NULL_TREE;
+	  OMP_CLAUSE_NUM_TEAMS_UPPER_EXPR (c) = nreverse (num_teams);
+	  OMP_CLAUSE_NUM_TEAMS_DIMS (c) = clauses->num_teams_dims;
+	}
+      else
+	{
+	  OMP_CLAUSE_NUM_TEAMS_UPPER_EXPR (c) = TREE_VALUE (num_teams);
+	  if (TREE_CHAIN(num_teams))
+	    OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (c)
+	      = TREE_VALUE (TREE_CHAIN (num_teams));
+	}
       omp_clauses = gfc_trans_add_clause (c, omp_clauses);
     }
 
@@ -8565,6 +8575,10 @@  gfc_split_omp_clauses (gfc_code *code,
 	    = code->ext.omp_clauses->lists[OMP_LIST_IS_DEVICE_PTR];
 	  clausesa[GFC_OMP_SPLIT_TARGET].lists[OMP_LIST_HAS_DEVICE_ADDR]
 	    = code->ext.omp_clauses->lists[OMP_LIST_HAS_DEVICE_ADDR];
+	  clausesa[GFC_OMP_SPLIT_TARGET].dyn_groupprivate
+	    = code->ext.omp_clauses->dyn_groupprivate;
+	  clausesa[GFC_OMP_SPLIT_TARGET].fallback
+	    = code->ext.omp_clauses->fallback;
 	  clausesa[GFC_OMP_SPLIT_TARGET].device
 	    = code->ext.omp_clauses->device;
 	  clausesa[GFC_OMP_SPLIT_TARGET].thread_limit_list
@@ -8603,6 +8617,10 @@  gfc_split_omp_clauses (gfc_code *code,
 	    = code->ext.omp_clauses->thread_limit_strict;
 	  clausesa[GFC_OMP_SPLIT_TEAMS].thread_limit_dims
 	    = code->ext.omp_clauses->thread_limit_dims;
+	  clausesa[GFC_OMP_SPLIT_TARGET].dyn_groupprivate
+	    = code->ext.omp_clauses->dyn_groupprivate;
+	  clausesa[GFC_OMP_SPLIT_TARGET].fallback
+	    = code->ext.omp_clauses->fallback;
 	  /* Shared and default clauses are allowed on parallel, teams
 	     and taskloop.  */
 	  clausesa[GFC_OMP_SPLIT_TEAMS].lists[OMP_LIST_SHARED]
@@ -9405,16 +9423,179 @@  gfc_trans_omp_target (gfc_code *code)
   tree stmt, omp_clauses = NULL_TREE;
 
   gfc_start_block (&block);
+
+  /* For target + teams, evaluate some clauses on the host; as for those their
+     expressions must be target consistent, this is also permitted when
+     nested and not only for combined directives.  */
+  bool combined_teams_dir;
+  switch (code->op)
+    {
+    case EXEC_OMP_TARGET_TEAMS:
+    case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE:
+    case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO:
+    case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
+    case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_SIMD:
+    case EXEC_OMP_TARGET_TEAMS_LOOP:
+      combined_teams_dir = true;
+      break;
+    default:
+      combined_teams_dir = false;
+      break;
+    }
+  tree tree_tgt_clauses = NULL_TREE, tree_teams_clauses = NULL_TREE;
+  gfc_omp_clauses *teams_clauses = NULL;
+  if (flag_openmp && code->op == EXEC_OMP_TARGET && code->block->next)
+    {
+      gfc_code *code2 = (code->block->next->op == EXEC_BLOCK
+			 ? code->block->next->ext.block.ns->code
+			 : code->block->next);
+      if (code2)
+	switch (code2->op)
+	  {
+	  case EXEC_OMP_TEAMS:
+	  case EXEC_OMP_TEAMS_DISTRIBUTE:
+	  case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO:
+	  case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
+	  case EXEC_OMP_TEAMS_DISTRIBUTE_SIMD:
+	  case EXEC_OMP_TEAMS_LOOP:
+	    teams_clauses = code2->ext.omp_clauses;
+	    break;
+	  default:
+	    break;
+	  }
+     }
+  if ((teams_clauses && teams_clauses->num_teams_list)
+       || (combined_teams_dir && code->ext.omp_clauses->num_teams_list))
+    {
+      gfc_omp_clauses *num_teams_clauses
+	= teams_clauses ? teams_clauses : code->ext.omp_clauses;
+      tree c, t, num_teams = NULL_TREE;
+      for (gfc_expr_list *el = num_teams_clauses->num_teams_list;
+	   el; el = el->next)
+	{
+	  t = gfc_convert_expr_to_tree (&block, el->expr);
+	  if (DECL_P (t))
+	    {
+	      c = build_omp_clause (gfc_get_location (&el->expr->where),
+				    OMP_CLAUSE_FIRSTPRIVATE);
+	      OMP_CLAUSE_DECL (c) = t;
+	      tree_tgt_clauses = gfc_trans_add_clause (c, tree_tgt_clauses);
+	    }
+	  num_teams = tree_cons (NULL_TREE, t, num_teams);
+	}
+      locus *loc = &num_teams_clauses->num_teams_list->expr->where;
+      c = build_omp_clause (gfc_get_location (loc), OMP_CLAUSE_NUM_TEAMS);
+      if (num_teams_clauses->num_teams_dims)
+	{
+	  OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (c) = NULL_TREE;
+	  OMP_CLAUSE_NUM_TEAMS_UPPER_EXPR (c) = nreverse (num_teams);
+	  OMP_CLAUSE_NUM_TEAMS_DIMS (c) = num_teams_clauses->num_teams_dims;
+	}
+      else
+	{
+	  OMP_CLAUSE_NUM_TEAMS_UPPER_EXPR (c) = TREE_VALUE (num_teams);
+	  if (TREE_CHAIN (num_teams))
+	    OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (c)
+	      = TREE_VALUE (TREE_CHAIN (num_teams));
+	}
+      tree_tgt_clauses = gfc_trans_add_clause (c, tree_tgt_clauses);
+      tree_teams_clauses = gfc_trans_add_clause (unshare_expr (c),
+						 tree_teams_clauses);
+      gfc_free_expr_list (num_teams_clauses->num_teams_list);
+      num_teams_clauses->num_teams_list = NULL;
+    }
+  if ((teams_clauses && teams_clauses->thread_limit_list)
+      || (combined_teams_dir && code->ext.omp_clauses->thread_limit_list))
+    {
+      /* thread_limit can be put on target and on teams, use the team one as
+	 having higher precedence.  */
+      gfc_omp_clauses *thread_limit_clauses
+	= (teams_clauses && teams_clauses->thread_limit_list
+	   ? teams_clauses : code->ext.omp_clauses);
+      tree c, t, thread_limit = NULL_TREE;
+      for (gfc_expr_list *el = thread_limit_clauses->thread_limit_list;
+	   el; el = el->next)
+	{
+	  t = gfc_convert_expr_to_tree (&block, el->expr);
+	  if (DECL_P (t))
+	    {
+	      c = build_omp_clause (gfc_get_location (&el->expr->where),
+				    OMP_CLAUSE_FIRSTPRIVATE);
+	      OMP_CLAUSE_DECL (c) = t;
+	      tree_tgt_clauses = gfc_trans_add_clause (c, tree_tgt_clauses);
+	    }
+	  thread_limit = tree_cons (NULL_TREE, t, thread_limit);
+	}
+      locus *loc = &thread_limit_clauses->thread_limit_list->expr->where;
+      c = build_omp_clause (gfc_get_location (loc), OMP_CLAUSE_THREAD_LIMIT);
+      OMP_CLAUSE_THREAD_LIMIT_EXPR (c) = nreverse (thread_limit);
+      OMP_CLAUSE_THREAD_LIMIT_STRICT (c)
+	= thread_limit_clauses->thread_limit_strict;
+      OMP_CLAUSE_THREAD_LIMIT_DIMS (c)
+	= thread_limit_clauses->thread_limit_dims;
+      tree_tgt_clauses = gfc_trans_add_clause (c, tree_tgt_clauses);
+      tree_teams_clauses = gfc_trans_add_clause (unshare_expr (c),
+						 tree_teams_clauses);
+      gfc_free_expr_list (thread_limit_clauses->thread_limit_list);
+      thread_limit_clauses->thread_limit_list = NULL;
+      gfc_free_expr_list (code->ext.omp_clauses->thread_limit_list);
+      code->ext.omp_clauses->thread_limit_list = NULL;
+    }
+  if ((teams_clauses && teams_clauses->dyn_groupprivate)
+      || (combined_teams_dir && code->ext.omp_clauses->dyn_groupprivate))
+    {
+      /* dyn_groupprivate can be put on target and on teams, use the team one as
+	 having higher precedence.  */
+      gfc_omp_clauses *dyn_gp_clauses
+	= (teams_clauses && teams_clauses->dyn_groupprivate
+	   ? teams_clauses : code->ext.omp_clauses);
+      gfc_omp_clauses tmp = {};
+      tmp.dyn_groupprivate = dyn_gp_clauses->dyn_groupprivate;
+      tmp.fallback = dyn_gp_clauses->fallback;
+      tree c = gfc_trans_omp_clauses (&block, &tmp, code->loc);
+      if (DECL_P (OMP_CLAUSE_DYN_GROUPPRIVATE_EXPR (c)))
+	{
+	  tree c2;
+	  OMP_CLAUSE_DYN_GROUPPRIVATE_EXPR (c)
+	    = gfc_evaluate_now (OMP_CLAUSE_DYN_GROUPPRIVATE_EXPR (c), &block);
+	  c2 = build_omp_clause (OMP_CLAUSE_LOCATION (c),
+				 OMP_CLAUSE_FIRSTPRIVATE);
+	  OMP_CLAUSE_DECL (c2) = OMP_CLAUSE_DYN_GROUPPRIVATE_EXPR (c);
+	  tree_tgt_clauses = gfc_trans_add_clause (c2, tree_tgt_clauses);
+	}
+      tree_tgt_clauses = gfc_trans_add_clause (c, tree_tgt_clauses);
+      tree_teams_clauses = gfc_trans_add_clause (unshare_expr (c),
+						 tree_teams_clauses);
+      gfc_free_expr (dyn_gp_clauses->dyn_groupprivate);
+      dyn_gp_clauses->dyn_groupprivate = NULL;
+      gfc_free_expr (code->ext.omp_clauses->dyn_groupprivate);
+      code->ext.omp_clauses->dyn_groupprivate = NULL;
+    }
+  /* FIXME: also 'if' and 'allocate' are target consistent.  */
+
   gfc_split_omp_clauses (code, clausesa);
   if (flag_openmp)
     omp_clauses
-      = gfc_trans_omp_clauses (&block, &clausesa[GFC_OMP_SPLIT_TARGET],
-			       code->loc);
+      = chainon (gfc_trans_omp_clauses (&block, &clausesa[GFC_OMP_SPLIT_TARGET],
+					code->loc), tree_tgt_clauses);
   switch (code->op)
     {
     case EXEC_OMP_TARGET:
       pushlevel ();
-      stmt = gfc_trans_omp_code (code->block->next, true);
+      if (tree_teams_clauses)
+	{
+	  gfc_code *code2 = code->block->next;
+	  if (code2->op == EXEC_BLOCK)
+	    {
+	      gcc_checking_assert (!code2->ext.block.ns->sym_root->left
+				   && !code2->ext.block.ns->sym_root->right);
+	      code2 = code2->ext.block.ns->code;
+	    }
+	  gcc_checking_assert (code2->next == NULL);
+	  stmt = gfc_trans_omp_teams (code2, clausesa, tree_teams_clauses);
+	}
+      else
+	stmt = gfc_trans_omp_code (code->block->next, true);
       stmt = build3_v (BIND_EXPR, NULL, stmt, poplevel (1, 0));
       break;
     case EXEC_OMP_TARGET_PARALLEL:
@@ -9464,38 +9645,8 @@  gfc_trans_omp_target (gfc_code *code)
 	poplevel (0, 0);
       break;
     default:
-      if (flag_openmp
-	  && (clausesa[GFC_OMP_SPLIT_TEAMS].num_teams_list
-	      || clausesa[GFC_OMP_SPLIT_TEAMS].thread_limit_list))
-	{
-	  gfc_omp_clauses clausesb;
-	  tree teams_clauses;
-	  /* For combined !$omp target teams, the num_teams and
-	     thread_limit clauses are evaluated before entering the
-	     target construct.  */
-	  memset (&clausesb, '\0', sizeof (clausesb));
-	  clausesb.num_teams_list
-	    = clausesa[GFC_OMP_SPLIT_TEAMS].num_teams_list;
-	  clausesb.num_teams_dims
-	    = clausesa[GFC_OMP_SPLIT_TEAMS].num_teams_dims;
-	  clausesb.thread_limit_list
-	    = clausesa[GFC_OMP_SPLIT_TEAMS].thread_limit_list;
-	  clausesb.thread_limit_strict
-	    = clausesa[GFC_OMP_SPLIT_TEAMS].thread_limit_strict;
-	  clausesb.thread_limit_dims
-	    = clausesa[GFC_OMP_SPLIT_TEAMS].thread_limit_dims;
-	  clausesa[GFC_OMP_SPLIT_TEAMS].num_teams_list = NULL;
-	  clausesa[GFC_OMP_SPLIT_TEAMS].thread_limit_list = NULL;
-	  teams_clauses
-	    = gfc_trans_omp_clauses (&block, &clausesb, code->loc);
-	  pushlevel ();
-	  stmt = gfc_trans_omp_teams (code, clausesa, teams_clauses);
-	}
-      else
-	{
-	  pushlevel ();
-	  stmt = gfc_trans_omp_teams (code, clausesa, NULL_TREE);
-	}
+      pushlevel ();
+      stmt = gfc_trans_omp_teams (code, clausesa, tree_teams_clauses);
       if (TREE_CODE (stmt) != BIND_EXPR)
 	stmt = build3_v (BIND_EXPR, NULL, stmt, poplevel (1, 0));
       else
diff --git a/gcc/gimplify.cc b/gcc/gimplify.cc
index 94d71d71fc2..d521bda8186 100644
--- a/gcc/gimplify.cc
+++ b/gcc/gimplify.cc
@@ -18790,6 +18790,12 @@  computable_teams_clause (tree *tp, int *walk_subtrees, void *)
 static void
 optimize_target_teams (tree target, gimple_seq *pre_p)
 {
+  /* If the NUM_TEAMS clause is on TARGET, assume that the front end already
+     took care of the target-consistent clauses.  Note that user code cannot
+     specify 'num_teams' on 'target', only on 'teams'.  */
+  if (omp_find_clause (OMP_TARGET_CLAUSES (target), OMP_CLAUSE_NUM_TEAMS))
+    return;
+
   tree body = OMP_BODY (target);
   tree teams = walk_tree (&body, find_omp_teams, NULL, NULL);
   tree num_teams_lower = NULL_TREE;
diff --git a/gcc/omp-general.cc b/gcc/omp-general.cc
index 9162972dc88..0a65108b616 100644
--- a/gcc/omp-general.cc
+++ b/gcc/omp-general.cc
@@ -3982,6 +3982,8 @@  omp_runtime_api_procname (const char *name)
       "calloc",
       "free",
       "get_device_distances",
+      "get_device_num_teams",
+      "get_device_teams_thread_limit",
       "get_interop_int",
       "get_interop_ptr",
       "get_mapped_ptr",
@@ -3994,6 +3996,8 @@  omp_runtime_api_procname (const char *name)
       "get_thread_limit_dim",
       "get_thread_num_dim",
       "realloc",
+      "set_device_num_teams",
+      "set_device_teams_thread_limit",
       "target_alloc",
       "target_associate_ptr",
       "target_disassociate_ptr",
diff --git a/gcc/testsuite/gfortran.dg/gomp/spatial-dimensions-1.f90 b/gcc/testsuite/gfortran.dg/gomp/spatial-dimensions-1.f90
index 6e000cb49c4..83d3201a215 100644
--- a/gcc/testsuite/gfortran.dg/gomp/spatial-dimensions-1.f90
+++ b/gcc/testsuite/gfortran.dg/gomp/spatial-dimensions-1.f90
@@ -165,7 +165,7 @@  end subroutine
 ! { dg-final { scan-tree-dump-times "#pragma omp parallel num_threads\\(strict:2\\) shared\\(x\\)" 1 "gimple" } }
 ! { dg-final { scan-tree-dump-times "#pragma omp teams num_teams\\(1234\\) thread_limit\\(2345\\) shared\\(x\\)" 1 "gimple" } }
 ! { dg-final { scan-tree-dump-times "#pragma omp parallel num_threads\\(3456\\) shared\\(x\\)" 1 "gimple" } }
-! { dg-final { scan-tree-dump-times "#pragma omp teams num_teams\\(123, 456\\) shared\\(x\\)" 1 "gimple" } }
+! { dg-final { scan-tree-dump-times "#pragma omp teams num_teams\\(123:456\\) shared\\(x\\)" 1 "gimple" } }
 ! { dg-final { scan-tree-dump-times "#pragma omp teams num_teams\\(4567\\) thread_limit\\(5678\\) shared\\(x\\)" 1 "gimple" } }
 ! { dg-final { scan-tree-dump-times "#pragma omp parallel num_threads\\(6789\\) shared\\(x\\)" 1 "gimple" } }
 ! { dg-final { scan-tree-dump-times "#pragma omp parallel num_threads\\(1, 2, 3\\) shared\\(x\\)" 1 "gimple" } }
diff --git a/gcc/testsuite/gfortran.dg/gomp/spatial-dimensions-4.f90 b/gcc/testsuite/gfortran.dg/gomp/spatial-dimensions-4.f90
index 3abca5248f3..f71cef119c0 100644
--- a/gcc/testsuite/gfortran.dg/gomp/spatial-dimensions-4.f90
+++ b/gcc/testsuite/gfortran.dg/gomp/spatial-dimensions-4.f90
@@ -15,6 +15,18 @@  subroutine sub(x)
 implicit none
 integer :: x, i
 
+!     #pragma omp target num_teams(-2) thread_limit(11) firstprivate(x) [child fn: sub_._omp_fn.0 ({.omp_data_arr.19, .omp_data_sizes.20, .omp_data_kinds.21})]
+!    #pragma omp target num_teams(-2) thread_limit(dims():22) map(tofrom:i [len: 4] [runtime_implicit]) firstprivate(x) [child fn: sub_._omp_fn.1 ({.omp_data_arr.24, .omp_data_sizes.25, .omp_data_kinds.26})]
+!    #pragma omp target thread_limit(41) num_teams(dims():43) map(tofrom:i [len: 4] [runtime_implicit]) firstprivate(x) [child fn: sub_._omp_fn.4 ({.omp_data_arr.33, .omp_data_sizes.34, .omp_data_kinds.35})]
+!          #pragma omp teams thread_limit(41) num_teams(dims():43) shared(i) shared(x)
+!    #pragma omp teams num_teams(dims():53) thread_limit(51)
+!    #pragma omp teams num_teams(dims():63) thread_limit(61) shared(i) shared(x)
+!    #pragma omp teams num_teams(1:93) thread_limit(91) shared(x)
+!    #pragma omp target thread_limit(991) num_teams(191:993) firstprivate(x) [child fn: sub_._omp_fn.12 ({.omp_data_arr.42, .omp_data_sizes.43, .omp_data_kinds.44})]
+!          #pragma omp teams thread_limit(991) num_teams(191:993) shared(x)
+
+
+
 !$omp target thread_limit(relaxed : 11)
 block
   x = 1
@@ -32,17 +44,16 @@  end do
 block
   x = 1
 end block
-! { dg-final { scan-tree-dump-times "#pragma omp target num_teams\\(-1\\) thread_limit\\(31\\) firstprivate\\(x\\) \\\[child fn" 1 "omplower" } }
-! { dg-final { scan-tree-dump-times "#pragma omp teams num_teams\\(dims\\(\\):33\\) thread_limit\\(31\\) shared\\(x\\)" 1 "omplower" } }
+! { dg-final { scan-tree-dump-times "#pragma omp target thread_limit\\(31\\) num_teams\\(dims\\(\\):33\\) firstprivate\\(x\\) \\\[child fn" 1 "omplower" } }
+! { dg-final { scan-tree-dump-times "#pragma omp teams thread_limit\\(31\\) num_teams\\(dims\\(\\):33\\) shared\\(x\\)" 1 "omplower" } }
 ! { dg-final { scan-tree-dump-times "__builtin_GOMP_teams4 \\(33, 33, 31, D.\[0-9]+\\);" 1 "ompexp" } }
 
-
 !$omp target teams distribute parallel do simd thread_limit(relaxed : 41) num_teams(dims(1) : 43) num_threads( dims ( 1 ) , relaxed : 44)
 do i = 1, 1
   x = 1
 end do
-! { dg-final { scan-tree-dump-times "#pragma omp target num_teams\\(-1\\) thread_limit\\(41\\) map\\(tofrom:i \\\[len: 4\\\] \\\[runtime_implicit\\\]\\) firstprivate\\(x\\) \\\[child fn" 1 "omplower" } }
-! { dg-final { scan-tree-dump-times "#pragma omp teams num_teams\\(dims\\(\\):43\\) thread_limit\\(41\\) shared\\(i\\) shared\\(x\\)" 1 "omplower" } }
+! { dg-final { scan-tree-dump-times "#pragma omp target thread_limit\\(41\\) num_teams\\(dims\\(\\):43\\) map\\(tofrom:i \\\[len: 4\\\] \\\[runtime_implicit\\\]\\) firstprivate\\(x\\) \\\[child fn" 1 "omplower" } }
+! { dg-final { scan-tree-dump-times "#pragma omp teams thread_limit\\(41\\) num_teams\\(dims\\(\\):43\\) shared\\(i\\) shared\\(x\\)" 1 "omplower" } }
 ! { dg-final { scan-tree-dump-times "#pragma omp parallel _looptemp_\\(D.\[0-9\]+\\) _looptemp_\\(D.\[0-9\]+\\) num_threads\\(dims\\(\\):44\\) lastprivate\\(i\\) shared\\(x\\) \\\[child fn" 1 "omplower" } }
 ! { dg-final { scan-tree-dump-times "__builtin_GOMP_parallel \\(sub_._omp_fn.\[0-9]+, &.omp_data_o.\[0-9]+, 44, 0\\);" 1 "ompexp" } }
 
@@ -80,15 +91,15 @@  end block
 block
   x = 1
 end block
-! { dg-final { scan-tree-dump-times "#pragma omp teams num_teams\\(1, 93\\) thread_limit\\(91\\) shared\\(x\\)" 1 "omplower" } }
+! { dg-final { scan-tree-dump-times "#pragma omp teams num_teams\\(1:93\\) thread_limit\\(91\\) shared\\(x\\)" 1 "omplower" } }
 ! { dg-final { scan-tree-dump-times "__builtin_GOMP_teams_reg \\(sub_._omp_fn.\[0-9\]+, &.omp_data_o.\[0-9\]+, 93, 91, 0\\);" 1 "ompexp" } }
 
 !$omp target teams thread_limit(relaxed : 991) num_teams(191 : 993)
 block
   x = 1
 end block
-! { dg-final { scan-tree-dump-times "#pragma omp target num_teams\\(-1\\) thread_limit\\(991\\) firstprivate\\(x\\) \\\[child fn" 1 "omplower" } }
-! { dg-final { scan-tree-dump-times "#pragma omp teams num_teams\\(191, 993\\) thread_limit\\(991\\) shared\\(x\\)" 1 "omplower" } }
+! { dg-final { scan-tree-dump-times "#pragma omp target thread_limit\\(991\\) num_teams\\(191:993\\) firstprivate\\(x\\) \\\[child fn" 1 "omplower" } }
+! { dg-final { scan-tree-dump-times "#pragma omp teams thread_limit\\(991\\) num_teams\\(191:993\\) shared\\(x\\)" 1 "omplower" } }
 
 !$omp teams thread_limit(relaxed : 1231) message("my1234")
 block
diff --git a/gcc/testsuite/gfortran.dg/gomp/spatial-dimensions-5.f90 b/gcc/testsuite/gfortran.dg/gomp/spatial-dimensions-5.f90
index 9cde28a76ef..f43678f8ae0 100644
--- a/gcc/testsuite/gfortran.dg/gomp/spatial-dimensions-5.f90
+++ b/gcc/testsuite/gfortran.dg/gomp/spatial-dimensions-5.f90
@@ -9,8 +9,8 @@  integer :: x, i
 do i = 1,1
   x = 0
 end do
-! { dg-final { scan-tree-dump-times "#pragma omp target num_teams\\(-1\\) message\\(.first. \\\[len:5\\\]\\) severity\\(fatal\\) thread_limit\\(strict,dims\\(\\):11, 12, 13\\) firstprivate\\(x\\)" 1 "gimple" } }
-! { dg-final { scan-tree-dump-times "#pragma omp teams num_teams\\(11, 22\\) thread_limit\\(strict,dims\\(\\):11, 12, 13\\) message\\(.first. \\\[len:5\\\]\\) severity\\(fatal\\) shared\\(x\\)" 1 "gimple" } }
+! { dg-final { scan-tree-dump-times "#pragma omp target message\\(.first. \\\[len:5\\\]\\) severity\\(fatal\\) thread_limit\\(strict,dims\\(\\):11, 12, 13\\) num_teams\\(11:22\\) firstprivate\\(x\\)" 1 "gimple" } }
+! { dg-final { scan-tree-dump-times "#pragma omp teams thread_limit\\(strict,dims\\(\\):11, 12, 13\\) num_teams\\(11:22\\) message\\(.first. \\\[len:5\\\]\\) severity\\(fatal\\) shared\\(x\\)" 1 "gimple" } }
 ! { dg-final { scan-tree-dump-times "#pragma omp parallel message\\(.first. \\\[len:5\\\]\\) severity\\(warning\\) num_threads\\(23, 45, 53\\) shared\\(x\\)" 1 "gimple" } }
 end
 
@@ -27,15 +27,15 @@  integer :: x, i
 do i = 1,1
   x = 0
 end do
-! { dg-final { scan-tree-dump-times "#pragma omp target num_teams\\(-1\\) message\\(.second. \\\[len:6\\\]\\) severity\\(fatal\\) thread_limit\\(11\\) firstprivate\\(x\\)" 1 "gimple" } }
-! { dg-final { scan-tree-dump-times "#pragma omp teams num_teams\\(dims\\(\\):111, 222, 333, 324\\) thread_limit\\(11\\) message\\(.second. \\\[len:6\\\]\\) severity\\(fatal\\) shared\\(x\\)" 1 "gimple" } }
+! { dg-final { scan-tree-dump-times "#pragma omp target message\\(.second. \\\[len:6\\\]\\) severity\\(fatal\\) thread_limit\\(11\\) num_teams\\(dims\\(\\):111, 222, 333, 324\\) firstprivate\\(x\\)" 1 "gimple" } }
+! { dg-final { scan-tree-dump-times "#pragma omp teams thread_limit\\(11\\) num_teams\\(dims\\(\\):111, 222, 333, 324\\) message\\(.second. \\\[len:6\\\]\\) severity\\(fatal\\) shared\\(x\\)" 1 "gimple" } }
 ! { dg-final { scan-tree-dump-times "#pragma omp parallel message\\(.second. \\\[len:6\\\]\\) severity\\(fatal\\) num_threads\\(strict:445, 553\\) shared\\(x\\)" 1 "gimple" } }
 
 !$omp teams distribute parallel do num_teams(11 : 55) thread_limit(strict : 11) num_threads(relaxed: 23,45,53) message("third") severity(warning)
 do i = 1,1
   x = 0
 end do
-! { dg-final { scan-tree-dump-times "#pragma omp teams message\\(.third. \\\[len:5\\\]\\) severity\\(fatal\\) num_teams\\(11, 55\\) thread_limit\\(strict:11\\) shared\\(x\\)" 1 "gimple" } }
+! { dg-final { scan-tree-dump-times "#pragma omp teams message\\(.third. \\\[len:5\\\]\\) severity\\(fatal\\) num_teams\\(11:55\\) thread_limit\\(strict:11\\) shared\\(x\\)" 1 "gimple" } }
 ! { dg-final { scan-tree-dump-times "#pragma omp parallel message\\(.third. \\\[len:5\\\]\\) severity\\(warning\\) num_threads\\(23, 45, 53\\) shared\\(x\\)" 1 "gimple" } }
 
 !$omp teams distribute parallel do num_teams(dims(2): 1111,33) thread_limit(dims(3) : 11,3,480) num_threads(strict, dims(2): 445,553) message("fourth") severity(fatal)
@@ -61,7 +61,7 @@  end block
 block
   x = 0
 end block
-! { dg-final { scan-tree-dump-times "#pragma omp teams message\\(.teams. \\\[len:5\\\]\\) severity\\(fatal\\) num_teams\\(14, 34\\) shared\\(x\\)" 1 "gimple" } }
+! { dg-final { scan-tree-dump-times "#pragma omp teams message\\(.teams. \\\[len:5\\\]\\) severity\\(fatal\\) num_teams\\(14:34\\) shared\\(x\\)" 1 "gimple" } }
 
 !$omp teams thread_limit(relaxed, dims(2): 514 , 384)
 block
diff --git a/libgomp/icv-device.c b/libgomp/icv-device.c
index 4cf464be8f5..07ab0c23923 100644
--- a/libgomp/icv-device.c
+++ b/libgomp/icv-device.c
@@ -113,6 +113,9 @@  omp_get_teams_thread_limit (void)
 
 ialias (omp_get_teams_thread_limit)
 
+/* Accepts thread_limits = 0 [which is well defined to mean implementation
+   defined], even though only positive values are permitted.  */
+
 void
 omp_set_teams_thread_limit (int thread_limit)
 {
diff --git a/libgomp/libgomp.map b/libgomp/libgomp.map
index 19890c05c76..68e10d5bb7d 100644
--- a/libgomp/libgomp.map
+++ b/libgomp/libgomp.map
@@ -245,6 +245,10 @@  OMP_6.0 {
 	omp_control_tool;
 	omp_control_tool_;
 	omp_control_tool_8_;
+	omp_get_device_num_teams;
+	omp_get_device_teams_thread_limit;
+	omp_set_device_num_teams;
+	omp_set_device_teams_thread_limit;
 } OMP_5.2;
 
 OMP_6.1 {
diff --git a/libgomp/libgomp.texi b/libgomp/libgomp.texi
index c276b4a0a2d..c070b37dd9c 100644
--- a/libgomp/libgomp.texi
+++ b/libgomp/libgomp.texi
@@ -605,7 +605,7 @@  to address of matching mapped list item per 5.1, Sect. 2.21.7.2 @tab N @tab
       @tab Y @tab
 @item @code{omp_get_device_num_teams}, @code{omp_set_device_num_teams},
       @code{omp_get_device_teams_thread_limit}, and
-      @code{omp_set_device_teams_thread_limit} routines @tab N @tab
+      @code{omp_set_device_teams_thread_limit} routines @tab Y @tab
 @item @code{omp_target_memset} and @code{omp_target_memset_async} routines
       @tab Y @tab
 @item Fortran version of the interop runtime routines @tab Y @tab
@@ -869,7 +869,8 @@  that does not use the clause @code{num_threads}.
 @end multitable
 
 @item @emph{See also}:
-@ref{omp_set_num_threads}, @ref{omp_set_dynamic}, @ref{omp_get_thread_limit}
+@ref{omp_set_num_threads}, @ref{omp_set_dynamic}, @ref{omp_get_thread_limit},
+@ref{omp_get_teams_thread_limit}
 
 @item @emph{Reference}:
 @uref{https://www.openmp.org, OpenMP specification v4.5}, Section 3.2.3.
@@ -1182,7 +1183,8 @@  each team created by a teams construct.
 @end multitable
 
 @item @emph{See also}:
-@ref{omp_set_teams_thread_limit}, @ref{OMP_TEAMS_THREAD_LIMIT}
+@ref{omp_set_teams_thread_limit}, @ref{OMP_TEAMS_THREAD_LIMIT},
+@ref{omp_get_device_teams_thread_limit}
 
 @item @emph{Reference}:
 @uref{https://www.openmp.org, OpenMP specification v5.1}, Section 3.4.6.
@@ -1453,7 +1455,8 @@  region.  They have C linkage and do not throw exceptions.
 @subsection @code{omp_get_num_teams} -- Number of teams
 @table @asis
 @item @emph{Description}:
-Returns the number of teams in the current team region.
+Returns the number of teams in the current team region and one if not inside
+a teams region.
 
 @item @emph{C/C++}:
 @multitable @columnfractions .20 .80
@@ -1466,7 +1469,8 @@  Returns the number of teams in the current team region.
 @end multitable
 
 @item @emph{See also}:
-@ref{omp_get_num_teams_dim}, @ref{OMP_NUM_TEAMS}, @ref{omp_get_team_num}
+@ref{omp_get_num_teams_dim}, @ref{OMP_NUM_TEAMS}, @ref{omp_get_team_num},
+@ref{omp_get_device_num_teams}
 
 @item @emph{Reference}:
 @uref{https://www.openmp.org, OpenMP specification v4.5}, Section 3.2.32.
@@ -1505,7 +1509,9 @@  Returns the team number of the calling thread.
 @item @emph{Description}:
 Specifies the upper bound for number of teams created by the teams construct
 which does not specify a @code{num_teams} clause.  The
-argument of @code{omp_set_num_teams} shall be a positive integer.
+argument of @code{omp_set_num_teams} shall be a non-negative integer; the value
+zero implies an implementation defined value of at least one.  This
+routine may only be called on the host.
 
 @item @emph{C/C++}:
 @multitable @columnfractions .20 .80
@@ -1519,7 +1525,8 @@  argument of @code{omp_set_num_teams} shall be a positive integer.
 @end multitable
 
 @item @emph{See also}:
-@ref{OMP_NUM_TEAMS}, @ref{omp_get_num_teams}, @ref{omp_get_max_teams}
+@ref{OMP_NUM_TEAMS}, @ref{omp_get_num_teams}, @ref{omp_get_max_teams},
+@ref{omp_set_device_num_teams}
 
 @item @emph{Reference}:
 @uref{https://www.openmp.org, OpenMP specification v5.1}, Section 3.4.3.
@@ -1574,7 +1581,8 @@  for each team created by the teams construct which does not specify a
 @end multitable
 
 @item @emph{See also}:
-@ref{OMP_TEAMS_THREAD_LIMIT}, @ref{omp_get_teams_thread_limit}, @ref{omp_get_thread_limit}
+@ref{OMP_TEAMS_THREAD_LIMIT}, @ref{omp_get_teams_thread_limit}, @ref{omp_get_thread_limit},
+@ref{omp_set_device_teams_thread_limit}
 
 @item @emph{Reference}:
 @uref{https://www.openmp.org, OpenMP specification v5.1}, Section 3.4.5.
@@ -2158,10 +2166,10 @@  They have C linkage and do not throw exceptions.
 * omp_get_uid_from_device::     Obtain the unique id of a device
 * omp_is_initial_device::       Whether executing on the host device
 * omp_get_initial_device::      Device number of host device
-@c * omp_get_device_num_teams::  <fixme>/TR13
-@c * omp_set_device_num_teams::  <fixme>/TR13
-@c * omp_get_device_teams_thread_limit::  <fixme>/TR13
-@c * omp_set_device_teams_thread_limit::  <fixme>/TR13
+* omp_get_device_num_teams::    Number of teams of a device
+* omp_set_device_num_teams::    Set upper teams limit on a device
+* omp_get_device_teams_thread_limit:: Get upper thread limit of a device
+* omp_set_device_teams_thread_limit:: Set upper thread limit of a device
 * omp_get_device_distances:: Obtain the NUMA distance of a device
 @end menu
 
@@ -2441,6 +2449,147 @@  to @code{omp_initial_device}; and otherwise it is replaced with a call to
 @end table
 
 
+
+@node omp_get_device_num_teams
+@subsection @code{omp_get_device_num_teams} -- Number of teams of a device
+@table @asis
+@item @emph{Description}:
+Returns the value of the @emph{nteams-var} ICV for the specified device number,
+which is used to determine the number of teams for a @code{teams} region on
+the device specified by the @var{device_num} argument, unless overridden by
+a @code{num_teams} clause on the construct.  If the @var{device_num} argument
+denotes the host device, the routine returns the same value as
+@code{omp_get_num_teams}.  If the @var{device_num} argument specifies a
+non-conforming device number or @code{omp_invalid_device}, the value zero is
+returned.  Invoking this routine on a non-host device has unspecified behavior.
+
+@item @emph{C/C++}:
+@multitable @columnfractions .20 .80
+@item @emph{Prototype}: @tab @code{int omp_get_device_num_teams(int device_num)}
+@end multitable
+
+@item @emph{Fortran}:
+@multitable @columnfractions .20 .80
+@item @emph{Interface}: @tab @code{integer function omp_get_device_num_teams(device_num)}
+@item                   @tab @code{integer, intent(in) :: device_num}
+@end multitable
+
+@item @emph{See also}:
+@ref{omp_set_device_num_teams}. @ref{omp_get_num_teams},
+@ref{omp_get_num_teams_dim}, @ref{OMP_NUM_TEAMS},
+
+@item @emph{Reference}:
+@uref{https://www.openmp.org, OpenMP specification v6.0}, Section 24.11
+@end table
+
+
+
+@node omp_set_device_num_teams
+@subsection @code{omp_set_device_num_teams} -- Set upper teams limit on a device
+@table @asis
+@item @emph{Description}:
+Sets the value of the @emph{nteams-var} ICV for the specified device number, which
+specifies the upper bound for number of teams created by a @code{teams} construct
+on the device specified by the @var{device_num} argument; this value is used if
+no @code{num_teams} clause is specified on the @code{teams} directive.  The
+@var{num_teams} argument shall be a non-negative integer; the value zero implies
+an implementation defined value of at least one.  If the @var{device_num} argument
+denotes the host device, the routine is identical to the @code{omp_set_num_teams}
+routine.  The @var{device_num} argument must be a conforming device number other
+than @code{omp_invalid_device}, else error termination is performed.  Invoking
+this routine on a non-host device has unspecified behavior.
+
+@item @emph{C/C++}:
+@multitable @columnfractions .20 .80
+@item @emph{Prototype}: @tab @code{void omp_set_device_num_teams(int num_teams, int device_num)}
+@end multitable
+
+@item @emph{Fortran}:
+@multitable @columnfractions .20 .80
+@item @emph{Interface}: @tab @code{subroutine omp_set_device_num_teams(num_teams, device_num)}
+@item                   @tab @code{integer, intent(in) :: num_teams, device_num}
+@end multitable
+
+@item @emph{See also}:
+@ref{omp_get_device_num_teams}, @ref{omp_set_num_teams}, @ref{omp_get_num_teams},
+@ref{omp_get_max_teams}, @ref{omp_get_supported_teams_dim}, @ref{OMP_NUM_TEAMS}
+
+@item @emph{Reference}:
+@uref{https://www.openmp.org, OpenMP specification v6.0}, Section 24.12
+@end table
+
+
+
+@node omp_get_device_teams_thread_limit
+@subsection @code{omp_get_device_teams_thread_limit} -- Get upper thread limit of a device
+@table @asis
+@item @emph{Description}:
+Returns the value of the @emph{teams-thread-limit-var} ICV for the specified
+device number, which is used to limits the number of threads that participate
+in each team created by a @code{teams} construct.  If the @var{device_num} argument
+denotes the host device, the routine returns the same value as
+@code{omp_get_teams_thread_limit}.  If the @var{device_num} argument specifies a
+non-conforming device number or @code{omp_invalid_device}, the value zero is
+returned.  Invoking this routine on a non-host device has unspecified behavior.
+
+@item @emph{C/C++}:
+@multitable @columnfractions .20 .80
+@item @emph{Prototype}: @tab @code{int omp_get_device_teams_thread_limit(int device_num)}
+@end multitable
+
+@item @emph{Fortran}:
+@multitable @columnfractions .20 .80
+@item @emph{Interface}: @tab @code{integer function omp_get_device_teams_thread_limit(device_num)}
+@item                   @tab @code{integer, intent(in) :: device_num}
+@end multitable
+
+@item @emph{See also}:
+@ref{omp_get_device_teams_thread_limit}, @ref{omp_get_teams_thread_limit},
+@ref{OMP_TEAMS_THREAD_LIMIT}, @ref{OMP_THREAD_LIMIT}
+
+@item @emph{Reference}:
+@uref{https://www.openmp.org, OpenMP specification v6.0}, Section 24.13
+@end table
+
+
+
+@node omp_set_device_teams_thread_limit
+@subsection @code{omp_set_device_teams_thread_limit} -- Set upper thread limit of a device
+@table @asis
+@item @emph{Description}:
+Sets the value of the @emph{teams-thread-limit-var} ICV for the specified device
+number, which specifies the upper bound for number of teams created by a
+@code{teams} construct on the device specified by the @var{device_num} argument.
+The @var{thread_limit} argument shall be positive integer.  If the @var{device_num}
+argument denotes the host device, the routine is identical to the
+@code{omp_set_teams_thread_limit} routine.  The @var{device_num} argument must be a
+conforming device number other than @code{omp_invalid_device}, else error
+termination is performed.  Invoking this routine on a non-host device has
+unspecified behavior.
+
+@item @emph{C/C++}:
+@multitable @columnfractions .20 .80
+@item @emph{Prototype}: @tab @code{void omp_set_device_teams_thread_limit(int thread_limit, device_num)}
+@end multitable
+
+@item @emph{Fortran}:
+@multitable @columnfractions .20 .80
+@item @emph{Interface}: @tab @code{subroutine omp_set_device_teams_thread_limit(thread_limit, device_num)}
+@item                   @tab @code{integer, intent(in) :: thread_limit, device_num}
+@end multitable
+
+@item @emph{See also}:
+@ref{omp_get_device_teams_thread_limit}, @ref{omp_set_teams_thread_limit},
+@ref{omp_get_teams_thread_limit},
+@ref{omp_get_thread_limit}, @ref{omp_get_supported_threads_dim},
+@ref{OMP_TEAMS_THREAD_LIMIT}, @ref{OMP_THREAD_LIMIT}
+
+@item @emph{Reference}:
+@uref{https://www.openmp.org, OpenMP specification v6.0}, Section 24.14
+@end table
+
+
+
 @node omp_get_device_distances
 @subsection @code{omp_get_device_distances} -- Obtain the NUMA distance of a device
 @table @asis
@@ -5007,7 +5156,7 @@  be a positive integer.  If undefined it defaults to 0 which means
 implementation defined upper bound.
 
 @item @emph{See also}:
-@ref{omp_set_num_teams}
+@ref{omp_set_num_teams}, @ref{omp_set_device_num_teams}
 
 @item @emph{Reference}: 
 @uref{https://www.openmp.org, OpenMP specification v5.1}, Section 6.23
@@ -5226,7 +5375,8 @@  the value of 0 is used which stands for an implementation defined upper
 limit.
 
 @item @emph{See also}:
-@ref{OMP_THREAD_LIMIT}, @ref{omp_set_teams_thread_limit}
+@ref{OMP_THREAD_LIMIT}, @ref{omp_set_teams_thread_limit},
+@ref{omp_set_device_teams_thread_limit}
 
 @item @emph{Reference}: 
 @uref{https://www.openmp.org, OpenMP specification v5.1}, Section 6.24
diff --git a/libgomp/omp.h.in b/libgomp/omp.h.in
index 6ffec871fd0..1f7b12ea710 100644
--- a/libgomp/omp.h.in
+++ b/libgomp/omp.h.in
@@ -342,6 +342,7 @@  extern int omp_get_num_devices (void) __GOMP_NOTHROW;
 extern int omp_get_device_num (void) __GOMP_NOTHROW;
 extern int omp_get_num_teams (void) __GOMP_NOTHROW;
 extern int omp_get_num_teams_dim (int) __GOMP_NOTHROW;
+extern int omp_get_device_num_teams (int) __GOMP_NOTHROW;
 extern int omp_get_team_num (void) __GOMP_NOTHROW;
 extern int omp_get_team_num_dim (int) __GOMP_NOTHROW;
 
@@ -355,9 +356,12 @@  extern __SIZE_TYPE__ omp_get_gprivate_limit (int,
 extern void omp_fulfill_event (omp_event_handle_t) __GOMP_NOTHROW;
 
 extern void omp_set_num_teams (int) __GOMP_NOTHROW;
+extern void omp_set_device_num_teams (int, int) __GOMP_NOTHROW;
 extern int omp_get_max_teams (void) __GOMP_NOTHROW;
 extern void omp_set_teams_thread_limit (int) __GOMP_NOTHROW;
+extern void omp_set_device_teams_thread_limit (int, int) __GOMP_NOTHROW;
 extern int omp_get_teams_thread_limit (void) __GOMP_NOTHROW;
+extern int omp_get_device_teams_thread_limit (int) __GOMP_NOTHROW;
 
 extern void *omp_target_alloc (__SIZE_TYPE__, int) __GOMP_NOTHROW;
 extern void omp_target_free (void *, int) __GOMP_NOTHROW;
diff --git a/libgomp/omp_lib.f90.in b/libgomp/omp_lib.f90.in
index 598ae10fbdf..8641607bfd9 100644
--- a/libgomp/omp_lib.f90.in
+++ b/libgomp/omp_lib.f90.in
@@ -476,6 +476,15 @@ 
           end function omp_get_thread_limit_dim
         end interface
 
+        interface
+          ! Use bind(C) for simplicity; will fail with default-kind-8 integer
+          function omp_get_device_teams_thread_limit (device_num) bind(C)
+            use iso_c_binding, only: c_int
+            integer (c_int), value :: device_num
+            integer (c_int) :: omp_get_device_teams_thread_limit
+          end function omp_get_device_teams_thread_limit
+        end interface
+
         interface omp_set_max_active_levels
           subroutine omp_set_max_active_levels (max_levels)
             integer (4), intent (in) :: max_levels
@@ -644,6 +653,15 @@ 
           end function omp_get_num_teams_dim
         end interface
 
+        interface
+          ! Use bind(C) for simplicity; will fail with default-kind-8 integer
+          function omp_get_device_num_teams (device_num) bind(C)
+            use iso_c_binding, only: c_int
+            integer (c_int), value :: device_num
+            integer (c_int) :: omp_get_device_num_teams
+          end function omp_get_device_num_teams
+        end interface
+
         interface
           function omp_get_team_num ()
             integer (4) :: omp_get_team_num
@@ -692,6 +710,14 @@ 
           end subroutine omp_set_num_teams_8
         end interface
 
+        interface
+          ! Use bind(C) for simplicity; will fail with default-kind-8 integer
+          subroutine omp_set_device_num_teams (num_teams, device_num) bind(C)
+            use iso_c_binding, only: c_int
+            integer (c_int), value, intent (in) :: num_teams, device_num
+          end subroutine omp_set_device_num_teams
+        end interface
+
         interface
           function omp_get_max_teams ()
             integer (4) :: omp_get_max_teams
@@ -707,6 +733,15 @@ 
           end subroutine omp_set_teams_thread_limit_8
         end interface
 
+        interface
+          ! Use bind(C) for simplicity; will fail with default-kind-8 integer
+          subroutine omp_set_device_teams_thread_limit (thread_limit, device_num) &
+              bind(C)
+            use iso_c_binding, only: c_int
+            integer (c_int), value, intent (in) :: thread_limit, device_num
+          end subroutine omp_set_device_teams_thread_limit
+        end interface
+
         interface
           function omp_get_teams_thread_limit ()
             integer (4) :: omp_get_teams_thread_limit
diff --git a/libgomp/omp_lib.h.in b/libgomp/omp_lib.h.in
index 70ebca71a9b..28a409a855f 100644
--- a/libgomp/omp_lib.h.in
+++ b/libgomp/omp_lib.h.in
@@ -371,6 +371,15 @@ 
         end function omp_get_thread_limit_dim
       end interface
 
+      interface
+!       Use bind(C) for simplicity; will fail with default-kind-8 integer
+        function omp_get_device_teams_thread_limit (device_num) bind(C)
+          use iso_c_binding, only: c_int
+          integer (c_int), value :: device_num
+          integer (c_int) :: omp_get_device_teams_thread_limit
+        end function omp_get_device_teams_thread_limit
+      end interface
+
       interface
 !       Implementation choice: bind(C) and no default-kind-8 integer
         function omp_get_num_teams_dim (dim) bind(C)
@@ -380,6 +389,15 @@ 
         end function omp_get_num_teams_dim
       end interface
 
+      interface
+!       Use bind(C) for simplicity; will fail with default-kind-8 integer
+        function omp_get_device_num_teams (device_num) bind(C)
+          use iso_c_binding, only: c_int
+          integer (c_int), value :: device_num
+          integer (c_int) :: omp_get_device_num_teams
+        end function omp_get_device_num_teams
+      end interface
+
       interface
 !       Implementation choice: bind(C) and no default-kind-8 integer
         function omp_get_team_num_dim (dim) bind(C)
@@ -404,6 +422,24 @@ 
       external omp_get_max_teams, omp_get_teams_thread_limit
       integer(4) omp_get_max_teams, omp_get_teams_thread_limit
 
+      interface
+!       Use bind(C) for simplicity; will fail with default-kind-8 integer
+        subroutine omp_set_device_num_teams (num_teams, device_num)             &
+     &      bind(C)
+          use iso_c_binding, only: c_int
+          integer (c_int), value, intent (in) :: num_teams, device_num
+        end subroutine omp_set_device_num_teams
+      end interface
+
+      interface
+!       Use bind(C) for simplicity; will fail with default-kind-8 integer
+        subroutine omp_set_device_teams_thread_limit (thread_limit,             &
+     &      device_num) bind(C)
+          use iso_c_binding, only: c_int
+          integer (c_int), value, intent (in) :: thread_limit,device_num
+        end subroutine omp_set_device_teams_thread_limit
+      end interface
+
       external omp_fulfill_event
 
       external omp_set_affinity_format, omp_get_affinity_format
diff --git a/libgomp/target.c b/libgomp/target.c
index f09e4ef3855..2bd1d573de4 100644
--- a/libgomp/target.c
+++ b/libgomp/target.c
@@ -2622,6 +2622,20 @@  gomp_update (struct gomp_device_descr *devicep, size_t mapnum, void **hostaddrs,
     }
 }
 
+/* WARNING: This gets the original on-host values of the device ICV values.
+   That is fine for the following ICVs:
+   - nteams-var ICV:
+     'omp_set_num_teams' sets it only for the host and
+     'omp_set_device_num_teams' also only runs on the host (but needs then
+     to update also the device value)
+   - thread-limit-var and thread-limit-teams-var ICVs:
+     The former is only temporarily modifiable using a clause, the latter
+     is settable via 'omp_set_teams_thread_limit' and
+     'omp_set_device_teams_thread_limit' but those run also only on the host.
+
+   If you call this function for any other ICV than the listed ones, you
+   may need to call gomp_copy_back_icvs first.  */
+
 static struct gomp_offload_icv_list *
 gomp_get_offload_icv_item (int dev_num)
 {
@@ -3404,12 +3418,12 @@  clear_unsupported_flags (struct gomp_device_descr *devicep, unsigned int flags)
   return flags;
 }
 
-static void
+static struct gomp_offload_icvs *
 gomp_copy_back_icvs (struct gomp_device_descr *devicep, int device)
 {
   struct gomp_offload_icv_list *item = gomp_get_offload_icv_item (device);
   if (item == NULL)
-    return;
+    return NULL;
 
   gomp_mutex_lock (&devicep->lock);
 
@@ -3433,6 +3447,35 @@  gomp_copy_back_icvs (struct gomp_device_descr *devicep, int device)
   if (dev_ptr != NULL)
     gomp_copy_dev2host (devicep, NULL, host_ptr, dev_ptr,
 			sizeof (struct gomp_offload_icvs));
+  return &item->icvs;
+}
+
+void
+gomp_copy_icvs_to_device (struct gomp_device_descr *devicep,
+			  struct gomp_offload_icvs *icvs)
+{
+  gomp_mutex_lock (&devicep->lock);
+
+  struct splay_tree_s *mem_map = &devicep->mem_map;
+  struct splay_tree_key_s cur_node;
+  void *dev_ptr = NULL;
+
+  void *host_ptr = (void*) icvs;
+  cur_node.host_start = (uintptr_t) host_ptr;
+  cur_node.host_end = cur_node.host_start;
+  splay_tree_key n = gomp_map_0len_lookup (mem_map, &cur_node);
+
+  if (n)
+    {
+      uintptr_t offset = cur_node.host_start - n->host_start;
+      dev_ptr = (void *) (n->tgt->tgt_start + n->tgt_offset + offset);
+    }
+
+  gomp_mutex_unlock (&devicep->lock);
+
+  if (dev_ptr != NULL)
+    gomp_copy_host2dev (devicep, NULL, dev_ptr, host_ptr,
+			sizeof (struct gomp_offload_icvs), false, NULL);
 }
 
 /* Like GOMP_target, but KINDS is 16-bit, UNUSED is no longer present,
@@ -3769,12 +3812,6 @@  GOMP_target_ext (int device, void (*fn) (void *), size_t mapnum,
     }
   if (refcount_set)
     htab_free (refcount_set);
-
-  /* Copy back ICVs from device to host.
-     HOST_PTR is expected to exist since it was added in
-     gomp_load_image_to_device if not already available.  */
-  gomp_copy_back_icvs (devicep, device);
-
 }
 
 
@@ -6286,6 +6323,97 @@  GOMP_interop (int device_num, int n_init, struct interop_obj_t ***init,
     }
 }
 
+void
+omp_set_device_num_teams (int num_teams, int device_num)
+{
+  if (device_num == omp_default_device)
+    device_num = gomp_get_default_device ();
+
+  if (device_num == omp_initial_device || device_num == gomp_get_num_devices ())
+    {
+      if (num_teams >= 0)
+	gomp_nteams_var = num_teams;
+      return;
+    }
+
+  struct gomp_device_descr *devicep = resolve_device (device_num, false);
+  if (devicep == NULL || num_teams < 0)
+    return;
+  struct gomp_offload_icvs *icvs = gomp_copy_back_icvs (devicep, device_num);
+  icvs->nteams = num_teams;
+  gomp_copy_icvs_to_device (devicep, icvs);
+}
+
+int
+omp_get_device_num_teams (int device_num)
+{
+  if (device_num == omp_default_device)
+    device_num = gomp_get_default_device ();
+
+  int num_devices = gomp_get_num_devices ();
+
+  if (device_num == omp_initial_device || device_num == num_devices)
+    {
+      struct gomp_thread *thr = gomp_thread ();
+      return thr->num_teams + 1;
+    }
+
+  if (device_num < 0 || device_num > num_devices)
+    return 0;
+
+  struct gomp_device_descr *devicep = resolve_device (device_num, false);
+  if (devicep == NULL)
+    return 0;
+  struct gomp_offload_icv_list *item = gomp_get_offload_icv_item (device_num);
+  return item ? item->icvs.nteams : 0;
+}
+
+/* Accepts thread_limits = 0 [which is well defined to mean implementation
+   defined], even though only positive values are permitted.  */
+
+void
+omp_set_device_teams_thread_limit (int thread_limit, int device_num)
+{
+  if (device_num == omp_default_device)
+    device_num = gomp_get_default_device ();
+
+  if (device_num == omp_initial_device || device_num == gomp_get_num_devices ())
+    {
+      if (thread_limit >= 0)
+	gomp_teams_thread_limit_var = thread_limit;
+      return;
+    }
+
+  struct gomp_device_descr *devicep = resolve_device (device_num, false);
+  if (devicep == NULL || thread_limit < 0)
+    return;
+  struct gomp_offload_icvs *icvs = gomp_copy_back_icvs (devicep, device_num);
+  icvs->teams_thread_limit = thread_limit;
+  gomp_copy_icvs_to_device (devicep, icvs);
+}
+
+int
+omp_get_device_teams_thread_limit (int device_num)
+{
+  if (device_num == omp_default_device)
+    device_num = gomp_get_default_device ();
+
+  int num_devices = gomp_get_num_devices ();
+
+  if (device_num == omp_initial_device || device_num == num_devices)
+    return gomp_teams_thread_limit_var;
+
+  if (device_num < 0 || device_num > num_devices)
+    return 0;
+
+  struct gomp_device_descr *devicep = resolve_device (device_num, false);
+  if (devicep == NULL)
+    return 0;
+
+  struct gomp_offload_icv_list *item = gomp_get_offload_icv_item (device_num);
+  return item ? item->icvs.teams_thread_limit : 0;
+}
+
 /* Query device-related data.  */
 
 int
@@ -6464,6 +6592,10 @@  omp_get_device_distances (int ndevs, const int *devs, int *distances)
     }
 }
 
+ialias (omp_set_device_num_teams)
+ialias (omp_get_device_num_teams)
+ialias (omp_set_device_teams_thread_limit)
+ialias (omp_get_device_teams_thread_limit)
 ialias (omp_get_supported_active_team_dims)
 ialias (omp_get_supported_active_league_dims)
 ialias (omp_get_supported_threads_dim)
diff --git a/libgomp/testsuite/libgomp.c-c++-common/icv-5.c b/libgomp/testsuite/libgomp.c-c++-common/icv-5.c
index 72d7af6dfd4..36462115786 100644
--- a/libgomp/testsuite/libgomp.c-c++-common/icv-5.c
+++ b/libgomp/testsuite/libgomp.c-c++-common/icv-5.c
@@ -89,10 +89,24 @@  main ()
 	  || omp_get_thread_num () >= 5 + i)
 	abort ();
 
+      /* The following is required per OpenMP semantic:
+
+	 An omp_set_num_teams region must be a strictly nested region of the
+	 implicit parallel region that surrounds the whole OpenMP program.
+
+	 And likewise for omp_set_teams_thread_limit.
+
+	 That's not the case inside 'target' and GCC fails unless the device ICVs
+	 are copied back to the host at the beginning or end of GOMP_target_ext.
+
+	 Hence set it on the host:  */
+
+      omp_set_device_num_teams (5 + i, i);
+      omp_set_device_teams_thread_limit (4 + i, i);
       #pragma omp target device (i)
       {
-	omp_set_num_teams (5 + i);
-	omp_set_teams_thread_limit (4 + i);
+	// invalid: omp_set_num_teams (5 + i);
+	// invalid: omp_set_teams_thread_limit (4 + i);
 	if (omp_get_max_teams () != 5 + i
 	    || omp_get_teams_thread_limit () != 4 + i)
 	  abort ();
diff --git a/libgomp/testsuite/libgomp.c-c++-common/icv-6.c b/libgomp/testsuite/libgomp.c-c++-common/icv-6.c
index 1b17f2d977a..b5aafbca5dc 100644
--- a/libgomp/testsuite/libgomp.c-c++-common/icv-6.c
+++ b/libgomp/testsuite/libgomp.c-c++-common/icv-6.c
@@ -62,10 +62,24 @@  main ()
 	  abort ();
       }
 
+      /* The following is required per OpenMP semantic:
+
+	 An omp_set_num_teams region must be a strictly nested region of the
+	 implicit parallel region that surrounds the whole OpenMP program.
+
+	 And likewise for omp_set_teams_thread_limit.
+
+	 That's not the case inside 'target' and GCC fails unless the device ICVs
+	 are copied back to the host at the beginning or end of GOMP_target_ext.
+
+	 Hence set it on the host:  */
+
+      omp_set_device_num_teams (3 + i, i);
+      omp_set_device_teams_thread_limit (2 + i, i);
       #pragma omp target device (i)
       {
-	omp_set_num_teams (3 + i);
-	omp_set_teams_thread_limit (2 + i);
+	// invalid: omp_set_num_teams (3 + i);
+	// invalid: omp_set_teams_thread_limit (2 + i);
 	if (omp_get_max_teams () != 3 + i
 	    || omp_get_teams_thread_limit () != 2 + i)
 	  abort ();
diff --git a/libgomp/testsuite/libgomp.c-c++-common/omp-device-num-teams-thread-limit-1.c b/libgomp/testsuite/libgomp.c-c++-common/omp-device-num-teams-thread-limit-1.c
new file mode 100644
index 00000000000..bd52df32c02
--- /dev/null
+++ b/libgomp/testsuite/libgomp.c-c++-common/omp-device-num-teams-thread-limit-1.c
@@ -0,0 +1,193 @@ 
+// This test assumes that no environment variable changes the default!
+// i.e. neither NUM_TEAMS (> 0) is set nor OMP_TEAMS_THREAD_LIMIT.
+
+#include <omp.h>
+
+int
+main ()
+{
+  int nteams, tlimit;
+  int ndevs = omp_get_num_devices ();
+
+  if (omp_default_device < -10 || omp_invalid_device < -10)
+    __builtin_abort ();
+
+  for (int dev = -10; dev < 10; dev++)
+    {
+      bool is_host = (dev == omp_initial_device
+		      || dev == ndevs
+		      || (dev == omp_default_device
+			  && (omp_get_default_device() == omp_initial_device
+			      || omp_get_default_device() == ndevs)));
+      bool is_invalid = (dev != omp_default_device
+			 && dev != omp_initial_device
+			 && (dev < 0 || dev > ndevs));
+
+      nteams = omp_get_device_num_teams (dev);
+      tlimit = omp_get_device_teams_thread_limit (dev);
+
+      if (is_host
+	  && (tlimit != omp_get_teams_thread_limit ()
+	      || tlimit != omp_get_device_teams_thread_limit (dev)))
+	__builtin_abort ();
+
+      if (is_invalid)
+	{
+	  if (nteams != 0 || tlimit != 0)
+	    __builtin_abort ();
+	}
+      else if (is_host && nteams != 1) // outside 'teams'
+	__builtin_abort ();
+      else if (!is_host && nteams != 0) // default init = 0 (according to the spec)
+	__builtin_abort ();
+
+      if (!is_invalid)
+	{
+	  #pragma omp target firstprivate(nteams, tlimit) device(dev)
+	  {
+	    if (tlimit != omp_get_teams_thread_limit ())
+	      __builtin_abort ();
+	  }
+	}
+    }
+
+  omp_set_default_device (omp_initial_device);
+
+  for (int i = 0; i < 4; i++)
+    {
+      int val1 = 4 + i;
+      int val2 = 3 + i;
+
+      switch(i)
+	{
+	case 0: omp_set_num_teams(val1); break;
+	case 1: omp_set_device_num_teams (val1, omp_initial_device); break;
+	case 2: omp_set_device_num_teams (val1, omp_default_device); break;
+	case 3: omp_set_device_num_teams (val1, ndevs); break;
+	}
+
+	#pragma omp teams
+	{
+	  #pragma omp parallel if(0)
+	  {
+	  if (val1 != omp_get_num_teams ())
+	    __builtin_abort ();
+	  if (val1 != omp_get_device_num_teams (omp_initial_device))
+	    __builtin_abort ();
+	  if (val1 != omp_get_device_num_teams (omp_default_device))
+	    __builtin_abort ();
+	  if (val1 != omp_get_device_num_teams (ndevs))
+	    __builtin_abort ();
+	  }
+	}
+
+      switch(i)
+	{
+	case 0: omp_set_teams_thread_limit (val2); break;
+	case 1: omp_set_device_teams_thread_limit (val2, omp_initial_device); break;
+	case 2: omp_set_device_teams_thread_limit (val2, omp_default_device); break;
+	case 3: omp_set_device_teams_thread_limit (val2, ndevs); break;
+	}
+
+      if (val2 != omp_get_teams_thread_limit ())
+	__builtin_abort ();
+      if (val2 != omp_get_device_teams_thread_limit (omp_initial_device))
+	__builtin_abort ();
+      if (val2 != omp_get_device_teams_thread_limit (omp_default_device))
+	__builtin_abort ();
+      if (val2 != omp_get_device_teams_thread_limit (ndevs))
+	__builtin_abort ();
+    }
+
+  for (int dev = 0; dev < ndevs; dev++)
+    {
+	 omp_set_device_num_teams (5, dev);
+	 if (5 != omp_get_device_num_teams (dev))
+	   __builtin_abort ();
+
+	 #pragma omp target teams device(dev)
+	  if (5 != omp_get_num_teams ())
+	    __builtin_abort ();
+
+	 omp_set_device_teams_thread_limit (7, dev);
+
+	 if (7 != omp_get_device_teams_thread_limit (dev))
+	   __builtin_abort ();
+
+      #pragma omp target teams device(dev) num_teams(1)
+	{
+	  #pragma omp parallel if(0)
+	  {
+	  if (7 != omp_get_teams_thread_limit ())
+	    __builtin_abort ();
+	  }
+        }
+    }
+
+  for (int dev = omp_initial_device; dev <= ndevs; dev++)
+    {
+      bool is_host = (dev == omp_initial_device || dev == ndevs);
+
+      omp_set_device_teams_thread_limit (8, dev);
+      if (omp_get_device_teams_thread_limit (dev) != 8)
+	__builtin_abort ();
+      if (is_host && omp_get_teams_thread_limit () != 8)
+	__builtin_abort ();
+
+      // Setting to value -1 is not permitted, hence, expect old value:
+      omp_set_device_teams_thread_limit (-1, dev);
+      if (omp_get_device_teams_thread_limit (dev) != 8)
+	__builtin_abort ();
+      if (is_host && omp_get_teams_thread_limit () != 8)
+	__builtin_abort ();
+
+      // Likewise.
+      if (is_host)
+	{
+	  omp_set_teams_thread_limit (-1);
+	  if (omp_get_device_teams_thread_limit (dev) != 8)
+	    __builtin_abort ();
+	  if (is_host && omp_get_teams_thread_limit () != 8)
+	    __builtin_abort ();
+	}
+
+      // Let's try value = 0. This value is well defined (to mean implementation
+      // defined) but not permitted. Hence, permit both results:
+      omp_set_device_teams_thread_limit (0, dev);
+      if (omp_get_device_teams_thread_limit (dev) != 8
+	  && omp_get_device_teams_thread_limit (dev) != 0)
+	__builtin_abort ();
+      if (is_host
+	  && omp_get_teams_thread_limit () != 8
+	  && omp_get_teams_thread_limit () != 0)
+	__builtin_abort ();
+
+      // Likewise.
+      if (is_host)
+	{
+	  omp_set_teams_thread_limit (0);
+	  if (omp_get_device_teams_thread_limit (dev) != 8
+	      &&  omp_get_device_teams_thread_limit (dev) != 0)
+	    __builtin_abort ();
+	  if (is_host
+	      && omp_get_teams_thread_limit () != 8
+	      && omp_get_teams_thread_limit () != 0)
+	    __builtin_abort ();
+	}
+
+      // However, the nteams-ICV can be set to zero,
+      // but we cannot check its value on the host as
+      // omp_get_num_teams gives the effective team size not the ICV value.
+      if (is_host)
+	continue;
+      
+      omp_set_device_num_teams (8, dev);
+      if (omp_get_device_num_teams (dev) != 8)
+	__builtin_abort ();
+
+      // Setting to value 0 is permitted, hence, expect that value:
+      omp_set_device_num_teams (0, dev);
+      if (omp_get_device_num_teams (dev) != 0)
+	__builtin_abort ();
+    }
+}
diff --git a/libgomp/testsuite/libgomp.fortran/icv-6.f90 b/libgomp/testsuite/libgomp.fortran/icv-6.f90
index c8e6a0d0f12..3984a6943c6 100644
--- a/libgomp/testsuite/libgomp.fortran/icv-6.f90
+++ b/libgomp/testsuite/libgomp.fortran/icv-6.f90
@@ -52,9 +52,20 @@  implicit none (type, external)
       !$omp end target
       if (err) stop 2
 
+      ! The following is required per OpenMP semantic:
+      !
+      ! An omp_set_num_teams region must be a strictly nested region of the
+      ! implicit parallel region that surrounds the whole OpenMP program.
+      !
+      ! That's not the case inside 'target' and GCC fails unless the device ICVs
+      ! are copied back to the host at the beginning or end of GOMP_target_ext.
+      !
+      ! Hence set it on the host:
+
+      call omp_set_device_num_teams (3 + i, i)
       err = .false.
       !$omp target device(i) map(tofrom: err)
-      call omp_set_num_teams (3 + i)
+       ! invalid: call omp_set_num_teams (3 + i)
       if (omp_get_max_teams () /= 3 + i) err = .true.
       !$omp end target
       if (err) stop 3
@@ -94,9 +105,20 @@  implicit none (type, external)
       !$omp end target
       if (err) stop 7
 
+      ! The following is required per OpenMP 6.x semantic:
+      !
+      ! An omp_set_device_teams_thread_limit region must be a strictly nested region
+      ! of the implicit parallel region that surrounds the whole OpenMP program.
+      !
+      ! That's not the case inside 'target' and GCC fails unless the device ICVs
+      ! are copied back to the host at the beginning or end of GOMP_target_ext.
+      !
+      ! Hence set it on the host:
+
+      call omp_set_device_teams_thread_limit (2 + i, i)
       err = .false.
       !$omp target device(i) map(tofrom: err)
-      call omp_set_teams_thread_limit (2 + i)
+      ! invalid: call omp_set_teams_thread_limit (2 + i)
       if (omp_get_teams_thread_limit () /= 2 + i) err = .true.
       !$omp end target
       if (err) stop 8
diff --git a/libgomp/testsuite/libgomp.fortran/omp-device-num-teams-thread-limit-1.f90 b/libgomp/testsuite/libgomp.fortran/omp-device-num-teams-thread-limit-1.f90
new file mode 100644
index 00000000000..c61e7b8d194
--- /dev/null
+++ b/libgomp/testsuite/libgomp.fortran/omp-device-num-teams-thread-limit-1.f90
@@ -0,0 +1,194 @@ 
+! This test assumes that no environment variable changes the default!
+! i.e. neither NUM_TEAMS (> 0) is set nor OMP_TEAMS_THREAD_LIMIT.
+
+program main
+  use omp_lib
+  implicit none (type, external)
+
+  integer :: nteams, tlimit
+  integer :: ndevs, dev, i
+
+  ndevs = omp_get_num_devices ()
+
+  if (omp_default_device < -10 .or. omp_invalid_device < -10) &
+    stop 1
+
+  do dev = -10, 10
+    block
+      logical :: is_host, is_invalid
+
+      is_host = (dev == omp_initial_device  &
+                 .or. dev == ndevs  &
+                 .or. (dev == omp_default_device  &
+                       .and. (omp_get_default_device() == omp_initial_device  &
+                              .or. omp_get_default_device() == ndevs)))
+      is_invalid = (dev /= omp_default_device  &
+                    .and. dev /= omp_initial_device  &
+                    .and. (dev < 0 .or. dev > ndevs))
+
+      nteams = omp_get_device_num_teams (dev)
+      tlimit = omp_get_device_teams_thread_limit (dev)
+
+      if (is_host  &
+          .and. (tlimit /= omp_get_teams_thread_limit ()  &
+                 .or. tlimit /= omp_get_device_teams_thread_limit (dev))) &
+        stop 2
+
+      if (is_invalid) then
+        if (nteams /= 0 .or. tlimit /= 0) &
+          stop 3
+      else if (is_host .and. nteams /= 1) then  ! outside 'teams'
+        stop 4
+      else if (.not. is_host .and. nteams /= 0) then  ! default init = 0 (according to the spec)
+        stop 5
+      end if
+
+      if (.not. is_invalid) then
+        !$omp target firstprivate(nteams, tlimit) device(dev)
+          if (tlimit /= omp_get_teams_thread_limit ()) &
+            stop 6
+        !$omp end target
+      end if
+    end block
+  end do
+
+  call omp_set_default_device (omp_initial_device)
+
+  do i = 0, 3
+  block
+    integer :: val1, val2
+
+    val1 = 4 + i
+    val2 = 3 + i
+
+    select case (i)
+      case(0); call omp_set_num_teams(val1)
+      case(1); call omp_set_device_num_teams (val1, omp_initial_device)
+      case(2); call omp_set_device_num_teams (val1, omp_default_device)
+      case(3); call omp_set_device_num_teams (val1, ndevs)
+    end select
+
+    !$omp teams
+      !$omp parallel if(.false.)
+        if (val1 /= omp_get_num_teams ()) &
+            stop 7
+        if (val1 /= omp_get_device_num_teams (omp_initial_device)) &
+            stop 8
+        if (val1 /= omp_get_device_num_teams (omp_default_device)) &
+            stop 9
+        if (val1 /= omp_get_device_num_teams (ndevs)) &
+            stop 10
+      !$omp end parallel
+    !$omp end teams
+
+    select case(i)
+      case(0); call omp_set_teams_thread_limit (val2)
+      case(1); call omp_set_device_teams_thread_limit (val2, omp_initial_device)
+      case(2); call omp_set_device_teams_thread_limit (val2, omp_default_device)
+      case(3); call omp_set_device_teams_thread_limit (val2, ndevs)
+    end select
+
+      if (val2 /= omp_get_teams_thread_limit ()) &
+        stop 11
+      if (val2 /= omp_get_device_teams_thread_limit (omp_initial_device)) &
+        stop 12
+      if (val2 /= omp_get_device_teams_thread_limit (omp_default_device)) &
+        stop 13
+      if (val2 /= omp_get_device_teams_thread_limit (ndevs)) &
+        stop 14
+  end block
+  end do
+
+  do dev = 0, ndevs - 1
+    call omp_set_device_num_teams (5, dev)
+    if (5 /= omp_get_device_num_teams (dev)) &
+      stop 15
+
+    !$omp target teams device(dev)
+      if (5 /= omp_get_num_teams ()) &
+        stop 16
+    !$omp end target teams
+
+    call omp_set_device_teams_thread_limit (7, dev)
+
+    if (7 /= omp_get_device_teams_thread_limit (dev)) &
+      stop 17
+
+    !$omp target teams device(dev) num_teams(1)
+      !$omp parallel if(.false.)
+        if (7 /= omp_get_teams_thread_limit ()) &
+          stop 18
+      !$omp end parallel
+    !$omp end target teams
+  end do
+
+  do dev = omp_initial_device, ndevs
+    block
+      logical :: is_host
+
+      is_host = (dev == omp_initial_device .or. dev == ndevs)
+
+      call omp_set_device_teams_thread_limit (8, dev)
+
+      if (omp_get_device_teams_thread_limit (dev) /= 8) &
+        stop 19
+      if (is_host .and. omp_get_teams_thread_limit () /= 8) &
+        stop 19
+
+      ! Setting to value -1 is not permitted, hence, expect old value:
+      call omp_set_device_teams_thread_limit (-1, dev)
+
+      if (omp_get_device_teams_thread_limit (dev) /= 8) &
+        stop 20
+      if (is_host .and. omp_get_teams_thread_limit () /= 8) &
+        stop 21
+
+      ! Likewise.
+      if (is_host) then
+        call omp_set_teams_thread_limit (-1)
+        if (omp_get_device_teams_thread_limit (dev) /= 8) &
+          stop 22
+        if (is_host .and. omp_get_teams_thread_limit () /= 8) &
+          stop 23
+      end if
+
+      ! Let's try value = 0. This value is well defined (to mean implementation
+      ! defined) but not permitted. Hence, permit both results:
+      call omp_set_device_teams_thread_limit (0, dev)
+      if (omp_get_device_teams_thread_limit (dev) /= 8 &
+          .and. omp_get_device_teams_thread_limit (dev) /= 0) &
+        stop 24
+      if (is_host &
+          .and. omp_get_teams_thread_limit () /= 8 &
+          .and. omp_get_teams_thread_limit () /= 0) &
+        stop 25
+
+      ! Likewise.
+      if (is_host) then
+        call omp_set_teams_thread_limit (0)
+        if (omp_get_device_teams_thread_limit (dev) /= 8 &
+            .and.  omp_get_device_teams_thread_limit (dev) /= 0) &
+          stop 26
+        if (is_host &
+            .and. omp_get_teams_thread_limit () /= 8 &
+            .and. omp_get_teams_thread_limit () /= 0) &
+          stop 27
+      end if
+
+      ! However, the nteams-ICV can be set to zero,
+      ! but we cannot check its value on the host as
+      ! omp_get_num_teams gives the effective team size not the ICV value.
+      if (is_host) &
+        cycle
+      
+      call omp_set_device_num_teams (8, dev)
+      if (omp_get_device_num_teams (dev) /= 8) &
+        stop 28
+
+      ! Setting to value 0 is permitted, hence, expect that value:
+      call omp_set_device_num_teams (0, dev)
+      if (omp_get_device_num_teams (dev) /= 0) &
+        stop 29
+    end block
+  end do
+end program