1.. SPDX-License-Identifier: GPL-2.0
2
3============================
4Glock internal locking rules
5============================
6
7This documents the basic principles of the glock state machine
8internals. Each glock (struct gfs2_glock in fs/gfs2/incore.h)
9has two main (internal) locks:
10
11 1. A spinlock (gl_lockref.lock) which protects the internal state such
12    as gl_state, gl_target and the list of holders (gl_holders)
13 2. A non-blocking bit lock, GLF_LOCK, which is used to prevent other
14    threads from making calls to the DLM, etc. at the same time. If a
15    thread takes this lock, it must then call run_queue (usually via the
16    workqueue) when it releases it in order to ensure any pending tasks
17    are completed.
18
19The gl_holders list contains all the queued lock requests (not
20just the holders) associated with the glock. If there are any
21held locks, then they will be contiguous entries at the head
22of the list. Locks are granted in strictly the order that they
23are queued.
24
25There are three lock states that users of the glock layer can request,
26namely shared (SH), deferred (DF) and exclusive (EX). Those translate
27to the following DLM lock modes:
28
29==========	====== =====================================================
30Glock mode      DLM    lock mode
31==========	====== =====================================================
32    UN          IV/NL  Unlocked (no DLM lock associated with glock) or NL
33    SH          PR     (Protected read)
34    DF          CW     (Concurrent write)
35    EX          EX     (Exclusive)
36==========	====== =====================================================
37
38Thus DF is basically a shared mode which is incompatible with the "normal"
39shared lock mode, SH. In GFS2 the DF mode is used exclusively for direct I/O
40operations. The glocks are basically a lock plus some routines which deal
41with cache management. The following rules apply for the cache:
42
43==========      ==========   ==============   ==========   ==============
44Glock mode      Cache data   Cache Metadata   Dirty Data   Dirty Metadata
45==========      ==========   ==============   ==========   ==============
46    UN             No              No             No            No
47    SH             Yes             Yes            No            No
48    DF             No              Yes            No            No
49    EX             Yes             Yes            Yes           Yes
50==========      ==========   ==============   ==========   ==============
51
52These rules are implemented using the various glock operations which
53are defined for each type of glock. Not all types of glocks use
54all the modes. Only inode glocks use the DF mode for example.
55
56Table of glock operations and per type constants:
57
58=============      =============================================================
59Field              Purpose
60=============      =============================================================
61go_xmote_th        Called before remote state change (e.g. to sync dirty data)
62go_xmote_bh        Called after remote state change (e.g. to refill cache)
63go_inval           Called if remote state change requires invalidating the cache
64go_demote_ok       Returns boolean value of whether its ok to demote a glock
65                   (e.g. checks timeout, and that there is no cached data)
66go_lock            Called for the first local holder of a lock
67go_unlock          Called on the final local unlock of a lock
68go_dump            Called to print content of object for debugfs file, or on
69                   error to dump glock to the log.
70go_type            The type of the glock, ``LM_TYPE_*``
71go_callback	   Called if the DLM sends a callback to drop this lock
72go_flags	   GLOF_ASPACE is set, if the glock has an address space
73                   associated with it
74=============      =============================================================
75
76The minimum hold time for each lock is the time after a remote lock
77grant for which we ignore remote demote requests. This is in order to
78prevent a situation where locks are being bounced around the cluster
79from node to node with none of the nodes making any progress. This
80tends to show up most with shared mmapped files which are being written
81to by multiple nodes. By delaying the demotion in response to a
82remote callback, that gives the userspace program time to make
83some progress before the pages are unmapped.
84
85There is a plan to try and remove the go_lock and go_unlock callbacks
86if possible, in order to try and speed up the fast path though the locking.
87Also, eventually we hope to make the glock "EX" mode locally shared
88such that any local locking will be done with the i_mutex as required
89rather than via the glock.
90
91Locking rules for glock operations:
92
93=============    ======================    =============================
94Operation        GLF_LOCK bit lock held    gl_lockref.lock spinlock held
95=============    ======================    =============================
96go_xmote_th           Yes                       No
97go_xmote_bh           Yes                       No
98go_inval              Yes                       No
99go_demote_ok          Sometimes                 Yes
100go_lock               Yes                       No
101go_unlock             Yes                       No
102go_dump               Sometimes                 Yes
103go_callback           Sometimes (N/A)           Yes
104=============    ======================    =============================
105
106.. Note::
107
108   Operations must not drop either the bit lock or the spinlock
109   if its held on entry. go_dump and do_demote_ok must never block.
110   Note that go_dump will only be called if the glock's state
111   indicates that it is caching uptodate data.
112
113Glock locking order within GFS2:
114
115 1. i_rwsem (if required)
116 2. Rename glock (for rename only)
117 3. Inode glock(s)
118    (Parents before children, inodes at "same level" with same parent in
119    lock number order)
120 4. Rgrp glock(s) (for (de)allocation operations)
121 5. Transaction glock (via gfs2_trans_begin) for non-read operations
122 6. i_rw_mutex (if required)
123 7. Page lock  (always last, very important!)
124
125There are two glocks per inode. One deals with access to the inode
126itself (locking order as above), and the other, known as the iopen
127glock is used in conjunction with the i_nlink field in the inode to
128determine the lifetime of the inode in question. Locking of inodes
129is on a per-inode basis. Locking of rgrps is on a per rgrp basis.
130In general we prefer to lock local locks prior to cluster locks.
131
132Glock Statistics
133----------------
134
135The stats are divided into two sets: those relating to the
136super block and those relating to an individual glock. The
137super block stats are done on a per cpu basis in order to
138try and reduce the overhead of gathering them. They are also
139further divided by glock type. All timings are in nanoseconds.
140
141In the case of both the super block and glock statistics,
142the same information is gathered in each case. The super
143block timing statistics are used to provide default values for
144the glock timing statistics, so that newly created glocks
145should have, as far as possible, a sensible starting point.
146The per-glock counters are initialised to zero when the
147glock is created. The per-glock statistics are lost when
148the glock is ejected from memory.
149
150The statistics are divided into three pairs of mean and
151variance, plus two counters. The mean/variance pairs are
152smoothed exponential estimates and the algorithm used is
153one which will be very familiar to those used to calculation
154of round trip times in network code. See "TCP/IP Illustrated,
155Volume 1", W. Richard Stevens, sect 21.3, "Round-Trip Time Measurement",
156p. 299 and onwards. Also, Volume 2, Sect. 25.10, p. 838 and onwards.
157Unlike the TCP/IP Illustrated case, the mean and variance are
158not scaled, but are in units of integer nanoseconds.
159
160The three pairs of mean/variance measure the following
161things:
162
163 1. DLM lock time (non-blocking requests)
164 2. DLM lock time (blocking requests)
165 3. Inter-request time (again to the DLM)
166
167A non-blocking request is one which will complete right
168away, whatever the state of the DLM lock in question. That
169currently means any requests when (a) the current state of
170the lock is exclusive, i.e. a lock demotion (b) the requested
171state is either null or unlocked (again, a demotion) or (c) the
172"try lock" flag is set. A blocking request covers all the other
173lock requests.
174
175There are two counters. The first is there primarily to show
176how many lock requests have been made, and thus how much data
177has gone into the mean/variance calculations. The other counter
178is counting queuing of holders at the top layer of the glock
179code. Hopefully that number will be a lot larger than the number
180of dlm lock requests issued.
181
182So why gather these statistics? There are several reasons
183we'd like to get a better idea of these timings:
184
1851. To be able to better set the glock "min hold time"
1862. To spot performance issues more easily
1873. To improve the algorithm for selecting resource groups for
188   allocation (to base it on lock wait time, rather than blindly
189   using a "try lock")
190
191Due to the smoothing action of the updates, a step change in
192some input quantity being sampled will only fully be taken
193into account after 8 samples (or 4 for the variance) and this
194needs to be carefully considered when interpreting the
195results.
196
197Knowing both the time it takes a lock request to complete and
198the average time between lock requests for a glock means we
199can compute the total percentage of the time for which the
200node is able to use a glock vs. time that the rest of the
201cluster has its share. That will be very useful when setting
202the lock min hold time.
203
204Great care has been taken to ensure that we
205measure exactly the quantities that we want, as accurately
206as possible. There are always inaccuracies in any
207measuring system, but I hope this is as accurate as we
208can reasonably make it.
209
210Per sb stats can be found here::
211
212    /sys/kernel/debug/gfs2/<fsname>/sbstats
213
214Per glock stats can be found here::
215
216    /sys/kernel/debug/gfs2/<fsname>/glstats
217
218Assuming that debugfs is mounted on /sys/kernel/debug and also
219that <fsname> is replaced with the name of the gfs2 filesystem
220in question.
221
222The abbreviations used in the output as are follows:
223
224=========  ================================================================
225srtt       Smoothed round trip time for non blocking dlm requests
226srttvar    Variance estimate for srtt
227srttb      Smoothed round trip time for (potentially) blocking dlm requests
228srttvarb   Variance estimate for srttb
229sirt       Smoothed inter request time (for dlm requests)
230sirtvar    Variance estimate for sirt
231dlm        Number of dlm requests made (dcnt in glstats file)
232queue      Number of glock requests queued (qcnt in glstats file)
233=========  ================================================================
234
235The sbstats file contains a set of these stats for each glock type (so 8 lines
236for each type) and for each cpu (one column per cpu). The glstats file contains
237a set of these stats for each glock in a similar format to the glocks file, but
238using the format mean/variance for each of the timing stats.
239
240The gfs2_glock_lock_time tracepoint prints out the current values of the stats
241for the glock in question, along with some addition information on each dlm
242reply that is received:
243
244======   =======================================
245status   The status of the dlm request
246flags    The dlm request flags
247tdiff    The time taken by this specific request
248======   =======================================
249
250(remaining fields as per above list)
251
252
253