Whamcloud - gitweb
LU-11696 utils: "lfs getsom" returns "24" to userspace
[fs/lustre-release.git] / lustre / utils / llsom_sync.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, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; if not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2017, DDN Storage Corporation.
24  */
25 /*
26  * lustre/utils/llsom_sync.c
27  *
28  * Tool for sync the LSOM xattr.
29  *
30  * Author: Qian Yingjin <qian@ddn.com>
31  */
32
33 #include <stdlib.h>
34 #include <errno.h>
35 #include <getopt.h>
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <poll.h>
39 #include <assert.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <time.h>
43 #include <linux/unistd.h>
44 #include <linux/kernel.h>
45 #include <sys/sysinfo.h>
46 #include <linux/lustre/lustre_user.h>
47 #include <lustre/lustreapi.h>
48 #include <linux/lustre/lustre_idl.h>
49 #include <linux/lustre/lustre_fid.h>
50 #include <libcfs/util/hash.h>
51 #include <libcfs/util/list.h>
52 #include <libcfs/util/parser.h>
53
54 #define container_of(ptr, type, member) ({                      \
55         const typeof(((type *) 0)->member) * __mptr = (ptr);     \
56         (type *) ((char *) __mptr - offsetof(type, member)); })
57
58 #define CHLG_POLL_INTV  60
59 #define REC_MIN_AGE     600
60 #define DEF_CACHE_SIZE  (256 * 1048576) /* 256MB */
61
62 struct options {
63         const char      *o_chlg_user;
64         const char      *o_mdtname;
65         const char      *o_mntpt;
66         bool             o_daemonize;
67         bool             o_data_sync;
68         int              o_verbose;
69         int              o_intv;
70         int              o_min_age;
71         unsigned long    o_cached_fid_hiwm; /* high watermark */
72         unsigned long    o_batch_sync_cnt;
73 };
74
75 struct options opt;
76
77 struct fid_rec {
78         struct hlist_node       fr_node;
79         struct list_head        fr_link;
80         lustre_fid              fr_fid;
81         __u64                   fr_time;
82         __u64                   fr_index;
83 };
84
85 static const int fid_hash_shift = 6;
86
87 #define FID_HASH_ENTRIES        (1 << fid_hash_shift)
88 #define FID_ON_HASH(f)          (!hlist_unhashed(&(f)->fr_node))
89
90 #if __BITS_PER_LONG == 32
91 #define FID_HASH_FN(f)  (hash_long(fid_flatten32(f), fid_hash_shift))
92 #elif __BITS_PER_LONG == 64
93 #define FID_HASH_FN(f)  (hash_long(fid_flatten(f), fid_hash_shift))
94 #else
95 #error Wordsize not 32 or 64
96 #endif
97
98 struct lsom_head {
99         struct hlist_head       *lh_hash;
100         struct list_head         lh_list; /* ordered list by record index */
101         unsigned long            lh_cached_count;
102 } head;
103
104 static void usage(char *prog)
105 {
106         printf("\nUsage: %s [options] -u <userid> -m <mdtdev> <mntpt>\n"
107                "options:\n"
108                "\t-d, --daemonize\n"
109                "\t-i, --interval, poll interval in second\n"
110                "\t-a, --min-age, min age before a record is processed.\n"
111                "\t-c, --max-cache, percentage of the memroy used for cache.\n"
112                "\t-s, --sync, data sync when update LSOM xattr\n"
113                "\t-v, --verbose, produce more verbose ouput\n",
114                prog);
115         exit(0);
116 }
117
118 static inline __u64 fid_flatten(const struct lu_fid *fid)
119 {
120         __u64 ino;
121         __u64 seq;
122
123         if (fid_is_igif(fid)) {
124                 ino = lu_igif_ino(fid);
125                 return ino;
126         }
127
128         seq = fid_seq(fid);
129
130         ino = (seq << 24) + ((seq >> 24) & 0xffffff0000ULL) + fid_oid(fid);
131
132         return ino ?: fid_oid(fid);
133 }
134
135 /**
136  * map fid to 32 bit value for ino on 32bit systems.
137  */
138 static inline __u32 fid_flatten32(const struct lu_fid *fid)
139 {
140         __u32 ino;
141         __u64 seq;
142
143         if (fid_is_igif(fid)) {
144                 ino = lu_igif_ino(fid);
145                 return ino;
146         }
147
148         seq = fid_seq(fid) - FID_SEQ_START;
149
150         /* Map the high bits of the OID into higher bits of the inode number so
151          * that inodes generated at about the same time have a reduced chance
152          * of collisions. This will give a period of 2^12 = 1024 unique clients
153          * (from SEQ) and up to min(LUSTRE_SEQ_MAX_WIDTH, 2^20) = 128k objects
154          * (from OID), or up to 128M inodes without collisions for new files.
155          */
156         ino = ((seq & 0x000fffffULL) << 12) + ((seq >> 8) & 0xfffff000) +
157               (seq >> (64 - (40-8)) & 0xffffff00) +
158               (fid_oid(fid) & 0xff000fff) + ((fid_oid(fid) & 0x00fff000) << 8);
159
160         return ino ?: fid_oid(fid);
161 }
162
163 static inline bool fid_eq(const lustre_fid *f1, const lustre_fid *f2)
164 {
165         return f1->f_seq == f2->f_seq && f1->f_oid == f2->f_oid &&
166                f1->f_ver == f2->f_ver;
167 }
168
169 static void fid_hash_del(struct fid_rec *f)
170 {
171         if (FID_ON_HASH(f))
172                 hlist_del_init(&f->fr_node);
173 }
174
175 static void fid_hash_add(struct fid_rec *f)
176 {
177         assert(!FID_ON_HASH(f));
178         hlist_add_head(&f->fr_node, &head.lh_hash[FID_HASH_FN(&f->fr_fid)]);
179 }
180
181 static struct fid_rec *fid_hash_find(const lustre_fid *fid)
182 {
183         struct hlist_head *hash_list;
184         struct hlist_node *entry, *next;
185         struct fid_rec *f;
186
187         hash_list = &head.lh_hash[FID_HASH_FN(fid)];
188         hlist_for_each_entry_safe(f, entry, next, hash_list, fr_node) {
189                 assert(FID_ON_HASH(f));
190                 if (fid_eq(fid, &f->fr_fid))
191                         return f;
192         }
193
194         return NULL;
195 }
196
197 static int lsom_setup(void)
198 {
199         int i;
200
201         /* set llapi message level */
202         llapi_msg_set_level(opt.o_verbose);
203
204         memset(&head, 0, sizeof(head));
205         head.lh_hash = malloc(sizeof(struct hlist_head) * FID_HASH_ENTRIES);
206         if (head.lh_hash == NULL) {
207                 llapi_err_noerrno(LLAPI_MSG_ERROR,
208                                  "failed to alloc memory for hash (%zu).",
209                                  sizeof(struct hlist_head) * FID_HASH_ENTRIES);
210                 return -ENOMEM;
211         }
212
213         for (i = 0; i < FID_HASH_ENTRIES; i++)
214                 INIT_HLIST_HEAD(&head.lh_hash[i]);
215
216         INIT_LIST_HEAD(&head.lh_list);
217         return 0;
218 }
219
220 static void lsom_cleanup(void)
221 {
222         free(head.lh_hash);
223 }
224
225 static int lsom_update_one(struct fid_rec *f)
226 {
227         struct stat st;
228         int fd;
229         int rc = 0;
230
231         fd = llapi_open_by_fid(opt.o_mntpt, &f->fr_fid,
232                                O_RDONLY | O_NOATIME);
233         if (fd < 0) {
234                 rc = -errno;
235
236                 /* The file may be deleted, clean the corresponding
237                  * changelog record and ignore this error.
238                  */
239                 if (rc == -ENOENT)
240                         goto clean_up;
241
242                 llapi_error(LLAPI_MSG_ERROR, rc,
243                             "llapi_open_by_fid for " DFID " failed",
244                             PFID(&f->fr_fid));
245                 return rc;
246         }
247
248         if (opt.o_data_sync) {
249                 __u64 dv;
250
251                 /* Flush dirty pages from clients */
252                 rc = llapi_get_data_version(fd, &dv, LL_DV_RD_FLUSH);
253                 if (rc < 0)
254                         llapi_error(LLAPI_MSG_ERROR, errno,
255                                     "failed to sync data for " DFID,
256                                     PFID(&f->fr_fid));
257                 /* ignore this error, continue to sync lsom data */
258         }
259
260         rc = fstat(fd, &st);
261         if (rc < 0) {
262                 llapi_error(LLAPI_MSG_ERROR, rc, "failed to stat FID: " DFID,
263                             PFID(&f->fr_fid));
264                 return rc;
265         }
266
267         /* After call fstat(), it already gets OST attrs to the client,
268          * when close the file, MDS will update the LSOM data itself
269          * according the size and blocks information from the client.
270          */
271         close(fd);
272
273         llapi_printf(LLAPI_MSG_DEBUG,
274                      "record %llu:%llu, updated LSOM for fid " DFID
275                      " size:%lu blocks:%lu\n", f->fr_time, f->fr_index,
276                      PFID(&f->fr_fid), st.st_size, st.st_blocks);
277
278 clean_up:
279         rc = llapi_changelog_clear(opt.o_mdtname,
280                                    opt.o_chlg_user, f->fr_index);
281         if (rc)
282                 llapi_error(LLAPI_MSG_ERROR, rc,
283                             "failed to clear changelog record: %s:%llu",
284                             opt.o_chlg_user, f->fr_index);
285         return rc;
286 }
287
288 static int lsom_start_update(int count)
289 {
290         int rc = 0;
291         int i = 0;
292
293         llapi_printf(LLAPI_MSG_INFO, "Start to sync %d records.\n", count);
294
295         while (i < count) {
296                 struct fid_rec *f;
297
298                 f = list_entry(head.lh_list.next, struct fid_rec, fr_link);
299                 rc = lsom_update_one(f);
300                 if (rc == 0) {
301                         list_del_init(&f->fr_link);
302                         fid_hash_del(f);
303                         free(f);
304                         head.lh_cached_count--;
305                         i++;
306                 } else {
307                         goto out;
308                 }
309         }
310
311 out:
312         return rc;
313 }
314
315 static int lsom_check_sync(void)
316 {
317         int rc = 0;
318         int count;
319
320 repeated:
321         count = 0;
322         if (list_empty(&head.lh_list))
323                 return 0;
324
325         if (head.lh_cached_count > opt.o_cached_fid_hiwm)
326                 count = opt.o_batch_sync_cnt;
327         else {
328                 struct fid_rec *f;
329                 time_t now;
330
331                 /* When the first record in the list was not being
332                  * processed for a long time (more than o_min_age),
333                  * pop the record, start to handle it immediately.
334                  */
335                 now = time(NULL);
336                 f = list_entry(head.lh_list.next, struct fid_rec, fr_link);
337                 if (now > ((f->fr_time >> 30) + opt.o_min_age))
338                         count = 1;
339         }
340
341         if (count > 0)
342                 rc = lsom_start_update(count);
343
344         if (rc == 0 && count == 1)
345                 goto repeated;
346
347         return rc;
348 }
349
350 static void lsom_sort_record_list(struct fid_rec *f)
351 {
352         struct list_head *pos;
353         bool need_move = false;
354
355         for (pos = f->fr_link.next; pos != &head.lh_list; pos = pos->next) {
356                 struct fid_rec *rec = list_entry(pos, struct fid_rec, fr_link);
357
358                 if (f->fr_index > rec->fr_index) {
359                         need_move = true;
360                         continue;
361                 } else {
362                         break;
363                 }
364         }
365
366         if (need_move)
367                 list_move_tail(&f->fr_link, pos);
368 }
369
370 static int process_record(struct changelog_rec *rec)
371 {
372         __u64 index = rec->cr_index;
373         int rc = 0;
374
375         if (rec->cr_type == CL_CLOSE || rec->cr_type == CL_TRUNC ||
376             rec->cr_type == CL_SETATTR) {
377                 struct fid_rec *f;
378
379                 f = fid_hash_find(&rec->cr_tfid);
380                 if (f == NULL) {
381                         f = malloc(sizeof(struct fid_rec));
382                         if (f == NULL) {
383                                 rc = -ENOMEM;
384                                 llapi_error(LLAPI_MSG_ERROR, rc,
385                                             "failed to alloc memory for fid_rec");
386                                 return rc;
387                         }
388
389                         f->fr_fid = rec->cr_tfid;
390                         f->fr_index = index;
391                         f->fr_time = rec->cr_time;
392                         INIT_HLIST_NODE(&f->fr_node);
393                         fid_hash_add(f);
394                         /*
395                          * The newly changelog record index is processed in the
396                          * ascending order, so it is safe to put the record at
397                          * the tail of the ordered list.
398                          */
399                         list_add_tail(&f->fr_link, &head.lh_list);
400                         head.lh_cached_count++;
401                 } else {
402                         f->fr_index = index;
403                         lsom_sort_record_list(f);
404                 }
405         }
406
407         llapi_printf(LLAPI_MSG_DEBUG, "Processed changelog record index:%llu "
408                      "type:%s(0x%x) FID:"DFID"\n", index,
409                      changelog_type2str(__le32_to_cpu(rec->cr_type)),
410                      __le32_to_cpu(rec->cr_type), PFID(&rec->cr_tfid));
411
412         return rc;
413 }
414
415 static unsigned long get_fid_cache_size(int pct)
416 {
417         struct sysinfo sinfo;
418         unsigned long cache_size;
419         int rc;
420
421         rc = sysinfo(&sinfo);
422         if (rc) {
423                 llapi_error(LLAPI_MSG_ERROR, rc, "failed to get sysinfo");
424                 /* ignore this error, just pick some reasonable static
425                  * limit for the cache size (e.g. 256MB, default value).
426                  */
427                 cache_size = DEF_CACHE_SIZE;
428         } else {
429                 /* maximum cached fid size is tunned according to total
430                  * memory size, e.g. 5% of the memroy.
431                  */
432                 cache_size = sinfo.totalram * pct / 100;
433         }
434
435         return cache_size;
436 }
437
438 int main(int argc, char **argv)
439 {
440         int                      c;
441         int                      rc;
442         void                    *chglog_hdlr;
443         struct changelog_rec    *rec;
444         bool                     stop = 0;
445         int                      ret = 0;
446         unsigned long            cache_size = DEF_CACHE_SIZE;
447         char                     fsname[MAX_OBD_NAME + 1];
448         static struct option options[] = {
449                 { "mdt", required_argument, NULL, 'm' },
450                 { "user", required_argument, 0, 'u'},
451                 { "daemonize", no_argument, NULL, 'd'},
452                 { "interval", required_argument, NULL, 'i'},
453                 { "min-age", required_argument, NULL, 'a'},
454                 { "max-cache", required_argument, NULL, 'c'},
455                 { "verbose", no_argument, NULL, 'v'},
456                 { "sync", no_argument, NULL, 's'},
457                 { "help", no_argument, NULL, 'h' },
458                 { NULL }
459         };
460
461         memset(&opt, 0, sizeof(opt));
462         opt.o_data_sync = false;
463         opt.o_verbose = LLAPI_MSG_INFO;
464         opt.o_intv = CHLG_POLL_INTV;
465         opt.o_min_age = REC_MIN_AGE;
466
467         while ((c = getopt_long(argc, argv, "u:hm:dsi:a:c:v", options, NULL))
468                != EOF) {
469                 switch (c) {
470                 default:
471                         rc = -EINVAL;
472                         llapi_error(LLAPI_MSG_ERROR, rc,
473                                     "%s: unknown option '-%c'\n",
474                                     argv[0], optopt);
475                         return rc;
476                 case 'u':
477                         opt.o_chlg_user = optarg;
478                         break;
479                 case 'h':
480                         usage(argv[0]);
481                         break;
482                 case 'm':
483                         opt.o_mdtname = optarg;
484                         break;
485                 case 'd':
486                         opt.o_daemonize = true;
487                         break;
488                 case 'i':
489                         opt.o_intv = atoi(optarg);
490                         if (opt.o_intv < 0) {
491                                 rc = -EINVAL;
492                                 llapi_error(LLAPI_MSG_ERROR, rc,
493                                             "bad value for -i %s", optarg);
494                                 return rc;
495                         }
496                         break;
497                 case 'a':
498                         opt.o_min_age = atoi(optarg);
499                         if (opt.o_min_age < 0) {
500                                 rc = -EINVAL;
501                                 llapi_error(LLAPI_MSG_ERROR, rc,
502                                             "bad value for -a %s", optarg);
503                                 return rc;
504                         }
505                         break;
506                 case 'c':
507                         rc = Parser_size(&cache_size, optarg);
508                         if (rc < 0) {
509                                 rc = -EINVAL;
510                                 llapi_error(LLAPI_MSG_ERROR, rc,
511                                             "bad valud for -c '%s'", optarg);
512                                 return rc;
513                         }
514
515                         /* For value < 100, it is taken as the percentage of
516                          * total memory instead.
517                          */
518                         if (cache_size < 100)
519                                 cache_size = get_fid_cache_size(cache_size);
520                         llapi_printf(LLAPI_MSG_INFO, "Cache size: %lu\n",
521                                      cache_size);
522                         break;
523                 case 'v':
524                         opt.o_verbose++;
525                         break;
526                 case 's':
527                         opt.o_data_sync = true;
528                         break;
529                 }
530         }
531
532         if (argc != optind + 1) {
533                 llapi_err_noerrno(LLAPI_MSG_ERROR,
534                                   "%s: no mount point specified\n", argv[0]);
535                 usage(argv[0]);
536         }
537
538         opt.o_mntpt = argv[optind];
539         rc = llapi_search_fsname(opt.o_mntpt, fsname);
540         if (rc < 0) {
541                 llapi_error(LLAPI_MSG_ERROR, rc,
542                             "cannot find a Lustre file system mounted at '%s'",
543                             opt.o_mntpt);
544                 return rc;
545         }
546
547         if (!opt.o_mdtname)
548                 usage(argv[0]);
549
550         if (!opt.o_chlg_user)
551                 usage(argv[0]);
552
553         if (opt.o_daemonize) {
554                 rc = daemon(1, 1);
555                 if (rc < 0) {
556                         rc = -errno;
557                         llapi_error(LLAPI_MSG_ERROR, rc, "cannot daemonize");
558                         return rc;
559                 }
560
561                 setbuf(stdout, NULL);
562         }
563
564         opt.o_cached_fid_hiwm = cache_size / sizeof(struct fid_rec);
565         opt.o_batch_sync_cnt = opt.o_cached_fid_hiwm / 2;
566
567         rc = lsom_setup();
568         if (rc < 0)
569                 return rc;
570
571         while (!stop) {
572                 bool eof = false;
573
574                 llapi_printf(LLAPI_MSG_DEBUG, "Start receiving records\n");
575                 rc = llapi_changelog_start(&chglog_hdlr,
576                                            CHANGELOG_FLAG_BLOCK |
577                                            CHANGELOG_FLAG_JOBID |
578                                            CHANGELOG_FLAG_EXTRA_FLAGS,
579                                            opt.o_mdtname, 0);
580                 if (rc) {
581                         llapi_error(LLAPI_MSG_ERROR, rc,
582                                     "unable to open changelog of MDT [%s]\n",
583                                     opt.o_mdtname);
584                         return rc;
585                 }
586
587                 while (!eof && !stop) {
588                         rc = llapi_changelog_recv(chglog_hdlr, &rec);
589                         switch (rc) {
590                         case 0:
591                                 rc = process_record(rec);
592                                 if (rc) {
593                                         llapi_error(LLAPI_MSG_ERROR, rc,
594                                                     "failed to process record");
595                                         ret = rc;
596                                 }
597
598                                 llapi_changelog_free(&rec);
599
600                                 rc = lsom_check_sync();
601                                 if (rc) {
602                                         stop = true;
603                                         ret = rc;
604                                 }
605
606                                 break;
607                         case 1: /* EOF */
608                                 llapi_printf(LLAPI_MSG_DEBUG,
609                                              "finished reading [%s]\n",
610                                              opt.o_mdtname);
611                                 eof = true;
612                                 break;
613                         case -EINVAL: /* FS unmounted */
614                         case -EPROTO:  /* error in KUC channel */
615                         default:
616                                 stop = true;
617                                 llapi_error(LLAPI_MSG_ERROR, rc,
618                                             "failed to get changelog record");
619                                 ret = rc;
620                                 break;
621                         }
622                 }
623
624                 /* reach EOF of changelog */
625                 rc = llapi_changelog_fini(&chglog_hdlr);
626                 if (rc) {
627                         llapi_error(LLAPI_MSG_ERROR, rc,
628                                     "unable to close changelog of MDT [%s]",
629                                     opt.o_mdtname);
630                         ret = rc;
631                         return rc;
632                 }
633
634                 if (opt.o_daemonize) {
635                         sleep(opt.o_intv);
636
637                         rc = lsom_check_sync();
638                         if (rc) {
639                                 stop = true;
640                                 ret = rc;
641                         }
642                 } else {
643                         lsom_start_update(head.lh_cached_count);
644                         stop = true;
645                 }
646         }
647
648         lsom_cleanup();
649         return ret;
650 }