1/* PPC GNU/Linux native support.
2
3   Copyright (C) 1988-2020 Free Software Foundation, Inc.
4
5   This file is part of GDB.
6
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 3 of the License, or
10   (at your option) any later version.
11
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20#include "defs.h"
21#include "frame.h"
22#include "inferior.h"
23#include "gdbthread.h"
24#include "gdbcore.h"
25#include "regcache.h"
26#include "regset.h"
27#include "target.h"
28#include "linux-nat.h"
29#include <sys/types.h>
30#include <signal.h>
31#include <sys/user.h>
32#include <sys/ioctl.h>
33#include <sys/uio.h>
34#include "gdbsupport/gdb_wait.h"
35#include <fcntl.h>
36#include <sys/procfs.h>
37#include "nat/gdb_ptrace.h"
38#include "nat/linux-ptrace.h"
39#include "inf-ptrace.h"
40#include <algorithm>
41#include <unordered_map>
42#include <list>
43
44/* Prototypes for supply_gregset etc.  */
45#include "gregset.h"
46#include "ppc-tdep.h"
47#include "ppc-linux-tdep.h"
48
49/* Required when using the AUXV.  */
50#include "elf/common.h"
51#include "auxv.h"
52
53#include "arch/ppc-linux-common.h"
54#include "arch/ppc-linux-tdesc.h"
55#include "nat/ppc-linux.h"
56#include "linux-tdep.h"
57
58/* Similarly for the hardware watchpoint support.  These requests are used
59   when the PowerPC HWDEBUG ptrace interface is not available.  */
60#ifndef PTRACE_GET_DEBUGREG
61#define PTRACE_GET_DEBUGREG    25
62#endif
63#ifndef PTRACE_SET_DEBUGREG
64#define PTRACE_SET_DEBUGREG    26
65#endif
66#ifndef PTRACE_GETSIGINFO
67#define PTRACE_GETSIGINFO    0x4202
68#endif
69
70/* These requests are used when the PowerPC HWDEBUG ptrace interface is
71   available.  It exposes the debug facilities of PowerPC processors, as well
72   as additional features of BookE processors, such as ranged breakpoints and
73   watchpoints and hardware-accelerated condition evaluation.  */
74#ifndef PPC_PTRACE_GETHWDBGINFO
75
76/* Not having PPC_PTRACE_GETHWDBGINFO defined means that the PowerPC HWDEBUG
77   ptrace interface is not present in ptrace.h, so we'll have to pretty much
78   include it all here so that the code at least compiles on older systems.  */
79#define PPC_PTRACE_GETHWDBGINFO 0x89
80#define PPC_PTRACE_SETHWDEBUG   0x88
81#define PPC_PTRACE_DELHWDEBUG   0x87
82
83struct ppc_debug_info
84{
85        uint32_t version;               /* Only version 1 exists to date.  */
86        uint32_t num_instruction_bps;
87        uint32_t num_data_bps;
88        uint32_t num_condition_regs;
89        uint32_t data_bp_alignment;
90        uint32_t sizeof_condition;      /* size of the DVC register.  */
91        uint64_t features;
92};
93
94/* Features will have bits indicating whether there is support for:  */
95#define PPC_DEBUG_FEATURE_INSN_BP_RANGE         0x1
96#define PPC_DEBUG_FEATURE_INSN_BP_MASK          0x2
97#define PPC_DEBUG_FEATURE_DATA_BP_RANGE         0x4
98#define PPC_DEBUG_FEATURE_DATA_BP_MASK          0x8
99
100struct ppc_hw_breakpoint
101{
102        uint32_t version;               /* currently, version must be 1 */
103        uint32_t trigger_type;          /* only some combinations allowed */
104        uint32_t addr_mode;             /* address match mode */
105        uint32_t condition_mode;        /* break/watchpoint condition flags */
106        uint64_t addr;                  /* break/watchpoint address */
107        uint64_t addr2;                 /* range end or mask */
108        uint64_t condition_value;       /* contents of the DVC register */
109};
110
111/* Trigger type.  */
112#define PPC_BREAKPOINT_TRIGGER_EXECUTE  0x1
113#define PPC_BREAKPOINT_TRIGGER_READ     0x2
114#define PPC_BREAKPOINT_TRIGGER_WRITE    0x4
115#define PPC_BREAKPOINT_TRIGGER_RW       0x6
116
117/* Address mode.  */
118#define PPC_BREAKPOINT_MODE_EXACT               0x0
119#define PPC_BREAKPOINT_MODE_RANGE_INCLUSIVE     0x1
120#define PPC_BREAKPOINT_MODE_RANGE_EXCLUSIVE     0x2
121#define PPC_BREAKPOINT_MODE_MASK                0x3
122
123/* Condition mode.  */
124#define PPC_BREAKPOINT_CONDITION_NONE   0x0
125#define PPC_BREAKPOINT_CONDITION_AND    0x1
126#define PPC_BREAKPOINT_CONDITION_EXACT  0x1
127#define PPC_BREAKPOINT_CONDITION_OR     0x2
128#define PPC_BREAKPOINT_CONDITION_AND_OR 0x3
129#define PPC_BREAKPOINT_CONDITION_BE_ALL 0x00ff0000
130#define PPC_BREAKPOINT_CONDITION_BE_SHIFT       16
131#define PPC_BREAKPOINT_CONDITION_BE(n)  \
132        (1<<((n)+PPC_BREAKPOINT_CONDITION_BE_SHIFT))
133#endif /* PPC_PTRACE_GETHWDBGINFO */
134
135/* Feature defined on Linux kernel v3.9: DAWR interface, that enables wider
136   watchpoint (up to 512 bytes).  */
137#ifndef PPC_DEBUG_FEATURE_DATA_BP_DAWR
138#define PPC_DEBUG_FEATURE_DATA_BP_DAWR	0x10
139#endif /* PPC_DEBUG_FEATURE_DATA_BP_DAWR */
140
141/* The version of the PowerPC HWDEBUG kernel interface that we will use, if
142   available.  */
143#define PPC_DEBUG_CURRENT_VERSION 1
144
145/* Similarly for the general-purpose (gp0 -- gp31)
146   and floating-point registers (fp0 -- fp31).  */
147#ifndef PTRACE_GETREGS
148#define PTRACE_GETREGS 12
149#endif
150#ifndef PTRACE_SETREGS
151#define PTRACE_SETREGS 13
152#endif
153#ifndef PTRACE_GETFPREGS
154#define PTRACE_GETFPREGS 14
155#endif
156#ifndef PTRACE_SETFPREGS
157#define PTRACE_SETFPREGS 15
158#endif
159
160/* This oddity is because the Linux kernel defines elf_vrregset_t as
161   an array of 33 16 bytes long elements.  I.e. it leaves out vrsave.
162   However the PTRACE_GETVRREGS and PTRACE_SETVRREGS requests return
163   the vrsave as an extra 4 bytes at the end.  I opted for creating a
164   flat array of chars, so that it is easier to manipulate for gdb.
165
166   There are 32 vector registers 16 bytes longs, plus a VSCR register
167   which is only 4 bytes long, but is fetched as a 16 bytes
168   quantity.  Up to here we have the elf_vrregset_t structure.
169   Appended to this there is space for the VRSAVE register: 4 bytes.
170   Even though this vrsave register is not included in the regset
171   typedef, it is handled by the ptrace requests.
172
173   The layout is like this (where x is the actual value of the vscr reg): */
174
175/* *INDENT-OFF* */
176/*
177Big-Endian:
178   |.|.|.|.|.....|.|.|.|.||.|.|.|x||.|
179   <------->     <-------><-------><->
180     VR0           VR31     VSCR    VRSAVE
181Little-Endian:
182   |.|.|.|.|.....|.|.|.|.||X|.|.|.||.|
183   <------->     <-------><-------><->
184     VR0           VR31     VSCR    VRSAVE
185*/
186/* *INDENT-ON* */
187
188typedef char gdb_vrregset_t[PPC_LINUX_SIZEOF_VRREGSET];
189
190/* This is the layout of the POWER7 VSX registers and the way they overlap
191   with the existing FPR and VMX registers.
192
193                    VSR doubleword 0               VSR doubleword 1
194           ----------------------------------------------------------------
195   VSR[0]  |             FPR[0]            |                              |
196           ----------------------------------------------------------------
197   VSR[1]  |             FPR[1]            |                              |
198           ----------------------------------------------------------------
199           |              ...              |                              |
200           |              ...              |                              |
201           ----------------------------------------------------------------
202   VSR[30] |             FPR[30]           |                              |
203           ----------------------------------------------------------------
204   VSR[31] |             FPR[31]           |                              |
205           ----------------------------------------------------------------
206   VSR[32] |                             VR[0]                            |
207           ----------------------------------------------------------------
208   VSR[33] |                             VR[1]                            |
209           ----------------------------------------------------------------
210           |                              ...                             |
211           |                              ...                             |
212           ----------------------------------------------------------------
213   VSR[62] |                             VR[30]                           |
214           ----------------------------------------------------------------
215   VSR[63] |                             VR[31]                           |
216          ----------------------------------------------------------------
217
218   VSX has 64 128bit registers.  The first 32 registers overlap with
219   the FP registers (doubleword 0) and hence extend them with additional
220   64 bits (doubleword 1).  The other 32 regs overlap with the VMX
221   registers.  */
222typedef char gdb_vsxregset_t[PPC_LINUX_SIZEOF_VSXREGSET];
223
224/* On PPC processors that support the Signal Processing Extension
225   (SPE) APU, the general-purpose registers are 64 bits long.
226   However, the ordinary Linux kernel PTRACE_PEEKUSER / PTRACE_POKEUSER
227   ptrace calls only access the lower half of each register, to allow
228   them to behave the same way they do on non-SPE systems.  There's a
229   separate pair of calls, PTRACE_GETEVRREGS / PTRACE_SETEVRREGS, that
230   read and write the top halves of all the general-purpose registers
231   at once, along with some SPE-specific registers.
232
233   GDB itself continues to claim the general-purpose registers are 32
234   bits long.  It has unnamed raw registers that hold the upper halves
235   of the gprs, and the full 64-bit SIMD views of the registers,
236   'ev0' -- 'ev31', are pseudo-registers that splice the top and
237   bottom halves together.
238
239   This is the structure filled in by PTRACE_GETEVRREGS and written to
240   the inferior's registers by PTRACE_SETEVRREGS.  */
241struct gdb_evrregset_t
242{
243  unsigned long evr[32];
244  unsigned long long acc;
245  unsigned long spefscr;
246};
247
248/* Non-zero if our kernel may support the PTRACE_GETVSXREGS and
249   PTRACE_SETVSXREGS requests, for reading and writing the VSX
250   POWER7 registers 0 through 31.  Zero if we've tried one of them and
251   gotten an error.  Note that VSX registers 32 through 63 overlap
252   with VR registers 0 through 31.  */
253int have_ptrace_getsetvsxregs = 1;
254
255/* Non-zero if our kernel may support the PTRACE_GETVRREGS and
256   PTRACE_SETVRREGS requests, for reading and writing the Altivec
257   registers.  Zero if we've tried one of them and gotten an
258   error.  */
259int have_ptrace_getvrregs = 1;
260
261/* Non-zero if our kernel may support the PTRACE_GETEVRREGS and
262   PTRACE_SETEVRREGS requests, for reading and writing the SPE
263   registers.  Zero if we've tried one of them and gotten an
264   error.  */
265int have_ptrace_getsetevrregs = 1;
266
267/* Non-zero if our kernel may support the PTRACE_GETREGS and
268   PTRACE_SETREGS requests, for reading and writing the
269   general-purpose registers.  Zero if we've tried one of
270   them and gotten an error.  */
271int have_ptrace_getsetregs = 1;
272
273/* Non-zero if our kernel may support the PTRACE_GETFPREGS and
274   PTRACE_SETFPREGS requests, for reading and writing the
275   floating-pointers registers.  Zero if we've tried one of
276   them and gotten an error.  */
277int have_ptrace_getsetfpregs = 1;
278
279/* Private arch info associated with each thread lwp_info object, used
280   for debug register handling.  */
281
282struct arch_lwp_info
283{
284  /* When true, indicates that the debug registers installed in the
285     thread no longer correspond to the watchpoints and breakpoints
286     requested by GDB.  */
287  bool debug_regs_stale;
288
289  /* We need a back-reference to the PTID of the thread so that we can
290     cleanup the debug register state of the thread in
291     low_delete_thread.  */
292  ptid_t lwp_ptid;
293};
294
295/* Class used to detect which set of ptrace requests that
296   ppc_linux_nat_target will use to install and remove hardware
297   breakpoints and watchpoints.
298
299   The interface is only detected once, testing the ptrace calls.  The
300   result can indicate that no interface is available.
301
302   The Linux kernel provides two different sets of ptrace requests to
303   handle hardware watchpoints and breakpoints for Power:
304
305   - PPC_PTRACE_GETHWDBGINFO, PPC_PTRACE_SETHWDEBUG, and
306     PPC_PTRACE_DELHWDEBUG.
307
308   Or
309
310   - PTRACE_SET_DEBUGREG and PTRACE_GET_DEBUGREG
311
312   The first set is the more flexible one and allows setting watchpoints
313   with a variable watched region length and, for BookE processors,
314   multiple types of debug registers (e.g. hardware breakpoints and
315   hardware-assisted conditions for watchpoints).  The second one only
316   allows setting one debug register, a watchpoint, so we only use it if
317   the first one is not available.  */
318
319class ppc_linux_dreg_interface
320{
321public:
322
323  ppc_linux_dreg_interface ()
324    : m_interface (), m_hwdebug_info ()
325  {
326  };
327
328  DISABLE_COPY_AND_ASSIGN (ppc_linux_dreg_interface);
329
330  /* One and only one of these three functions returns true, indicating
331     whether the corresponding interface is the one we detected.  The
332     interface must already have been detected as a precontidion.  */
333
334  bool hwdebug_p ()
335  {
336    gdb_assert (detected_p ());
337    return *m_interface == HWDEBUG;
338  }
339
340  bool debugreg_p ()
341  {
342    gdb_assert (detected_p ());
343    return *m_interface == DEBUGREG;
344  }
345
346  bool unavailable_p ()
347  {
348    gdb_assert (detected_p ());
349    return *m_interface == UNAVAILABLE;
350  }
351
352  /* Returns the debug register capabilities of the target.  Should only
353     be called if the interface is HWDEBUG.  */
354  const struct ppc_debug_info &hwdebug_info ()
355  {
356    gdb_assert (hwdebug_p ());
357
358    return m_hwdebug_info;
359  }
360
361  /* Returns true if the interface has already been detected.  This is
362     useful for cases when we know there is no work to be done if the
363     interface hasn't been detected yet.  */
364  bool detected_p ()
365  {
366    return m_interface.has_value ();
367  }
368
369  /* Detect the available interface, if any, if it hasn't been detected
370     before, using PTID for the necessary ptrace calls.  */
371
372  void detect (const ptid_t &ptid)
373  {
374    if (m_interface.has_value ())
375      return;
376
377    gdb_assert (ptid.lwp_p ());
378
379    bool no_features = false;
380
381    if (ptrace (PPC_PTRACE_GETHWDBGINFO, ptid.lwp (), 0, &m_hwdebug_info)
382	>= 0)
383      {
384	/* If there are no advertised features, we don't use the
385	   HWDEBUG interface and try the DEBUGREG interface instead.
386	   It shouldn't be necessary to do this, however, when the
387	   kernel is configured without CONFIG_HW_BREAKPOINTS (selected
388	   by CONFIG_PERF_EVENTS), there is a bug that causes
389	   watchpoints installed with the HWDEBUG interface not to
390	   trigger.  When this is the case, features will be zero,
391	   which we use as an indicator to fall back to the DEBUGREG
392	   interface.  */
393	if (m_hwdebug_info.features != 0)
394	  {
395	    m_interface.emplace (HWDEBUG);
396	    return;
397	  }
398	else
399	  no_features = true;
400      }
401
402    /* EIO indicates that the request is invalid, so we try DEBUGREG
403       next.  Technically, it can also indicate other failures, but we
404       can't differentiate those.
405
406       Other errors could happen for various reasons.  We could get an
407       ESRCH if the traced thread was killed by a signal.  Trying to
408       detect the interface with another thread in the future would be
409       complicated, as callers would have to handle an "unknown
410       interface" case.  It's also unclear if raising an exception
411       here would be safe.
412
413       Other errors, such as ENODEV, could be more permanent and cause
414       a failure for any thread.
415
416       For simplicity, with all errors other than EIO, we set the
417       interface to UNAVAILABLE and don't try DEBUGREG.  If DEBUGREG
418       fails too, we'll also set the interface to UNAVAILABLE.  It's
419       unlikely that trying the DEBUGREG interface with this same thread
420       would work, for errors other than EIO.  This means that these
421       errors will cause hardware watchpoints and breakpoints to become
422       unavailable throughout a GDB session.  */
423
424    if (no_features || errno == EIO)
425      {
426	unsigned long wp;
427
428	if (ptrace (PTRACE_GET_DEBUGREG, ptid.lwp (), 0, &wp) >= 0)
429	  {
430	    m_interface.emplace (DEBUGREG);
431	    return;
432	  }
433      }
434
435    if (errno != EIO)
436      warning (_("Error when detecting the debug register interface. "
437		 "Debug registers will be unavailable."));
438
439    m_interface.emplace (UNAVAILABLE);
440    return;
441  }
442
443private:
444
445  /* HWDEBUG represents the set of calls PPC_PTRACE_GETHWDBGINFO,
446     PPC_PTRACE_SETHWDEBUG and PPC_PTRACE_DELHWDEBUG.
447
448     DEBUGREG represents the set of calls PTRACE_SET_DEBUGREG and
449     PTRACE_GET_DEBUGREG.
450
451     UNAVAILABLE can indicate that the kernel doesn't support any of the
452     two sets of requests or that there was an error when we tried to
453     detect wich interface is available.  */
454
455  enum debug_reg_interface
456    {
457     UNAVAILABLE,
458     HWDEBUG,
459     DEBUGREG
460    };
461
462  /* The interface option.  Initialized if has_value () returns true.  */
463  gdb::optional<enum debug_reg_interface> m_interface;
464
465  /* The info returned by the kernel with PPC_PTRACE_GETHWDBGINFO.  Only
466     valid if we determined that the interface is HWDEBUG.  */
467  struct ppc_debug_info m_hwdebug_info;
468};
469
470/* Per-process information.  This includes the hardware watchpoints and
471   breakpoints that GDB requested to this target.  */
472
473struct ppc_linux_process_info
474{
475  /* The list of hardware watchpoints and breakpoints that GDB requested
476     for this process.
477
478     Only used when the interface is HWDEBUG.  */
479  std::list<struct ppc_hw_breakpoint> requested_hw_bps;
480
481  /* The watchpoint value that GDB requested for this process.
482
483     Only used when the interface is DEBUGREG.  */
484  gdb::optional<long> requested_wp_val;
485};
486
487struct ppc_linux_nat_target final : public linux_nat_target
488{
489  /* Add our register access methods.  */
490  void fetch_registers (struct regcache *, int) override;
491  void store_registers (struct regcache *, int) override;
492
493  /* Add our breakpoint/watchpoint methods.  */
494  int can_use_hw_breakpoint (enum bptype, int, int) override;
495
496  int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *)
497    override;
498
499  int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *)
500    override;
501
502  int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
503
504  int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
505			 struct expression *) override;
506
507  int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
508			 struct expression *) override;
509
510  int insert_mask_watchpoint (CORE_ADDR, CORE_ADDR, enum target_hw_bp_type)
511    override;
512
513  int remove_mask_watchpoint (CORE_ADDR, CORE_ADDR, enum target_hw_bp_type)
514    override;
515
516  bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
517
518  bool can_accel_watchpoint_condition (CORE_ADDR, int, int, struct expression *)
519    override;
520
521  int masked_watch_num_registers (CORE_ADDR, CORE_ADDR) override;
522
523  int ranged_break_num_registers () override;
524
525  const struct target_desc *read_description ()  override;
526
527  int auxv_parse (gdb_byte **readptr,
528		  gdb_byte *endptr, CORE_ADDR *typep, CORE_ADDR *valp)
529    override;
530
531  /* Override linux_nat_target low methods.  */
532  bool low_stopped_by_watchpoint () override;
533
534  bool low_stopped_data_address (CORE_ADDR *) override;
535
536  void low_new_thread (struct lwp_info *lp) override;
537
538  void low_delete_thread (arch_lwp_info *) override;
539
540  void low_new_fork (struct lwp_info *, pid_t) override;
541
542  void low_new_clone (struct lwp_info *, pid_t) override;
543
544  void low_forget_process (pid_t pid) override;
545
546  void low_prepare_to_resume (struct lwp_info *) override;
547
548private:
549
550  void copy_thread_dreg_state (const ptid_t &parent_ptid,
551			       const ptid_t &child_ptid);
552
553  void mark_thread_stale (struct lwp_info *lp);
554
555  void mark_debug_registers_changed (pid_t pid);
556
557  void register_hw_breakpoint (pid_t pid,
558			       const struct ppc_hw_breakpoint &bp);
559
560  void clear_hw_breakpoint (pid_t pid,
561			    const struct ppc_hw_breakpoint &a);
562
563  void register_wp (pid_t pid, long wp_value);
564
565  void clear_wp (pid_t pid);
566
567  bool can_use_watchpoint_cond_accel (void);
568
569  void calculate_dvc (CORE_ADDR addr, int len,
570		      CORE_ADDR data_value,
571		      uint32_t *condition_mode,
572		      uint64_t *condition_value);
573
574  int check_condition (CORE_ADDR watch_addr,
575		       struct expression *cond,
576		       CORE_ADDR *data_value, int *len);
577
578  int num_memory_accesses (const std::vector<value_ref_ptr> &chain);
579
580  int get_trigger_type (enum target_hw_bp_type type);
581
582  void create_watchpoint_request (struct ppc_hw_breakpoint *p,
583				  CORE_ADDR addr,
584				  int len,
585				  enum target_hw_bp_type type,
586				  struct expression *cond,
587				  int insert);
588
589  bool hwdebug_point_cmp (const struct ppc_hw_breakpoint &a,
590			  const struct ppc_hw_breakpoint &b);
591
592  void init_arch_lwp_info (struct lwp_info *lp);
593
594  arch_lwp_info *get_arch_lwp_info (struct lwp_info *lp);
595
596  /* The ptrace interface we'll use to install hardware watchpoints and
597     breakpoints (debug registers).  */
598  ppc_linux_dreg_interface m_dreg_interface;
599
600  /* A map from pids to structs containing info specific to each
601     process.  */
602  std::unordered_map<pid_t, ppc_linux_process_info> m_process_info;
603
604  /* Callable object to hash ptids by their lwp number.  */
605  struct ptid_hash
606  {
607    std::size_t operator() (const ptid_t &ptid) const
608    {
609      return std::hash<long>{} (ptid.lwp ());
610    }
611  };
612
613  /* A map from ptid_t objects to a list of pairs of slots and hardware
614     breakpoint objects.  This keeps track of which hardware breakpoints
615     and watchpoints were last installed in each slot of each thread.
616
617     Only used when the interface is HWDEBUG.  */
618  std::unordered_map <ptid_t,
619		      std::list<std::pair<long, ppc_hw_breakpoint>>,
620		      ptid_hash> m_installed_hw_bps;
621};
622
623static ppc_linux_nat_target the_ppc_linux_nat_target;
624
625/* *INDENT-OFF* */
626/* registers layout, as presented by the ptrace interface:
627PT_R0, PT_R1, PT_R2, PT_R3, PT_R4, PT_R5, PT_R6, PT_R7,
628PT_R8, PT_R9, PT_R10, PT_R11, PT_R12, PT_R13, PT_R14, PT_R15,
629PT_R16, PT_R17, PT_R18, PT_R19, PT_R20, PT_R21, PT_R22, PT_R23,
630PT_R24, PT_R25, PT_R26, PT_R27, PT_R28, PT_R29, PT_R30, PT_R31,
631PT_FPR0, PT_FPR0 + 2, PT_FPR0 + 4, PT_FPR0 + 6,
632PT_FPR0 + 8, PT_FPR0 + 10, PT_FPR0 + 12, PT_FPR0 + 14,
633PT_FPR0 + 16, PT_FPR0 + 18, PT_FPR0 + 20, PT_FPR0 + 22,
634PT_FPR0 + 24, PT_FPR0 + 26, PT_FPR0 + 28, PT_FPR0 + 30,
635PT_FPR0 + 32, PT_FPR0 + 34, PT_FPR0 + 36, PT_FPR0 + 38,
636PT_FPR0 + 40, PT_FPR0 + 42, PT_FPR0 + 44, PT_FPR0 + 46,
637PT_FPR0 + 48, PT_FPR0 + 50, PT_FPR0 + 52, PT_FPR0 + 54,
638PT_FPR0 + 56, PT_FPR0 + 58, PT_FPR0 + 60, PT_FPR0 + 62,
639PT_NIP, PT_MSR, PT_CCR, PT_LNK, PT_CTR, PT_XER, PT_MQ */
640/* *INDENT_ON * */
641
642static int
643ppc_register_u_addr (struct gdbarch *gdbarch, int regno)
644{
645  int u_addr = -1;
646  struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
647  /* NOTE: cagney/2003-11-25: This is the word size used by the ptrace
648     interface, and not the wordsize of the program's ABI.  */
649  int wordsize = sizeof (long);
650
651  /* General purpose registers occupy 1 slot each in the buffer.  */
652  if (regno >= tdep->ppc_gp0_regnum
653      && regno < tdep->ppc_gp0_regnum + ppc_num_gprs)
654    u_addr = ((regno - tdep->ppc_gp0_regnum + PT_R0) * wordsize);
655
656  /* Floating point regs: eight bytes each in both 32- and 64-bit
657     ptrace interfaces.  Thus, two slots each in 32-bit interface, one
658     slot each in 64-bit interface.  */
659  if (tdep->ppc_fp0_regnum >= 0
660      && regno >= tdep->ppc_fp0_regnum
661      && regno < tdep->ppc_fp0_regnum + ppc_num_fprs)
662    u_addr = (PT_FPR0 * wordsize) + ((regno - tdep->ppc_fp0_regnum) * 8);
663
664  /* UISA special purpose registers: 1 slot each.  */
665  if (regno == gdbarch_pc_regnum (gdbarch))
666    u_addr = PT_NIP * wordsize;
667  if (regno == tdep->ppc_lr_regnum)
668    u_addr = PT_LNK * wordsize;
669  if (regno == tdep->ppc_cr_regnum)
670    u_addr = PT_CCR * wordsize;
671  if (regno == tdep->ppc_xer_regnum)
672    u_addr = PT_XER * wordsize;
673  if (regno == tdep->ppc_ctr_regnum)
674    u_addr = PT_CTR * wordsize;
675#ifdef PT_MQ
676  if (regno == tdep->ppc_mq_regnum)
677    u_addr = PT_MQ * wordsize;
678#endif
679  if (regno == tdep->ppc_ps_regnum)
680    u_addr = PT_MSR * wordsize;
681  if (regno == PPC_ORIG_R3_REGNUM)
682    u_addr = PT_ORIG_R3 * wordsize;
683  if (regno == PPC_TRAP_REGNUM)
684    u_addr = PT_TRAP * wordsize;
685  if (tdep->ppc_fpscr_regnum >= 0
686      && regno == tdep->ppc_fpscr_regnum)
687    {
688      /* NOTE: cagney/2005-02-08: On some 64-bit GNU/Linux systems the
689	 kernel headers incorrectly contained the 32-bit definition of
690	 PT_FPSCR.  For the 32-bit definition, floating-point
691	 registers occupy two 32-bit "slots", and the FPSCR lives in
692	 the second half of such a slot-pair (hence +1).  For 64-bit,
693	 the FPSCR instead occupies the full 64-bit 2-word-slot and
694	 hence no adjustment is necessary.  Hack around this.  */
695      if (wordsize == 8 && PT_FPSCR == (48 + 32 + 1))
696	u_addr = (48 + 32) * wordsize;
697      /* If the FPSCR is 64-bit wide, we need to fetch the whole 64-bit
698	 slot and not just its second word.  The PT_FPSCR supplied when
699	 GDB is compiled as a 32-bit app doesn't reflect this.  */
700      else if (wordsize == 4 && register_size (gdbarch, regno) == 8
701	       && PT_FPSCR == (48 + 2*32 + 1))
702	u_addr = (48 + 2*32) * wordsize;
703      else
704	u_addr = PT_FPSCR * wordsize;
705    }
706  return u_addr;
707}
708
709/* The Linux kernel ptrace interface for POWER7 VSX registers uses the
710   registers set mechanism, as opposed to the interface for all the
711   other registers, that stores/fetches each register individually.  */
712static void
713fetch_vsx_registers (struct regcache *regcache, int tid, int regno)
714{
715  int ret;
716  gdb_vsxregset_t regs;
717  const struct regset *vsxregset = ppc_linux_vsxregset ();
718
719  ret = ptrace (PTRACE_GETVSXREGS, tid, 0, &regs);
720  if (ret < 0)
721    {
722      if (errno == EIO)
723	{
724	  have_ptrace_getsetvsxregs = 0;
725	  return;
726	}
727      perror_with_name (_("Unable to fetch VSX registers"));
728    }
729
730  vsxregset->supply_regset (vsxregset, regcache, regno, &regs,
731			    PPC_LINUX_SIZEOF_VSXREGSET);
732}
733
734/* The Linux kernel ptrace interface for AltiVec registers uses the
735   registers set mechanism, as opposed to the interface for all the
736   other registers, that stores/fetches each register individually.  */
737static void
738fetch_altivec_registers (struct regcache *regcache, int tid,
739			 int regno)
740{
741  int ret;
742  gdb_vrregset_t regs;
743  struct gdbarch *gdbarch = regcache->arch ();
744  const struct regset *vrregset = ppc_linux_vrregset (gdbarch);
745
746  ret = ptrace (PTRACE_GETVRREGS, tid, 0, &regs);
747  if (ret < 0)
748    {
749      if (errno == EIO)
750        {
751          have_ptrace_getvrregs = 0;
752          return;
753        }
754      perror_with_name (_("Unable to fetch AltiVec registers"));
755    }
756
757  vrregset->supply_regset (vrregset, regcache, regno, &regs,
758			   PPC_LINUX_SIZEOF_VRREGSET);
759}
760
761/* Fetch the top 32 bits of TID's general-purpose registers and the
762   SPE-specific registers, and place the results in EVRREGSET.  If we
763   don't support PTRACE_GETEVRREGS, then just fill EVRREGSET with
764   zeros.
765
766   All the logic to deal with whether or not the PTRACE_GETEVRREGS and
767   PTRACE_SETEVRREGS requests are supported is isolated here, and in
768   set_spe_registers.  */
769static void
770get_spe_registers (int tid, struct gdb_evrregset_t *evrregset)
771{
772  if (have_ptrace_getsetevrregs)
773    {
774      if (ptrace (PTRACE_GETEVRREGS, tid, 0, evrregset) >= 0)
775        return;
776      else
777        {
778          /* EIO means that the PTRACE_GETEVRREGS request isn't supported;
779             we just return zeros.  */
780          if (errno == EIO)
781            have_ptrace_getsetevrregs = 0;
782          else
783            /* Anything else needs to be reported.  */
784            perror_with_name (_("Unable to fetch SPE registers"));
785        }
786    }
787
788  memset (evrregset, 0, sizeof (*evrregset));
789}
790
791/* Supply values from TID for SPE-specific raw registers: the upper
792   halves of the GPRs, the accumulator, and the spefscr.  REGNO must
793   be the number of an upper half register, acc, spefscr, or -1 to
794   supply the values of all registers.  */
795static void
796fetch_spe_register (struct regcache *regcache, int tid, int regno)
797{
798  struct gdbarch *gdbarch = regcache->arch ();
799  struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
800  struct gdb_evrregset_t evrregs;
801
802  gdb_assert (sizeof (evrregs.evr[0])
803              == register_size (gdbarch, tdep->ppc_ev0_upper_regnum));
804  gdb_assert (sizeof (evrregs.acc)
805              == register_size (gdbarch, tdep->ppc_acc_regnum));
806  gdb_assert (sizeof (evrregs.spefscr)
807              == register_size (gdbarch, tdep->ppc_spefscr_regnum));
808
809  get_spe_registers (tid, &evrregs);
810
811  if (regno == -1)
812    {
813      int i;
814
815      for (i = 0; i < ppc_num_gprs; i++)
816        regcache->raw_supply (tdep->ppc_ev0_upper_regnum + i, &evrregs.evr[i]);
817    }
818  else if (tdep->ppc_ev0_upper_regnum <= regno
819           && regno < tdep->ppc_ev0_upper_regnum + ppc_num_gprs)
820    regcache->raw_supply (regno,
821			  &evrregs.evr[regno - tdep->ppc_ev0_upper_regnum]);
822
823  if (regno == -1
824      || regno == tdep->ppc_acc_regnum)
825    regcache->raw_supply (tdep->ppc_acc_regnum, &evrregs.acc);
826
827  if (regno == -1
828      || regno == tdep->ppc_spefscr_regnum)
829    regcache->raw_supply (tdep->ppc_spefscr_regnum, &evrregs.spefscr);
830}
831
832/* Use ptrace to fetch all registers from the register set with note
833   type REGSET_ID, size REGSIZE, and layout described by REGSET, from
834   process/thread TID and supply their values to REGCACHE.  If ptrace
835   returns ENODATA to indicate the regset is unavailable, mark the
836   registers as unavailable in REGCACHE.  */
837
838static void
839fetch_regset (struct regcache *regcache, int tid,
840	      int regset_id, int regsetsize, const struct regset *regset)
841{
842  void *buf = alloca (regsetsize);
843  struct iovec iov;
844
845  iov.iov_base = buf;
846  iov.iov_len = regsetsize;
847
848  if (ptrace (PTRACE_GETREGSET, tid, regset_id, &iov) < 0)
849    {
850      if (errno == ENODATA)
851	regset->supply_regset (regset, regcache, -1, NULL, regsetsize);
852      else
853	perror_with_name (_("Couldn't get register set"));
854    }
855  else
856    regset->supply_regset (regset, regcache, -1, buf, regsetsize);
857}
858
859/* Use ptrace to store register REGNUM of the regset with note type
860   REGSET_ID, size REGSETSIZE, and layout described by REGSET, from
861   REGCACHE back to process/thread TID.  If REGNUM is -1 all registers
862   in the set are collected and stored.  */
863
864static void
865store_regset (const struct regcache *regcache, int tid, int regnum,
866	      int regset_id, int regsetsize, const struct regset *regset)
867{
868  void *buf = alloca (regsetsize);
869  struct iovec iov;
870
871  iov.iov_base = buf;
872  iov.iov_len = regsetsize;
873
874  /* Make sure that the buffer that will be stored has up to date values
875     for the registers that won't be collected.  */
876  if (ptrace (PTRACE_GETREGSET, tid, regset_id, &iov) < 0)
877    perror_with_name (_("Couldn't get register set"));
878
879  regset->collect_regset (regset, regcache, regnum, buf, regsetsize);
880
881  if (ptrace (PTRACE_SETREGSET, tid, regset_id, &iov) < 0)
882    perror_with_name (_("Couldn't set register set"));
883}
884
885/* Check whether the kernel provides a register set with number
886   REGSET_ID of size REGSETSIZE for process/thread TID.  */
887
888static bool
889check_regset (int tid, int regset_id, int regsetsize)
890{
891  void *buf = alloca (regsetsize);
892  struct iovec iov;
893
894  iov.iov_base = buf;
895  iov.iov_len = regsetsize;
896
897  if (ptrace (PTRACE_GETREGSET, tid, regset_id, &iov) >= 0
898      || errno == ENODATA)
899    return true;
900  else
901    return false;
902}
903
904static void
905fetch_register (struct regcache *regcache, int tid, int regno)
906{
907  struct gdbarch *gdbarch = regcache->arch ();
908  struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
909  /* This isn't really an address.  But ptrace thinks of it as one.  */
910  CORE_ADDR regaddr = ppc_register_u_addr (gdbarch, regno);
911  int bytes_transferred;
912  gdb_byte buf[PPC_MAX_REGISTER_SIZE];
913
914  if (altivec_register_p (gdbarch, regno))
915    {
916      /* If this is the first time through, or if it is not the first
917         time through, and we have confirmed that there is kernel
918         support for such a ptrace request, then go and fetch the
919         register.  */
920      if (have_ptrace_getvrregs)
921       {
922         fetch_altivec_registers (regcache, tid, regno);
923         return;
924       }
925     /* If we have discovered that there is no ptrace support for
926        AltiVec registers, fall through and return zeroes, because
927        regaddr will be -1 in this case.  */
928    }
929  else if (vsx_register_p (gdbarch, regno))
930    {
931      if (have_ptrace_getsetvsxregs)
932	{
933	  fetch_vsx_registers (regcache, tid, regno);
934	  return;
935	}
936    }
937  else if (spe_register_p (gdbarch, regno))
938    {
939      fetch_spe_register (regcache, tid, regno);
940      return;
941    }
942  else if (regno == PPC_DSCR_REGNUM)
943    {
944      gdb_assert (tdep->ppc_dscr_regnum != -1);
945
946      fetch_regset (regcache, tid, NT_PPC_DSCR,
947		    PPC_LINUX_SIZEOF_DSCRREGSET,
948		    &ppc32_linux_dscrregset);
949      return;
950    }
951  else if (regno == PPC_PPR_REGNUM)
952    {
953      gdb_assert (tdep->ppc_ppr_regnum != -1);
954
955      fetch_regset (regcache, tid, NT_PPC_PPR,
956		    PPC_LINUX_SIZEOF_PPRREGSET,
957		    &ppc32_linux_pprregset);
958      return;
959    }
960  else if (regno == PPC_TAR_REGNUM)
961    {
962      gdb_assert (tdep->ppc_tar_regnum != -1);
963
964      fetch_regset (regcache, tid, NT_PPC_TAR,
965		    PPC_LINUX_SIZEOF_TARREGSET,
966		    &ppc32_linux_tarregset);
967      return;
968    }
969  else if (PPC_IS_EBB_REGNUM (regno))
970    {
971      gdb_assert (tdep->have_ebb);
972
973      fetch_regset (regcache, tid, NT_PPC_EBB,
974		    PPC_LINUX_SIZEOF_EBBREGSET,
975		    &ppc32_linux_ebbregset);
976      return;
977    }
978  else if (PPC_IS_PMU_REGNUM (regno))
979    {
980      gdb_assert (tdep->ppc_mmcr0_regnum != -1);
981
982      fetch_regset (regcache, tid, NT_PPC_PMU,
983		    PPC_LINUX_SIZEOF_PMUREGSET,
984		    &ppc32_linux_pmuregset);
985      return;
986    }
987  else if (PPC_IS_TMSPR_REGNUM (regno))
988    {
989      gdb_assert (tdep->have_htm_spr);
990
991      fetch_regset (regcache, tid, NT_PPC_TM_SPR,
992		    PPC_LINUX_SIZEOF_TM_SPRREGSET,
993		    &ppc32_linux_tm_sprregset);
994      return;
995    }
996  else if (PPC_IS_CKPTGP_REGNUM (regno))
997    {
998      gdb_assert (tdep->have_htm_core);
999
1000      const struct regset *cgprregset = ppc_linux_cgprregset (gdbarch);
1001      fetch_regset (regcache, tid, NT_PPC_TM_CGPR,
1002		    (tdep->wordsize == 4?
1003		     PPC32_LINUX_SIZEOF_CGPRREGSET
1004		     : PPC64_LINUX_SIZEOF_CGPRREGSET),
1005		    cgprregset);
1006      return;
1007    }
1008  else if (PPC_IS_CKPTFP_REGNUM (regno))
1009    {
1010      gdb_assert (tdep->have_htm_fpu);
1011
1012      fetch_regset (regcache, tid, NT_PPC_TM_CFPR,
1013		    PPC_LINUX_SIZEOF_CFPRREGSET,
1014		    &ppc32_linux_cfprregset);
1015      return;
1016    }
1017  else if (PPC_IS_CKPTVMX_REGNUM (regno))
1018    {
1019      gdb_assert (tdep->have_htm_altivec);
1020
1021      const struct regset *cvmxregset = ppc_linux_cvmxregset (gdbarch);
1022      fetch_regset (regcache, tid, NT_PPC_TM_CVMX,
1023		    PPC_LINUX_SIZEOF_CVMXREGSET,
1024		    cvmxregset);
1025      return;
1026    }
1027  else if (PPC_IS_CKPTVSX_REGNUM (regno))
1028    {
1029      gdb_assert (tdep->have_htm_vsx);
1030
1031      fetch_regset (regcache, tid, NT_PPC_TM_CVSX,
1032		    PPC_LINUX_SIZEOF_CVSXREGSET,
1033		    &ppc32_linux_cvsxregset);
1034      return;
1035    }
1036  else if (regno == PPC_CPPR_REGNUM)
1037    {
1038      gdb_assert (tdep->ppc_cppr_regnum != -1);
1039
1040      fetch_regset (regcache, tid, NT_PPC_TM_CPPR,
1041		    PPC_LINUX_SIZEOF_CPPRREGSET,
1042		    &ppc32_linux_cpprregset);
1043      return;
1044    }
1045  else if (regno == PPC_CDSCR_REGNUM)
1046    {
1047      gdb_assert (tdep->ppc_cdscr_regnum != -1);
1048
1049      fetch_regset (regcache, tid, NT_PPC_TM_CDSCR,
1050		    PPC_LINUX_SIZEOF_CDSCRREGSET,
1051		    &ppc32_linux_cdscrregset);
1052      return;
1053    }
1054  else if (regno == PPC_CTAR_REGNUM)
1055    {
1056      gdb_assert (tdep->ppc_ctar_regnum != -1);
1057
1058      fetch_regset (regcache, tid, NT_PPC_TM_CTAR,
1059		    PPC_LINUX_SIZEOF_CTARREGSET,
1060		    &ppc32_linux_ctarregset);
1061      return;
1062    }
1063
1064  if (regaddr == -1)
1065    {
1066      memset (buf, '\0', register_size (gdbarch, regno));   /* Supply zeroes */
1067      regcache->raw_supply (regno, buf);
1068      return;
1069    }
1070
1071  /* Read the raw register using sizeof(long) sized chunks.  On a
1072     32-bit platform, 64-bit floating-point registers will require two
1073     transfers.  */
1074  for (bytes_transferred = 0;
1075       bytes_transferred < register_size (gdbarch, regno);
1076       bytes_transferred += sizeof (long))
1077    {
1078      long l;
1079
1080      errno = 0;
1081      l = ptrace (PTRACE_PEEKUSER, tid, (PTRACE_TYPE_ARG3) regaddr, 0);
1082      regaddr += sizeof (long);
1083      if (errno != 0)
1084	{
1085          char message[128];
1086	  xsnprintf (message, sizeof (message), "reading register %s (#%d)",
1087		     gdbarch_register_name (gdbarch, regno), regno);
1088	  perror_with_name (message);
1089	}
1090      memcpy (&buf[bytes_transferred], &l, sizeof (l));
1091    }
1092
1093  /* Now supply the register.  Keep in mind that the regcache's idea
1094     of the register's size may not be a multiple of sizeof
1095     (long).  */
1096  if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_LITTLE)
1097    {
1098      /* Little-endian values are always found at the left end of the
1099         bytes transferred.  */
1100      regcache->raw_supply (regno, buf);
1101    }
1102  else if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
1103    {
1104      /* Big-endian values are found at the right end of the bytes
1105         transferred.  */
1106      size_t padding = (bytes_transferred - register_size (gdbarch, regno));
1107      regcache->raw_supply (regno, buf + padding);
1108    }
1109  else
1110    internal_error (__FILE__, __LINE__,
1111                    _("fetch_register: unexpected byte order: %d"),
1112                    gdbarch_byte_order (gdbarch));
1113}
1114
1115/* This function actually issues the request to ptrace, telling
1116   it to get all general-purpose registers and put them into the
1117   specified regset.
1118
1119   If the ptrace request does not exist, this function returns 0
1120   and properly sets the have_ptrace_* flag.  If the request fails,
1121   this function calls perror_with_name.  Otherwise, if the request
1122   succeeds, then the regcache gets filled and 1 is returned.  */
1123static int
1124fetch_all_gp_regs (struct regcache *regcache, int tid)
1125{
1126  gdb_gregset_t gregset;
1127
1128  if (ptrace (PTRACE_GETREGS, tid, 0, (void *) &gregset) < 0)
1129    {
1130      if (errno == EIO)
1131        {
1132          have_ptrace_getsetregs = 0;
1133          return 0;
1134        }
1135      perror_with_name (_("Couldn't get general-purpose registers."));
1136    }
1137
1138  supply_gregset (regcache, (const gdb_gregset_t *) &gregset);
1139
1140  return 1;
1141}
1142
1143/* This is a wrapper for the fetch_all_gp_regs function.  It is
1144   responsible for verifying if this target has the ptrace request
1145   that can be used to fetch all general-purpose registers at one
1146   shot.  If it doesn't, then we should fetch them using the
1147   old-fashioned way, which is to iterate over the registers and
1148   request them one by one.  */
1149static void
1150fetch_gp_regs (struct regcache *regcache, int tid)
1151{
1152  struct gdbarch *gdbarch = regcache->arch ();
1153  struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1154  int i;
1155
1156  if (have_ptrace_getsetregs)
1157    if (fetch_all_gp_regs (regcache, tid))
1158      return;
1159
1160  /* If we've hit this point, it doesn't really matter which
1161     architecture we are using.  We just need to read the
1162     registers in the "old-fashioned way".  */
1163  for (i = 0; i < ppc_num_gprs; i++)
1164    fetch_register (regcache, tid, tdep->ppc_gp0_regnum + i);
1165}
1166
1167/* This function actually issues the request to ptrace, telling
1168   it to get all floating-point registers and put them into the
1169   specified regset.
1170
1171   If the ptrace request does not exist, this function returns 0
1172   and properly sets the have_ptrace_* flag.  If the request fails,
1173   this function calls perror_with_name.  Otherwise, if the request
1174   succeeds, then the regcache gets filled and 1 is returned.  */
1175static int
1176fetch_all_fp_regs (struct regcache *regcache, int tid)
1177{
1178  gdb_fpregset_t fpregs;
1179
1180  if (ptrace (PTRACE_GETFPREGS, tid, 0, (void *) &fpregs) < 0)
1181    {
1182      if (errno == EIO)
1183        {
1184          have_ptrace_getsetfpregs = 0;
1185          return 0;
1186        }
1187      perror_with_name (_("Couldn't get floating-point registers."));
1188    }
1189
1190  supply_fpregset (regcache, (const gdb_fpregset_t *) &fpregs);
1191
1192  return 1;
1193}
1194
1195/* This is a wrapper for the fetch_all_fp_regs function.  It is
1196   responsible for verifying if this target has the ptrace request
1197   that can be used to fetch all floating-point registers at one
1198   shot.  If it doesn't, then we should fetch them using the
1199   old-fashioned way, which is to iterate over the registers and
1200   request them one by one.  */
1201static void
1202fetch_fp_regs (struct regcache *regcache, int tid)
1203{
1204  struct gdbarch *gdbarch = regcache->arch ();
1205  struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1206  int i;
1207
1208  if (have_ptrace_getsetfpregs)
1209    if (fetch_all_fp_regs (regcache, tid))
1210      return;
1211
1212  /* If we've hit this point, it doesn't really matter which
1213     architecture we are using.  We just need to read the
1214     registers in the "old-fashioned way".  */
1215  for (i = 0; i < ppc_num_fprs; i++)
1216    fetch_register (regcache, tid, tdep->ppc_fp0_regnum + i);
1217}
1218
1219static void
1220fetch_ppc_registers (struct regcache *regcache, int tid)
1221{
1222  struct gdbarch *gdbarch = regcache->arch ();
1223  struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1224
1225  fetch_gp_regs (regcache, tid);
1226  if (tdep->ppc_fp0_regnum >= 0)
1227    fetch_fp_regs (regcache, tid);
1228  fetch_register (regcache, tid, gdbarch_pc_regnum (gdbarch));
1229  if (tdep->ppc_ps_regnum != -1)
1230    fetch_register (regcache, tid, tdep->ppc_ps_regnum);
1231  if (tdep->ppc_cr_regnum != -1)
1232    fetch_register (regcache, tid, tdep->ppc_cr_regnum);
1233  if (tdep->ppc_lr_regnum != -1)
1234    fetch_register (regcache, tid, tdep->ppc_lr_regnum);
1235  if (tdep->ppc_ctr_regnum != -1)
1236    fetch_register (regcache, tid, tdep->ppc_ctr_regnum);
1237  if (tdep->ppc_xer_regnum != -1)
1238    fetch_register (regcache, tid, tdep->ppc_xer_regnum);
1239  if (tdep->ppc_mq_regnum != -1)
1240    fetch_register (regcache, tid, tdep->ppc_mq_regnum);
1241  if (ppc_linux_trap_reg_p (gdbarch))
1242    {
1243      fetch_register (regcache, tid, PPC_ORIG_R3_REGNUM);
1244      fetch_register (regcache, tid, PPC_TRAP_REGNUM);
1245    }
1246  if (tdep->ppc_fpscr_regnum != -1)
1247    fetch_register (regcache, tid, tdep->ppc_fpscr_regnum);
1248  if (have_ptrace_getvrregs)
1249    if (tdep->ppc_vr0_regnum != -1 && tdep->ppc_vrsave_regnum != -1)
1250      fetch_altivec_registers (regcache, tid, -1);
1251  if (have_ptrace_getsetvsxregs)
1252    if (tdep->ppc_vsr0_upper_regnum != -1)
1253      fetch_vsx_registers (regcache, tid, -1);
1254  if (tdep->ppc_ev0_upper_regnum >= 0)
1255    fetch_spe_register (regcache, tid, -1);
1256  if (tdep->ppc_ppr_regnum != -1)
1257    fetch_regset (regcache, tid, NT_PPC_PPR,
1258		  PPC_LINUX_SIZEOF_PPRREGSET,
1259		  &ppc32_linux_pprregset);
1260  if (tdep->ppc_dscr_regnum != -1)
1261    fetch_regset (regcache, tid, NT_PPC_DSCR,
1262		  PPC_LINUX_SIZEOF_DSCRREGSET,
1263		  &ppc32_linux_dscrregset);
1264  if (tdep->ppc_tar_regnum != -1)
1265    fetch_regset (regcache, tid, NT_PPC_TAR,
1266		  PPC_LINUX_SIZEOF_TARREGSET,
1267		  &ppc32_linux_tarregset);
1268  if (tdep->have_ebb)
1269    fetch_regset (regcache, tid, NT_PPC_EBB,
1270		  PPC_LINUX_SIZEOF_EBBREGSET,
1271		  &ppc32_linux_ebbregset);
1272  if (tdep->ppc_mmcr0_regnum != -1)
1273    fetch_regset (regcache, tid, NT_PPC_PMU,
1274		  PPC_LINUX_SIZEOF_PMUREGSET,
1275		  &ppc32_linux_pmuregset);
1276  if (tdep->have_htm_spr)
1277    fetch_regset (regcache, tid, NT_PPC_TM_SPR,
1278		  PPC_LINUX_SIZEOF_TM_SPRREGSET,
1279		  &ppc32_linux_tm_sprregset);
1280  if (tdep->have_htm_core)
1281    {
1282      const struct regset *cgprregset = ppc_linux_cgprregset (gdbarch);
1283      fetch_regset (regcache, tid, NT_PPC_TM_CGPR,
1284		    (tdep->wordsize == 4?
1285		     PPC32_LINUX_SIZEOF_CGPRREGSET
1286		     : PPC64_LINUX_SIZEOF_CGPRREGSET),
1287		    cgprregset);
1288    }
1289  if (tdep->have_htm_fpu)
1290    fetch_regset (regcache, tid, NT_PPC_TM_CFPR,
1291		  PPC_LINUX_SIZEOF_CFPRREGSET,
1292		  &ppc32_linux_cfprregset);
1293  if (tdep->have_htm_altivec)
1294    {
1295      const struct regset *cvmxregset = ppc_linux_cvmxregset (gdbarch);
1296      fetch_regset (regcache, tid, NT_PPC_TM_CVMX,
1297		    PPC_LINUX_SIZEOF_CVMXREGSET,
1298		    cvmxregset);
1299    }
1300  if (tdep->have_htm_vsx)
1301    fetch_regset (regcache, tid, NT_PPC_TM_CVSX,
1302		  PPC_LINUX_SIZEOF_CVSXREGSET,
1303		  &ppc32_linux_cvsxregset);
1304  if (tdep->ppc_cppr_regnum != -1)
1305    fetch_regset (regcache, tid, NT_PPC_TM_CPPR,
1306		  PPC_LINUX_SIZEOF_CPPRREGSET,
1307		  &ppc32_linux_cpprregset);
1308  if (tdep->ppc_cdscr_regnum != -1)
1309    fetch_regset (regcache, tid, NT_PPC_TM_CDSCR,
1310		  PPC_LINUX_SIZEOF_CDSCRREGSET,
1311		  &ppc32_linux_cdscrregset);
1312  if (tdep->ppc_ctar_regnum != -1)
1313    fetch_regset (regcache, tid, NT_PPC_TM_CTAR,
1314		  PPC_LINUX_SIZEOF_CTARREGSET,
1315		  &ppc32_linux_ctarregset);
1316}
1317
1318/* Fetch registers from the child process.  Fetch all registers if
1319   regno == -1, otherwise fetch all general registers or all floating
1320   point registers depending upon the value of regno.  */
1321void
1322ppc_linux_nat_target::fetch_registers (struct regcache *regcache, int regno)
1323{
1324  pid_t tid = get_ptrace_pid (regcache->ptid ());
1325
1326  if (regno == -1)
1327    fetch_ppc_registers (regcache, tid);
1328  else
1329    fetch_register (regcache, tid, regno);
1330}
1331
1332static void
1333store_vsx_registers (const struct regcache *regcache, int tid, int regno)
1334{
1335  int ret;
1336  gdb_vsxregset_t regs;
1337  const struct regset *vsxregset = ppc_linux_vsxregset ();
1338
1339  ret = ptrace (PTRACE_GETVSXREGS, tid, 0, &regs);
1340  if (ret < 0)
1341    {
1342      if (errno == EIO)
1343	{
1344	  have_ptrace_getsetvsxregs = 0;
1345	  return;
1346	}
1347      perror_with_name (_("Unable to fetch VSX registers"));
1348    }
1349
1350  vsxregset->collect_regset (vsxregset, regcache, regno, &regs,
1351			     PPC_LINUX_SIZEOF_VSXREGSET);
1352
1353  ret = ptrace (PTRACE_SETVSXREGS, tid, 0, &regs);
1354  if (ret < 0)
1355    perror_with_name (_("Unable to store VSX registers"));
1356}
1357
1358static void
1359store_altivec_registers (const struct regcache *regcache, int tid,
1360			 int regno)
1361{
1362  int ret;
1363  gdb_vrregset_t regs;
1364  struct gdbarch *gdbarch = regcache->arch ();
1365  const struct regset *vrregset = ppc_linux_vrregset (gdbarch);
1366
1367  ret = ptrace (PTRACE_GETVRREGS, tid, 0, &regs);
1368  if (ret < 0)
1369    {
1370      if (errno == EIO)
1371        {
1372          have_ptrace_getvrregs = 0;
1373          return;
1374        }
1375      perror_with_name (_("Unable to fetch AltiVec registers"));
1376    }
1377
1378  vrregset->collect_regset (vrregset, regcache, regno, &regs,
1379			    PPC_LINUX_SIZEOF_VRREGSET);
1380
1381  ret = ptrace (PTRACE_SETVRREGS, tid, 0, &regs);
1382  if (ret < 0)
1383    perror_with_name (_("Unable to store AltiVec registers"));
1384}
1385
1386/* Assuming TID refers to an SPE process, set the top halves of TID's
1387   general-purpose registers and its SPE-specific registers to the
1388   values in EVRREGSET.  If we don't support PTRACE_SETEVRREGS, do
1389   nothing.
1390
1391   All the logic to deal with whether or not the PTRACE_GETEVRREGS and
1392   PTRACE_SETEVRREGS requests are supported is isolated here, and in
1393   get_spe_registers.  */
1394static void
1395set_spe_registers (int tid, struct gdb_evrregset_t *evrregset)
1396{
1397  if (have_ptrace_getsetevrregs)
1398    {
1399      if (ptrace (PTRACE_SETEVRREGS, tid, 0, evrregset) >= 0)
1400        return;
1401      else
1402        {
1403          /* EIO means that the PTRACE_SETEVRREGS request isn't
1404             supported; we fail silently, and don't try the call
1405             again.  */
1406          if (errno == EIO)
1407            have_ptrace_getsetevrregs = 0;
1408          else
1409            /* Anything else needs to be reported.  */
1410            perror_with_name (_("Unable to set SPE registers"));
1411        }
1412    }
1413}
1414
1415/* Write GDB's value for the SPE-specific raw register REGNO to TID.
1416   If REGNO is -1, write the values of all the SPE-specific
1417   registers.  */
1418static void
1419store_spe_register (const struct regcache *regcache, int tid, int regno)
1420{
1421  struct gdbarch *gdbarch = regcache->arch ();
1422  struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1423  struct gdb_evrregset_t evrregs;
1424
1425  gdb_assert (sizeof (evrregs.evr[0])
1426              == register_size (gdbarch, tdep->ppc_ev0_upper_regnum));
1427  gdb_assert (sizeof (evrregs.acc)
1428              == register_size (gdbarch, tdep->ppc_acc_regnum));
1429  gdb_assert (sizeof (evrregs.spefscr)
1430              == register_size (gdbarch, tdep->ppc_spefscr_regnum));
1431
1432  if (regno == -1)
1433    /* Since we're going to write out every register, the code below
1434       should store to every field of evrregs; if that doesn't happen,
1435       make it obvious by initializing it with suspicious values.  */
1436    memset (&evrregs, 42, sizeof (evrregs));
1437  else
1438    /* We can only read and write the entire EVR register set at a
1439       time, so to write just a single register, we do a
1440       read-modify-write maneuver.  */
1441    get_spe_registers (tid, &evrregs);
1442
1443  if (regno == -1)
1444    {
1445      int i;
1446
1447      for (i = 0; i < ppc_num_gprs; i++)
1448	regcache->raw_collect (tdep->ppc_ev0_upper_regnum + i,
1449			       &evrregs.evr[i]);
1450    }
1451  else if (tdep->ppc_ev0_upper_regnum <= regno
1452           && regno < tdep->ppc_ev0_upper_regnum + ppc_num_gprs)
1453    regcache->raw_collect (regno,
1454			   &evrregs.evr[regno - tdep->ppc_ev0_upper_regnum]);
1455
1456  if (regno == -1
1457      || regno == tdep->ppc_acc_regnum)
1458    regcache->raw_collect (tdep->ppc_acc_regnum,
1459			   &evrregs.acc);
1460
1461  if (regno == -1
1462      || regno == tdep->ppc_spefscr_regnum)
1463    regcache->raw_collect (tdep->ppc_spefscr_regnum,
1464			   &evrregs.spefscr);
1465
1466  /* Write back the modified register set.  */
1467  set_spe_registers (tid, &evrregs);
1468}
1469
1470static void
1471store_register (const struct regcache *regcache, int tid, int regno)
1472{
1473  struct gdbarch *gdbarch = regcache->arch ();
1474  struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1475  /* This isn't really an address.  But ptrace thinks of it as one.  */
1476  CORE_ADDR regaddr = ppc_register_u_addr (gdbarch, regno);
1477  int i;
1478  size_t bytes_to_transfer;
1479  gdb_byte buf[PPC_MAX_REGISTER_SIZE];
1480
1481  if (altivec_register_p (gdbarch, regno))
1482    {
1483      store_altivec_registers (regcache, tid, regno);
1484      return;
1485    }
1486  else if (vsx_register_p (gdbarch, regno))
1487    {
1488      store_vsx_registers (regcache, tid, regno);
1489      return;
1490    }
1491  else if (spe_register_p (gdbarch, regno))
1492    {
1493      store_spe_register (regcache, tid, regno);
1494      return;
1495    }
1496  else if (regno == PPC_DSCR_REGNUM)
1497    {
1498      gdb_assert (tdep->ppc_dscr_regnum != -1);
1499
1500      store_regset (regcache, tid, regno, NT_PPC_DSCR,
1501		    PPC_LINUX_SIZEOF_DSCRREGSET,
1502		    &ppc32_linux_dscrregset);
1503      return;
1504    }
1505  else if (regno == PPC_PPR_REGNUM)
1506    {
1507      gdb_assert (tdep->ppc_ppr_regnum != -1);
1508
1509      store_regset (regcache, tid, regno, NT_PPC_PPR,
1510		    PPC_LINUX_SIZEOF_PPRREGSET,
1511		    &ppc32_linux_pprregset);
1512      return;
1513    }
1514  else if (regno == PPC_TAR_REGNUM)
1515    {
1516      gdb_assert (tdep->ppc_tar_regnum != -1);
1517
1518      store_regset (regcache, tid, regno, NT_PPC_TAR,
1519		    PPC_LINUX_SIZEOF_TARREGSET,
1520		    &ppc32_linux_tarregset);
1521      return;
1522    }
1523  else if (PPC_IS_EBB_REGNUM (regno))
1524    {
1525      gdb_assert (tdep->have_ebb);
1526
1527      store_regset (regcache, tid, regno, NT_PPC_EBB,
1528		    PPC_LINUX_SIZEOF_EBBREGSET,
1529		    &ppc32_linux_ebbregset);
1530      return;
1531    }
1532  else if (PPC_IS_PMU_REGNUM (regno))
1533    {
1534      gdb_assert (tdep->ppc_mmcr0_regnum != -1);
1535
1536      store_regset (regcache, tid, regno, NT_PPC_PMU,
1537		    PPC_LINUX_SIZEOF_PMUREGSET,
1538		    &ppc32_linux_pmuregset);
1539      return;
1540    }
1541  else if (PPC_IS_TMSPR_REGNUM (regno))
1542    {
1543      gdb_assert (tdep->have_htm_spr);
1544
1545      store_regset (regcache, tid, regno, NT_PPC_TM_SPR,
1546		    PPC_LINUX_SIZEOF_TM_SPRREGSET,
1547		    &ppc32_linux_tm_sprregset);
1548      return;
1549    }
1550  else if (PPC_IS_CKPTGP_REGNUM (regno))
1551    {
1552      gdb_assert (tdep->have_htm_core);
1553
1554      const struct regset *cgprregset = ppc_linux_cgprregset (gdbarch);
1555      store_regset (regcache, tid, regno, NT_PPC_TM_CGPR,
1556		    (tdep->wordsize == 4?
1557		     PPC32_LINUX_SIZEOF_CGPRREGSET
1558		     : PPC64_LINUX_SIZEOF_CGPRREGSET),
1559		    cgprregset);
1560      return;
1561    }
1562  else if (PPC_IS_CKPTFP_REGNUM (regno))
1563    {
1564      gdb_assert (tdep->have_htm_fpu);
1565
1566      store_regset (regcache, tid, regno, NT_PPC_TM_CFPR,
1567		    PPC_LINUX_SIZEOF_CFPRREGSET,
1568		    &ppc32_linux_cfprregset);
1569      return;
1570    }
1571  else if (PPC_IS_CKPTVMX_REGNUM (regno))
1572    {
1573      gdb_assert (tdep->have_htm_altivec);
1574
1575      const struct regset *cvmxregset = ppc_linux_cvmxregset (gdbarch);
1576      store_regset (regcache, tid, regno, NT_PPC_TM_CVMX,
1577		    PPC_LINUX_SIZEOF_CVMXREGSET,
1578		    cvmxregset);
1579      return;
1580    }
1581  else if (PPC_IS_CKPTVSX_REGNUM (regno))
1582    {
1583      gdb_assert (tdep->have_htm_vsx);
1584
1585      store_regset (regcache, tid, regno, NT_PPC_TM_CVSX,
1586		    PPC_LINUX_SIZEOF_CVSXREGSET,
1587		    &ppc32_linux_cvsxregset);
1588      return;
1589    }
1590  else if (regno == PPC_CPPR_REGNUM)
1591    {
1592      gdb_assert (tdep->ppc_cppr_regnum != -1);
1593
1594      store_regset (regcache, tid, regno, NT_PPC_TM_CPPR,
1595		    PPC_LINUX_SIZEOF_CPPRREGSET,
1596		    &ppc32_linux_cpprregset);
1597      return;
1598    }
1599  else if (regno == PPC_CDSCR_REGNUM)
1600    {
1601      gdb_assert (tdep->ppc_cdscr_regnum != -1);
1602
1603      store_regset (regcache, tid, regno, NT_PPC_TM_CDSCR,
1604		    PPC_LINUX_SIZEOF_CDSCRREGSET,
1605		    &ppc32_linux_cdscrregset);
1606      return;
1607    }
1608  else if (regno == PPC_CTAR_REGNUM)
1609    {
1610      gdb_assert (tdep->ppc_ctar_regnum != -1);
1611
1612      store_regset (regcache, tid, regno, NT_PPC_TM_CTAR,
1613		    PPC_LINUX_SIZEOF_CTARREGSET,
1614		    &ppc32_linux_ctarregset);
1615      return;
1616    }
1617
1618  if (regaddr == -1)
1619    return;
1620
1621  /* First collect the register.  Keep in mind that the regcache's
1622     idea of the register's size may not be a multiple of sizeof
1623     (long).  */
1624  memset (buf, 0, sizeof buf);
1625  bytes_to_transfer = align_up (register_size (gdbarch, regno), sizeof (long));
1626  if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_LITTLE)
1627    {
1628      /* Little-endian values always sit at the left end of the buffer.  */
1629      regcache->raw_collect (regno, buf);
1630    }
1631  else if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
1632    {
1633      /* Big-endian values sit at the right end of the buffer.  */
1634      size_t padding = (bytes_to_transfer - register_size (gdbarch, regno));
1635      regcache->raw_collect (regno, buf + padding);
1636    }
1637
1638  for (i = 0; i < bytes_to_transfer; i += sizeof (long))
1639    {
1640      long l;
1641
1642      memcpy (&l, &buf[i], sizeof (l));
1643      errno = 0;
1644      ptrace (PTRACE_POKEUSER, tid, (PTRACE_TYPE_ARG3) regaddr, l);
1645      regaddr += sizeof (long);
1646
1647      if (errno == EIO
1648          && (regno == tdep->ppc_fpscr_regnum
1649	      || regno == PPC_ORIG_R3_REGNUM
1650	      || regno == PPC_TRAP_REGNUM))
1651	{
1652	  /* Some older kernel versions don't allow fpscr, orig_r3
1653	     or trap to be written.  */
1654	  continue;
1655	}
1656
1657      if (errno != 0)
1658	{
1659          char message[128];
1660	  xsnprintf (message, sizeof (message), "writing register %s (#%d)",
1661		     gdbarch_register_name (gdbarch, regno), regno);
1662	  perror_with_name (message);
1663	}
1664    }
1665}
1666
1667/* This function actually issues the request to ptrace, telling
1668   it to store all general-purpose registers present in the specified
1669   regset.
1670
1671   If the ptrace request does not exist, this function returns 0
1672   and properly sets the have_ptrace_* flag.  If the request fails,
1673   this function calls perror_with_name.  Otherwise, if the request
1674   succeeds, then the regcache is stored and 1 is returned.  */
1675static int
1676store_all_gp_regs (const struct regcache *regcache, int tid, int regno)
1677{
1678  gdb_gregset_t gregset;
1679
1680  if (ptrace (PTRACE_GETREGS, tid, 0, (void *) &gregset) < 0)
1681    {
1682      if (errno == EIO)
1683        {
1684          have_ptrace_getsetregs = 0;
1685          return 0;
1686        }
1687      perror_with_name (_("Couldn't get general-purpose registers."));
1688    }
1689
1690  fill_gregset (regcache, &gregset, regno);
1691
1692  if (ptrace (PTRACE_SETREGS, tid, 0, (void *) &gregset) < 0)
1693    {
1694      if (errno == EIO)
1695        {
1696          have_ptrace_getsetregs = 0;
1697          return 0;
1698        }
1699      perror_with_name (_("Couldn't set general-purpose registers."));
1700    }
1701
1702  return 1;
1703}
1704
1705/* This is a wrapper for the store_all_gp_regs function.  It is
1706   responsible for verifying if this target has the ptrace request
1707   that can be used to store all general-purpose registers at one
1708   shot.  If it doesn't, then we should store them using the
1709   old-fashioned way, which is to iterate over the registers and
1710   store them one by one.  */
1711static void
1712store_gp_regs (const struct regcache *regcache, int tid, int regno)
1713{
1714  struct gdbarch *gdbarch = regcache->arch ();
1715  struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1716  int i;
1717
1718  if (have_ptrace_getsetregs)
1719    if (store_all_gp_regs (regcache, tid, regno))
1720      return;
1721
1722  /* If we hit this point, it doesn't really matter which
1723     architecture we are using.  We just need to store the
1724     registers in the "old-fashioned way".  */
1725  for (i = 0; i < ppc_num_gprs; i++)
1726    store_register (regcache, tid, tdep->ppc_gp0_regnum + i);
1727}
1728
1729/* This function actually issues the request to ptrace, telling
1730   it to store all floating-point registers present in the specified
1731   regset.
1732
1733   If the ptrace request does not exist, this function returns 0
1734   and properly sets the have_ptrace_* flag.  If the request fails,
1735   this function calls perror_with_name.  Otherwise, if the request
1736   succeeds, then the regcache is stored and 1 is returned.  */
1737static int
1738store_all_fp_regs (const struct regcache *regcache, int tid, int regno)
1739{
1740  gdb_fpregset_t fpregs;
1741
1742  if (ptrace (PTRACE_GETFPREGS, tid, 0, (void *) &fpregs) < 0)
1743    {
1744      if (errno == EIO)
1745        {
1746          have_ptrace_getsetfpregs = 0;
1747          return 0;
1748        }
1749      perror_with_name (_("Couldn't get floating-point registers."));
1750    }
1751
1752  fill_fpregset (regcache, &fpregs, regno);
1753
1754  if (ptrace (PTRACE_SETFPREGS, tid, 0, (void *) &fpregs) < 0)
1755    {
1756      if (errno == EIO)
1757        {
1758          have_ptrace_getsetfpregs = 0;
1759          return 0;
1760        }
1761      perror_with_name (_("Couldn't set floating-point registers."));
1762    }
1763
1764  return 1;
1765}
1766
1767/* This is a wrapper for the store_all_fp_regs function.  It is
1768   responsible for verifying if this target has the ptrace request
1769   that can be used to store all floating-point registers at one
1770   shot.  If it doesn't, then we should store them using the
1771   old-fashioned way, which is to iterate over the registers and
1772   store them one by one.  */
1773static void
1774store_fp_regs (const struct regcache *regcache, int tid, int regno)
1775{
1776  struct gdbarch *gdbarch = regcache->arch ();
1777  struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1778  int i;
1779
1780  if (have_ptrace_getsetfpregs)
1781    if (store_all_fp_regs (regcache, tid, regno))
1782      return;
1783
1784  /* If we hit this point, it doesn't really matter which
1785     architecture we are using.  We just need to store the
1786     registers in the "old-fashioned way".  */
1787  for (i = 0; i < ppc_num_fprs; i++)
1788    store_register (regcache, tid, tdep->ppc_fp0_regnum + i);
1789}
1790
1791static void
1792store_ppc_registers (const struct regcache *regcache, int tid)
1793{
1794  struct gdbarch *gdbarch = regcache->arch ();
1795  struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1796
1797  store_gp_regs (regcache, tid, -1);
1798  if (tdep->ppc_fp0_regnum >= 0)
1799    store_fp_regs (regcache, tid, -1);
1800  store_register (regcache, tid, gdbarch_pc_regnum (gdbarch));
1801  if (tdep->ppc_ps_regnum != -1)
1802    store_register (regcache, tid, tdep->ppc_ps_regnum);
1803  if (tdep->ppc_cr_regnum != -1)
1804    store_register (regcache, tid, tdep->ppc_cr_regnum);
1805  if (tdep->ppc_lr_regnum != -1)
1806    store_register (regcache, tid, tdep->ppc_lr_regnum);
1807  if (tdep->ppc_ctr_regnum != -1)
1808    store_register (regcache, tid, tdep->ppc_ctr_regnum);
1809  if (tdep->ppc_xer_regnum != -1)
1810    store_register (regcache, tid, tdep->ppc_xer_regnum);
1811  if (tdep->ppc_mq_regnum != -1)
1812    store_register (regcache, tid, tdep->ppc_mq_regnum);
1813  if (tdep->ppc_fpscr_regnum != -1)
1814    store_register (regcache, tid, tdep->ppc_fpscr_regnum);
1815  if (ppc_linux_trap_reg_p (gdbarch))
1816    {
1817      store_register (regcache, tid, PPC_ORIG_R3_REGNUM);
1818      store_register (regcache, tid, PPC_TRAP_REGNUM);
1819    }
1820  if (have_ptrace_getvrregs)
1821    if (tdep->ppc_vr0_regnum != -1 && tdep->ppc_vrsave_regnum != -1)
1822      store_altivec_registers (regcache, tid, -1);
1823  if (have_ptrace_getsetvsxregs)
1824    if (tdep->ppc_vsr0_upper_regnum != -1)
1825      store_vsx_registers (regcache, tid, -1);
1826  if (tdep->ppc_ev0_upper_regnum >= 0)
1827    store_spe_register (regcache, tid, -1);
1828  if (tdep->ppc_ppr_regnum != -1)
1829    store_regset (regcache, tid, -1, NT_PPC_PPR,
1830		  PPC_LINUX_SIZEOF_PPRREGSET,
1831		  &ppc32_linux_pprregset);
1832  if (tdep->ppc_dscr_regnum != -1)
1833    store_regset (regcache, tid, -1, NT_PPC_DSCR,
1834		  PPC_LINUX_SIZEOF_DSCRREGSET,
1835		  &ppc32_linux_dscrregset);
1836  if (tdep->ppc_tar_regnum != -1)
1837    store_regset (regcache, tid, -1, NT_PPC_TAR,
1838		  PPC_LINUX_SIZEOF_TARREGSET,
1839		  &ppc32_linux_tarregset);
1840
1841  if (tdep->ppc_mmcr0_regnum != -1)
1842    store_regset (regcache, tid, -1, NT_PPC_PMU,
1843		  PPC_LINUX_SIZEOF_PMUREGSET,
1844		  &ppc32_linux_pmuregset);
1845
1846  if (tdep->have_htm_spr)
1847    store_regset (regcache, tid, -1, NT_PPC_TM_SPR,
1848		  PPC_LINUX_SIZEOF_TM_SPRREGSET,
1849		  &ppc32_linux_tm_sprregset);
1850
1851  /* Because the EBB and checkpointed HTM registers can be
1852     unavailable, attempts to store them here would cause this
1853     function to fail most of the time, so we ignore them.  */
1854}
1855
1856void
1857ppc_linux_nat_target::store_registers (struct regcache *regcache, int regno)
1858{
1859  pid_t tid = get_ptrace_pid (regcache->ptid ());
1860
1861  if (regno >= 0)
1862    store_register (regcache, tid, regno);
1863  else
1864    store_ppc_registers (regcache, tid);
1865}
1866
1867/* Functions for transferring registers between a gregset_t or fpregset_t
1868   (see sys/ucontext.h) and gdb's regcache.  The word size is that used
1869   by the ptrace interface, not the current program's ABI.  Eg. if a
1870   powerpc64-linux gdb is being used to debug a powerpc32-linux app, we
1871   read or write 64-bit gregsets.  This is to suit the host libthread_db.  */
1872
1873void
1874supply_gregset (struct regcache *regcache, const gdb_gregset_t *gregsetp)
1875{
1876  const struct regset *regset = ppc_linux_gregset (sizeof (long));
1877
1878  ppc_supply_gregset (regset, regcache, -1, gregsetp, sizeof (*gregsetp));
1879}
1880
1881void
1882fill_gregset (const struct regcache *regcache,
1883	      gdb_gregset_t *gregsetp, int regno)
1884{
1885  const struct regset *regset = ppc_linux_gregset (sizeof (long));
1886
1887  if (regno == -1)
1888    memset (gregsetp, 0, sizeof (*gregsetp));
1889  ppc_collect_gregset (regset, regcache, regno, gregsetp, sizeof (*gregsetp));
1890}
1891
1892void
1893supply_fpregset (struct regcache *regcache, const gdb_fpregset_t * fpregsetp)
1894{
1895  const struct regset *regset = ppc_linux_fpregset ();
1896
1897  ppc_supply_fpregset (regset, regcache, -1,
1898		       fpregsetp, sizeof (*fpregsetp));
1899}
1900
1901void
1902fill_fpregset (const struct regcache *regcache,
1903	       gdb_fpregset_t *fpregsetp, int regno)
1904{
1905  const struct regset *regset = ppc_linux_fpregset ();
1906
1907  ppc_collect_fpregset (regset, regcache, regno,
1908			fpregsetp, sizeof (*fpregsetp));
1909}
1910
1911int
1912ppc_linux_nat_target::auxv_parse (gdb_byte **readptr,
1913				  gdb_byte *endptr, CORE_ADDR *typep,
1914				  CORE_ADDR *valp)
1915{
1916  int tid = inferior_ptid.lwp ();
1917  if (tid == 0)
1918    tid = inferior_ptid.pid ();
1919
1920  int sizeof_auxv_field = ppc_linux_target_wordsize (tid);
1921
1922  enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
1923  gdb_byte *ptr = *readptr;
1924
1925  if (endptr == ptr)
1926    return 0;
1927
1928  if (endptr - ptr < sizeof_auxv_field * 2)
1929    return -1;
1930
1931  *typep = extract_unsigned_integer (ptr, sizeof_auxv_field, byte_order);
1932  ptr += sizeof_auxv_field;
1933  *valp = extract_unsigned_integer (ptr, sizeof_auxv_field, byte_order);
1934  ptr += sizeof_auxv_field;
1935
1936  *readptr = ptr;
1937  return 1;
1938}
1939
1940const struct target_desc *
1941ppc_linux_nat_target::read_description ()
1942{
1943  int tid = inferior_ptid.lwp ();
1944  if (tid == 0)
1945    tid = inferior_ptid.pid ();
1946
1947  if (have_ptrace_getsetevrregs)
1948    {
1949      struct gdb_evrregset_t evrregset;
1950
1951      if (ptrace (PTRACE_GETEVRREGS, tid, 0, &evrregset) >= 0)
1952        return tdesc_powerpc_e500l;
1953
1954      /* EIO means that the PTRACE_GETEVRREGS request isn't supported.
1955	 Anything else needs to be reported.  */
1956      else if (errno != EIO)
1957	perror_with_name (_("Unable to fetch SPE registers"));
1958    }
1959
1960  struct ppc_linux_features features = ppc_linux_no_features;
1961
1962  features.wordsize = ppc_linux_target_wordsize (tid);
1963
1964  CORE_ADDR hwcap = linux_get_hwcap (current_top_target ());
1965  CORE_ADDR hwcap2 = linux_get_hwcap2 (current_top_target ());
1966
1967  if (have_ptrace_getsetvsxregs
1968      && (hwcap & PPC_FEATURE_HAS_VSX))
1969    {
1970      gdb_vsxregset_t vsxregset;
1971
1972      if (ptrace (PTRACE_GETVSXREGS, tid, 0, &vsxregset) >= 0)
1973	features.vsx = true;
1974
1975      /* EIO means that the PTRACE_GETVSXREGS request isn't supported.
1976	 Anything else needs to be reported.  */
1977      else if (errno != EIO)
1978	perror_with_name (_("Unable to fetch VSX registers"));
1979    }
1980
1981  if (have_ptrace_getvrregs
1982      && (hwcap & PPC_FEATURE_HAS_ALTIVEC))
1983    {
1984      gdb_vrregset_t vrregset;
1985
1986      if (ptrace (PTRACE_GETVRREGS, tid, 0, &vrregset) >= 0)
1987        features.altivec = true;
1988
1989      /* EIO means that the PTRACE_GETVRREGS request isn't supported.
1990	 Anything else needs to be reported.  */
1991      else if (errno != EIO)
1992	perror_with_name (_("Unable to fetch AltiVec registers"));
1993    }
1994
1995  features.isa205 = ppc_linux_has_isa205 (hwcap);
1996
1997  if ((hwcap2 & PPC_FEATURE2_DSCR)
1998      && check_regset (tid, NT_PPC_PPR, PPC_LINUX_SIZEOF_PPRREGSET)
1999      && check_regset (tid, NT_PPC_DSCR, PPC_LINUX_SIZEOF_DSCRREGSET))
2000    {
2001      features.ppr_dscr = true;
2002      if ((hwcap2 & PPC_FEATURE2_ARCH_2_07)
2003	  && (hwcap2 & PPC_FEATURE2_TAR)
2004	  && (hwcap2 & PPC_FEATURE2_EBB)
2005	  && check_regset (tid, NT_PPC_TAR, PPC_LINUX_SIZEOF_TARREGSET)
2006	  && check_regset (tid, NT_PPC_EBB, PPC_LINUX_SIZEOF_EBBREGSET)
2007	  && check_regset (tid, NT_PPC_PMU, PPC_LINUX_SIZEOF_PMUREGSET))
2008	{
2009	  features.isa207 = true;
2010	  if ((hwcap2 & PPC_FEATURE2_HTM)
2011	      && check_regset (tid, NT_PPC_TM_SPR,
2012			       PPC_LINUX_SIZEOF_TM_SPRREGSET))
2013	    features.htm = true;
2014	}
2015    }
2016
2017  return ppc_linux_match_description (features);
2018}
2019
2020/* Routines for installing hardware watchpoints and breakpoints.  When
2021   GDB requests a hardware watchpoint or breakpoint to be installed, we
2022   register the request for the pid of inferior_ptid in a map with one
2023   entry per process.  We then issue a stop request to all the threads of
2024   this process, and mark a per-thread flag indicating that their debug
2025   registers should be updated.  Right before they are next resumed, we
2026   remove all previously installed debug registers and install all the
2027   ones GDB requested.  We then update a map with one entry per thread
2028   that keeps track of what debug registers were last installed in each
2029   thread.
2030
2031   We use this second map to remove installed registers before installing
2032   the ones requested by GDB, and to copy the debug register state after
2033   a thread clones or forks, since depending on the kernel configuration,
2034   debug registers can be inherited.  */
2035
2036/* Check if we support and have enough resources to install a hardware
2037   watchpoint or breakpoint.  See the description in target.h.  */
2038
2039int
2040ppc_linux_nat_target::can_use_hw_breakpoint (enum bptype type, int cnt,
2041					     int ot)
2042{
2043  int total_hw_wp, total_hw_bp;
2044
2045  m_dreg_interface.detect (inferior_ptid);
2046
2047  if (m_dreg_interface.unavailable_p ())
2048    return 0;
2049
2050  if (m_dreg_interface.hwdebug_p ())
2051    {
2052      /* When PowerPC HWDEBUG ptrace interface is available, the number of
2053	 available hardware watchpoints and breakpoints is stored at the
2054	 hwdebug_info struct.  */
2055      total_hw_bp = m_dreg_interface.hwdebug_info ().num_instruction_bps;
2056      total_hw_wp = m_dreg_interface.hwdebug_info ().num_data_bps;
2057    }
2058  else
2059    {
2060      gdb_assert (m_dreg_interface.debugreg_p ());
2061
2062      /* With the DEBUGREG ptrace interface, we should consider having 1
2063	 hardware watchpoint and no hardware breakpoints.  */
2064      total_hw_bp = 0;
2065      total_hw_wp = 1;
2066    }
2067
2068  if (type == bp_hardware_watchpoint || type == bp_read_watchpoint
2069      || type == bp_access_watchpoint || type == bp_watchpoint)
2070    {
2071      if (total_hw_wp == 0)
2072	return 0;
2073      else if (cnt + ot > total_hw_wp)
2074	return -1;
2075      else
2076	return 1;
2077    }
2078  else if (type == bp_hardware_breakpoint)
2079    {
2080      if (total_hw_bp == 0)
2081	return 0;
2082      else if (cnt > total_hw_bp)
2083	return -1;
2084      else
2085	return 1;
2086    }
2087
2088  return 0;
2089}
2090
2091/* Returns 1 if we can watch LEN bytes at address ADDR, 0 otherwise.  */
2092
2093int
2094ppc_linux_nat_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
2095{
2096  /* Handle sub-8-byte quantities.  */
2097  if (len <= 0)
2098    return 0;
2099
2100  m_dreg_interface.detect (inferior_ptid);
2101
2102  if (m_dreg_interface.unavailable_p ())
2103    return 0;
2104
2105  /* The PowerPC HWDEBUG ptrace interface tells if there are alignment
2106     restrictions for watchpoints in the processors.  In that case, we use that
2107     information to determine the hardcoded watchable region for
2108     watchpoints.  */
2109  if (m_dreg_interface.hwdebug_p ())
2110    {
2111      int region_size;
2112      const struct ppc_debug_info &hwdebug_info = (m_dreg_interface
2113						   .hwdebug_info ());
2114
2115      /* Embedded DAC-based processors, like the PowerPC 440 have ranged
2116	 watchpoints and can watch any access within an arbitrary memory
2117	 region. This is useful to watch arrays and structs, for instance.  It
2118         takes two hardware watchpoints though.  */
2119      if (len > 1
2120	  && hwdebug_info.features & PPC_DEBUG_FEATURE_DATA_BP_RANGE
2121	  && linux_get_hwcap (current_top_target ()) & PPC_FEATURE_BOOKE)
2122	return 2;
2123      /* Check if the processor provides DAWR interface.  */
2124      if (hwdebug_info.features & PPC_DEBUG_FEATURE_DATA_BP_DAWR)
2125	/* DAWR interface allows to watch up to 512 byte wide ranges which
2126	   can't cross a 512 byte boundary.  */
2127	region_size = 512;
2128      else
2129	region_size = hwdebug_info.data_bp_alignment;
2130      /* Server processors provide one hardware watchpoint and addr+len should
2131         fall in the watchable region provided by the ptrace interface.  */
2132      if (region_size
2133	  && (addr + len > (addr & ~(region_size - 1)) + region_size))
2134	return 0;
2135    }
2136  /* addr+len must fall in the 8 byte watchable region for DABR-based
2137     processors (i.e., server processors).  Without the new PowerPC HWDEBUG
2138     ptrace interface, DAC-based processors (i.e., embedded processors) will
2139     use addresses aligned to 4-bytes due to the way the read/write flags are
2140     passed in the old ptrace interface.  */
2141  else
2142    {
2143      gdb_assert (m_dreg_interface.debugreg_p ());
2144
2145      if (((linux_get_hwcap (current_top_target ()) & PPC_FEATURE_BOOKE)
2146	   && (addr + len) > (addr & ~3) + 4)
2147	  || (addr + len) > (addr & ~7) + 8)
2148	return 0;
2149    }
2150
2151  return 1;
2152}
2153
2154/* This function compares two ppc_hw_breakpoint structs
2155   field-by-field.  */
2156
2157bool
2158ppc_linux_nat_target::hwdebug_point_cmp (const struct ppc_hw_breakpoint &a,
2159					 const struct ppc_hw_breakpoint &b)
2160{
2161  return (a.trigger_type == b.trigger_type
2162	  && a.addr_mode == b.addr_mode
2163	  && a.condition_mode == b.condition_mode
2164	  && a.addr == b.addr
2165	  && a.addr2 == b.addr2
2166	  && a.condition_value == b.condition_value);
2167}
2168
2169/* Return the number of registers needed for a ranged breakpoint.  */
2170
2171int
2172ppc_linux_nat_target::ranged_break_num_registers ()
2173{
2174  m_dreg_interface.detect (inferior_ptid);
2175
2176  return ((m_dreg_interface.hwdebug_p ()
2177	   && (m_dreg_interface.hwdebug_info ().features
2178	       & PPC_DEBUG_FEATURE_INSN_BP_RANGE))?
2179	  2 : -1);
2180}
2181
2182/* Register the hardware breakpoint described by BP_TGT, to be inserted
2183   when the threads of inferior_ptid are resumed.  Returns 0 for success,
2184   or -1 if the HWDEBUG interface that we need for hardware breakpoints
2185   is not available.  */
2186
2187int
2188ppc_linux_nat_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
2189					    struct bp_target_info *bp_tgt)
2190{
2191  struct ppc_hw_breakpoint p;
2192
2193  m_dreg_interface.detect (inferior_ptid);
2194
2195  if (!m_dreg_interface.hwdebug_p ())
2196    return -1;
2197
2198  p.version = PPC_DEBUG_CURRENT_VERSION;
2199  p.trigger_type = PPC_BREAKPOINT_TRIGGER_EXECUTE;
2200  p.condition_mode = PPC_BREAKPOINT_CONDITION_NONE;
2201  p.addr = (uint64_t) (bp_tgt->placed_address = bp_tgt->reqstd_address);
2202  p.condition_value = 0;
2203
2204  if (bp_tgt->length)
2205    {
2206      p.addr_mode = PPC_BREAKPOINT_MODE_RANGE_INCLUSIVE;
2207
2208      /* The breakpoint will trigger if the address of the instruction is
2209	 within the defined range, as follows: p.addr <= address < p.addr2.  */
2210      p.addr2 = (uint64_t) bp_tgt->placed_address + bp_tgt->length;
2211    }
2212  else
2213    {
2214      p.addr_mode = PPC_BREAKPOINT_MODE_EXACT;
2215      p.addr2 = 0;
2216    }
2217
2218  register_hw_breakpoint (inferior_ptid.pid (), p);
2219
2220  return 0;
2221}
2222
2223/* Clear a registration for the hardware breakpoint given by type BP_TGT.
2224   It will be removed from the threads of inferior_ptid when they are
2225   next resumed.  Returns 0 for success, or -1 if the HWDEBUG interface
2226   that we need for hardware breakpoints is not available.  */
2227
2228int
2229ppc_linux_nat_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
2230					    struct bp_target_info *bp_tgt)
2231{
2232  struct ppc_hw_breakpoint p;
2233
2234  m_dreg_interface.detect (inferior_ptid);
2235
2236  if (!m_dreg_interface.hwdebug_p ())
2237    return -1;
2238
2239  p.version = PPC_DEBUG_CURRENT_VERSION;
2240  p.trigger_type = PPC_BREAKPOINT_TRIGGER_EXECUTE;
2241  p.condition_mode = PPC_BREAKPOINT_CONDITION_NONE;
2242  p.addr = (uint64_t) bp_tgt->placed_address;
2243  p.condition_value = 0;
2244
2245  if (bp_tgt->length)
2246    {
2247      p.addr_mode = PPC_BREAKPOINT_MODE_RANGE_INCLUSIVE;
2248
2249      /* The breakpoint will trigger if the address of the instruction is within
2250	 the defined range, as follows: p.addr <= address < p.addr2.  */
2251      p.addr2 = (uint64_t) bp_tgt->placed_address + bp_tgt->length;
2252    }
2253  else
2254    {
2255      p.addr_mode = PPC_BREAKPOINT_MODE_EXACT;
2256      p.addr2 = 0;
2257    }
2258
2259  clear_hw_breakpoint (inferior_ptid.pid (), p);
2260
2261  return 0;
2262}
2263
2264/* Return the trigger value to set in a ppc_hw_breakpoint object for a
2265   given hardware watchpoint TYPE.  We assume type is not hw_execute.  */
2266
2267int
2268ppc_linux_nat_target::get_trigger_type (enum target_hw_bp_type type)
2269{
2270  int t;
2271
2272  if (type == hw_read)
2273    t = PPC_BREAKPOINT_TRIGGER_READ;
2274  else if (type == hw_write)
2275    t = PPC_BREAKPOINT_TRIGGER_WRITE;
2276  else
2277    t = PPC_BREAKPOINT_TRIGGER_READ | PPC_BREAKPOINT_TRIGGER_WRITE;
2278
2279  return t;
2280}
2281
2282/* Register a new masked watchpoint at ADDR using the mask MASK, to be
2283   inserted when the threads of inferior_ptid are resumed.  RW may be
2284   hw_read for a read watchpoint, hw_write for a write watchpoint or
2285   hw_access for an access watchpoint.  */
2286
2287int
2288ppc_linux_nat_target::insert_mask_watchpoint (CORE_ADDR addr,  CORE_ADDR mask,
2289					      target_hw_bp_type rw)
2290{
2291  struct ppc_hw_breakpoint p;
2292
2293  gdb_assert (m_dreg_interface.hwdebug_p ());
2294
2295  p.version = PPC_DEBUG_CURRENT_VERSION;
2296  p.trigger_type = get_trigger_type (rw);
2297  p.addr_mode = PPC_BREAKPOINT_MODE_MASK;
2298  p.condition_mode = PPC_BREAKPOINT_CONDITION_NONE;
2299  p.addr = addr;
2300  p.addr2 = mask;
2301  p.condition_value = 0;
2302
2303  register_hw_breakpoint (inferior_ptid.pid (), p);
2304
2305  return 0;
2306}
2307
2308/* Clear a registration for a masked watchpoint at ADDR with the mask
2309   MASK.  It will be removed from the threads of inferior_ptid when they
2310   are next resumed.  RW may be hw_read for a read watchpoint, hw_write
2311   for a write watchpoint or hw_access for an access watchpoint.  */
2312
2313int
2314ppc_linux_nat_target::remove_mask_watchpoint (CORE_ADDR addr, CORE_ADDR mask,
2315					      target_hw_bp_type rw)
2316{
2317  struct ppc_hw_breakpoint p;
2318
2319  gdb_assert (m_dreg_interface.hwdebug_p ());
2320
2321  p.version = PPC_DEBUG_CURRENT_VERSION;
2322  p.trigger_type = get_trigger_type (rw);
2323  p.addr_mode = PPC_BREAKPOINT_MODE_MASK;
2324  p.condition_mode = PPC_BREAKPOINT_CONDITION_NONE;
2325  p.addr = addr;
2326  p.addr2 = mask;
2327  p.condition_value = 0;
2328
2329  clear_hw_breakpoint (inferior_ptid.pid (), p);
2330
2331  return 0;
2332}
2333
2334/* Check whether we have at least one free DVC register for the threads
2335   of the pid of inferior_ptid.  */
2336
2337bool
2338ppc_linux_nat_target::can_use_watchpoint_cond_accel (void)
2339{
2340  m_dreg_interface.detect (inferior_ptid);
2341
2342  if (!m_dreg_interface.hwdebug_p ())
2343    return false;
2344
2345  int cnt = m_dreg_interface.hwdebug_info ().num_condition_regs;
2346
2347  if (cnt == 0)
2348    return false;
2349
2350  auto process_it = m_process_info.find (inferior_ptid.pid ());
2351
2352  /* No breakpoints or watchpoints have been requested for this process,
2353     we have at least one free DVC register.  */
2354  if (process_it == m_process_info.end ())
2355    return true;
2356
2357  for (const ppc_hw_breakpoint &bp : process_it->second.requested_hw_bps)
2358    if (bp.condition_mode != PPC_BREAKPOINT_CONDITION_NONE)
2359      cnt--;
2360
2361  if (cnt <= 0)
2362    return false;
2363
2364  return true;
2365}
2366
2367/* Calculate the enable bits and the contents of the Data Value Compare
2368   debug register present in BookE processors.
2369
2370   ADDR is the address to be watched, LEN is the length of watched data
2371   and DATA_VALUE is the value which will trigger the watchpoint.
2372   On exit, CONDITION_MODE will hold the enable bits for the DVC, and
2373   CONDITION_VALUE will hold the value which should be put in the
2374   DVC register.  */
2375
2376void
2377ppc_linux_nat_target::calculate_dvc (CORE_ADDR addr, int len,
2378				     CORE_ADDR data_value,
2379				     uint32_t *condition_mode,
2380				     uint64_t *condition_value)
2381{
2382  const struct ppc_debug_info &hwdebug_info = (m_dreg_interface.
2383					       hwdebug_info ());
2384
2385  int i, num_byte_enable, align_offset, num_bytes_off_dvc,
2386      rightmost_enabled_byte;
2387  CORE_ADDR addr_end_data, addr_end_dvc;
2388
2389  /* The DVC register compares bytes within fixed-length windows which
2390     are word-aligned, with length equal to that of the DVC register.
2391     We need to calculate where our watch region is relative to that
2392     window and enable comparison of the bytes which fall within it.  */
2393
2394  align_offset = addr % hwdebug_info.sizeof_condition;
2395  addr_end_data = addr + len;
2396  addr_end_dvc = (addr - align_offset
2397		  + hwdebug_info.sizeof_condition);
2398  num_bytes_off_dvc = (addr_end_data > addr_end_dvc)?
2399			 addr_end_data - addr_end_dvc : 0;
2400  num_byte_enable = len - num_bytes_off_dvc;
2401  /* Here, bytes are numbered from right to left.  */
2402  rightmost_enabled_byte = (addr_end_data < addr_end_dvc)?
2403			      addr_end_dvc - addr_end_data : 0;
2404
2405  *condition_mode = PPC_BREAKPOINT_CONDITION_AND;
2406  for (i = 0; i < num_byte_enable; i++)
2407    *condition_mode
2408      |= PPC_BREAKPOINT_CONDITION_BE (i + rightmost_enabled_byte);
2409
2410  /* Now we need to match the position within the DVC of the comparison
2411     value with where the watch region is relative to the window
2412     (i.e., the ALIGN_OFFSET).  */
2413
2414  *condition_value = ((uint64_t) data_value >> num_bytes_off_dvc * 8
2415		      << rightmost_enabled_byte * 8);
2416}
2417
2418/* Return the number of memory locations that need to be accessed to
2419   evaluate the expression which generated the given value chain.
2420   Returns -1 if there's any register access involved, or if there are
2421   other kinds of values which are not acceptable in a condition
2422   expression (e.g., lval_computed or lval_internalvar).  */
2423
2424int
2425ppc_linux_nat_target::num_memory_accesses (const std::vector<value_ref_ptr>
2426					   &chain)
2427{
2428  int found_memory_cnt = 0;
2429
2430  /* The idea here is that evaluating an expression generates a series
2431     of values, one holding the value of every subexpression.  (The
2432     expression a*b+c has five subexpressions: a, b, a*b, c, and
2433     a*b+c.)  GDB's values hold almost enough information to establish
2434     the criteria given above --- they identify memory lvalues,
2435     register lvalues, computed values, etcetera.  So we can evaluate
2436     the expression, and then scan the chain of values that leaves
2437     behind to determine the memory locations involved in the evaluation
2438     of an expression.
2439
2440     However, I don't think that the values returned by inferior
2441     function calls are special in any way.  So this function may not
2442     notice that an expression contains an inferior function call.
2443     FIXME.  */
2444
2445  for (const value_ref_ptr &iter : chain)
2446    {
2447      struct value *v = iter.get ();
2448
2449      /* Constants and values from the history are fine.  */
2450      if (VALUE_LVAL (v) == not_lval || deprecated_value_modifiable (v) == 0)
2451	continue;
2452      else if (VALUE_LVAL (v) == lval_memory)
2453	{
2454	  /* A lazy memory lvalue is one that GDB never needed to fetch;
2455	     we either just used its address (e.g., `a' in `a.b') or
2456	     we never needed it at all (e.g., `a' in `a,b').  */
2457	  if (!value_lazy (v))
2458	    found_memory_cnt++;
2459	}
2460      /* Other kinds of values are not fine.  */
2461      else
2462	return -1;
2463    }
2464
2465  return found_memory_cnt;
2466}
2467
2468/* Verifies whether the expression COND can be implemented using the
2469   DVC (Data Value Compare) register in BookE processors.  The expression
2470   must test the watch value for equality with a constant expression.
2471   If the function returns 1, DATA_VALUE will contain the constant against
2472   which the watch value should be compared and LEN will contain the size
2473   of the constant.  */
2474
2475int
2476ppc_linux_nat_target::check_condition (CORE_ADDR watch_addr,
2477				       struct expression *cond,
2478				       CORE_ADDR *data_value, int *len)
2479{
2480  int pc = 1, num_accesses_left, num_accesses_right;
2481  struct value *left_val, *right_val;
2482  std::vector<value_ref_ptr> left_chain, right_chain;
2483
2484  if (cond->elts[0].opcode != BINOP_EQUAL)
2485    return 0;
2486
2487  fetch_subexp_value (cond, &pc, &left_val, NULL, &left_chain, 0);
2488  num_accesses_left = num_memory_accesses (left_chain);
2489
2490  if (left_val == NULL || num_accesses_left < 0)
2491    return 0;
2492
2493  fetch_subexp_value (cond, &pc, &right_val, NULL, &right_chain, 0);
2494  num_accesses_right = num_memory_accesses (right_chain);
2495
2496  if (right_val == NULL || num_accesses_right < 0)
2497    return 0;
2498
2499  if (num_accesses_left == 1 && num_accesses_right == 0
2500      && VALUE_LVAL (left_val) == lval_memory
2501      && value_address (left_val) == watch_addr)
2502    {
2503      *data_value = value_as_long (right_val);
2504
2505      /* DATA_VALUE is the constant in RIGHT_VAL, but actually has
2506	 the same type as the memory region referenced by LEFT_VAL.  */
2507      *len = TYPE_LENGTH (check_typedef (value_type (left_val)));
2508    }
2509  else if (num_accesses_left == 0 && num_accesses_right == 1
2510	   && VALUE_LVAL (right_val) == lval_memory
2511	   && value_address (right_val) == watch_addr)
2512    {
2513      *data_value = value_as_long (left_val);
2514
2515      /* DATA_VALUE is the constant in LEFT_VAL, but actually has
2516	 the same type as the memory region referenced by RIGHT_VAL.  */
2517      *len = TYPE_LENGTH (check_typedef (value_type (right_val)));
2518    }
2519  else
2520    return 0;
2521
2522  return 1;
2523}
2524
2525/* Return true if the target is capable of using hardware to evaluate the
2526   condition expression, thus only triggering the watchpoint when it is
2527   true.  */
2528
2529bool
2530ppc_linux_nat_target::can_accel_watchpoint_condition (CORE_ADDR addr,
2531						      int len, int rw,
2532						      struct expression *cond)
2533{
2534  CORE_ADDR data_value;
2535
2536  m_dreg_interface.detect (inferior_ptid);
2537
2538  return (m_dreg_interface.hwdebug_p ()
2539	  && (m_dreg_interface.hwdebug_info ().num_condition_regs > 0)
2540	  && check_condition (addr, cond, &data_value, &len));
2541}
2542
2543/* Set up P with the parameters necessary to request a watchpoint covering
2544   LEN bytes starting at ADDR and if possible with condition expression COND
2545   evaluated by hardware.  INSERT tells if we are creating a request for
2546   inserting or removing the watchpoint.  */
2547
2548void
2549ppc_linux_nat_target::create_watchpoint_request (struct ppc_hw_breakpoint *p,
2550						 CORE_ADDR addr, int len,
2551						 enum target_hw_bp_type type,
2552						 struct expression *cond,
2553						 int insert)
2554{
2555  const struct ppc_debug_info &hwdebug_info = (m_dreg_interface
2556					       .hwdebug_info ());
2557
2558  if (len == 1
2559      || !(hwdebug_info.features & PPC_DEBUG_FEATURE_DATA_BP_RANGE))
2560    {
2561      int use_condition;
2562      CORE_ADDR data_value;
2563
2564      use_condition = (insert? can_use_watchpoint_cond_accel ()
2565			: hwdebug_info.num_condition_regs > 0);
2566      if (cond && use_condition && check_condition (addr, cond,
2567						    &data_value, &len))
2568	calculate_dvc (addr, len, data_value, &p->condition_mode,
2569		       &p->condition_value);
2570      else
2571	{
2572	  p->condition_mode = PPC_BREAKPOINT_CONDITION_NONE;
2573	  p->condition_value = 0;
2574	}
2575
2576      p->addr_mode = PPC_BREAKPOINT_MODE_EXACT;
2577      p->addr2 = 0;
2578    }
2579  else
2580    {
2581      p->addr_mode = PPC_BREAKPOINT_MODE_RANGE_INCLUSIVE;
2582      p->condition_mode = PPC_BREAKPOINT_CONDITION_NONE;
2583      p->condition_value = 0;
2584
2585      /* The watchpoint will trigger if the address of the memory access is
2586	 within the defined range, as follows: p->addr <= address < p->addr2.
2587
2588	 Note that the above sentence just documents how ptrace interprets
2589	 its arguments; the watchpoint is set to watch the range defined by
2590	 the user _inclusively_, as specified by the user interface.  */
2591      p->addr2 = (uint64_t) addr + len;
2592    }
2593
2594  p->version = PPC_DEBUG_CURRENT_VERSION;
2595  p->trigger_type = get_trigger_type (type);
2596  p->addr = (uint64_t) addr;
2597}
2598
2599/* Register a watchpoint, to be inserted when the threads of the group of
2600   inferior_ptid are next resumed.  Returns 0 on success, and -1 if there
2601   is no ptrace interface available to install the watchpoint.  */
2602
2603int
2604ppc_linux_nat_target::insert_watchpoint (CORE_ADDR addr, int len,
2605					 enum target_hw_bp_type type,
2606					 struct expression *cond)
2607{
2608  m_dreg_interface.detect (inferior_ptid);
2609
2610  if (m_dreg_interface.unavailable_p ())
2611    return -1;
2612
2613  if (m_dreg_interface.hwdebug_p ())
2614    {
2615      struct ppc_hw_breakpoint p;
2616
2617      create_watchpoint_request (&p, addr, len, type, cond, 1);
2618
2619      register_hw_breakpoint (inferior_ptid.pid (), p);
2620    }
2621  else
2622    {
2623      gdb_assert (m_dreg_interface.debugreg_p ());
2624
2625      long wp_value;
2626      long read_mode, write_mode;
2627
2628      if (linux_get_hwcap (current_top_target ()) & PPC_FEATURE_BOOKE)
2629	{
2630	  /* PowerPC 440 requires only the read/write flags to be passed
2631	     to the kernel.  */
2632	  read_mode = 1;
2633	  write_mode = 2;
2634	}
2635      else
2636	{
2637	  /* PowerPC 970 and other DABR-based processors are required to pass
2638	     the Breakpoint Translation bit together with the flags.  */
2639	  read_mode = 5;
2640	  write_mode = 6;
2641	}
2642
2643      wp_value = addr & ~(read_mode | write_mode);
2644      switch (type)
2645	{
2646	  case hw_read:
2647	    /* Set read and translate bits.  */
2648	    wp_value |= read_mode;
2649	    break;
2650	  case hw_write:
2651	    /* Set write and translate bits.  */
2652	    wp_value |= write_mode;
2653	    break;
2654	  case hw_access:
2655	    /* Set read, write and translate bits.  */
2656	    wp_value |= read_mode | write_mode;
2657	    break;
2658	}
2659
2660      register_wp (inferior_ptid.pid (), wp_value);
2661    }
2662
2663  return 0;
2664}
2665
2666/* Clear a registration for a hardware watchpoint.  It will be removed
2667   from the threads of the group of inferior_ptid when they are next
2668   resumed.  */
2669
2670int
2671ppc_linux_nat_target::remove_watchpoint (CORE_ADDR addr, int len,
2672					 enum target_hw_bp_type type,
2673					 struct expression *cond)
2674{
2675  gdb_assert (!m_dreg_interface.unavailable_p ());
2676
2677  if (m_dreg_interface.hwdebug_p ())
2678    {
2679      struct ppc_hw_breakpoint p;
2680
2681      create_watchpoint_request (&p, addr, len, type, cond, 0);
2682
2683      clear_hw_breakpoint (inferior_ptid.pid (), p);
2684    }
2685  else
2686    {
2687      gdb_assert (m_dreg_interface.debugreg_p ());
2688
2689      clear_wp (inferior_ptid.pid ());
2690    }
2691
2692  return 0;
2693}
2694
2695/* Clean up the per-process info associated with PID.  When using the
2696   HWDEBUG interface, we also erase the per-thread state of installed
2697   debug registers for all the threads that belong to the group of PID.
2698
2699   Usually the thread state is cleaned up by low_delete_thread.  We also
2700   do it here because low_new_thread is not called for the initial LWP,
2701   so low_delete_thread won't be able to clean up this state.  */
2702
2703void
2704ppc_linux_nat_target::low_forget_process (pid_t pid)
2705{
2706  if ((!m_dreg_interface.detected_p ())
2707      || (m_dreg_interface.unavailable_p ()))
2708    return;
2709
2710  ptid_t pid_ptid (pid, 0, 0);
2711
2712  m_process_info.erase (pid);
2713
2714  if (m_dreg_interface.hwdebug_p ())
2715    {
2716      for (auto it = m_installed_hw_bps.begin ();
2717	   it != m_installed_hw_bps.end ();)
2718	{
2719	  if (it->first.matches (pid_ptid))
2720	    it = m_installed_hw_bps.erase (it);
2721	  else
2722	    it++;
2723	}
2724    }
2725}
2726
2727/* Copy the per-process state associated with the pid of PARENT to the
2728   sate of CHILD_PID.  GDB expects that a forked process will have the
2729   same hardware breakpoints and watchpoints as the parent.
2730
2731   If we're using the HWDEBUG interface, also copy the thread debug
2732   register state for the ptid of PARENT to the state for CHILD_PID.
2733
2734   Like for clone events, we assume the kernel will copy the debug
2735   registers from the parent thread to the child. The
2736   low_prepare_to_resume function is made to work even if it doesn't.
2737
2738   We copy the thread state here and not in low_new_thread since we don't
2739   have the pid of the parent in low_new_thread.  Even if we did,
2740   low_new_thread might not be called immediately after the fork event is
2741   detected.  For instance, with the checkpointing system (see
2742   linux-fork.c), the thread won't be added until GDB decides to switch
2743   to a new checkpointed process.  At that point, the debug register
2744   state of the parent thread is unlikely to correspond to the state it
2745   had at the point when it forked.  */
2746
2747void
2748ppc_linux_nat_target::low_new_fork (struct lwp_info *parent,
2749				    pid_t child_pid)
2750{
2751  if ((!m_dreg_interface.detected_p ())
2752      || (m_dreg_interface.unavailable_p ()))
2753    return;
2754
2755  auto process_it = m_process_info.find (parent->ptid.pid ());
2756
2757  if (process_it != m_process_info.end ())
2758    m_process_info[child_pid] = m_process_info[parent->ptid.pid ()];
2759
2760  if (m_dreg_interface.hwdebug_p ())
2761    {
2762      ptid_t child_ptid (child_pid, child_pid, 0);
2763
2764      copy_thread_dreg_state (parent->ptid, child_ptid);
2765    }
2766}
2767
2768/* Copy the thread debug register state from the PARENT thread to the the
2769   state for CHILD_LWP, if we're using the HWDEBUG interface.  We assume
2770   the kernel copies the debug registers from one thread to another after
2771   a clone event.  The low_prepare_to_resume function is made to work
2772   even if it doesn't.  */
2773
2774void
2775ppc_linux_nat_target::low_new_clone (struct lwp_info *parent,
2776				     pid_t child_lwp)
2777{
2778  if ((!m_dreg_interface.detected_p ())
2779      || (m_dreg_interface.unavailable_p ()))
2780    return;
2781
2782  if (m_dreg_interface.hwdebug_p ())
2783    {
2784      ptid_t child_ptid (parent->ptid.pid (), child_lwp, 0);
2785
2786      copy_thread_dreg_state (parent->ptid, child_ptid);
2787    }
2788}
2789
2790/* Initialize the arch-specific thread state for LP so that it contains
2791   the ptid for lp, so that we can use it in low_delete_thread.  Mark the
2792   new thread LP as stale so that we update its debug registers before
2793   resuming it.  This is not called for the initial thread.  */
2794
2795void
2796ppc_linux_nat_target::low_new_thread (struct lwp_info *lp)
2797{
2798  init_arch_lwp_info (lp);
2799
2800  mark_thread_stale (lp);
2801}
2802
2803/* Delete the per-thread debug register stale flag.  */
2804
2805void
2806ppc_linux_nat_target::low_delete_thread (struct arch_lwp_info
2807					 *lp_arch_info)
2808{
2809  if (lp_arch_info != NULL)
2810    {
2811      if (m_dreg_interface.detected_p ()
2812	  && m_dreg_interface.hwdebug_p ())
2813	m_installed_hw_bps.erase (lp_arch_info->lwp_ptid);
2814
2815      xfree (lp_arch_info);
2816    }
2817}
2818
2819/* Install or delete debug registers in thread LP so that it matches what
2820   GDB requested before it is resumed.  */
2821
2822void
2823ppc_linux_nat_target::low_prepare_to_resume (struct lwp_info *lp)
2824{
2825  if ((!m_dreg_interface.detected_p ())
2826      || (m_dreg_interface.unavailable_p ()))
2827    return;
2828
2829  /* We have to re-install or clear the debug registers if we set the
2830     stale flag.
2831
2832     In addition, some kernels configurations can disable a hardware
2833     watchpoint after it is hit.  Usually, GDB will remove and re-install
2834     a hardware watchpoint when the thread stops if "breakpoint
2835     always-inserted" is off, or to single-step a watchpoint.  But so
2836     that we don't rely on this behavior, if we stop due to a hardware
2837     breakpoint or watchpoint, we also refresh our debug registers.  */
2838
2839  arch_lwp_info *lp_arch_info = get_arch_lwp_info (lp);
2840
2841  bool stale_dregs = (lp->stop_reason == TARGET_STOPPED_BY_WATCHPOINT
2842		      || lp->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT
2843		      || lp_arch_info->debug_regs_stale);
2844
2845  if (!stale_dregs)
2846    return;
2847
2848  gdb_assert (lp->ptid.lwp_p ());
2849
2850  auto process_it = m_process_info.find (lp->ptid.pid ());
2851
2852  if (m_dreg_interface.hwdebug_p ())
2853    {
2854      /* First, delete any hardware watchpoint or breakpoint installed in
2855	 the inferior and update the thread state.  */
2856      auto installed_it = m_installed_hw_bps.find (lp->ptid);
2857
2858      if (installed_it != m_installed_hw_bps.end ())
2859	{
2860	  auto &bp_list = installed_it->second;
2861
2862	  for (auto bp_it = bp_list.begin (); bp_it != bp_list.end ();)
2863	    {
2864	      /* We ignore ENOENT to account for various possible kernel
2865		 behaviors, e.g. the kernel might or might not copy debug
2866		 registers across forks and clones, and we always copy
2867		 the debug register state when fork and clone events are
2868		 detected.  */
2869	      if (ptrace (PPC_PTRACE_DELHWDEBUG, lp->ptid.lwp (), 0,
2870			  bp_it->first) < 0)
2871		if (errno != ENOENT)
2872		  perror_with_name (_("Error deleting hardware "
2873				      "breakpoint or watchpoint"));
2874
2875	      /* We erase the entries one at a time after successfuly
2876		 removing the corresponding slot form the thread so that
2877		 if we throw an exception above in a future iteration the
2878		 map remains consistent.  */
2879	      bp_it = bp_list.erase (bp_it);
2880	    }
2881
2882	  gdb_assert (bp_list.empty ());
2883	}
2884
2885      /* Now we install all the requested hardware breakpoints and
2886	 watchpoints and update the thread state.  */
2887
2888      if (process_it != m_process_info.end ())
2889	{
2890	  auto &bp_list = m_installed_hw_bps[lp->ptid];
2891
2892	  for (ppc_hw_breakpoint bp
2893		 : process_it->second.requested_hw_bps)
2894	    {
2895	      long slot = ptrace (PPC_PTRACE_SETHWDEBUG, lp->ptid.lwp (),
2896				  0, &bp);
2897
2898	      if (slot < 0)
2899		perror_with_name (_("Error setting hardware "
2900				    "breakpoint or watchpoint"));
2901
2902	      /* Keep track of which slots we installed in this
2903		 thread.  */
2904	      bp_list.emplace (bp_list.begin (), slot, bp);
2905	    }
2906	}
2907    }
2908  else
2909    {
2910      gdb_assert (m_dreg_interface.debugreg_p ());
2911
2912      /* Passing 0 to PTRACE_SET_DEBUGREG will clear the watchpoint.  We
2913	 always clear the watchpoint instead of just overwriting it, in
2914	 case there is a request for a new watchpoint, because on some
2915	 older kernel versions and configurations simply overwriting the
2916	 watchpoint after it was hit would not re-enable it.  */
2917      if (ptrace (PTRACE_SET_DEBUGREG, lp->ptid.lwp (), 0, 0) < 0)
2918	perror_with_name (_("Error clearing hardware watchpoint"));
2919
2920      /* GDB requested a watchpoint to be installed.  */
2921      if (process_it != m_process_info.end ()
2922	  && process_it->second.requested_wp_val.has_value ())
2923	{
2924	  long wp = *(process_it->second.requested_wp_val);
2925
2926	  if (ptrace (PTRACE_SET_DEBUGREG, lp->ptid.lwp (), 0, wp) < 0)
2927	    perror_with_name (_("Error setting hardware watchpoint"));
2928	}
2929    }
2930
2931  lp_arch_info->debug_regs_stale = false;
2932}
2933
2934/* Return true if INFERIOR_PTID is known to have been stopped by a
2935   hardware watchpoint, false otherwise.  If true is returned, write the
2936   address that the kernel reported as causing the SIGTRAP in ADDR_P.  */
2937
2938bool
2939ppc_linux_nat_target::low_stopped_data_address (CORE_ADDR *addr_p)
2940{
2941  siginfo_t siginfo;
2942
2943  if (!linux_nat_get_siginfo (inferior_ptid, &siginfo))
2944    return false;
2945
2946  if (siginfo.si_signo != SIGTRAP
2947      || (siginfo.si_code & 0xffff) != 0x0004 /* TRAP_HWBKPT */)
2948    return false;
2949
2950  gdb_assert (!m_dreg_interface.unavailable_p ());
2951
2952  /* Check if this signal corresponds to a hardware breakpoint.  We only
2953     need to check this if we're using the HWDEBUG interface, since the
2954     DEBUGREG interface only allows setting one hardware watchpoint.  */
2955  if (m_dreg_interface.hwdebug_p ())
2956    {
2957      /* The index (or slot) of the *point is passed in the si_errno
2958	 field.  Currently, this is only the case if the kernel was
2959	 configured with CONFIG_PPC_ADV_DEBUG_REGS.  If not, we assume
2960	 the kernel will set si_errno to a value that doesn't correspond
2961	 to any real slot.  */
2962      int slot = siginfo.si_errno;
2963
2964      auto installed_it = m_installed_hw_bps.find (inferior_ptid);
2965
2966      /* We must have installed slots for the thread if it got a
2967	 TRAP_HWBKPT signal.  */
2968      gdb_assert (installed_it != m_installed_hw_bps.end ());
2969
2970      for (const auto & slot_bp_pair : installed_it->second)
2971	if (slot_bp_pair.first == slot
2972	    && (slot_bp_pair.second.trigger_type
2973		== PPC_BREAKPOINT_TRIGGER_EXECUTE))
2974	  return false;
2975    }
2976
2977  *addr_p = (CORE_ADDR) (uintptr_t) siginfo.si_addr;
2978  return true;
2979}
2980
2981/* Return true if INFERIOR_PTID is known to have been stopped by a
2982   hardware watchpoint, false otherwise.  */
2983
2984bool
2985ppc_linux_nat_target::low_stopped_by_watchpoint ()
2986{
2987  CORE_ADDR addr;
2988  return low_stopped_data_address (&addr);
2989}
2990
2991bool
2992ppc_linux_nat_target::watchpoint_addr_within_range (CORE_ADDR addr,
2993						    CORE_ADDR start,
2994						    int length)
2995{
2996  gdb_assert (!m_dreg_interface.unavailable_p ());
2997
2998  int mask;
2999
3000  if (m_dreg_interface.hwdebug_p ()
3001      && linux_get_hwcap (current_top_target ()) & PPC_FEATURE_BOOKE)
3002    return start <= addr && start + length >= addr;
3003  else if (linux_get_hwcap (current_top_target ()) & PPC_FEATURE_BOOKE)
3004    mask = 3;
3005  else
3006    mask = 7;
3007
3008  addr &= ~mask;
3009
3010  /* Check whether [start, start+length-1] intersects [addr, addr+mask].  */
3011  return start <= addr + mask && start + length - 1 >= addr;
3012}
3013
3014/* Return the number of registers needed for a masked hardware watchpoint.  */
3015
3016int
3017ppc_linux_nat_target::masked_watch_num_registers (CORE_ADDR addr,
3018						  CORE_ADDR mask)
3019{
3020  m_dreg_interface.detect (inferior_ptid);
3021
3022  if (!m_dreg_interface.hwdebug_p ()
3023      || (m_dreg_interface.hwdebug_info ().features
3024	  & PPC_DEBUG_FEATURE_DATA_BP_MASK) == 0)
3025    return -1;
3026  else if ((mask & 0xC0000000) != 0xC0000000)
3027    {
3028      warning (_("The given mask covers kernel address space "
3029		 "and cannot be used.\n"));
3030
3031      return -2;
3032    }
3033  else
3034    return 2;
3035}
3036
3037/* Copy the per-thread debug register state, if any, from thread
3038   PARENT_PTID to thread CHILD_PTID, if the debug register being used is
3039   HWDEBUG.  */
3040
3041void
3042ppc_linux_nat_target::copy_thread_dreg_state (const ptid_t &parent_ptid,
3043					      const ptid_t &child_ptid)
3044{
3045  gdb_assert (m_dreg_interface.hwdebug_p ());
3046
3047  auto installed_it = m_installed_hw_bps.find (parent_ptid);
3048
3049  if (installed_it != m_installed_hw_bps.end ())
3050    m_installed_hw_bps[child_ptid] = m_installed_hw_bps[parent_ptid];
3051}
3052
3053/* Mark the debug register stale flag for the new thread, if we have
3054   already detected which debug register interface we use.  */
3055
3056void
3057ppc_linux_nat_target::mark_thread_stale (struct lwp_info *lp)
3058{
3059  if ((!m_dreg_interface.detected_p ())
3060      || (m_dreg_interface.unavailable_p ()))
3061    return;
3062
3063  arch_lwp_info *lp_arch_info = get_arch_lwp_info (lp);
3064
3065  lp_arch_info->debug_regs_stale = true;
3066}
3067
3068/* Mark all the threads of the group of PID as stale with respect to
3069   debug registers and issue a stop request to each such thread that
3070   isn't already stopped.  */
3071
3072void
3073ppc_linux_nat_target::mark_debug_registers_changed (pid_t pid)
3074{
3075  /* We do this in two passes to make sure all threads are marked even if
3076     we get an exception when stopping one of them.  */
3077
3078  iterate_over_lwps (ptid_t (pid),
3079		     [this] (struct lwp_info *lp) -> int {
3080		       this->mark_thread_stale (lp);
3081		       return 0;
3082		     });
3083
3084  iterate_over_lwps (ptid_t (pid),
3085		     [] (struct lwp_info *lp) -> int {
3086		       if (!lwp_is_stopped (lp))
3087			 linux_stop_lwp (lp);
3088		       return 0;
3089		     });
3090}
3091
3092/* Register a hardware breakpoint or watchpoint BP for the pid PID, then
3093   mark the stale flag for all threads of the group of PID, and issue a
3094   stop request for them.  The breakpoint or watchpoint will be installed
3095   the next time each thread is resumed.  Should only be used if the
3096   debug register interface is HWDEBUG.  */
3097
3098void
3099ppc_linux_nat_target::register_hw_breakpoint (pid_t pid,
3100					      const struct
3101					      ppc_hw_breakpoint &bp)
3102{
3103  gdb_assert (m_dreg_interface.hwdebug_p ());
3104
3105  m_process_info[pid].requested_hw_bps.push_back (bp);
3106
3107  mark_debug_registers_changed (pid);
3108}
3109
3110/* Clear a registration for a hardware breakpoint or watchpoint BP for
3111   the pid PID, then mark the stale flag for all threads of the group of
3112   PID, and issue a stop request for them.  The breakpoint or watchpoint
3113   will be removed the next time each thread is resumed.  Should only be
3114   used if the debug register interface is HWDEBUG.  */
3115
3116void
3117ppc_linux_nat_target::clear_hw_breakpoint (pid_t pid,
3118					   const struct ppc_hw_breakpoint &bp)
3119{
3120  gdb_assert (m_dreg_interface.hwdebug_p ());
3121
3122  auto process_it = m_process_info.find (pid);
3123
3124  gdb_assert (process_it != m_process_info.end ());
3125
3126  auto bp_it = std::find_if (process_it->second.requested_hw_bps.begin (),
3127			     process_it->second.requested_hw_bps.end (),
3128			     [&bp, this]
3129			     (const struct ppc_hw_breakpoint &curr)
3130			     { return hwdebug_point_cmp (bp, curr); }
3131			     );
3132
3133  /* If GDB is removing a watchpoint, it must have been inserted.  */
3134  gdb_assert (bp_it != process_it->second.requested_hw_bps.end ());
3135
3136  process_it->second.requested_hw_bps.erase (bp_it);
3137
3138  mark_debug_registers_changed (pid);
3139}
3140
3141/* Register the hardware watchpoint value WP_VALUE for the pid PID,
3142   then mark the stale flag for all threads of the group of PID, and
3143   issue a stop request for them.  The breakpoint or watchpoint will be
3144   installed the next time each thread is resumed.  Should only be used
3145   if the debug register interface is DEBUGREG.  */
3146
3147void
3148ppc_linux_nat_target::register_wp (pid_t pid, long wp_value)
3149{
3150  gdb_assert (m_dreg_interface.debugreg_p ());
3151
3152  /* Our other functions should have told GDB that we only have one
3153     hardware watchpoint with this interface.  */
3154  gdb_assert (!m_process_info[pid].requested_wp_val.has_value ());
3155
3156  m_process_info[pid].requested_wp_val.emplace (wp_value);
3157
3158  mark_debug_registers_changed (pid);
3159}
3160
3161/* Clear the hardware watchpoint registration for the pid PID, then mark
3162   the stale flag for all threads of the group of PID, and issue a stop
3163   request for them.  The breakpoint or watchpoint will be installed the
3164   next time each thread is resumed.  Should only be used if the debug
3165   register interface is DEBUGREG.  */
3166
3167void
3168ppc_linux_nat_target::clear_wp (pid_t pid)
3169{
3170  gdb_assert (m_dreg_interface.debugreg_p ());
3171
3172  auto process_it = m_process_info.find (pid);
3173
3174  gdb_assert (process_it != m_process_info.end ());
3175  gdb_assert (process_it->second.requested_wp_val.has_value ());
3176
3177  process_it->second.requested_wp_val.reset ();
3178
3179  mark_debug_registers_changed (pid);
3180}
3181
3182/* Initialize the arch-specific thread state for LWP, if it not already
3183   created.  */
3184
3185void
3186ppc_linux_nat_target::init_arch_lwp_info (struct lwp_info *lp)
3187{
3188  if (lwp_arch_private_info (lp) == NULL)
3189    {
3190      lwp_set_arch_private_info (lp, XCNEW (struct arch_lwp_info));
3191      lwp_arch_private_info (lp)->debug_regs_stale = false;
3192      lwp_arch_private_info (lp)->lwp_ptid = lp->ptid;
3193    }
3194}
3195
3196/* Get the arch-specific thread state for LWP, creating it if
3197   necessary.  */
3198
3199arch_lwp_info *
3200ppc_linux_nat_target::get_arch_lwp_info (struct lwp_info *lp)
3201{
3202  init_arch_lwp_info (lp);
3203
3204  return lwp_arch_private_info (lp);
3205}
3206
3207void _initialize_ppc_linux_nat ();
3208void
3209_initialize_ppc_linux_nat ()
3210{
3211  linux_target = &the_ppc_linux_nat_target;
3212
3213  /* Register the target.  */
3214  add_inf_child_target (linux_target);
3215}
3216