d45a9e6ead80c5f5e43e66f5d9125f6736ad6225
[linux-block.git] / drivers / md / md.h
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /*
3    md.h : kernel internal structure of the Linux MD driver
4           Copyright (C) 1996-98 Ingo Molnar, Gadi Oxman
5
6 */
7
8 #ifndef _MD_MD_H
9 #define _MD_MD_H
10
11 #include <linux/blkdev.h>
12 #include <linux/backing-dev.h>
13 #include <linux/badblocks.h>
14 #include <linux/kobject.h>
15 #include <linux/list.h>
16 #include <linux/mm.h>
17 #include <linux/mutex.h>
18 #include <linux/timer.h>
19 #include <linux/wait.h>
20 #include <linux/workqueue.h>
21 #include <linux/raid/md_u.h>
22 #include <trace/events/block.h>
23
24 #define MaxSector (~(sector_t)0)
25
26 enum md_submodule_type {
27         MD_PERSONALITY = 0,
28         MD_CLUSTER,
29         MD_BITMAP, /* TODO */
30 };
31
32 enum md_submodule_id {
33         ID_LINEAR       = LEVEL_LINEAR,
34         ID_RAID0        = 0,
35         ID_RAID1        = 1,
36         ID_RAID4        = 4,
37         ID_RAID5        = 5,
38         ID_RAID6        = 6,
39         ID_RAID10       = 10,
40         ID_CLUSTER,
41         ID_BITMAP,      /* TODO */
42         ID_LLBITMAP,    /* TODO */
43 };
44
45 struct md_submodule_head {
46         enum md_submodule_type  type;
47         enum md_submodule_id    id;
48         const char              *name;
49         struct module           *owner;
50 };
51
52 /*
53  * These flags should really be called "NO_RETRY" rather than
54  * "FAILFAST" because they don't make any promise about time lapse,
55  * only about the number of retries, which will be zero.
56  * REQ_FAILFAST_DRIVER is not included because
57  * Commit: 4a27446f3e39 ("[SCSI] modify scsi to handle new fail fast flags.")
58  * seems to suggest that the errors it avoids retrying should usually
59  * be retried.
60  */
61 #define MD_FAILFAST     (REQ_FAILFAST_DEV | REQ_FAILFAST_TRANSPORT)
62
63 /* Status of sync thread. */
64 enum sync_action {
65         /*
66          * Represent by MD_RECOVERY_SYNC, start when:
67          * 1) after assemble, sync data from first rdev to other copies, this
68          * must be done first before other sync actions and will only execute
69          * once;
70          * 2) resize the array(notice that this is not reshape), sync data for
71          * the new range;
72          */
73         ACTION_RESYNC,
74         /*
75          * Represent by MD_RECOVERY_RECOVER, start when:
76          * 1) for new replacement, sync data based on the replace rdev or
77          * available copies from other rdev;
78          * 2) for new member disk while the array is degraded, sync data from
79          * other rdev;
80          * 3) reassemble after power failure or re-add a hot removed rdev, sync
81          * data from first rdev to other copies based on bitmap;
82          */
83         ACTION_RECOVER,
84         /*
85          * Represent by MD_RECOVERY_SYNC | MD_RECOVERY_REQUESTED |
86          * MD_RECOVERY_CHECK, start when user echo "check" to sysfs api
87          * sync_action, used to check if data copies from differenct rdev are
88          * the same. The number of mismatch sectors will be exported to user
89          * by sysfs api mismatch_cnt;
90          */
91         ACTION_CHECK,
92         /*
93          * Represent by MD_RECOVERY_SYNC | MD_RECOVERY_REQUESTED, start when
94          * user echo "repair" to sysfs api sync_action, usually paired with
95          * ACTION_CHECK, used to force syncing data once user found that there
96          * are inconsistent data,
97          */
98         ACTION_REPAIR,
99         /*
100          * Represent by MD_RECOVERY_RESHAPE, start when new member disk is added
101          * to the conf, notice that this is different from spares or
102          * replacement;
103          */
104         ACTION_RESHAPE,
105         /*
106          * Represent by MD_RECOVERY_FROZEN, can be set by sysfs api sync_action
107          * or internal usage like setting the array read-only, will forbid above
108          * actions.
109          */
110         ACTION_FROZEN,
111         /*
112          * All above actions don't match.
113          */
114         ACTION_IDLE,
115         NR_SYNC_ACTIONS,
116 };
117
118 /*
119  * The struct embedded in rdev is used to serialize IO.
120  */
121 struct serial_in_rdev {
122         struct rb_root_cached serial_rb;
123         spinlock_t serial_lock;
124         wait_queue_head_t serial_io_wait;
125 };
126
127 /*
128  * MD's 'extended' device
129  */
130 struct md_rdev {
131         struct list_head same_set;      /* RAID devices within the same set */
132
133         sector_t sectors;               /* Device size (in 512bytes sectors) */
134         struct mddev *mddev;            /* RAID array if running */
135         unsigned long last_events;      /* IO event timestamp */
136
137         /*
138          * If meta_bdev is non-NULL, it means that a separate device is
139          * being used to store the metadata (superblock/bitmap) which
140          * would otherwise be contained on the same device as the data (bdev).
141          */
142         struct block_device *meta_bdev;
143         struct block_device *bdev;      /* block device handle */
144         struct file *bdev_file;         /* Handle from open for bdev */
145
146         struct page     *sb_page, *bb_page;
147         int             sb_loaded;
148         __u64           sb_events;
149         sector_t        data_offset;    /* start of data in array */
150         sector_t        new_data_offset;/* only relevant while reshaping */
151         sector_t        sb_start;       /* offset of the super block (in 512byte sectors) */
152         int             sb_size;        /* bytes in the superblock */
153         int             preferred_minor;        /* autorun support */
154
155         struct kobject  kobj;
156
157         /* A device can be in one of three states based on two flags:
158          * Not working:   faulty==1 in_sync==0
159          * Fully working: faulty==0 in_sync==1
160          * Working, but not
161          * in sync with array
162          *                faulty==0 in_sync==0
163          *
164          * It can never have faulty==1, in_sync==1
165          * This reduces the burden of testing multiple flags in many cases
166          */
167
168         unsigned long   flags;  /* bit set of 'enum flag_bits' bits. */
169         wait_queue_head_t blocked_wait;
170
171         int desc_nr;                    /* descriptor index in the superblock */
172         int raid_disk;                  /* role of device in array */
173         int new_raid_disk;              /* role that the device will have in
174                                          * the array after a level-change completes.
175                                          */
176         int saved_raid_disk;            /* role that device used to have in the
177                                          * array and could again if we did a partial
178                                          * resync from the bitmap
179                                          */
180         union {
181                 sector_t recovery_offset;/* If this device has been partially
182                                          * recovered, this is where we were
183                                          * up to.
184                                          */
185                 sector_t journal_tail;  /* If this device is a journal device,
186                                          * this is the journal tail (journal
187                                          * recovery start point)
188                                          */
189         };
190
191         atomic_t        nr_pending;     /* number of pending requests.
192                                          * only maintained for arrays that
193                                          * support hot removal
194                                          */
195         atomic_t        read_errors;    /* number of consecutive read errors that
196                                          * we have tried to ignore.
197                                          */
198         time64_t        last_read_error;        /* monotonic time since our
199                                                  * last read error
200                                                  */
201         atomic_t        corrected_errors; /* number of corrected read errors,
202                                            * for reporting to userspace and storing
203                                            * in superblock.
204                                            */
205
206         struct serial_in_rdev *serial;  /* used for raid1 io serialization */
207
208         struct kernfs_node *sysfs_state; /* handle for 'state'
209                                            * sysfs entry */
210         /* handle for 'unacknowledged_bad_blocks' sysfs dentry */
211         struct kernfs_node *sysfs_unack_badblocks;
212         /* handle for 'bad_blocks' sysfs dentry */
213         struct kernfs_node *sysfs_badblocks;
214         struct badblocks badblocks;
215
216         struct {
217                 short offset;   /* Offset from superblock to start of PPL.
218                                  * Not used by external metadata. */
219                 unsigned int size;      /* Size in sectors of the PPL space */
220                 sector_t sector;        /* First sector of the PPL space */
221         } ppl;
222 };
223 enum flag_bits {
224         Faulty,                 /* device is known to have a fault */
225         In_sync,                /* device is in_sync with rest of array */
226         Bitmap_sync,            /* ..actually, not quite In_sync.  Need a
227                                  * bitmap-based recovery to get fully in sync.
228                                  * The bit is only meaningful before device
229                                  * has been passed to pers->hot_add_disk.
230                                  */
231         WriteMostly,            /* Avoid reading if at all possible */
232         AutoDetected,           /* added by auto-detect */
233         Blocked,                /* An error occurred but has not yet
234                                  * been acknowledged by the metadata
235                                  * handler, so don't allow writes
236                                  * until it is cleared */
237         WriteErrorSeen,         /* A write error has been seen on this
238                                  * device
239                                  */
240         FaultRecorded,          /* Intermediate state for clearing
241                                  * Blocked.  The Fault is/will-be
242                                  * recorded in the metadata, but that
243                                  * metadata hasn't been stored safely
244                                  * on disk yet.
245                                  */
246         BlockedBadBlocks,       /* A writer is blocked because they
247                                  * found an unacknowledged bad-block.
248                                  * This can safely be cleared at any
249                                  * time, and the writer will re-check.
250                                  * It may be set at any time, and at
251                                  * worst the writer will timeout and
252                                  * re-check.  So setting it as
253                                  * accurately as possible is good, but
254                                  * not absolutely critical.
255                                  */
256         WantReplacement,        /* This device is a candidate to be
257                                  * hot-replaced, either because it has
258                                  * reported some faults, or because
259                                  * of explicit request.
260                                  */
261         Replacement,            /* This device is a replacement for
262                                  * a want_replacement device with same
263                                  * raid_disk number.
264                                  */
265         Candidate,              /* For clustered environments only:
266                                  * This device is seen locally but not
267                                  * by the whole cluster
268                                  */
269         Journal,                /* This device is used as journal for
270                                  * raid-5/6.
271                                  * Usually, this device should be faster
272                                  * than other devices in the array
273                                  */
274         ClusterRemove,
275         ExternalBbl,            /* External metadata provides bad
276                                  * block management for a disk
277                                  */
278         FailFast,               /* Minimal retries should be attempted on
279                                  * this device, so use REQ_FAILFAST_DEV.
280                                  * Also don't try to repair failed reads.
281                                  * It is expects that no bad block log
282                                  * is present.
283                                  */
284         LastDev,                /* Seems to be the last working dev as
285                                  * it didn't fail, so don't use FailFast
286                                  * any more for metadata
287                                  */
288         CollisionCheck,         /*
289                                  * check if there is collision between raid1
290                                  * serial bios.
291                                  */
292         Nonrot,                 /* non-rotational device (SSD) */
293 };
294
295 static inline int is_badblock(struct md_rdev *rdev, sector_t s, sector_t sectors,
296                               sector_t *first_bad, sector_t *bad_sectors)
297 {
298         if (unlikely(rdev->badblocks.count)) {
299                 int rv = badblocks_check(&rdev->badblocks, rdev->data_offset + s,
300                                         sectors,
301                                         first_bad, bad_sectors);
302                 if (rv)
303                         *first_bad -= rdev->data_offset;
304                 return rv;
305         }
306         return 0;
307 }
308
309 static inline int rdev_has_badblock(struct md_rdev *rdev, sector_t s,
310                                     int sectors)
311 {
312         sector_t first_bad;
313         sector_t bad_sectors;
314
315         return is_badblock(rdev, s, sectors, &first_bad, &bad_sectors);
316 }
317
318 extern bool rdev_set_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
319                                int is_new);
320 extern void rdev_clear_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
321                                  int is_new);
322 struct md_cluster_info;
323 struct md_cluster_operations;
324
325 /**
326  * enum mddev_flags - md device flags.
327  * @MD_ARRAY_FIRST_USE: First use of array, needs initialization.
328  * @MD_CLOSING: If set, we are closing the array, do not open it then.
329  * @MD_JOURNAL_CLEAN: A raid with journal is already clean.
330  * @MD_HAS_JOURNAL: The raid array has journal feature set.
331  * @MD_CLUSTER_RESYNC_LOCKED: cluster raid only, which means node, already took
332  *                             resync lock, need to release the lock.
333  * @MD_FAILFAST_SUPPORTED: Using MD_FAILFAST on metadata writes is supported as
334  *                          calls to md_error() will never cause the array to
335  *                          become failed.
336  * @MD_HAS_PPL:  The raid array has PPL feature set.
337  * @MD_HAS_MULTIPLE_PPLS: The raid array has multiple PPLs feature set.
338  * @MD_NOT_READY: do_md_run() is active, so 'array_state', ust not report that
339  *                 array is ready yet.
340  * @MD_BROKEN: This is used to stop writes and mark array as failed.
341  * @MD_DELETED: This device is being deleted
342  *
343  * change UNSUPPORTED_MDDEV_FLAGS for each array type if new flag is added
344  */
345 enum mddev_flags {
346         MD_ARRAY_FIRST_USE,
347         MD_CLOSING,
348         MD_JOURNAL_CLEAN,
349         MD_HAS_JOURNAL,
350         MD_CLUSTER_RESYNC_LOCKED,
351         MD_FAILFAST_SUPPORTED,
352         MD_HAS_PPL,
353         MD_HAS_MULTIPLE_PPLS,
354         MD_NOT_READY,
355         MD_BROKEN,
356         MD_DELETED,
357 };
358
359 enum mddev_sb_flags {
360         MD_SB_CHANGE_DEVS,              /* Some device status has changed */
361         MD_SB_CHANGE_CLEAN,     /* transition to or from 'clean' */
362         MD_SB_CHANGE_PENDING,   /* switch from 'clean' to 'active' in progress */
363         MD_SB_NEED_REWRITE,     /* metadata write needs to be repeated */
364 };
365
366 #define NR_SERIAL_INFOS         8
367 /* record current range of serialize IOs */
368 struct serial_info {
369         struct rb_node node;
370         sector_t start;         /* start sector of rb node */
371         sector_t last;          /* end sector of rb node */
372         sector_t _subtree_last; /* highest sector in subtree of rb node */
373 };
374
375 /*
376  * mddev->curr_resync stores the current sector of the resync but
377  * also has some overloaded values.
378  */
379 enum {
380         /* No resync in progress */
381         MD_RESYNC_NONE = 0,
382         /* Yielded to allow another conflicting resync to commence */
383         MD_RESYNC_YIELDED = 1,
384         /* Delayed to check that there is no conflict with another sync */
385         MD_RESYNC_DELAYED = 2,
386         /* Any value greater than or equal to this is in an active resync */
387         MD_RESYNC_ACTIVE = 3,
388 };
389
390 struct mddev {
391         void                            *private;
392         struct md_personality           *pers;
393         dev_t                           unit;
394         int                             md_minor;
395         struct list_head                disks;
396         unsigned long                   flags;
397         unsigned long                   sb_flags;
398
399         int                             suspended;
400         struct mutex                    suspend_mutex;
401         struct percpu_ref               active_io;
402         int                             ro;
403         int                             sysfs_active; /* set when sysfs deletes
404                                                        * are happening, so run/
405                                                        * takeover/stop are not safe
406                                                        */
407         struct gendisk                  *gendisk;    /* mdraid gendisk */
408         struct gendisk                  *dm_gendisk; /* dm-raid gendisk */
409
410         struct kobject                  kobj;
411         int                             hold_active;
412 #define UNTIL_IOCTL     1
413 #define UNTIL_STOP      2
414
415         /* Superblock information */
416         int                             major_version,
417                                         minor_version,
418                                         patch_version;
419         int                             persistent;
420         int                             external;       /* metadata is
421                                                          * managed externally */
422         char                            metadata_type[17]; /* externally set*/
423         int                             chunk_sectors;
424         time64_t                        ctime, utime;
425         int                             level, layout;
426         char                            clevel[16];
427         int                             raid_disks;
428         int                             max_disks;
429         sector_t                        dev_sectors;    /* used size of
430                                                          * component devices */
431         sector_t                        array_sectors; /* exported array size */
432         int                             external_size; /* size managed
433                                                         * externally */
434         __u64                           events;
435         /* If the last 'event' was simply a clean->dirty transition, and
436          * we didn't write it to the spares, then it is safe and simple
437          * to just decrement the event count on a dirty->clean transition.
438          * So we record that possibility here.
439          */
440         int                             can_decrease_events;
441
442         char                            uuid[16];
443
444         /* If the array is being reshaped, we need to record the
445          * new shape and an indication of where we are up to.
446          * This is written to the superblock.
447          * If reshape_position is MaxSector, then no reshape is happening (yet).
448          */
449         sector_t                        reshape_position;
450         int                             delta_disks, new_level, new_layout;
451         int                             new_chunk_sectors;
452         int                             reshape_backwards;
453
454         struct md_thread __rcu          *thread;        /* management thread */
455         struct md_thread __rcu          *sync_thread;   /* doing resync or reconstruct */
456
457         /*
458          * Set when a sync operation is started. It holds this value even
459          * when the sync thread is "frozen" (interrupted) or "idle" (stopped
460          * or finished). It is overwritten when a new sync operation is begun.
461          */
462         enum sync_action                last_sync_action;
463         sector_t                        curr_resync;    /* last block scheduled */
464         /* As resync requests can complete out of order, we cannot easily track
465          * how much resync has been completed.  So we occasionally pause until
466          * everything completes, then set curr_resync_completed to curr_resync.
467          * As such it may be well behind the real resync mark, but it is a value
468          * we are certain of.
469          */
470         sector_t                        curr_resync_completed;
471         unsigned long                   resync_mark;    /* a recent timestamp */
472         sector_t                        resync_mark_cnt;/* blocks written at resync_mark */
473         sector_t                        curr_mark_cnt; /* blocks scheduled now */
474
475         sector_t                        resync_max_sectors; /* may be set by personality */
476
477         atomic64_t                      resync_mismatches; /* count of sectors where
478                                                             * parity/replica mismatch found
479                                                             */
480
481         /* allow user-space to request suspension of IO to regions of the array */
482         sector_t                        suspend_lo;
483         sector_t                        suspend_hi;
484         /* if zero, use the system-wide default */
485         int                             sync_speed_min;
486         int                             sync_speed_max;
487         int                             sync_io_depth;
488
489         /* resync even though the same disks are shared among md-devices */
490         int                             parallel_resync;
491
492         int                             ok_start_degraded;
493
494         unsigned long                   recovery;
495         /* If a RAID personality determines that recovery (of a particular
496          * device) will fail due to a read error on the source device, it
497          * takes a copy of this number and does not attempt recovery again
498          * until this number changes.
499          */
500         int                             recovery_disabled;
501
502         int                             in_sync;        /* know to not need resync */
503         /* 'open_mutex' avoids races between 'md_open' and 'do_md_stop', so
504          * that we are never stopping an array while it is open.
505          * 'reconfig_mutex' protects all other reconfiguration.
506          * These locks are separate due to conflicting interactions
507          * with disk->open_mutex.
508          * Lock ordering is:
509          *  reconfig_mutex -> disk->open_mutex
510          *  disk->open_mutex -> open_mutex:  e.g. __blkdev_get -> md_open
511          */
512         struct mutex                    open_mutex;
513         struct mutex                    reconfig_mutex;
514         atomic_t                        active;         /* general refcount */
515         atomic_t                        openers;        /* number of active opens */
516
517         int                             changed;        /* True if we might need to
518                                                          * reread partition info */
519         int                             degraded;       /* whether md should consider
520                                                          * adding a spare
521                                                          */
522
523         unsigned long                   normal_io_events; /* IO event timestamp */
524         atomic_t                        recovery_active; /* blocks scheduled, but not written */
525         wait_queue_head_t               recovery_wait;
526         sector_t                        recovery_cp;
527         sector_t                        resync_min;     /* user requested sync
528                                                          * starts here */
529         sector_t                        resync_max;     /* resync should pause
530                                                          * when it gets here */
531
532         struct kernfs_node              *sysfs_state;   /* handle for 'array_state'
533                                                          * file in sysfs.
534                                                          */
535         struct kernfs_node              *sysfs_action;  /* handle for 'sync_action' */
536         struct kernfs_node              *sysfs_completed;       /*handle for 'sync_completed' */
537         struct kernfs_node              *sysfs_degraded;        /*handle for 'degraded' */
538         struct kernfs_node              *sysfs_level;           /*handle for 'level' */
539
540         /* used for delayed sysfs removal */
541         struct work_struct del_work;
542         /* used for register new sync thread */
543         struct work_struct sync_work;
544
545         /* "lock" protects:
546          *   flush_bio transition from NULL to !NULL
547          *   rdev superblocks, events
548          *   clearing MD_CHANGE_*
549          *   in_sync - and related safemode and MD_CHANGE changes
550          *   pers (also protected by reconfig_mutex and pending IO).
551          *   clearing ->bitmap
552          *   clearing ->bitmap_info.file
553          *   changing ->resync_{min,max}
554          *   setting MD_RECOVERY_RUNNING (which interacts with resync_{min,max})
555          */
556         spinlock_t                      lock;
557         wait_queue_head_t               sb_wait;        /* for waiting on superblock updates */
558         atomic_t                        pending_writes; /* number of active superblock writes */
559
560         unsigned int                    safemode;       /* if set, update "clean" superblock
561                                                          * when no writes pending.
562                                                          */
563         unsigned int                    safemode_delay;
564         struct timer_list               safemode_timer;
565         struct percpu_ref               writes_pending;
566         int                             sync_checkers;  /* # of threads checking writes_pending */
567
568         void                            *bitmap; /* the bitmap for the device */
569         struct bitmap_operations        *bitmap_ops;
570         struct {
571                 struct file             *file; /* the bitmap file */
572                 loff_t                  offset; /* offset from superblock of
573                                                  * start of bitmap. May be
574                                                  * negative, but not '0'
575                                                  * For external metadata, offset
576                                                  * from start of device.
577                                                  */
578                 unsigned long           space; /* space available at this offset */
579                 loff_t                  default_offset; /* this is the offset to use when
580                                                          * hot-adding a bitmap.  It should
581                                                          * eventually be settable by sysfs.
582                                                          */
583                 unsigned long           default_space; /* space available at
584                                                         * default offset */
585                 struct mutex            mutex;
586                 unsigned long           chunksize;
587                 unsigned long           daemon_sleep; /* how many jiffies between updates? */
588                 unsigned long           max_write_behind; /* write-behind mode */
589                 int                     external;
590                 int                     nodes; /* Maximum number of nodes in the cluster */
591                 char                    cluster_name[64]; /* Name of the cluster */
592         } bitmap_info;
593
594         atomic_t                        max_corr_read_errors; /* max read retries */
595         struct list_head                all_mddevs;
596
597         const struct attribute_group    *to_remove;
598
599         struct bio_set                  bio_set;
600         struct bio_set                  sync_set; /* for sync operations like
601                                                    * metadata and bitmap writes
602                                                    */
603         struct bio_set                  io_clone_set;
604
605         struct work_struct event_work;  /* used by dm to report failure event */
606         mempool_t *serial_info_pool;
607         void (*sync_super)(struct mddev *mddev, struct md_rdev *rdev);
608         struct md_cluster_info          *cluster_info;
609         struct md_cluster_operations *cluster_ops;
610         unsigned int                    good_device_nr; /* good device num within cluster raid */
611         unsigned int                    noio_flag; /* for memalloc scope API */
612
613         /*
614          * Temporarily store rdev that will be finally removed when
615          * reconfig_mutex is unlocked, protected by reconfig_mutex.
616          */
617         struct list_head                deleting;
618
619         /* The sequence number for sync thread */
620         atomic_t sync_seq;
621
622         bool    has_superblocks:1;
623         bool    fail_last_dev:1;
624         bool    serialize_policy:1;
625 };
626
627 enum recovery_flags {
628         /* flags for sync thread running status */
629
630         /*
631          * set when one of sync action is set and new sync thread need to be
632          * registered, or just add/remove spares from conf.
633          */
634         MD_RECOVERY_NEEDED,
635         /* sync thread is running, or about to be started */
636         MD_RECOVERY_RUNNING,
637         /* sync thread needs to be aborted for some reason */
638         MD_RECOVERY_INTR,
639         /* sync thread is done and is waiting to be unregistered */
640         MD_RECOVERY_DONE,
641         /* running sync thread must abort immediately, and not restart */
642         MD_RECOVERY_FROZEN,
643         /* waiting for pers->start() to finish */
644         MD_RECOVERY_WAIT,
645         /* interrupted because io-error */
646         MD_RECOVERY_ERROR,
647
648         /* flags determines sync action, see details in enum sync_action */
649
650         /* if just this flag is set, action is resync. */
651         MD_RECOVERY_SYNC,
652         /*
653          * paired with MD_RECOVERY_SYNC, if MD_RECOVERY_CHECK is not set,
654          * action is repair, means user requested resync.
655          */
656         MD_RECOVERY_REQUESTED,
657         /*
658          * paired with MD_RECOVERY_SYNC and MD_RECOVERY_REQUESTED, action is
659          * check.
660          */
661         MD_RECOVERY_CHECK,
662         /* recovery, or need to try it */
663         MD_RECOVERY_RECOVER,
664         /* reshape */
665         MD_RECOVERY_RESHAPE,
666         /* remote node is running resync thread */
667         MD_RESYNCING_REMOTE,
668 };
669
670 enum md_ro_state {
671         MD_RDWR,
672         MD_RDONLY,
673         MD_AUTO_READ,
674         MD_MAX_STATE
675 };
676
677 static inline bool md_is_rdwr(struct mddev *mddev)
678 {
679         return (mddev->ro == MD_RDWR);
680 }
681
682 static inline bool reshape_interrupted(struct mddev *mddev)
683 {
684         /* reshape never start */
685         if (mddev->reshape_position == MaxSector)
686                 return false;
687
688         /* interrupted */
689         if (!test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
690                 return true;
691
692         /* running reshape will be interrupted soon. */
693         if (test_bit(MD_RECOVERY_WAIT, &mddev->recovery) ||
694             test_bit(MD_RECOVERY_INTR, &mddev->recovery) ||
695             test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
696                 return true;
697
698         return false;
699 }
700
701 static inline int __must_check mddev_lock(struct mddev *mddev)
702 {
703         return mutex_lock_interruptible(&mddev->reconfig_mutex);
704 }
705
706 /* Sometimes we need to take the lock in a situation where
707  * failure due to interrupts is not acceptable.
708  */
709 static inline void mddev_lock_nointr(struct mddev *mddev)
710 {
711         mutex_lock(&mddev->reconfig_mutex);
712 }
713
714 static inline int mddev_trylock(struct mddev *mddev)
715 {
716         return mutex_trylock(&mddev->reconfig_mutex);
717 }
718 extern void mddev_unlock(struct mddev *mddev);
719
720 struct md_personality
721 {
722         struct md_submodule_head head;
723
724         bool __must_check (*make_request)(struct mddev *mddev, struct bio *bio);
725         /*
726          * start up works that do NOT require md_thread. tasks that
727          * requires md_thread should go into start()
728          */
729         int (*run)(struct mddev *mddev);
730         /* start up works that require md threads */
731         int (*start)(struct mddev *mddev);
732         void (*free)(struct mddev *mddev, void *priv);
733         void (*status)(struct seq_file *seq, struct mddev *mddev);
734         /* error_handler must set ->faulty and clear ->in_sync
735          * if appropriate, and should abort recovery if needed
736          */
737         void (*error_handler)(struct mddev *mddev, struct md_rdev *rdev);
738         int (*hot_add_disk) (struct mddev *mddev, struct md_rdev *rdev);
739         int (*hot_remove_disk) (struct mddev *mddev, struct md_rdev *rdev);
740         int (*spare_active) (struct mddev *mddev);
741         sector_t (*sync_request)(struct mddev *mddev, sector_t sector_nr,
742                                  sector_t max_sector, int *skipped);
743         int (*resize) (struct mddev *mddev, sector_t sectors);
744         sector_t (*size) (struct mddev *mddev, sector_t sectors, int raid_disks);
745         int (*check_reshape) (struct mddev *mddev);
746         int (*start_reshape) (struct mddev *mddev);
747         void (*finish_reshape) (struct mddev *mddev);
748         void (*update_reshape_pos) (struct mddev *mddev);
749         void (*prepare_suspend) (struct mddev *mddev);
750         /* quiesce suspends or resumes internal processing.
751          * 1 - stop new actions and wait for action io to complete
752          * 0 - return to normal behaviour
753          */
754         void (*quiesce) (struct mddev *mddev, int quiesce);
755         /* takeover is used to transition an array from one
756          * personality to another.  The new personality must be able
757          * to handle the data in the current layout.
758          * e.g. 2drive raid1 -> 2drive raid5
759          *      ndrive raid5 -> degraded n+1drive raid6 with special layout
760          * If the takeover succeeds, a new 'private' structure is returned.
761          * This needs to be installed and then ->run used to activate the
762          * array.
763          */
764         void *(*takeover) (struct mddev *mddev);
765         /* Changes the consistency policy of an active array. */
766         int (*change_consistency_policy)(struct mddev *mddev, const char *buf);
767         /* convert io ranges from array to bitmap */
768         void (*bitmap_sector)(struct mddev *mddev, sector_t *offset,
769                               unsigned long *sectors);
770 };
771
772 struct md_sysfs_entry {
773         struct attribute attr;
774         ssize_t (*show)(struct mddev *, char *);
775         ssize_t (*store)(struct mddev *, const char *, size_t);
776 };
777 extern const struct attribute_group md_bitmap_group;
778
779 static inline struct kernfs_node *sysfs_get_dirent_safe(struct kernfs_node *sd, char *name)
780 {
781         if (sd)
782                 return sysfs_get_dirent(sd, name);
783         return sd;
784 }
785 static inline void sysfs_notify_dirent_safe(struct kernfs_node *sd)
786 {
787         if (sd)
788                 sysfs_notify_dirent(sd);
789 }
790
791 static inline char * mdname (struct mddev * mddev)
792 {
793         return mddev->gendisk ? mddev->gendisk->disk_name : "mdX";
794 }
795
796 static inline int sysfs_link_rdev(struct mddev *mddev, struct md_rdev *rdev)
797 {
798         char nm[20];
799         if (!test_bit(Replacement, &rdev->flags) &&
800             !test_bit(Journal, &rdev->flags) &&
801             mddev->kobj.sd) {
802                 sprintf(nm, "rd%d", rdev->raid_disk);
803                 return sysfs_create_link(&mddev->kobj, &rdev->kobj, nm);
804         } else
805                 return 0;
806 }
807
808 static inline void sysfs_unlink_rdev(struct mddev *mddev, struct md_rdev *rdev)
809 {
810         char nm[20];
811         if (!test_bit(Replacement, &rdev->flags) &&
812             !test_bit(Journal, &rdev->flags) &&
813             mddev->kobj.sd) {
814                 sprintf(nm, "rd%d", rdev->raid_disk);
815                 sysfs_remove_link(&mddev->kobj, nm);
816         }
817 }
818
819 /*
820  * iterates through some rdev ringlist. It's safe to remove the
821  * current 'rdev'. Dont touch 'tmp' though.
822  */
823 #define rdev_for_each_list(rdev, tmp, head)                             \
824         list_for_each_entry_safe(rdev, tmp, head, same_set)
825
826 /*
827  * iterates through the 'same array disks' ringlist
828  */
829 #define rdev_for_each(rdev, mddev)                              \
830         list_for_each_entry(rdev, &((mddev)->disks), same_set)
831
832 #define rdev_for_each_safe(rdev, tmp, mddev)                            \
833         list_for_each_entry_safe(rdev, tmp, &((mddev)->disks), same_set)
834
835 #define rdev_for_each_rcu(rdev, mddev)                          \
836         list_for_each_entry_rcu(rdev, &((mddev)->disks), same_set)
837
838 struct md_thread {
839         void                    (*run) (struct md_thread *thread);
840         struct mddev            *mddev;
841         wait_queue_head_t       wqueue;
842         unsigned long           flags;
843         struct task_struct      *tsk;
844         unsigned long           timeout;
845         void                    *private;
846 };
847
848 struct md_io_clone {
849         struct mddev    *mddev;
850         struct bio      *orig_bio;
851         unsigned long   start_time;
852         sector_t        offset;
853         unsigned long   sectors;
854         struct bio      bio_clone;
855 };
856
857 #define THREAD_WAKEUP  0
858
859 static inline void safe_put_page(struct page *p)
860 {
861         if (p) put_page(p);
862 }
863
864 int register_md_submodule(struct md_submodule_head *msh);
865 void unregister_md_submodule(struct md_submodule_head *msh);
866
867 extern struct md_thread *md_register_thread(
868         void (*run)(struct md_thread *thread),
869         struct mddev *mddev,
870         const char *name);
871 extern void md_unregister_thread(struct mddev *mddev, struct md_thread __rcu **threadp);
872 extern void md_wakeup_thread(struct md_thread __rcu *thread);
873 extern void md_check_recovery(struct mddev *mddev);
874 extern void md_reap_sync_thread(struct mddev *mddev);
875 extern enum sync_action md_sync_action(struct mddev *mddev);
876 extern enum sync_action md_sync_action_by_name(const char *page);
877 extern const char *md_sync_action_name(enum sync_action action);
878 extern void md_write_start(struct mddev *mddev, struct bio *bi);
879 extern void md_write_inc(struct mddev *mddev, struct bio *bi);
880 extern void md_write_end(struct mddev *mddev);
881 extern void md_done_sync(struct mddev *mddev, int blocks, int ok);
882 extern void md_error(struct mddev *mddev, struct md_rdev *rdev);
883 extern void md_finish_reshape(struct mddev *mddev);
884 void md_submit_discard_bio(struct mddev *mddev, struct md_rdev *rdev,
885                         struct bio *bio, sector_t start, sector_t size);
886 void md_account_bio(struct mddev *mddev, struct bio **bio);
887 void md_free_cloned_bio(struct bio *bio);
888
889 extern bool __must_check md_flush_request(struct mddev *mddev, struct bio *bio);
890 extern void md_super_write(struct mddev *mddev, struct md_rdev *rdev,
891                            sector_t sector, int size, struct page *page);
892 extern int md_super_wait(struct mddev *mddev);
893 extern int sync_page_io(struct md_rdev *rdev, sector_t sector, int size,
894                 struct page *page, blk_opf_t opf, bool metadata_op);
895 extern void md_do_sync(struct md_thread *thread);
896 extern void md_new_event(void);
897 extern void md_allow_write(struct mddev *mddev);
898 extern void md_wait_for_blocked_rdev(struct md_rdev *rdev, struct mddev *mddev);
899 extern void md_set_array_sectors(struct mddev *mddev, sector_t array_sectors);
900 extern int md_check_no_bitmap(struct mddev *mddev);
901 extern int md_integrity_register(struct mddev *mddev);
902 extern int strict_strtoul_scaled(const char *cp, unsigned long *res, int scale);
903
904 extern int mddev_init(struct mddev *mddev);
905 extern void mddev_destroy(struct mddev *mddev);
906 void md_init_stacking_limits(struct queue_limits *lim);
907 struct mddev *md_alloc(dev_t dev, char *name);
908 void mddev_put(struct mddev *mddev);
909 extern int md_run(struct mddev *mddev);
910 extern int md_start(struct mddev *mddev);
911 extern void md_stop(struct mddev *mddev);
912 extern void md_stop_writes(struct mddev *mddev);
913 extern int md_rdev_init(struct md_rdev *rdev);
914 extern void md_rdev_clear(struct md_rdev *rdev);
915
916 extern bool md_handle_request(struct mddev *mddev, struct bio *bio);
917 extern int mddev_suspend(struct mddev *mddev, bool interruptible);
918 extern void mddev_resume(struct mddev *mddev);
919 extern void md_idle_sync_thread(struct mddev *mddev);
920 extern void md_frozen_sync_thread(struct mddev *mddev);
921 extern void md_unfrozen_sync_thread(struct mddev *mddev);
922
923 extern void md_update_sb(struct mddev *mddev, int force);
924 extern void mddev_create_serial_pool(struct mddev *mddev, struct md_rdev *rdev);
925 extern void mddev_destroy_serial_pool(struct mddev *mddev,
926                                       struct md_rdev *rdev);
927 struct md_rdev *md_find_rdev_nr_rcu(struct mddev *mddev, int nr);
928 struct md_rdev *md_find_rdev_rcu(struct mddev *mddev, dev_t dev);
929
930 static inline bool is_rdev_broken(struct md_rdev *rdev)
931 {
932         return !disk_live(rdev->bdev->bd_disk);
933 }
934
935 static inline void rdev_dec_pending(struct md_rdev *rdev, struct mddev *mddev)
936 {
937         int faulty = test_bit(Faulty, &rdev->flags);
938         if (atomic_dec_and_test(&rdev->nr_pending) && faulty) {
939                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
940                 md_wakeup_thread(mddev->thread);
941         }
942 }
943
944 static inline int mddev_is_clustered(struct mddev *mddev)
945 {
946         return mddev->cluster_info && mddev->bitmap_info.nodes > 1;
947 }
948
949 /* clear unsupported mddev_flags */
950 static inline void mddev_clear_unsupported_flags(struct mddev *mddev,
951         unsigned long unsupported_flags)
952 {
953         mddev->flags &= ~unsupported_flags;
954 }
955
956 static inline void mddev_check_write_zeroes(struct mddev *mddev, struct bio *bio)
957 {
958         if (bio_op(bio) == REQ_OP_WRITE_ZEROES &&
959             !bio->bi_bdev->bd_disk->queue->limits.max_write_zeroes_sectors)
960                 mddev->gendisk->queue->limits.max_write_zeroes_sectors = 0;
961 }
962
963 static inline int mddev_suspend_and_lock(struct mddev *mddev)
964 {
965         int ret;
966
967         ret = mddev_suspend(mddev, true);
968         if (ret)
969                 return ret;
970
971         ret = mddev_lock(mddev);
972         if (ret)
973                 mddev_resume(mddev);
974
975         return ret;
976 }
977
978 static inline void mddev_suspend_and_lock_nointr(struct mddev *mddev)
979 {
980         mddev_suspend(mddev, false);
981         mutex_lock(&mddev->reconfig_mutex);
982 }
983
984 static inline void mddev_unlock_and_resume(struct mddev *mddev)
985 {
986         mddev_unlock(mddev);
987         mddev_resume(mddev);
988 }
989
990 struct mdu_array_info_s;
991 struct mdu_disk_info_s;
992
993 extern int mdp_major;
994 extern struct workqueue_struct *md_bitmap_wq;
995 void md_autostart_arrays(int part);
996 int md_set_array_info(struct mddev *mddev, struct mdu_array_info_s *info);
997 int md_add_new_disk(struct mddev *mddev, struct mdu_disk_info_s *info);
998 int do_md_run(struct mddev *mddev);
999 #define MDDEV_STACK_INTEGRITY   (1u << 0)
1000 int mddev_stack_rdev_limits(struct mddev *mddev, struct queue_limits *lim,
1001                 unsigned int flags);
1002 int mddev_stack_new_rdev(struct mddev *mddev, struct md_rdev *rdev);
1003 void mddev_update_io_opt(struct mddev *mddev, unsigned int nr_stripes);
1004
1005 extern const struct block_device_operations md_fops;
1006
1007 /*
1008  * MD devices can be used undeneath by DM, in which case ->gendisk is NULL.
1009  */
1010 static inline bool mddev_is_dm(struct mddev *mddev)
1011 {
1012         return !mddev->gendisk;
1013 }
1014
1015 static inline void mddev_trace_remap(struct mddev *mddev, struct bio *bio,
1016                 sector_t sector)
1017 {
1018         if (!mddev_is_dm(mddev))
1019                 trace_block_bio_remap(bio, disk_devt(mddev->gendisk), sector);
1020 }
1021
1022 static inline bool rdev_blocked(struct md_rdev *rdev)
1023 {
1024         /*
1025          * Blocked will be set by error handler and cleared by daemon after
1026          * updating superblock, meanwhile write IO should be blocked to prevent
1027          * reading old data after power failure.
1028          */
1029         if (test_bit(Blocked, &rdev->flags))
1030                 return true;
1031
1032         /*
1033          * Faulty device should not be accessed anymore, there is no need to
1034          * wait for bad block to be acknowledged.
1035          */
1036         if (test_bit(Faulty, &rdev->flags))
1037                 return false;
1038
1039         /* rdev is blocked by badblocks. */
1040         if (test_bit(BlockedBadBlocks, &rdev->flags))
1041                 return true;
1042
1043         return false;
1044 }
1045
1046 #define mddev_add_trace_msg(mddev, fmt, args...)                        \
1047 do {                                                                    \
1048         if (!mddev_is_dm(mddev))                                        \
1049                 blk_add_trace_msg((mddev)->gendisk->queue, fmt, ##args); \
1050 } while (0)
1051
1052 #endif /* _MD_MD_H */