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