Whamcloud - gitweb
LU-3935 scrub: support dryrun mode OI scrub
[fs/lustre-release.git] / lustre / osd-ldiskfs / osd_scrub.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2012, 2013, Intel Corporation.
24  */
25 /*
26  * lustre/osd-ldiskfs/osd_scrub.c
27  *
28  * Top-level entry points into osd module
29  *
30  * The OI scrub is used for rebuilding Object Index files when restores MDT from
31  * file-level backup.
32  *
33  * The otable based iterator scans ldiskfs inode table to feed up layer LFSCK.
34  *
35  * Author: Fan Yong <yong.fan@whamcloud.com>
36  */
37
38 #ifndef EXPORT_SYMTAB
39 # define EXPORT_SYMTAB
40 #endif
41 #define DEBUG_SUBSYSTEM S_MDS
42
43 #include <lustre/lustre_idl.h>
44 #include <lustre_disk.h>
45 #include <dt_object.h>
46
47 #include "osd_internal.h"
48 #include "osd_oi.h"
49 #include "osd_scrub.h"
50
51 #define HALF_SEC        (CFS_HZ >> 1)
52
53 #define OSD_OTABLE_MAX_HASH             0x00000000ffffffffULL
54
55 #define SCRUB_NEXT_BREAK        1 /* exit current loop and process next group */
56 #define SCRUB_NEXT_CONTINUE     2 /* skip current object and process next bit */
57 #define SCRUB_NEXT_EXIT         3 /* exit all the loops */
58 #define SCRUB_NEXT_WAIT         4 /* wait for free cache slot */
59 #define SCRUB_NEXT_CRASH        5 /* simulate system crash during OI scrub */
60 #define SCRUB_NEXT_FATAL        6 /* simulate failure during OI scrub */
61 #define SCRUB_NEXT_NOSCRUB      7 /* new created object, no scrub on it */
62 #define SCRUB_NEXT_NOLMA        8 /* the inode has no FID-in-LMA */
63
64 /* misc functions */
65
66 static inline struct osd_device *osd_scrub2dev(struct osd_scrub *scrub)
67 {
68         return container_of0(scrub, struct osd_device, od_scrub);
69 }
70
71 static inline struct super_block *osd_scrub2sb(struct osd_scrub *scrub)
72 {
73         return osd_sb(osd_scrub2dev(scrub));
74 }
75
76 static inline int osd_scrub_has_window(struct osd_scrub *scrub,
77                                        struct osd_otable_cache *ooc)
78 {
79         return scrub->os_pos_current < ooc->ooc_pos_preload + SCRUB_WINDOW_SIZE;
80 }
81
82 /**
83  * update/insert/delete the specified OI mapping (@fid @id) according to the ops
84  *
85  * \retval   1, changed nothing
86  * \retval   0, changed successfully
87  * \retval -ve, on error
88  */
89 static int osd_scrub_refresh_mapping(struct osd_thread_info *info,
90                                      struct osd_device *dev,
91                                      const struct lu_fid *fid,
92                                      const struct osd_inode_id *id,
93                                      int ops, bool force)
94 {
95         struct lu_fid         *oi_fid = &info->oti_fid2;
96         struct osd_inode_id   *oi_id  = &info->oti_id2;
97         struct iam_container  *bag;
98         struct iam_path_descr *ipd;
99         handle_t              *jh;
100         int                    rc;
101         ENTRY;
102
103         if (dev->od_scrub.os_file.sf_param & SP_DRYRUN && !force)
104                 RETURN(0);
105
106         fid_cpu_to_be(oi_fid, fid);
107         if (id != NULL)
108                 osd_id_pack(oi_id, id);
109         jh = ldiskfs_journal_start_sb(osd_sb(dev),
110                                       osd_dto_credits_noquota[ops]);
111         if (IS_ERR(jh)) {
112                 rc = PTR_ERR(jh);
113                 CERROR("%.16s: fail to start trans for scrub store: rc = %d\n",
114                        LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, rc);
115                 RETURN(rc);
116         }
117
118         bag = &osd_fid2oi(dev, fid)->oi_dir.od_container;
119         ipd = osd_idx_ipd_get(info->oti_env, bag);
120         if (unlikely(ipd == NULL)) {
121                 ldiskfs_journal_stop(jh);
122                 CERROR("%.16s: fail to get ipd for scrub store\n",
123                        LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name);
124                 RETURN(-ENOMEM);
125         }
126
127         switch (ops) {
128         case DTO_INDEX_UPDATE:
129                 rc = iam_update(jh, bag, (const struct iam_key *)oi_fid,
130                                 (struct iam_rec *)oi_id, ipd);
131                 if (unlikely(rc == -ENOENT)) {
132                         /* Some unlink thread may removed the OI mapping. */
133                         rc = 1;
134                 }
135                 break;
136         case DTO_INDEX_INSERT:
137                 rc = iam_insert(jh, bag, (const struct iam_key *)oi_fid,
138                                 (struct iam_rec *)oi_id, ipd);
139                 if (unlikely(rc == -EEXIST)) {
140                         rc = 1;
141                         /* XXX: There are trouble things when adding OI
142                          *      mapping for IGIF object, which may cause
143                          *      multiple objects to be mapped to the same
144                          *      IGIF formatted FID. Consider the following
145                          *      situations:
146                          *
147                          *      1) The MDT is upgrading from 1.8 device.
148                          *      The OI scrub generates IGIF FID1 for the
149                          *      OBJ1 and adds the OI mapping.
150                          *
151                          *      2) For some reason, the OI scrub does not
152                          *      process all the IGIF objects completely.
153                          *
154                          *      3) The MDT is backuped and restored against
155                          *      this device.
156                          *
157                          *      4) When the MDT mounts up, the OI scrub will
158                          *      try to rebuild the OI files. For some IGIF
159                          *      object, OBJ2, which was not processed by the
160                          *      OI scrub before the backup/restore, and the
161                          *      new generated IGIF formatted FID may be just
162                          *      the FID1, the same as OBJ1.
163                          *
164                          *      Under such case, the OI scrub cannot know how
165                          *      to generate new FID for the OBJ2.
166                          *
167                          *      Currently, we do nothing for that. One possible
168                          *      solution is to generate new normal FID for the
169                          *      conflict object.
170                          *
171                          *      Anyway, it is rare, only exists in theory. */
172                 }
173                 break;
174         case DTO_INDEX_DELETE:
175                 rc = iam_delete(jh, bag, (const struct iam_key *)oi_fid, ipd);
176                 if (rc == -ENOENT) {
177                         /* It is normal that the unlink thread has removed the
178                          * OI mapping already. */
179                         rc = 1;
180                 }
181                 break;
182         default:
183                 LASSERTF(0, "Unexpected ops %d\n", ops);
184                 break;
185         }
186         osd_ipd_put(info->oti_env, bag, ipd);
187         ldiskfs_journal_stop(jh);
188         RETURN(rc);
189 }
190
191 /* OI_scrub file ops */
192
193 static void osd_scrub_file_to_cpu(struct scrub_file *des,
194                                   struct scrub_file *src)
195 {
196         memcpy(des->sf_uuid, src->sf_uuid, 16);
197         des->sf_flags   = le64_to_cpu(src->sf_flags);
198         des->sf_magic   = le32_to_cpu(src->sf_magic);
199         des->sf_status  = le16_to_cpu(src->sf_status);
200         des->sf_param   = le16_to_cpu(src->sf_param);
201         des->sf_time_last_complete      =
202                                 le64_to_cpu(src->sf_time_last_complete);
203         des->sf_time_latest_start       =
204                                 le64_to_cpu(src->sf_time_latest_start);
205         des->sf_time_last_checkpoint    =
206                                 le64_to_cpu(src->sf_time_last_checkpoint);
207         des->sf_pos_latest_start        =
208                                 le64_to_cpu(src->sf_pos_latest_start);
209         des->sf_pos_last_checkpoint     =
210                                 le64_to_cpu(src->sf_pos_last_checkpoint);
211         des->sf_pos_first_inconsistent  =
212                                 le64_to_cpu(src->sf_pos_first_inconsistent);
213         des->sf_items_checked           =
214                                 le64_to_cpu(src->sf_items_checked);
215         des->sf_items_updated           =
216                                 le64_to_cpu(src->sf_items_updated);
217         des->sf_items_failed            =
218                                 le64_to_cpu(src->sf_items_failed);
219         des->sf_items_updated_prior     =
220                                 le64_to_cpu(src->sf_items_updated_prior);
221         des->sf_run_time        = le32_to_cpu(src->sf_run_time);
222         des->sf_success_count   = le32_to_cpu(src->sf_success_count);
223         des->sf_oi_count        = le16_to_cpu(src->sf_oi_count);
224         memcpy(des->sf_oi_bitmap, src->sf_oi_bitmap, SCRUB_OI_BITMAP_SIZE);
225 }
226
227 static void osd_scrub_file_to_le(struct scrub_file *des,
228                                  struct scrub_file *src)
229 {
230         memcpy(des->sf_uuid, src->sf_uuid, 16);
231         des->sf_flags   = cpu_to_le64(src->sf_flags);
232         des->sf_magic   = cpu_to_le32(src->sf_magic);
233         des->sf_status  = cpu_to_le16(src->sf_status);
234         des->sf_param   = cpu_to_le16(src->sf_param);
235         des->sf_time_last_complete      =
236                                 cpu_to_le64(src->sf_time_last_complete);
237         des->sf_time_latest_start       =
238                                 cpu_to_le64(src->sf_time_latest_start);
239         des->sf_time_last_checkpoint    =
240                                 cpu_to_le64(src->sf_time_last_checkpoint);
241         des->sf_pos_latest_start        =
242                                 cpu_to_le64(src->sf_pos_latest_start);
243         des->sf_pos_last_checkpoint     =
244                                 cpu_to_le64(src->sf_pos_last_checkpoint);
245         des->sf_pos_first_inconsistent  =
246                                 cpu_to_le64(src->sf_pos_first_inconsistent);
247         des->sf_items_checked           =
248                                 cpu_to_le64(src->sf_items_checked);
249         des->sf_items_updated           =
250                                 cpu_to_le64(src->sf_items_updated);
251         des->sf_items_failed            =
252                                 cpu_to_le64(src->sf_items_failed);
253         des->sf_items_updated_prior     =
254                                 cpu_to_le64(src->sf_items_updated_prior);
255         des->sf_run_time        = cpu_to_le32(src->sf_run_time);
256         des->sf_success_count   = cpu_to_le32(src->sf_success_count);
257         des->sf_oi_count        = cpu_to_le16(src->sf_oi_count);
258         memcpy(des->sf_oi_bitmap, src->sf_oi_bitmap, SCRUB_OI_BITMAP_SIZE);
259 }
260
261 static void osd_scrub_file_init(struct osd_scrub *scrub, __u8 *uuid)
262 {
263         struct scrub_file *sf = &scrub->os_file;
264
265         memset(sf, 0, sizeof(*sf));
266         memcpy(sf->sf_uuid, uuid, 16);
267         sf->sf_magic = SCRUB_MAGIC_V1;
268         sf->sf_status = SS_INIT;
269 }
270
271 void osd_scrub_file_reset(struct osd_scrub *scrub, __u8 *uuid, __u64 flags)
272 {
273         struct scrub_file *sf = &scrub->os_file;
274
275         CDEBUG(D_LFSCK, "Reset OI scrub file, flags = "LPX64"\n", flags);
276         memcpy(sf->sf_uuid, uuid, 16);
277         sf->sf_status = SS_INIT;
278         sf->sf_flags |= flags;
279         sf->sf_run_time = 0;
280         sf->sf_time_latest_start = 0;
281         sf->sf_time_last_checkpoint = 0;
282         sf->sf_pos_latest_start = 0;
283         sf->sf_pos_last_checkpoint = 0;
284         sf->sf_pos_first_inconsistent = 0;
285         sf->sf_items_checked = 0;
286         sf->sf_items_updated = 0;
287         sf->sf_items_failed = 0;
288         sf->sf_items_updated_prior = 0;
289         sf->sf_items_noscrub = 0;
290         sf->sf_items_igif = 0;
291 }
292
293 static int osd_scrub_file_load(struct osd_scrub *scrub)
294 {
295         loff_t  pos  = 0;
296         char   *name = LDISKFS_SB(osd_scrub2sb(scrub))->s_es->s_volume_name;
297         int     len  = sizeof(scrub->os_file_disk);
298         int     rc;
299
300         rc = osd_ldiskfs_read(scrub->os_inode, &scrub->os_file_disk, len, &pos);
301         if (rc == len) {
302                 struct scrub_file *sf = &scrub->os_file;
303
304                 osd_scrub_file_to_cpu(sf, &scrub->os_file_disk);
305                 if (sf->sf_magic != SCRUB_MAGIC_V1) {
306                         CWARN("%.16s: invalid scrub magic 0x%x != 0x%x\n,",
307                               name, sf->sf_magic, SCRUB_MAGIC_V1);
308                         /* Process it as new scrub file. */
309                         rc = -ENOENT;
310                 } else {
311                         rc = 0;
312                 }
313         } else if (rc != 0) {
314                 CERROR("%.16s: fail to load scrub file, expected = %d, "
315                        "rc = %d\n", name, len, rc);
316                 if (rc > 0)
317                         rc = -EFAULT;
318         } else {
319                 /* return -ENOENT for empty scrub file case. */
320                 rc = -ENOENT;
321         }
322
323         return rc;
324 }
325
326 int osd_scrub_file_store(struct osd_scrub *scrub)
327 {
328         struct osd_device *dev;
329         handle_t          *jh;
330         loff_t             pos     = 0;
331         int                len     = sizeof(scrub->os_file_disk);
332         int                credits;
333         int                rc;
334
335         dev = container_of0(scrub, struct osd_device, od_scrub);
336         credits = osd_dto_credits_noquota[DTO_WRITE_BASE] +
337                   osd_dto_credits_noquota[DTO_WRITE_BLOCK];
338         jh = ldiskfs_journal_start_sb(osd_sb(dev), credits);
339         if (IS_ERR(jh)) {
340                 rc = PTR_ERR(jh);
341                 CERROR("%.16s: fail to start trans for scrub store, rc = %d\n",
342                        LDISKFS_SB(osd_scrub2sb(scrub))->s_es->s_volume_name,rc);
343                 return rc;
344         }
345
346         osd_scrub_file_to_le(&scrub->os_file_disk, &scrub->os_file);
347         rc = osd_ldiskfs_write_record(scrub->os_inode, &scrub->os_file_disk,
348                                       len, 0, &pos, jh);
349         ldiskfs_journal_stop(jh);
350         if (rc != 0)
351                 CERROR("%.16s: fail to store scrub file, expected = %d, "
352                        "rc = %d\n",
353                        LDISKFS_SB(osd_scrub2sb(scrub))->s_es->s_volume_name,
354                        len, rc);
355         scrub->os_time_last_checkpoint = cfs_time_current();
356         scrub->os_time_next_checkpoint = scrub->os_time_last_checkpoint +
357                                 cfs_time_seconds(SCRUB_CHECKPOINT_INTERVAL);
358         return rc;
359 }
360
361 static int
362 osd_scrub_check_update(struct osd_thread_info *info, struct osd_device *dev,
363                        struct osd_idmap_cache *oic, int val)
364 {
365         struct osd_scrub             *scrub  = &dev->od_scrub;
366         struct scrub_file            *sf     = &scrub->os_file;
367         struct lu_fid                *fid    = &oic->oic_fid;
368         struct osd_inode_id          *lid    = &oic->oic_lid;
369         struct osd_inode_id          *lid2   = &info->oti_id;
370         struct osd_inconsistent_item *oii    = NULL;
371         struct inode                 *inode  = NULL;
372         int                           ops    = DTO_INDEX_UPDATE;
373         int                           idx;
374         int                           rc;
375         ENTRY;
376
377         down_write(&scrub->os_rwsem);
378         scrub->os_new_checked++;
379         if (val < 0)
380                 GOTO(out, rc = val);
381
382         if (scrub->os_in_prior)
383                 oii = cfs_list_entry(oic, struct osd_inconsistent_item,
384                                      oii_cache);
385
386         if (lid->oii_ino < sf->sf_pos_latest_start && oii == NULL)
387                 GOTO(out, rc = 0);
388
389         if (fid_is_igif(fid))
390                 sf->sf_items_igif++;
391
392         if ((val == SCRUB_NEXT_NOLMA) &&
393             (!dev->od_handle_nolma || OBD_FAIL_CHECK(OBD_FAIL_FID_NOLMA)))
394                 GOTO(out, rc = 0);
395
396         if ((oii != NULL && oii->oii_insert) || (val == SCRUB_NEXT_NOLMA))
397                 goto iget;
398
399         /* XXX: Currently, no FID-in-LMA for OST object, so osd_oi_lookup()
400          *      without checking FLD is enough.
401          *
402          *      It should be updated if FID-in-LMA for OSD object introduced
403          *      in the future. */
404         rc = osd_oi_lookup(info, dev, fid, lid2, false);
405         if (rc != 0) {
406                 if (rc != -ENOENT)
407                         GOTO(out, rc);
408
409 iget:
410                 inode = osd_iget(info, dev, lid);
411                 if (IS_ERR(inode)) {
412                         rc = PTR_ERR(inode);
413                         /* Someone removed the inode. */
414                         if (rc == -ENOENT || rc == -ESTALE)
415                                 rc = 0;
416                         GOTO(out, rc);
417                 }
418
419                 /* Check whether the inode to be unlinked during OI scrub. */
420                 if (unlikely(inode->i_nlink == 0)) {
421                         iput(inode);
422                         GOTO(out, rc = 0);
423                 }
424
425                 ops = DTO_INDEX_INSERT;
426                 idx = osd_oi_fid2idx(dev, fid);
427                 if (val == SCRUB_NEXT_NOLMA) {
428                         sf->sf_flags |= SF_UPGRADE;
429                         scrub->os_full_speed = 1;
430                         if (!(sf->sf_param & SP_DRYRUN)) {
431                                 rc = osd_ea_fid_set(info, inode, fid, 0);
432                                 if (rc != 0)
433                                         GOTO(out, rc);
434                         }
435
436                         if (!(sf->sf_flags & SF_INCONSISTENT))
437                                 dev->od_igif_inoi = 0;
438                 } else {
439                         sf->sf_flags |= SF_RECREATED;
440                         scrub->os_full_speed = 1;
441                         if (unlikely(!ldiskfs_test_bit(idx, sf->sf_oi_bitmap)))
442                                 ldiskfs_set_bit(idx, sf->sf_oi_bitmap);
443                 }
444         } else if (osd_id_eq(lid, lid2)) {
445                 GOTO(out, rc = 0);
446         } else {
447                 sf->sf_flags |= SF_INCONSISTENT;
448                 scrub->os_full_speed = 1;
449
450                 /* XXX: If the device is restored from file-level backup, then
451                  *      some IGIFs may have been already in OI files, and some
452                  *      may be not yet. Means upgrading from 1.8 may be partly
453                  *      processed, but some clients may hold some immobilized
454                  *      IGIFs, and use them to access related objects. Under
455                  *      such case, OSD does not know whether an given IGIF has
456                  *      been processed or to be processed, and it also cannot
457                  *      generate local ino#/gen# directly from the immobilized
458                  *      IGIF because of the backup/restore. Then force OSD to
459                  *      lookup the given IGIF in OI files, and if no entry,
460                  *      then ask the client to retry after upgrading completed.
461                  *      No better choice. */
462                 dev->od_igif_inoi = 1;
463         }
464
465         rc = osd_scrub_refresh_mapping(info, dev, fid, lid, ops, false);
466         if (rc == 0) {
467                 if (scrub->os_in_prior)
468                         sf->sf_items_updated_prior++;
469                 else
470                         sf->sf_items_updated++;
471         }
472
473         GOTO(out, rc);
474
475 out:
476         if (rc < 0) {
477                 sf->sf_items_failed++;
478                 if (sf->sf_pos_first_inconsistent == 0 ||
479                     sf->sf_pos_first_inconsistent > lid->oii_ino)
480                         sf->sf_pos_first_inconsistent = lid->oii_ino;
481         } else {
482                 rc = 0;
483         }
484
485         if (ops == DTO_INDEX_INSERT) {
486                 /* There may be conflict unlink during the OI scrub,
487                  * if happend, then remove the new added OI mapping. */
488                 if (unlikely(inode->i_nlink == 0))
489                         osd_scrub_refresh_mapping(info, dev, fid, lid,
490                                                   DTO_INDEX_DELETE, false);
491                 iput(inode);
492         }
493         up_write(&scrub->os_rwsem);
494
495         if (oii != NULL) {
496                 LASSERT(!cfs_list_empty(&oii->oii_list));
497
498                 spin_lock(&scrub->os_lock);
499                 cfs_list_del_init(&oii->oii_list);
500                 spin_unlock(&scrub->os_lock);
501                 OBD_FREE_PTR(oii);
502         }
503         RETURN(sf->sf_param & SP_FAILOUT ? rc : 0);
504 }
505
506 /* OI scrub APIs */
507
508 static int osd_scrub_prep(struct osd_device *dev)
509 {
510         struct osd_scrub     *scrub  = &dev->od_scrub;
511         struct ptlrpc_thread *thread = &scrub->os_thread;
512         struct scrub_file    *sf     = &scrub->os_file;
513         __u32                 flags  = scrub->os_start_flags;
514         int                   rc;
515         bool                  drop_dryrun = false;
516         ENTRY;
517
518         down_write(&scrub->os_rwsem);
519         if (flags & SS_SET_FAILOUT)
520                 sf->sf_param |= SP_FAILOUT;
521
522         if (flags & SS_CLEAR_FAILOUT)
523                 sf->sf_param &= ~SP_FAILOUT;
524
525         if (flags & SS_SET_DRYRUN)
526                 sf->sf_param |= SP_DRYRUN;
527
528         if (flags & SS_CLEAR_DRYRUN && sf->sf_param & SP_DRYRUN) {
529                 sf->sf_param &= ~SP_DRYRUN;
530                 drop_dryrun = true;
531         }
532
533         if (flags & SS_RESET)
534                 osd_scrub_file_reset(scrub,
535                         LDISKFS_SB(osd_sb(dev))->s_es->s_uuid, 0);
536
537         if (flags & SS_AUTO) {
538                 scrub->os_full_speed = 1;
539                 sf->sf_flags |= SF_AUTO;
540                 /* For the case of OI scrub auto triggered, NOT dryrun. */
541                 sf->sf_param &= ~SP_FAILOUT;
542         } else {
543                 scrub->os_full_speed = 0;
544         }
545
546         if (sf->sf_flags & (SF_RECREATED | SF_INCONSISTENT | SF_UPGRADE))
547                 scrub->os_full_speed = 1;
548
549         scrub->os_in_prior = 0;
550         spin_lock(&scrub->os_lock);
551         scrub->os_waiting = 0;
552         scrub->os_paused = 0;
553         spin_unlock(&scrub->os_lock);
554         scrub->os_new_checked = 0;
555         if (drop_dryrun && sf->sf_pos_first_inconsistent != 0)
556                 sf->sf_pos_latest_start = sf->sf_pos_first_inconsistent;
557         else if (sf->sf_pos_last_checkpoint != 0)
558                 sf->sf_pos_latest_start = sf->sf_pos_last_checkpoint + 1;
559         else
560                 sf->sf_pos_latest_start = LDISKFS_FIRST_INO(osd_sb(dev)) + 1;
561
562         scrub->os_pos_current = sf->sf_pos_latest_start;
563         sf->sf_status = SS_SCANNING;
564         sf->sf_time_latest_start = cfs_time_current_sec();
565         sf->sf_time_last_checkpoint = sf->sf_time_latest_start;
566         rc = osd_scrub_file_store(scrub);
567         if (rc == 0) {
568                 spin_lock(&scrub->os_lock);
569                 thread_set_flags(thread, SVC_RUNNING);
570                 spin_unlock(&scrub->os_lock);
571                 wake_up_all(&thread->t_ctl_waitq);
572         }
573         up_write(&scrub->os_rwsem);
574
575         RETURN(rc);
576 }
577
578 static int osd_scrub_checkpoint(struct osd_scrub *scrub)
579 {
580         struct scrub_file *sf = &scrub->os_file;
581         int                rc;
582
583         if (likely(cfs_time_before(cfs_time_current(),
584                                    scrub->os_time_next_checkpoint) ||
585                    scrub->os_new_checked == 0))
586                 return 0;
587
588         down_write(&scrub->os_rwsem);
589         sf->sf_items_checked += scrub->os_new_checked;
590         scrub->os_new_checked = 0;
591         sf->sf_pos_last_checkpoint = scrub->os_pos_current;
592         sf->sf_time_last_checkpoint = cfs_time_current_sec();
593         sf->sf_run_time += cfs_duration_sec(cfs_time_current() + HALF_SEC -
594                                             scrub->os_time_last_checkpoint);
595         rc = osd_scrub_file_store(scrub);
596         up_write(&scrub->os_rwsem);
597
598         return rc;
599 }
600
601 static void osd_scrub_post(struct osd_scrub *scrub, int result)
602 {
603         struct scrub_file *sf = &scrub->os_file;
604         ENTRY;
605
606         down_write(&scrub->os_rwsem);
607         spin_lock(&scrub->os_lock);
608         thread_set_flags(&scrub->os_thread, SVC_STOPPING);
609         spin_unlock(&scrub->os_lock);
610         if (scrub->os_new_checked > 0) {
611                 sf->sf_items_checked += scrub->os_new_checked;
612                 scrub->os_new_checked = 0;
613                 sf->sf_pos_last_checkpoint = scrub->os_pos_current;
614         }
615         sf->sf_time_last_checkpoint = cfs_time_current_sec();
616         if (result > 0) {
617                 struct osd_device *dev =
618                         container_of0(scrub, struct osd_device, od_scrub);
619
620                 dev->od_igif_inoi = 1;
621                 sf->sf_status = SS_COMPLETED;
622                 if (!(sf->sf_param & SP_DRYRUN)) {
623                         memset(sf->sf_oi_bitmap, 0, SCRUB_OI_BITMAP_SIZE);
624                         sf->sf_flags &= ~(SF_RECREATED | SF_INCONSISTENT |
625                                           SF_UPGRADE | SF_AUTO);
626                 }
627                 sf->sf_time_last_complete = sf->sf_time_last_checkpoint;
628                 sf->sf_success_count++;
629         } else if (result == 0) {
630                 if (scrub->os_paused)
631                         sf->sf_status = SS_PAUSED;
632                 else
633                         sf->sf_status = SS_STOPPED;
634         } else {
635                 sf->sf_status = SS_FAILED;
636         }
637         sf->sf_run_time += cfs_duration_sec(cfs_time_current() + HALF_SEC -
638                                             scrub->os_time_last_checkpoint);
639         result = osd_scrub_file_store(scrub);
640         if (result < 0)
641                 CERROR("%.16s: fail to osd_scrub_post, rc = %d\n",
642                        LDISKFS_SB(osd_scrub2sb(scrub))->s_es->s_volume_name,
643                        result);
644         up_write(&scrub->os_rwsem);
645
646         EXIT;
647 }
648
649 /* iteration engine */
650
651 struct osd_iit_param {
652         struct super_block *sb;
653         struct buffer_head *bitmap;
654         ldiskfs_group_t bg;
655         __u32 gbase;
656         __u32 offset;
657 };
658
659 typedef int (*osd_iit_next_policy)(struct osd_thread_info *info,
660                                    struct osd_device *dev,
661                                    struct osd_iit_param *param,
662                                    struct osd_idmap_cache **oic,
663                                    int noslot);
664
665 typedef int (*osd_iit_exec_policy)(struct osd_thread_info *info,
666                                    struct osd_device *dev,
667                                    struct osd_iit_param *param,
668                                    struct osd_idmap_cache *oic,
669                                    int *noslot, int rc);
670
671 static int osd_iit_next(struct osd_iit_param *param, __u32 *pos)
672 {
673         param->offset = ldiskfs_find_next_bit(param->bitmap->b_data,
674                         LDISKFS_INODES_PER_GROUP(param->sb), param->offset);
675         if (param->offset >= LDISKFS_INODES_PER_GROUP(param->sb)) {
676                 *pos = 1 + (param->bg+1) * LDISKFS_INODES_PER_GROUP(param->sb);
677                 return SCRUB_NEXT_BREAK;
678         } else {
679                 *pos = param->gbase + param->offset;
680                 return 0;
681         }
682 }
683
684 static int osd_iit_iget(struct osd_thread_info *info, struct osd_device *dev,
685                         struct lu_fid *fid, struct osd_inode_id *lid, __u32 pos,
686                         struct super_block *sb, bool scrub)
687 {
688         struct lustre_mdt_attrs *lma   = &info->oti_mdt_attrs;
689         struct inode            *inode;
690         int                      rc;
691
692         osd_id_gen(lid, pos, OSD_OII_NOGEN);
693         inode = osd_iget(info, dev, lid);
694         if (IS_ERR(inode)) {
695                 rc = PTR_ERR(inode);
696                 /* The inode may be removed after bitmap searching, or the
697                  * file is new created without inode initialized yet. */
698                 if (rc == -ENOENT || rc == -ESTALE)
699                         return SCRUB_NEXT_CONTINUE;
700
701                 CERROR("%.16s: fail to read inode, ino# = %u, rc = %d\n",
702                        LDISKFS_SB(sb)->s_es->s_volume_name, pos, rc);
703                 return rc;
704         }
705
706         /* If the inode has no OI mapping, then it is special locally used,
707          * should be invisible to OI scrub or up layer LFSCK. */
708         if (ldiskfs_test_inode_state(inode, LDISKFS_STATE_LUSTRE_NO_OI)) {
709                 iput(inode);
710                 return SCRUB_NEXT_CONTINUE;
711         }
712
713         if (scrub &&
714             ldiskfs_test_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB)) {
715                 /* Only skip it for the first OI scrub accessing. */
716                 ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
717                 iput(inode);
718                 return SCRUB_NEXT_NOSCRUB;
719         }
720
721         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
722         if (rc == 0) {
723                 if (fid_is_llog(&lma->lma_self_fid) ||
724                     (!scrub && fid_is_internal(&lma->lma_self_fid)) ||
725                     (scrub && (lma->lma_incompat & LMAI_AGENT)))
726                         rc = SCRUB_NEXT_CONTINUE;
727                 else
728                         *fid = lma->lma_self_fid;
729         } else if (rc == -ENODATA) {
730                 lu_igif_build(fid, inode->i_ino, inode->i_generation);
731                 if (scrub)
732                         rc = SCRUB_NEXT_NOLMA;
733                 else
734                         rc = 0;
735         }
736         iput(inode);
737         return rc;
738 }
739
740 static int osd_scrub_next(struct osd_thread_info *info, struct osd_device *dev,
741                           struct osd_iit_param *param,
742                           struct osd_idmap_cache **oic, int noslot)
743 {
744         struct osd_scrub     *scrub  = &dev->od_scrub;
745         struct ptlrpc_thread *thread = &scrub->os_thread;
746         struct lu_fid        *fid;
747         struct osd_inode_id  *lid;
748         int                   rc;
749
750         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_DELAY) && cfs_fail_val > 0) {
751                 struct l_wait_info lwi;
752
753                 lwi = LWI_TIMEOUT(cfs_time_seconds(cfs_fail_val), NULL, NULL);
754                 l_wait_event(thread->t_ctl_waitq,
755                              !cfs_list_empty(&scrub->os_inconsistent_items) ||
756                              !thread_is_running(thread),
757                              &lwi);
758         }
759
760         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_CRASH)) {
761                 spin_lock(&scrub->os_lock);
762                 thread_set_flags(thread, SVC_STOPPING);
763                 spin_unlock(&scrub->os_lock);
764                 return SCRUB_NEXT_CRASH;
765         }
766
767         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_FATAL))
768                 return SCRUB_NEXT_FATAL;
769
770         if (unlikely(!thread_is_running(thread)))
771                 return SCRUB_NEXT_EXIT;
772
773         if (!cfs_list_empty(&scrub->os_inconsistent_items)) {
774                 struct osd_inconsistent_item *oii;
775
776                 oii = cfs_list_entry(scrub->os_inconsistent_items.next,
777                                      struct osd_inconsistent_item, oii_list);
778                 *oic = &oii->oii_cache;
779                 scrub->os_in_prior = 1;
780                 return 0;
781         }
782
783         if (noslot != 0)
784                 return SCRUB_NEXT_WAIT;
785
786         rc = osd_iit_next(param, &scrub->os_pos_current);
787         if (rc != 0)
788                 return rc;
789
790         *oic = &scrub->os_oic;
791         fid = &(*oic)->oic_fid;
792         lid = &(*oic)->oic_lid;
793         rc = osd_iit_iget(info, dev, fid, lid,
794                           scrub->os_pos_current, param->sb, true);
795         return rc;
796 }
797
798 static int osd_preload_next(struct osd_thread_info *info,
799                             struct osd_device *dev, struct osd_iit_param *param,
800                             struct osd_idmap_cache **oic, int noslot)
801 {
802         struct osd_otable_cache *ooc    = &dev->od_otable_it->ooi_cache;
803         struct osd_scrub        *scrub;
804         struct ptlrpc_thread    *thread;
805         int                      rc;
806
807         rc = osd_iit_next(param, &ooc->ooc_pos_preload);
808         if (rc != 0)
809                 return rc;
810
811         scrub = &dev->od_scrub;
812         thread = &scrub->os_thread;
813         if (thread_is_running(thread) &&
814             ooc->ooc_pos_preload >= scrub->os_pos_current)
815                 return SCRUB_NEXT_EXIT;
816
817         rc = osd_iit_iget(info, dev,
818                           &ooc->ooc_cache[ooc->ooc_producer_idx].oic_fid,
819                           &ooc->ooc_cache[ooc->ooc_producer_idx].oic_lid,
820                           ooc->ooc_pos_preload, param->sb, false);
821         /* If succeed, it needs to move forward; otherwise up layer LFSCK may
822          * ignore the failure, so it still need to skip the inode next time. */
823         ooc->ooc_pos_preload = param->gbase + ++(param->offset);
824         return rc;
825 }
826
827 static inline int
828 osd_scrub_wakeup(struct osd_scrub *scrub, struct osd_otable_it *it)
829 {
830         spin_lock(&scrub->os_lock);
831         if (osd_scrub_has_window(scrub, &it->ooi_cache) ||
832             !cfs_list_empty(&scrub->os_inconsistent_items) ||
833             it->ooi_waiting || !thread_is_running(&scrub->os_thread))
834                 scrub->os_waiting = 0;
835         else
836                 scrub->os_waiting = 1;
837         spin_unlock(&scrub->os_lock);
838
839         return !scrub->os_waiting;
840 }
841
842 static int osd_scrub_exec(struct osd_thread_info *info, struct osd_device *dev,
843                           struct osd_iit_param *param,
844                           struct osd_idmap_cache *oic, int *noslot, int rc)
845 {
846         struct l_wait_info       lwi    = { 0 };
847         struct osd_scrub        *scrub  = &dev->od_scrub;
848         struct scrub_file       *sf     = &scrub->os_file;
849         struct ptlrpc_thread    *thread = &scrub->os_thread;
850         struct osd_otable_it    *it     = dev->od_otable_it;
851         struct osd_otable_cache *ooc    = it ? &it->ooi_cache : NULL;
852
853         switch (rc) {
854         case SCRUB_NEXT_CONTINUE:
855                 goto next;
856         case SCRUB_NEXT_WAIT:
857                 goto wait;
858         case SCRUB_NEXT_NOSCRUB:
859                 down_write(&scrub->os_rwsem);
860                 scrub->os_new_checked++;
861                 sf->sf_items_noscrub++;
862                 up_write(&scrub->os_rwsem);
863                 goto next;
864         }
865
866         rc = osd_scrub_check_update(info, dev, oic, rc);
867         if (rc != 0)
868                 return rc;
869
870         rc = osd_scrub_checkpoint(scrub);
871         if (rc != 0) {
872                 CERROR("%.16s: fail to checkpoint, pos = %u, rc = %d\n",
873                        LDISKFS_SB(param->sb)->s_es->s_volume_name,
874                        scrub->os_pos_current, rc);
875                 /* Continue, as long as the scrub itself can go ahead. */
876         }
877
878         if (scrub->os_in_prior) {
879                 scrub->os_in_prior = 0;
880                 return 0;
881         }
882
883 next:
884         scrub->os_pos_current = param->gbase + ++(param->offset);
885
886 wait:
887         if (it != NULL && it->ooi_waiting &&
888             ooc->ooc_pos_preload < scrub->os_pos_current) {
889                 spin_lock(&scrub->os_lock);
890                 it->ooi_waiting = 0;
891                 cfs_waitq_broadcast(&thread->t_ctl_waitq);
892                 spin_unlock(&scrub->os_lock);
893         }
894
895         if (scrub->os_full_speed || rc == SCRUB_NEXT_CONTINUE)
896                 return 0;
897
898         if (osd_scrub_has_window(scrub, ooc)) {
899                 *noslot = 0;
900                 return 0;
901         }
902
903         l_wait_event(thread->t_ctl_waitq,
904                      osd_scrub_wakeup(scrub, it),
905                      &lwi);
906
907         if (osd_scrub_has_window(scrub, ooc))
908                 *noslot = 0;
909         else
910                 *noslot = 1;
911         return 0;
912 }
913
914 static int osd_preload_exec(struct osd_thread_info *info,
915                             struct osd_device *dev, struct osd_iit_param *param,
916                             struct osd_idmap_cache *oic, int *noslot, int rc)
917 {
918         struct osd_otable_cache *ooc = &dev->od_otable_it->ooi_cache;
919
920         if (rc == 0) {
921                 ooc->ooc_cached_items++;
922                 ooc->ooc_producer_idx = (ooc->ooc_producer_idx + 1) &
923                                         ~OSD_OTABLE_IT_CACHE_MASK;
924         }
925         return rc > 0 ? 0 : rc;
926 }
927
928 #define SCRUB_IT_ALL    1
929 #define SCRUB_IT_CRASH  2
930
931 static int osd_inode_iteration(struct osd_thread_info *info,
932                                struct osd_device *dev, __u32 max, bool preload)
933 {
934         osd_iit_next_policy   next;
935         osd_iit_exec_policy   exec;
936         __u32                *pos;
937         __u32                *count;
938         struct osd_iit_param  param;
939         __u32                 limit;
940         int                   noslot = 0;
941         int                   rc;
942         ENTRY;
943
944         if (!preload) {
945                 struct osd_scrub *scrub = &dev->od_scrub;
946
947                 next = osd_scrub_next;
948                 exec = osd_scrub_exec;
949                 pos = &scrub->os_pos_current;
950                 count = &scrub->os_new_checked;
951         } else {
952                 struct osd_otable_cache *ooc = &dev->od_otable_it->ooi_cache;
953
954                 next = osd_preload_next;
955                 exec = osd_preload_exec;
956                 pos = &ooc->ooc_pos_preload;
957                 count = &ooc->ooc_cached_items;
958         }
959         param.sb = osd_sb(dev);
960         limit = le32_to_cpu(LDISKFS_SB(param.sb)->s_es->s_inodes_count);
961
962         while (*pos <= limit && *count < max) {
963                 struct osd_idmap_cache *oic = NULL;
964
965                 param.bg = (*pos - 1) / LDISKFS_INODES_PER_GROUP(param.sb);
966                 param.offset = (*pos - 1) % LDISKFS_INODES_PER_GROUP(param.sb);
967                 param.gbase = 1 + param.bg * LDISKFS_INODES_PER_GROUP(param.sb);
968                 param.bitmap = ldiskfs_read_inode_bitmap(param.sb, param.bg);
969                 if (param.bitmap == NULL) {
970                         CERROR("%.16s: fail to read bitmap for %u, "
971                                "scrub will stop, urgent mode\n",
972                                LDISKFS_SB(param.sb)->s_es->s_volume_name,
973                                (__u32)param.bg);
974                         RETURN(-EIO);
975                 }
976
977                 while (param.offset < LDISKFS_INODES_PER_GROUP(param.sb) &&
978                        *count < max) {
979                         rc = next(info, dev, &param, &oic, noslot);
980                         switch (rc) {
981                         case SCRUB_NEXT_BREAK:
982                                 goto next_group;
983                         case SCRUB_NEXT_EXIT:
984                                 brelse(param.bitmap);
985                                 RETURN(0);
986                         case SCRUB_NEXT_CRASH:
987                                 brelse(param.bitmap);
988                                 RETURN(SCRUB_IT_CRASH);
989                         case SCRUB_NEXT_FATAL:
990                                 brelse(param.bitmap);
991                                 RETURN(-EINVAL);
992                         }
993
994                         rc = exec(info, dev, &param, oic, &noslot, rc);
995                         if (rc != 0) {
996                                 brelse(param.bitmap);
997                                 RETURN(rc);
998                         }
999
1000                         if (preload && dev->od_otable_it->ooi_stopping) {
1001                                 brelse(param.bitmap);
1002                                 RETURN(0);
1003                         }
1004                 }
1005
1006 next_group:
1007                 brelse(param.bitmap);
1008
1009                 if (preload && dev->od_otable_it->ooi_stopping)
1010                         RETURN(0);
1011         }
1012
1013         if (*pos > limit)
1014                 RETURN(SCRUB_IT_ALL);
1015         RETURN(0);
1016 }
1017
1018 static int osd_otable_it_preload(const struct lu_env *env,
1019                                  struct osd_otable_it *it)
1020 {
1021         struct osd_device       *dev   = it->ooi_dev;
1022         struct osd_scrub        *scrub = &dev->od_scrub;
1023         struct osd_otable_cache *ooc   = &it->ooi_cache;
1024         int                      rc;
1025         ENTRY;
1026
1027         rc = osd_inode_iteration(osd_oti_get(env), dev,
1028                                  OSD_OTABLE_IT_CACHE_SIZE, true);
1029         if (rc == SCRUB_IT_ALL)
1030                 it->ooi_all_cached = 1;
1031
1032         CDEBUG(D_LFSCK, "OSD pre-loaded: max = %u, preload = %u, rc = %d\n",
1033                le32_to_cpu(LDISKFS_SB(osd_sb(dev))->s_es->s_inodes_count),
1034                ooc->ooc_pos_preload, rc);
1035
1036         if (scrub->os_waiting && osd_scrub_has_window(scrub, ooc)) {
1037                 scrub->os_waiting = 0;
1038                 cfs_waitq_broadcast(&scrub->os_thread.t_ctl_waitq);
1039         }
1040
1041         RETURN(rc < 0 ? rc : ooc->ooc_cached_items);
1042 }
1043
1044 static int osd_scrub_main(void *args)
1045 {
1046         struct lu_env         env;
1047         struct osd_device    *dev    = (struct osd_device *)args;
1048         struct osd_scrub     *scrub  = &dev->od_scrub;
1049         struct ptlrpc_thread *thread = &scrub->os_thread;
1050         struct super_block   *sb     = osd_sb(dev);
1051         int                   rc;
1052         ENTRY;
1053
1054         cfs_daemonize("OI_scrub");
1055         rc = lu_env_init(&env, LCT_DT_THREAD);
1056         if (rc != 0) {
1057                 CERROR("%.16s: OI scrub, fail to init env, rc = %d\n",
1058                        LDISKFS_SB(sb)->s_es->s_volume_name, rc);
1059                 GOTO(noenv, rc);
1060         }
1061
1062         rc = osd_scrub_prep(dev);
1063         if (rc != 0) {
1064                 CERROR("%.16s: OI scrub, fail to scrub prep, rc = %d\n",
1065                        LDISKFS_SB(sb)->s_es->s_volume_name, rc);
1066                 GOTO(out, rc);
1067         }
1068
1069         if (!scrub->os_full_speed) {
1070                 struct l_wait_info lwi = { 0 };
1071                 struct osd_otable_it *it = dev->od_otable_it;
1072                 struct osd_otable_cache *ooc = &it->ooi_cache;
1073
1074                 l_wait_event(thread->t_ctl_waitq,
1075                              it->ooi_user_ready || !thread_is_running(thread),
1076                              &lwi);
1077                 if (unlikely(!thread_is_running(thread)))
1078                         GOTO(post, rc = 0);
1079
1080                 scrub->os_pos_current = ooc->ooc_pos_preload;
1081         }
1082
1083         CDEBUG(D_LFSCK, "OI scrub: flags = 0x%x, pos = %u\n",
1084                scrub->os_start_flags, scrub->os_pos_current);
1085
1086         rc = osd_inode_iteration(osd_oti_get(&env), dev, ~0U, false);
1087         if (unlikely(rc == SCRUB_IT_CRASH))
1088                 GOTO(out, rc = -EINVAL);
1089         GOTO(post, rc);
1090
1091 post:
1092         osd_scrub_post(scrub, rc);
1093         CDEBUG(D_LFSCK, "OI scrub: stop, rc = %d, pos = %u\n",
1094                rc, scrub->os_pos_current);
1095
1096 out:
1097         while (!cfs_list_empty(&scrub->os_inconsistent_items)) {
1098                 struct osd_inconsistent_item *oii;
1099
1100                 oii = cfs_list_entry(scrub->os_inconsistent_items.next,
1101                                      struct osd_inconsistent_item, oii_list);
1102                 cfs_list_del_init(&oii->oii_list);
1103                 OBD_FREE_PTR(oii);
1104         }
1105         lu_env_fini(&env);
1106
1107 noenv:
1108         spin_lock(&scrub->os_lock);
1109         thread_set_flags(thread, SVC_STOPPED);
1110         cfs_waitq_broadcast(&thread->t_ctl_waitq);
1111         spin_unlock(&scrub->os_lock);
1112         return rc;
1113 }
1114
1115 /* initial OI scrub */
1116
1117 typedef int (*scandir_t)(struct osd_thread_info *, struct osd_device *,
1118                          struct dentry *, filldir_t filldir);
1119
1120 static int osd_ios_varfid_fill(void *buf, const char *name, int namelen,
1121                                loff_t offset, __u64 ino, unsigned d_type);
1122
1123 static int
1124 osd_ios_general_scan(struct osd_thread_info *info, struct osd_device *dev,
1125                      struct dentry *dentry, filldir_t filldir);
1126 static int
1127 osd_ios_ROOT_scan(struct osd_thread_info *info, struct osd_device *dev,
1128                   struct dentry *dentry, filldir_t filldir);
1129
1130 static int
1131 osd_ios_OBJECTS_scan(struct osd_thread_info *info, struct osd_device *dev,
1132                      struct dentry *dentry, filldir_t filldir);
1133
1134 enum osd_lf_flags {
1135         OLF_SCAN_SUBITEMS       = 0x0001,
1136         OLF_HIDE_FID            = 0x0002,
1137         OLF_SHOW_NAME           = 0x0004,
1138 };
1139
1140 struct osd_lf_map {
1141         char            *olm_name;
1142         struct lu_fid    olm_fid;
1143         __u16            olm_flags;
1144         scandir_t        olm_scandir;
1145         filldir_t        olm_filldir;
1146 };
1147
1148 /* Add the new introduced local files in the list in the future. */
1149 static const struct osd_lf_map osd_lf_maps[] = {
1150         /* CATALOGS */
1151         { CATLIST, { FID_SEQ_LOCAL_FILE, LLOG_CATALOGS_OID, 0 }, OLF_SHOW_NAME,
1152                 NULL, NULL },
1153
1154         /* CONFIGS */
1155         { MOUNT_CONFIGS_DIR, { FID_SEQ_LOCAL_FILE, MGS_CONFIGS_OID, 0 },
1156                 OLF_SCAN_SUBITEMS, osd_ios_general_scan,
1157                 osd_ios_varfid_fill },
1158
1159         /* NIDTBL_VERSIONS */
1160         { MGS_NIDTBL_DIR, { 0, 0, 0 }, OLF_SCAN_SUBITEMS,
1161                 osd_ios_general_scan, osd_ios_varfid_fill },
1162
1163         /* PENDING */
1164         { "PENDING", { 0, 0, 0 }, 0, NULL, NULL },
1165
1166         /* ROOT */
1167         { "ROOT", { FID_SEQ_ROOT, 1, 0 },
1168                 OLF_SCAN_SUBITEMS | OLF_HIDE_FID, osd_ios_ROOT_scan, NULL },
1169
1170         /* changelog_catalog */
1171         { CHANGELOG_CATALOG, { 0, 0, 0 }, 0, NULL, NULL },
1172
1173         /* changelog_users */
1174         { CHANGELOG_USERS, { 0, 0, 0 }, 0, NULL, NULL },
1175
1176         /* fld */
1177         { "fld", { FID_SEQ_LOCAL_FILE, FLD_INDEX_OID, 0 }, OLF_SHOW_NAME,
1178                 NULL, NULL },
1179
1180         /* last_rcvd */
1181         { LAST_RCVD, { FID_SEQ_LOCAL_FILE, LAST_RECV_OID, 0 }, OLF_SHOW_NAME,
1182                 NULL, NULL },
1183
1184         /* lfsck_bookmark */
1185         { "lfsck_bookmark", { 0, 0, 0 }, 0, NULL, NULL },
1186
1187         /* lov_objid */
1188         { LOV_OBJID, { FID_SEQ_LOCAL_FILE, MDD_LOV_OBJ_OID, 0 }, OLF_SHOW_NAME,
1189                 NULL, NULL },
1190
1191         /* lov_objseq */
1192         { LOV_OBJSEQ, { FID_SEQ_LOCAL_FILE, MDD_LOV_OBJ_OSEQ, 0 },
1193                 OLF_SHOW_NAME, NULL, NULL },
1194
1195         /* quota_master */
1196         { QMT_DIR, { 0, 0, 0 }, OLF_SCAN_SUBITEMS,
1197                 osd_ios_general_scan, osd_ios_varfid_fill },
1198
1199         /* quota_slave */
1200         { QSD_DIR, { 0, 0, 0 }, OLF_SCAN_SUBITEMS,
1201                 osd_ios_general_scan, osd_ios_varfid_fill },
1202
1203         /* seq_ctl */
1204         { "seq_ctl", { FID_SEQ_LOCAL_FILE, FID_SEQ_CTL_OID, 0 },
1205                 OLF_SHOW_NAME, NULL, NULL },
1206
1207         /* seq_srv */
1208         { "seq_srv", { FID_SEQ_LOCAL_FILE, FID_SEQ_SRV_OID, 0 },
1209                 OLF_SHOW_NAME, NULL, NULL },
1210
1211         /* health_check */
1212         { HEALTH_CHECK, { FID_SEQ_LOCAL_FILE, OFD_HEALTH_CHECK_OID, 0 },
1213                 OLF_SHOW_NAME, NULL, NULL },
1214
1215         /* lfsck_namespace */
1216         { "lfsck_namespace", { 0, 0, 0 }, 0, NULL, NULL },
1217
1218         /* OBJECTS, upgrade from old device */
1219         { OBJECTS, { 0, 0, 0 }, OLF_SCAN_SUBITEMS, osd_ios_OBJECTS_scan, NULL },
1220
1221         /* lquota_v2.user, upgrade from old device */
1222         { "lquota_v2.user", { 0, 0, 0 }, 0, NULL, NULL },
1223
1224         /* lquota_v2.group, upgrade from old device */
1225         { "lquota_v2.group", { 0, 0, 0 }, 0, NULL, NULL },
1226
1227         /* LAST_GROUP, upgrade from old device */
1228         { "LAST_GROUP", { FID_SEQ_LOCAL_FILE, OFD_LAST_GROUP_OID, 0 },
1229                 OLF_SHOW_NAME, NULL, NULL },
1230
1231         { NULL, { 0, 0, 0 }, 0, NULL, NULL }
1232 };
1233
1234 struct osd_ios_item {
1235         cfs_list_t       oii_list;
1236         struct dentry   *oii_dentry;
1237         scandir_t        oii_scandir;
1238         filldir_t        oii_filldir;
1239 };
1240
1241 struct osd_ios_filldir_buf {
1242         struct osd_thread_info  *oifb_info;
1243         struct osd_device       *oifb_dev;
1244         struct dentry           *oifb_dentry;
1245 };
1246
1247 static inline struct dentry *
1248 osd_ios_lookup_one_len(const char *name, struct dentry *parent, int namelen)
1249 {
1250         struct dentry *dentry;
1251
1252         CDEBUG(D_LFSCK, "init lookup one: parent = %.*s, name = %.*s\n",
1253                parent->d_name.len, parent->d_name.name, namelen, name);
1254
1255         dentry = ll_lookup_one_len(name, parent, namelen);
1256         if (!IS_ERR(dentry) && dentry->d_inode == NULL) {
1257                 dput(dentry);
1258                 return ERR_PTR(-ENOENT);
1259         }
1260
1261         return dentry;
1262 }
1263
1264 static inline void
1265 osd_ios_llogname2fid(struct lu_fid *fid, const char *name, int namelen)
1266 {
1267         obd_id id = 0;
1268         int    i  = 0;
1269
1270         fid->f_seq = FID_SEQ_LLOG;
1271         while (i < namelen)
1272                 id = id * 10 + name[i++] - '0';
1273
1274         fid->f_oid = id & 0x00000000ffffffffULL;
1275         fid->f_ver = id >> 32;
1276 }
1277
1278 static inline void
1279 osd_ios_Oname2fid(struct lu_fid *fid, const char *name, int namelen)
1280 {
1281         __u64 seq = 0;
1282         int   i   = 0;
1283
1284         while (i < namelen)
1285                 seq = seq * 10 + name[i++] - '0';
1286
1287         lu_last_id_fid(fid, seq);
1288 }
1289
1290 static int
1291 osd_ios_new_item(struct osd_device *dev, struct dentry *dentry,
1292                  scandir_t scandir, filldir_t filldir)
1293 {
1294         struct osd_ios_item *item;
1295         ENTRY;
1296
1297         OBD_ALLOC_PTR(item);
1298         if (item == NULL)
1299                 RETURN(-ENOMEM);
1300
1301         CFS_INIT_LIST_HEAD(&item->oii_list);
1302         item->oii_dentry = dget(dentry);
1303         item->oii_scandir = scandir;
1304         item->oii_filldir = filldir;
1305         cfs_list_add_tail(&item->oii_list, &dev->od_ios_list);
1306
1307         RETURN(0);
1308 }
1309
1310 /**
1311  * osd_ios_scan_one() - check/fix LMA FID and OI entry for one inode
1312  *
1313  * The passed \a inode's \a fid is verified against the LMA FID. If the \a fid
1314  * is NULL or is empty the IGIF FID is used. The FID is verified in the OI to
1315  * reference the inode, or fixed if it is missing or references another inode.
1316  */
1317 static int
1318 osd_ios_scan_one(struct osd_thread_info *info, struct osd_device *dev,
1319                  struct inode *inode, const struct lu_fid *fid, int flags)
1320 {
1321         struct lustre_mdt_attrs *lma    = &info->oti_mdt_attrs;
1322         struct osd_inode_id     *id     = &info->oti_id;
1323         struct osd_inode_id     *id2    = &info->oti_id2;
1324         struct osd_scrub        *scrub  = &dev->od_scrub;
1325         struct scrub_file       *sf     = &scrub->os_file;
1326         struct lu_fid            tfid;
1327         int                      rc;
1328         ENTRY;
1329
1330         CDEBUG(D_LFSCK, "init scan one: ino = %ld\n", inode->i_ino);
1331
1332         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
1333         if (rc != 0 && rc != -ENODATA)
1334                 RETURN(rc);
1335
1336         osd_id_gen(id, inode->i_ino, inode->i_generation);
1337         if (rc == -ENODATA) {
1338                 if (fid == NULL || fid_is_zero(fid) || flags & OLF_HIDE_FID)
1339                         lu_igif_build(&tfid, inode->i_ino, inode->i_generation);
1340                 else
1341                         tfid = *fid;
1342                 rc = osd_ea_fid_set(info, inode, &tfid, 0);
1343                 if (rc != 0)
1344                         RETURN(rc);
1345         } else {
1346                 tfid = lma->lma_self_fid;
1347         }
1348
1349         rc = __osd_oi_lookup(info, dev, &tfid, id2);
1350         if (rc != 0) {
1351                 if (rc != -ENOENT)
1352                         RETURN(rc);
1353
1354                 rc = osd_scrub_refresh_mapping(info, dev, &tfid, id,
1355                                                DTO_INDEX_INSERT, true);
1356                 RETURN(rc);
1357         }
1358
1359         if (osd_id_eq_strict(id, id2))
1360                 RETURN(0);
1361
1362         if (!(sf->sf_flags & SF_INCONSISTENT)) {
1363                 osd_scrub_file_reset(scrub,
1364                                      LDISKFS_SB(osd_sb(dev))->s_es->s_uuid,
1365                                      SF_INCONSISTENT);
1366                 rc = osd_scrub_file_store(scrub);
1367                 if (rc != 0)
1368                         RETURN(rc);
1369         }
1370
1371         rc = osd_scrub_refresh_mapping(info, dev, &tfid, id, DTO_INDEX_UPDATE, true);
1372
1373         RETURN(rc);
1374 }
1375
1376 static int osd_ios_varfid_fill(void *buf, const char *name, int namelen,
1377                                loff_t offset, __u64 ino, unsigned d_type)
1378 {
1379         struct osd_ios_filldir_buf *fill_buf = buf;
1380         struct osd_device          *dev      = fill_buf->oifb_dev;
1381         struct dentry              *child;
1382         int                         rc;
1383         ENTRY;
1384
1385         /* skip any '.' started names */
1386         if (name[0] == '.')
1387                 RETURN(0);
1388
1389         child = osd_ios_lookup_one_len(name, fill_buf->oifb_dentry, namelen);
1390         if (IS_ERR(child))
1391                 RETURN(PTR_ERR(child));
1392
1393         rc = osd_ios_scan_one(fill_buf->oifb_info, dev, child->d_inode,
1394                               NULL, 0);
1395         if (rc == 0 && S_ISDIR(child->d_inode->i_mode))
1396                 rc = osd_ios_new_item(dev, child, osd_ios_general_scan,
1397                                       osd_ios_varfid_fill);
1398         dput(child);
1399
1400         RETURN(rc);
1401 }
1402
1403 static int osd_ios_root_fill(void *buf, const char *name, int namelen,
1404                              loff_t offset, __u64 ino, unsigned d_type)
1405 {
1406         struct osd_ios_filldir_buf *fill_buf = buf;
1407         struct osd_device          *dev      = fill_buf->oifb_dev;
1408         const struct osd_lf_map    *map;
1409         struct dentry              *child;
1410         int                         rc       = 0;
1411         ENTRY;
1412
1413         /* skip any '.' started names */
1414         if (name[0] == '.')
1415                 RETURN(0);
1416
1417         for (map = osd_lf_maps; map->olm_name != NULL; map++) {
1418                 if (strlen(map->olm_name) != namelen)
1419                         continue;
1420
1421                 if (strncmp(map->olm_name, name, namelen) == 0)
1422                         break;
1423         }
1424
1425         if (map->olm_name == NULL)
1426                 RETURN(0);
1427
1428         child = osd_ios_lookup_one_len(name, fill_buf->oifb_dentry, namelen);
1429         if (IS_ERR(child))
1430                 RETURN(PTR_ERR(child));
1431
1432         rc = osd_ios_scan_one(fill_buf->oifb_info, dev, child->d_inode,
1433                               &map->olm_fid, map->olm_flags);
1434         if (rc == 0 && map->olm_flags & OLF_SCAN_SUBITEMS)
1435                 rc = osd_ios_new_item(dev, child, map->olm_scandir,
1436                                       map->olm_filldir);
1437         dput(child);
1438
1439         RETURN(rc);
1440 }
1441
1442 static int
1443 osd_ios_general_scan(struct osd_thread_info *info, struct osd_device *dev,
1444                      struct dentry *dentry, filldir_t filldir)
1445 {
1446         struct osd_ios_filldir_buf    buf   = { info, dev, dentry };
1447         struct file                  *filp  = &info->oti_it_ea.oie_file;
1448         struct inode                 *inode = dentry->d_inode;
1449         const struct file_operations *fops  = inode->i_fop;
1450         int                           rc;
1451         ENTRY;
1452
1453         LASSERT(filldir != NULL);
1454
1455         filp->f_pos = 0;
1456         filp->f_dentry = dentry;
1457         filp->f_mode = FMODE_64BITHASH;
1458         filp->f_mapping = inode->i_mapping;
1459         filp->f_op = fops;
1460         filp->private_data = NULL;
1461
1462         rc = fops->readdir(filp, &buf, filldir);
1463         fops->release(inode, filp);
1464
1465         RETURN(rc);
1466 }
1467
1468 static int
1469 osd_ios_ROOT_scan(struct osd_thread_info *info, struct osd_device *dev,
1470                   struct dentry *dentry, filldir_t filldir)
1471 {
1472         struct osd_scrub  *scrub  = &dev->od_scrub;
1473         struct scrub_file *sf     = &scrub->os_file;
1474         struct dentry     *child;
1475         int                rc;
1476         ENTRY;
1477
1478         /* It is existing MDT device. */
1479         dev->od_handle_nolma = 1;
1480         child = osd_ios_lookup_one_len(dot_lustre_name, dentry,
1481                                        strlen(dot_lustre_name));
1482         if (IS_ERR(child)) {
1483                 rc = PTR_ERR(child);
1484                 if (rc == -ENOENT) {
1485                         /* It is 1.8 MDT device. */
1486                         if (!(sf->sf_flags & SF_UPGRADE)) {
1487                                 osd_scrub_file_reset(scrub,
1488                                         LDISKFS_SB(osd_sb(dev))->s_es->s_uuid,
1489                                         SF_UPGRADE);
1490                                 rc = osd_scrub_file_store(scrub);
1491                         } else {
1492                                 rc = 0;
1493                         }
1494                 }
1495         } else {
1496                 /* For lustre-2.x (x <= 3), the ".lustre" has NO FID-in-LMA,
1497                  * so the client will get IGIF for the ".lustre" object when
1498                  * the MDT restart.
1499                  *
1500                  * From the OI scrub view, when the MDT upgrade to Lustre-2.4,
1501                  * it does not know whether there are some old clients cached
1502                  * the ".lustre" IGIF during the upgrading. Two choices:
1503                  *
1504                  * 1) Generate IGIF-in-LMA and IGIF-in-OI for the ".lustre".
1505                  *    It will allow the old connected clients to access the
1506                  *    ".lustre" with cached IGIF. But it will cause others
1507                  *    on the MDT failed to check "fid_is_dot_lustre()".
1508                  *
1509                  * 2) Use fixed FID {FID_SEQ_DOT_LUSTRE, FID_OID_DOT_LUSTRE, 0}
1510                  *    for ".lustre" in spite of whether there are some clients
1511                  *    cached the ".lustre" IGIF or not. It enables the check
1512                  *    "fid_is_dot_lustre()" on the MDT, although it will cause
1513                  *    that the old connected clients cannot access the ".lustre"
1514                  *    with the cached IGIF.
1515                  *
1516                  * Usually, it is rare case for the old connected clients
1517                  * to access the ".lustre" with cached IGIF. So we prefer
1518                  * to the solution 2). */
1519                 rc = osd_ios_scan_one(info, dev, child->d_inode,
1520                                       &LU_DOT_LUSTRE_FID, 0);
1521                 dput(child);
1522         }
1523
1524         RETURN(rc);
1525 }
1526
1527 static int
1528 osd_ios_OBJECTS_scan(struct osd_thread_info *info, struct osd_device *dev,
1529                      struct dentry *dentry, filldir_t filldir)
1530 {
1531         struct dentry *child;
1532         int            rc;
1533         ENTRY;
1534
1535         child = osd_ios_lookup_one_len(ADMIN_USR, dentry, strlen(ADMIN_USR));
1536         if (!IS_ERR(child)) {
1537                 rc = osd_ios_scan_one(info, dev, child->d_inode, NULL, 0);
1538                 dput(child);
1539         } else {
1540                 rc = PTR_ERR(child);
1541         }
1542
1543         if (rc != 0 && rc != -ENOENT)
1544                 RETURN(rc);
1545
1546         child = osd_ios_lookup_one_len(ADMIN_GRP, dentry, strlen(ADMIN_GRP));
1547         if (!IS_ERR(child)) {
1548                 rc = osd_ios_scan_one(info, dev, child->d_inode, NULL, 0);
1549                 dput(child);
1550         } else {
1551                 rc = PTR_ERR(child);
1552         }
1553
1554         if (rc == -ENOENT)
1555                 rc = 0;
1556
1557         RETURN(rc);
1558 }
1559
1560 static int osd_initial_OI_scrub(struct osd_thread_info *info,
1561                                 struct osd_device *dev)
1562 {
1563         struct osd_ios_item     *item    = NULL;
1564         scandir_t                scandir = osd_ios_general_scan;
1565         filldir_t                filldir = osd_ios_root_fill;
1566         struct dentry           *dentry  = osd_sb(dev)->s_root;
1567         const struct osd_lf_map *map     = osd_lf_maps;
1568         int                      rc;
1569         ENTRY;
1570
1571         /* Lookup IGIF in OI by force for initial OI scrub. */
1572         dev->od_igif_inoi = 1;
1573
1574         while (1) {
1575                 rc = scandir(info, dev, dentry, filldir);
1576                 if (item != NULL) {
1577                         dput(item->oii_dentry);
1578                         OBD_FREE_PTR(item);
1579                 }
1580
1581                 if (rc != 0)
1582                         break;
1583
1584                 if (cfs_list_empty(&dev->od_ios_list))
1585                         break;
1586
1587                 item = cfs_list_entry(dev->od_ios_list.next,
1588                                       struct osd_ios_item, oii_list);
1589                 cfs_list_del_init(&item->oii_list);
1590
1591                 LASSERT(item->oii_scandir != NULL);
1592                 scandir = item->oii_scandir;
1593                 filldir = item->oii_filldir;
1594                 dentry = item->oii_dentry;
1595         }
1596
1597         while (!cfs_list_empty(&dev->od_ios_list)) {
1598                 item = cfs_list_entry(dev->od_ios_list.next,
1599                                       struct osd_ios_item, oii_list);
1600                 cfs_list_del_init(&item->oii_list);
1601                 dput(item->oii_dentry);
1602                 OBD_FREE_PTR(item);
1603         }
1604
1605         if (rc != 0)
1606                 RETURN(rc);
1607
1608         /* There maybe the case that the object has been removed, but its OI
1609          * mapping is still in the OI file, such as the "CATALOGS" after MDT
1610          * file-level backup/restore. So here cleanup the stale OI mappings. */
1611         while (map->olm_name != NULL) {
1612                 struct dentry *child;
1613
1614                 if (fid_is_zero(&map->olm_fid)) {
1615                         map++;
1616                         continue;
1617                 }
1618
1619                 child = osd_ios_lookup_one_len(map->olm_name,
1620                                                osd_sb(dev)->s_root,
1621                                                strlen(map->olm_name));
1622                 if (!IS_ERR(child))
1623                         dput(child);
1624                 else if (PTR_ERR(child) == -ENOENT)
1625                         osd_scrub_refresh_mapping(info, dev, &map->olm_fid,
1626                                                   NULL, DTO_INDEX_DELETE, true);
1627                 map++;
1628         }
1629
1630         RETURN(0);
1631 }
1632
1633 char *osd_lf_fid2name(const struct lu_fid *fid)
1634 {
1635         const struct osd_lf_map *map = osd_lf_maps;
1636
1637         while (map->olm_name != NULL) {
1638                 if (!lu_fid_eq(fid, &map->olm_fid)) {
1639                         map++;
1640                         continue;
1641                 }
1642
1643                 if (map->olm_flags & OLF_SHOW_NAME)
1644                         return map->olm_name;
1645                 else
1646                         return "";
1647         }
1648
1649         return NULL;
1650 }
1651
1652 /* OI scrub start/stop */
1653
1654 static int do_osd_scrub_start(struct osd_device *dev, __u32 flags)
1655 {
1656         struct osd_scrub     *scrub  = &dev->od_scrub;
1657         struct ptlrpc_thread *thread = &scrub->os_thread;
1658         struct l_wait_info    lwi    = { 0 };
1659         int                   rc;
1660         ENTRY;
1661
1662 again:
1663         /* os_lock: sync status between stop and scrub thread */
1664         spin_lock(&scrub->os_lock);
1665         if (thread_is_running(thread)) {
1666                 spin_unlock(&scrub->os_lock);
1667                 RETURN(-EALREADY);
1668         } else if (unlikely(thread_is_stopping(thread))) {
1669                 spin_unlock(&scrub->os_lock);
1670                 l_wait_event(thread->t_ctl_waitq,
1671                              thread_is_stopped(thread),
1672                              &lwi);
1673                 goto again;
1674         }
1675         spin_unlock(&scrub->os_lock);
1676
1677         if (scrub->os_file.sf_status == SS_COMPLETED)
1678                 flags |= SS_RESET;
1679
1680         scrub->os_start_flags = flags;
1681         thread_set_flags(thread, 0);
1682         rc = cfs_create_thread(osd_scrub_main, dev, 0);
1683         if (rc < 0) {
1684                 CERROR("%.16s: cannot start iteration thread, rc = %d\n",
1685                        LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, rc);
1686                 RETURN(rc);
1687         }
1688
1689         l_wait_event(thread->t_ctl_waitq,
1690                      thread_is_running(thread) || thread_is_stopped(thread),
1691                      &lwi);
1692
1693         RETURN(0);
1694 }
1695
1696 int osd_scrub_start(struct osd_device *dev)
1697 {
1698         int rc;
1699         ENTRY;
1700
1701         /* od_otable_mutex: prevent curcurrent start/stop */
1702         mutex_lock(&dev->od_otable_mutex);
1703         rc = do_osd_scrub_start(dev, SS_AUTO);
1704         mutex_unlock(&dev->od_otable_mutex);
1705
1706         RETURN(rc == -EALREADY ? 0 : rc);
1707 }
1708
1709 static void do_osd_scrub_stop(struct osd_scrub *scrub)
1710 {
1711         struct ptlrpc_thread *thread = &scrub->os_thread;
1712         struct l_wait_info    lwi    = { 0 };
1713
1714         /* os_lock: sync status between stop and scrub thread */
1715         spin_lock(&scrub->os_lock);
1716         if (!thread_is_init(thread) && !thread_is_stopped(thread)) {
1717                 thread_set_flags(thread, SVC_STOPPING);
1718                 spin_unlock(&scrub->os_lock);
1719                 cfs_waitq_broadcast(&thread->t_ctl_waitq);
1720                 l_wait_event(thread->t_ctl_waitq,
1721                              thread_is_stopped(thread),
1722                              &lwi);
1723                 /* Do not skip the last lock/unlock, which can guarantee that
1724                  * the caller cannot return until the OI scrub thread exit. */
1725                 spin_lock(&scrub->os_lock);
1726         }
1727         spin_unlock(&scrub->os_lock);
1728 }
1729
1730 static void osd_scrub_stop(struct osd_device *dev)
1731 {
1732         /* od_otable_mutex: prevent curcurrent start/stop */
1733         mutex_lock(&dev->od_otable_mutex);
1734         dev->od_scrub.os_paused = 1;
1735         do_osd_scrub_stop(&dev->od_scrub);
1736         mutex_unlock(&dev->od_otable_mutex);
1737 }
1738
1739 /* OI scrub setup/cleanup */
1740
1741 static const char osd_scrub_name[] = "OI_scrub";
1742
1743 int osd_scrub_setup(const struct lu_env *env, struct osd_device *dev)
1744 {
1745         struct osd_thread_info     *info   = osd_oti_get(env);
1746         struct osd_scrub           *scrub  = &dev->od_scrub;
1747         struct lvfs_run_ctxt       *ctxt   = &scrub->os_ctxt;
1748         struct scrub_file          *sf     = &scrub->os_file;
1749         struct super_block         *sb     = osd_sb(dev);
1750         struct ldiskfs_super_block *es     = LDISKFS_SB(sb)->s_es;
1751         struct lvfs_run_ctxt        saved;
1752         struct file                *filp;
1753         int                         dirty  = 0;
1754         int                         rc     = 0;
1755         ENTRY;
1756
1757         memset(scrub, 0, sizeof(*scrub));
1758         OBD_SET_CTXT_MAGIC(ctxt);
1759         ctxt->pwdmnt = dev->od_mnt;
1760         ctxt->pwd = dev->od_mnt->mnt_root;
1761         ctxt->fs = get_ds();
1762
1763         cfs_waitq_init(&scrub->os_thread.t_ctl_waitq);
1764         init_rwsem(&scrub->os_rwsem);
1765         spin_lock_init(&scrub->os_lock);
1766         CFS_INIT_LIST_HEAD(&scrub->os_inconsistent_items);
1767
1768         push_ctxt(&saved, ctxt, NULL);
1769         filp = filp_open(osd_scrub_name, O_RDWR | O_CREAT, 0644);
1770         if (IS_ERR(filp))
1771                 RETURN(PTR_ERR(filp));
1772
1773         scrub->os_inode = igrab(filp->f_dentry->d_inode);
1774         filp_close(filp, 0);
1775         pop_ctxt(&saved, ctxt, NULL);
1776         ldiskfs_set_inode_state(scrub->os_inode,
1777                                 LDISKFS_STATE_LUSTRE_NO_OI);
1778
1779         rc = osd_scrub_file_load(scrub);
1780         if (rc == -ENOENT) {
1781                 osd_scrub_file_init(scrub, es->s_uuid);
1782                 dirty = 1;
1783         } else if (rc != 0) {
1784                 RETURN(rc);
1785         } else {
1786                 if (memcmp(sf->sf_uuid, es->s_uuid, 16) != 0) {
1787                         osd_scrub_file_reset(scrub, es->s_uuid,SF_INCONSISTENT);
1788                         dirty = 1;
1789                 } else if (sf->sf_status == SS_SCANNING) {
1790                         sf->sf_status = SS_CRASHED;
1791                         dirty = 1;
1792                 }
1793         }
1794
1795         if (sf->sf_pos_last_checkpoint != 0)
1796                 scrub->os_pos_current = sf->sf_pos_last_checkpoint + 1;
1797         else
1798                 scrub->os_pos_current = LDISKFS_FIRST_INO(sb) + 1;
1799
1800         if (dirty != 0) {
1801                 rc = osd_scrub_file_store(scrub);
1802                 if (rc != 0)
1803                         RETURN(rc);
1804         }
1805
1806         /* Initialize OI files. */
1807         rc = osd_oi_init(info, dev);
1808         if (rc < 0)
1809                 RETURN(rc);
1810
1811         rc = osd_initial_OI_scrub(info, dev);
1812         if (rc == 0) {
1813                 if ((sf->sf_flags & SF_UPGRADE) &&
1814                    !(sf->sf_flags & SF_INCONSISTENT))
1815                         /* The 'od_igif_inoi' will be set after the
1816                          * upgrading completed, needs NOT remount. */
1817                         dev->od_igif_inoi = 0;
1818                 else
1819                         /* The 'od_igif_inoi' will be set under the
1820                          * following cases:
1821                          * 1) new created system, or
1822                          * 2) restored from file-level backup, or
1823                          * 3) the upgrading completed.
1824                          *
1825                          * The 'od_igif_inoi' may be cleared by OI scrub
1826                          * later if found that the system is upgrading. */
1827                         dev->od_igif_inoi = 1;
1828
1829                 if (!dev->od_noscrub &&
1830                     ((sf->sf_status == SS_PAUSED) ||
1831                      (sf->sf_status == SS_CRASHED &&
1832                       sf->sf_flags & (SF_RECREATED | SF_INCONSISTENT |
1833                                       SF_UPGRADE | SF_AUTO)) ||
1834                      (sf->sf_status == SS_INIT &&
1835                       sf->sf_flags & (SF_RECREATED | SF_INCONSISTENT |
1836                                       SF_UPGRADE))))
1837                         rc = osd_scrub_start(dev);
1838         }
1839
1840         RETURN(rc);
1841 }
1842
1843 void osd_scrub_cleanup(const struct lu_env *env, struct osd_device *dev)
1844 {
1845         struct osd_scrub *scrub = &dev->od_scrub;
1846
1847         LASSERT(dev->od_otable_it == NULL);
1848
1849         if (scrub->os_inode != NULL) {
1850                 osd_scrub_stop(dev);
1851                 iput(scrub->os_inode);
1852                 scrub->os_inode = NULL;
1853         }
1854         if (dev->od_oi_table != NULL)
1855                 osd_oi_fini(osd_oti_get(env), dev);
1856 }
1857
1858 /* object table based iteration APIs */
1859
1860 static struct dt_it *osd_otable_it_init(const struct lu_env *env,
1861                                        struct dt_object *dt, __u32 attr,
1862                                        struct lustre_capa *capa)
1863 {
1864         enum dt_otable_it_flags flags = attr >> DT_OTABLE_IT_FLAGS_SHIFT;
1865         enum dt_otable_it_valid valid = attr & ~DT_OTABLE_IT_FLAGS_MASK;
1866         struct osd_device      *dev   = osd_dev(dt->do_lu.lo_dev);
1867         struct osd_scrub       *scrub = &dev->od_scrub;
1868         struct osd_otable_it   *it;
1869         __u32                   start = 0;
1870         int                     rc;
1871         ENTRY;
1872
1873         /* od_otable_mutex: prevent curcurrent init/fini */
1874         mutex_lock(&dev->od_otable_mutex);
1875         if (dev->od_otable_it != NULL)
1876                 GOTO(out, it = ERR_PTR(-EALREADY));
1877
1878         OBD_ALLOC_PTR(it);
1879         if (it == NULL)
1880                 GOTO(out, it = ERR_PTR(-ENOMEM));
1881
1882         dev->od_otable_it = it;
1883         it->ooi_dev = dev;
1884         it->ooi_pid = cfs_curproc_pid();
1885         it->ooi_cache.ooc_consumer_idx = -1;
1886         if (flags & DOIF_OUTUSED)
1887                 it->ooi_used_outside = 1;
1888
1889         if (flags & DOIF_RESET)
1890                 start |= SS_RESET;
1891
1892         if (valid & DOIV_ERROR_HANDLE) {
1893                 if (flags & DOIF_FAILOUT)
1894                         start |= SS_SET_FAILOUT;
1895                 else
1896                         start |= SS_CLEAR_FAILOUT;
1897         }
1898
1899         if (valid & DOIV_DRYRUN) {
1900                 if (flags & DOIF_DRYRUN)
1901                         start |= SS_SET_DRYRUN;
1902                 else
1903                         start |= SS_CLEAR_DRYRUN;
1904         }
1905
1906         rc = do_osd_scrub_start(dev, start);
1907         if (rc < 0 && rc != -EALREADY) {
1908                 dev->od_otable_it = NULL;
1909                 OBD_FREE_PTR(it);
1910                 GOTO(out, it = ERR_PTR(rc));
1911         }
1912
1913         it->ooi_cache.ooc_pos_preload = scrub->os_pos_current;
1914
1915         GOTO(out, it);
1916
1917 out:
1918         mutex_unlock(&dev->od_otable_mutex);
1919         return (struct dt_it *)it;
1920 }
1921
1922 static void osd_otable_it_fini(const struct lu_env *env, struct dt_it *di)
1923 {
1924         struct osd_otable_it *it  = (struct osd_otable_it *)di;
1925         struct osd_device    *dev = it->ooi_dev;
1926
1927         /* od_otable_mutex: prevent curcurrent init/fini */
1928         mutex_lock(&dev->od_otable_mutex);
1929         do_osd_scrub_stop(&dev->od_scrub);
1930         LASSERT(dev->od_otable_it == it);
1931
1932         dev->od_otable_it = NULL;
1933         mutex_unlock(&dev->od_otable_mutex);
1934         OBD_FREE_PTR(it);
1935 }
1936
1937 static int osd_otable_it_get(const struct lu_env *env,
1938                              struct dt_it *di, const struct dt_key *key)
1939 {
1940         return 0;
1941 }
1942
1943 /**
1944  * It is hack here:
1945  *
1946  * Sometimes the otable-based iteration driver (LFSCK) may be blocked in OSD
1947  * layer when someone wants to stop/pause the iteration. Under such case, we
1948  * need some mechanism to notify the event and wakeup the blocker.
1949  */
1950 static void osd_otable_it_put(const struct lu_env *env, struct dt_it *di)
1951 {
1952         struct osd_otable_it *it  = (struct osd_otable_it *)di;
1953         struct osd_device    *dev = it->ooi_dev;
1954
1955         /* od_otable_mutex: prevent curcurrent init/fini */
1956         mutex_lock(&dev->od_otable_mutex);
1957         if (it->ooi_pid == cfs_curproc_pid()) {
1958                 dev->od_scrub.os_paused = 1;
1959         } else {
1960                 struct ptlrpc_thread *thread = &dev->od_scrub.os_thread;
1961
1962                 it->ooi_stopping = 1;
1963                 if (it->ooi_waiting)
1964                         cfs_waitq_broadcast(&thread->t_ctl_waitq);
1965         }
1966         mutex_unlock(&dev->od_otable_mutex);
1967 }
1968
1969 static inline int
1970 osd_otable_it_wakeup(struct osd_scrub *scrub, struct osd_otable_it *it)
1971 {
1972         spin_lock(&scrub->os_lock);
1973         if (it->ooi_cache.ooc_pos_preload < scrub->os_pos_current ||
1974             scrub->os_waiting || it->ooi_stopping ||
1975             !thread_is_running(&scrub->os_thread))
1976                 it->ooi_waiting = 0;
1977         else
1978                 it->ooi_waiting = 1;
1979         spin_unlock(&scrub->os_lock);
1980
1981         return !it->ooi_waiting;
1982 }
1983
1984 static int osd_otable_it_next(const struct lu_env *env, struct dt_it *di)
1985 {
1986         struct osd_otable_it    *it     = (struct osd_otable_it *)di;
1987         struct osd_device       *dev    = it->ooi_dev;
1988         struct osd_scrub        *scrub  = &dev->od_scrub;
1989         struct osd_otable_cache *ooc    = &it->ooi_cache;
1990         struct ptlrpc_thread    *thread = &scrub->os_thread;
1991         struct l_wait_info       lwi    = { 0 };
1992         int                      rc;
1993         ENTRY;
1994
1995         LASSERT(it->ooi_user_ready);
1996
1997 again:
1998         if (!thread_is_running(thread) && !it->ooi_used_outside)
1999                 RETURN(1);
2000
2001         if (ooc->ooc_cached_items > 0) {
2002                 ooc->ooc_cached_items--;
2003                 ooc->ooc_consumer_idx = (ooc->ooc_consumer_idx + 1) &
2004                                         ~OSD_OTABLE_IT_CACHE_MASK;
2005                 RETURN(0);
2006         }
2007
2008         if (it->ooi_all_cached) {
2009                 l_wait_event(thread->t_ctl_waitq,
2010                              !thread_is_running(thread),
2011                              &lwi);
2012                 RETURN(1);
2013         }
2014
2015         if (scrub->os_waiting && osd_scrub_has_window(scrub, ooc)) {
2016                 spin_lock(&scrub->os_lock);
2017                 scrub->os_waiting = 0;
2018                 cfs_waitq_broadcast(&scrub->os_thread.t_ctl_waitq);
2019                 spin_unlock(&scrub->os_lock);
2020         }
2021
2022         if (it->ooi_cache.ooc_pos_preload >= scrub->os_pos_current)
2023                 l_wait_event(thread->t_ctl_waitq,
2024                              osd_otable_it_wakeup(scrub, it),
2025                              &lwi);
2026
2027         if (!thread_is_running(thread) && !it->ooi_used_outside)
2028                 RETURN(1);
2029
2030         if (it->ooi_stopping)
2031                 RETURN(0);
2032
2033         rc = osd_otable_it_preload(env, it);
2034         if (rc >= 0)
2035                 goto again;
2036
2037         RETURN(rc);
2038 }
2039
2040 static struct dt_key *osd_otable_it_key(const struct lu_env *env,
2041                                         const struct dt_it *di)
2042 {
2043         return NULL;
2044 }
2045
2046 static int osd_otable_it_key_size(const struct lu_env *env,
2047                                   const struct dt_it *di)
2048 {
2049         return sizeof(__u64);
2050 }
2051
2052 static int osd_otable_it_rec(const struct lu_env *env, const struct dt_it *di,
2053                              struct dt_rec *rec, __u32 attr)
2054 {
2055         struct osd_otable_it    *it  = (struct osd_otable_it *)di;
2056         struct osd_otable_cache *ooc = &it->ooi_cache;
2057
2058         *(struct lu_fid *)rec = ooc->ooc_cache[ooc->ooc_consumer_idx].oic_fid;
2059
2060         /* Filter out Invald FID already. */
2061         LASSERTF(fid_is_sane((struct lu_fid *)rec),
2062                  "Invalid FID "DFID", p_idx = %d, c_idx = %d\n",
2063                  PFID((struct lu_fid *)rec),
2064                  ooc->ooc_producer_idx, ooc->ooc_consumer_idx);
2065
2066         return 0;
2067 }
2068
2069 static __u64 osd_otable_it_store(const struct lu_env *env,
2070                                  const struct dt_it *di)
2071 {
2072         struct osd_otable_it    *it  = (struct osd_otable_it *)di;
2073         struct osd_otable_cache *ooc = &it->ooi_cache;
2074         __u64                    hash;
2075
2076         if (it->ooi_user_ready && ooc->ooc_consumer_idx != -1)
2077                 hash = ooc->ooc_cache[ooc->ooc_consumer_idx].oic_lid.oii_ino;
2078         else
2079                 hash = ooc->ooc_pos_preload;
2080         return hash;
2081 }
2082
2083 /**
2084  * Set the OSD layer iteration start position as the specified hash.
2085  */
2086 static int osd_otable_it_load(const struct lu_env *env,
2087                               const struct dt_it *di, __u64 hash)
2088 {
2089         struct osd_otable_it    *it    = (struct osd_otable_it *)di;
2090         struct osd_device       *dev   = it->ooi_dev;
2091         struct osd_otable_cache *ooc   = &it->ooi_cache;
2092         struct osd_scrub        *scrub = &dev->od_scrub;
2093         int                      rc;
2094         ENTRY;
2095
2096         /* Forbid to set iteration position after iteration started. */
2097         if (it->ooi_user_ready)
2098                 RETURN(-EPERM);
2099
2100         if (hash > OSD_OTABLE_MAX_HASH)
2101                 hash = OSD_OTABLE_MAX_HASH;
2102
2103         ooc->ooc_pos_preload = hash;
2104         if (ooc->ooc_pos_preload <= LDISKFS_FIRST_INO(osd_sb(dev)))
2105                 ooc->ooc_pos_preload = LDISKFS_FIRST_INO(osd_sb(dev)) + 1;
2106
2107         it->ooi_user_ready = 1;
2108         if (!scrub->os_full_speed)
2109                 cfs_waitq_broadcast(&scrub->os_thread.t_ctl_waitq);
2110
2111         /* Unplug OSD layer iteration by the first next() call. */
2112         rc = osd_otable_it_next(env, (struct dt_it *)it);
2113
2114         RETURN(rc);
2115 }
2116
2117 static int osd_otable_it_key_rec(const struct lu_env *env,
2118                                  const struct dt_it *di, void *key_rec)
2119 {
2120         return 0;
2121 }
2122
2123 const struct dt_index_operations osd_otable_ops = {
2124         .dio_it = {
2125                 .init     = osd_otable_it_init,
2126                 .fini     = osd_otable_it_fini,
2127                 .get      = osd_otable_it_get,
2128                 .put      = osd_otable_it_put,
2129                 .next     = osd_otable_it_next,
2130                 .key      = osd_otable_it_key,
2131                 .key_size = osd_otable_it_key_size,
2132                 .rec      = osd_otable_it_rec,
2133                 .store    = osd_otable_it_store,
2134                 .load     = osd_otable_it_load,
2135                 .key_rec  = osd_otable_it_key_rec,
2136         }
2137 };
2138
2139 /* high priority inconsistent items list APIs */
2140
2141 int osd_oii_insert(struct osd_device *dev, struct osd_idmap_cache *oic,
2142                    int insert)
2143 {
2144         struct osd_inconsistent_item *oii;
2145         struct osd_scrub             *scrub  = &dev->od_scrub;
2146         struct ptlrpc_thread         *thread = &scrub->os_thread;
2147         int                           wakeup = 0;
2148         ENTRY;
2149
2150         OBD_ALLOC_PTR(oii);
2151         if (unlikely(oii == NULL))
2152                 RETURN(-ENOMEM);
2153
2154         CFS_INIT_LIST_HEAD(&oii->oii_list);
2155         oii->oii_cache = *oic;
2156         oii->oii_insert = insert;
2157
2158         spin_lock(&scrub->os_lock);
2159         if (unlikely(!thread_is_running(thread))) {
2160                 spin_unlock(&scrub->os_lock);
2161                 OBD_FREE_PTR(oii);
2162                 RETURN(-EAGAIN);
2163         }
2164
2165         if (cfs_list_empty(&scrub->os_inconsistent_items))
2166                 wakeup = 1;
2167         cfs_list_add_tail(&oii->oii_list, &scrub->os_inconsistent_items);
2168         spin_unlock(&scrub->os_lock);
2169
2170         if (wakeup != 0)
2171                 cfs_waitq_broadcast(&thread->t_ctl_waitq);
2172
2173         RETURN(0);
2174 }
2175
2176 int osd_oii_lookup(struct osd_device *dev, const struct lu_fid *fid,
2177                    struct osd_inode_id *id)
2178 {
2179         struct osd_scrub             *scrub = &dev->od_scrub;
2180         struct osd_inconsistent_item *oii;
2181         ENTRY;
2182
2183         spin_lock(&scrub->os_lock);
2184         cfs_list_for_each_entry(oii, &scrub->os_inconsistent_items, oii_list) {
2185                 if (lu_fid_eq(fid, &oii->oii_cache.oic_fid)) {
2186                         *id = oii->oii_cache.oic_lid;
2187                         spin_unlock(&scrub->os_lock);
2188                         RETURN(0);
2189                 }
2190         }
2191         spin_unlock(&scrub->os_lock);
2192
2193         RETURN(-ENOENT);
2194 }
2195
2196 /* OI scrub dump */
2197
2198 static const char *scrub_status_names[] = {
2199         "init",
2200         "scanning",
2201         "completed",
2202         "failed",
2203         "stopped",
2204         "paused",
2205         "crashed",
2206         NULL
2207 };
2208
2209 static const char *scrub_flags_names[] = {
2210         "recreated",
2211         "inconsistent",
2212         "auto",
2213         "upgrade",
2214         NULL
2215 };
2216
2217 static const char *scrub_param_names[] = {
2218         "failout",
2219         "dryrun",
2220         NULL
2221 };
2222
2223 static int scrub_bits_dump(char **buf, int *len, int bits, const char *names[],
2224                            const char *prefix)
2225 {
2226         int save = *len;
2227         int flag;
2228         int rc;
2229         int i;
2230
2231         rc = snprintf(*buf, *len, "%s:%c", prefix, bits != 0 ? ' ' : '\n');
2232         if (rc <= 0)
2233                 return -ENOSPC;
2234
2235         *buf += rc;
2236         *len -= rc;
2237         for (i = 0, flag = 1; bits != 0; i++, flag = 1 << i) {
2238                 if (flag & bits) {
2239                         bits &= ~flag;
2240                         rc = snprintf(*buf, *len, "%s%c", names[i],
2241                                       bits != 0 ? ',' : '\n');
2242                         if (rc <= 0)
2243                                 return -ENOSPC;
2244
2245                         *buf += rc;
2246                         *len -= rc;
2247                 }
2248         }
2249         return save - *len;
2250 }
2251
2252 static int scrub_time_dump(char **buf, int *len, __u64 time, const char *prefix)
2253 {
2254         int rc;
2255
2256         if (time != 0)
2257                 rc = snprintf(*buf, *len, "%s: "LPU64" seconds\n", prefix,
2258                               cfs_time_current_sec() - time);
2259         else
2260                 rc = snprintf(*buf, *len, "%s: N/A\n", prefix);
2261         if (rc <= 0)
2262                 return -ENOSPC;
2263
2264         *buf += rc;
2265         *len -= rc;
2266         return rc;
2267 }
2268
2269 static int scrub_pos_dump(char **buf, int *len, __u64 pos, const char *prefix)
2270 {
2271         int rc;
2272
2273         if (pos != 0)
2274                 rc = snprintf(*buf, *len, "%s: "LPU64"\n", prefix, pos);
2275         else
2276                 rc = snprintf(*buf, *len, "%s: N/A\n", prefix);
2277         if (rc <= 0)
2278                 return -ENOSPC;
2279
2280         *buf += rc;
2281         *len -= rc;
2282         return rc;
2283 }
2284
2285 int osd_scrub_dump(struct osd_device *dev, char *buf, int len)
2286 {
2287         struct osd_scrub  *scrub   = &dev->od_scrub;
2288         struct scrub_file *sf      = &scrub->os_file;
2289         __u64              checked;
2290         __u64              speed;
2291         int                save    = len;
2292         int                ret     = -ENOSPC;
2293         int                rc;
2294
2295         down_read(&scrub->os_rwsem);
2296         rc = snprintf(buf, len,
2297                       "name: OI_scrub\n"
2298                       "magic: 0x%x\n"
2299                       "oi_files: %d\n"
2300                       "status: %s\n",
2301                       sf->sf_magic, (int)sf->sf_oi_count,
2302                       scrub_status_names[sf->sf_status]);
2303         if (rc <= 0)
2304                 goto out;
2305
2306         buf += rc;
2307         len -= rc;
2308         rc = scrub_bits_dump(&buf, &len, sf->sf_flags, scrub_flags_names,
2309                              "flags");
2310         if (rc < 0)
2311                 goto out;
2312
2313         rc = scrub_bits_dump(&buf, &len, sf->sf_param, scrub_param_names,
2314                              "param");
2315         if (rc < 0)
2316                 goto out;
2317
2318         rc = scrub_time_dump(&buf, &len, sf->sf_time_last_complete,
2319                              "time_since_last_completed");
2320         if (rc < 0)
2321                 goto out;
2322
2323         rc = scrub_time_dump(&buf, &len, sf->sf_time_latest_start,
2324                              "time_since_latest_start");
2325         if (rc < 0)
2326                 goto out;
2327
2328         rc = scrub_time_dump(&buf, &len, sf->sf_time_last_checkpoint,
2329                              "time_since_last_checkpoint");
2330         if (rc < 0)
2331                 goto out;
2332
2333         rc = scrub_pos_dump(&buf, &len, sf->sf_pos_latest_start,
2334                             "latest_start_position");
2335         if (rc < 0)
2336                 goto out;
2337
2338         rc = scrub_pos_dump(&buf, &len, sf->sf_pos_last_checkpoint,
2339                             "last_checkpoint_position");
2340         if (rc < 0)
2341                 goto out;
2342
2343         rc = scrub_pos_dump(&buf, &len, sf->sf_pos_first_inconsistent,
2344                             "first_failure_position");
2345         if (rc < 0)
2346                 goto out;
2347
2348         checked = sf->sf_items_checked + scrub->os_new_checked;
2349         rc = snprintf(buf, len,
2350                       "checked: "LPU64"\n"
2351                       "updated: "LPU64"\n"
2352                       "failed: "LPU64"\n"
2353                       "prior_updated: "LPU64"\n"
2354                       "noscrub: "LPU64"\n"
2355                       "igif: "LPU64"\n"
2356                       "success_count: %u\n",
2357                       checked, sf->sf_items_updated, sf->sf_items_failed,
2358                       sf->sf_items_updated_prior, sf->sf_items_noscrub,
2359                       sf->sf_items_igif, sf->sf_success_count);
2360         if (rc <= 0)
2361                 goto out;
2362
2363         buf += rc;
2364         len -= rc;
2365         speed = checked;
2366         if (thread_is_running(&scrub->os_thread)) {
2367                 cfs_duration_t duration = cfs_time_current() -
2368                                           scrub->os_time_last_checkpoint;
2369                 __u64 new_checked = scrub->os_new_checked * CFS_HZ;
2370                 __u32 rtime = sf->sf_run_time +
2371                               cfs_duration_sec(duration + HALF_SEC);
2372
2373                 if (duration != 0)
2374                         do_div(new_checked, duration);
2375                 if (rtime != 0)
2376                         do_div(speed, rtime);
2377                 rc = snprintf(buf, len,
2378                               "run_time: %u seconds\n"
2379                               "average_speed: "LPU64" objects/sec\n"
2380                               "real-time_speed: "LPU64" objects/sec\n"
2381                               "current_position: %u\n",
2382                               rtime, speed, new_checked, scrub->os_pos_current);
2383         } else {
2384                 if (sf->sf_run_time != 0)
2385                         do_div(speed, sf->sf_run_time);
2386                 rc = snprintf(buf, len,
2387                               "run_time: %u seconds\n"
2388                               "average_speed: "LPU64" objects/sec\n"
2389                               "real-time_speed: N/A\n"
2390                               "current_position: N/A\n",
2391                               sf->sf_run_time, speed);
2392         }
2393         if (rc <= 0)
2394                 goto out;
2395
2396         buf += rc;
2397         len -= rc;
2398         ret = save - len;
2399
2400 out:
2401         up_read(&scrub->os_rwsem);
2402         return ret;
2403 }