Whamcloud - gitweb
LU-9859 libcfs: replace cfs_rand() with prandom_u32_max()
[fs/lustre-release.git] / lustre / mgc / mgc_request.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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/mgc/mgc_request.c
33  *
34  * Author: Nathan Rutman <nathan@clusterfs.com>
35  */
36
37 #define DEBUG_SUBSYSTEM S_MGC
38 #define D_MGC D_CONFIG /*|D_WARNING*/
39
40 #include <linux/module.h>
41 #include <linux/kthread.h>
42 #include <linux/random.h>
43
44 #include <dt_object.h>
45 #include <lprocfs_status.h>
46 #include <lustre_dlm.h>
47 #include <lustre_disk.h>
48 #include <lustre_log.h>
49 #include <lustre_nodemap.h>
50 #include <lustre_swab.h>
51 #include <obd_class.h>
52 #include <lustre_barrier.h>
53
54 #include "mgc_internal.h"
55
56 static int mgc_name2resid(char *name, int len, struct ldlm_res_id *res_id,
57                           int type)
58 {
59         __u64 resname = 0;
60
61         if (len > sizeof(resname)) {
62                 CERROR("name too long: %s\n", name);
63                 return -EINVAL;
64         }
65         if (len <= 0) {
66                 CERROR("missing name: %s\n", name);
67                 return -EINVAL;
68         }
69         memcpy(&resname, name, len);
70
71         /* Always use the same endianness for the resid */
72         memset(res_id, 0, sizeof(*res_id));
73         res_id->name[0] = cpu_to_le64(resname);
74         /* XXX: unfortunately, sptlprc and config llog share one lock */
75         switch(type) {
76         case CONFIG_T_CONFIG:
77         case CONFIG_T_SPTLRPC:
78                 resname = 0;
79                 break;
80         case CONFIG_T_RECOVER:
81         case CONFIG_T_PARAMS:
82         case CONFIG_T_NODEMAP:
83         case CONFIG_T_BARRIER:
84                 resname = type;
85                 break;
86         default:
87                 LBUG();
88         }
89         res_id->name[1] = cpu_to_le64(resname);
90         CDEBUG(D_MGC, "log %s to resid %#llx/%#llx (%.8s)\n", name,
91                res_id->name[0], res_id->name[1], (char *)&res_id->name[0]);
92         return 0;
93 }
94
95 int mgc_fsname2resid(char *fsname, struct ldlm_res_id *res_id, int type)
96 {
97         /* fsname is at most 8 chars long, maybe contain "-".
98          * e.g. "lustre", "SUN-000" */
99         return mgc_name2resid(fsname, strlen(fsname), res_id, type);
100 }
101 EXPORT_SYMBOL(mgc_fsname2resid);
102
103 int mgc_logname2resid(char *logname, struct ldlm_res_id *res_id, int type)
104 {
105         char *name_end;
106         int len;
107
108         /* logname consists of "fsname-nodetype".
109          * e.g. "lustre-MDT0001", "SUN-000-client"
110          * there is an exception: llog "params" */
111         name_end = strrchr(logname, '-');
112         if (!name_end)
113                 len = strlen(logname);
114         else
115                 len = name_end - logname;
116         return mgc_name2resid(logname, len, res_id, type);
117 }
118 EXPORT_SYMBOL(mgc_logname2resid);
119
120 /********************** config llog list **********************/
121 static struct list_head config_llog_list = LIST_HEAD_INIT(config_llog_list);
122 static DEFINE_SPINLOCK(config_list_lock);       /* protects config_llog_list */
123
124 /* Take a reference to a config log */
125 static int config_log_get(struct config_llog_data *cld)
126 {
127         ENTRY;
128         atomic_inc(&cld->cld_refcount);
129         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
130                 atomic_read(&cld->cld_refcount));
131         RETURN(0);
132 }
133
134 /* Drop a reference to a config log.  When no longer referenced,
135    we can free the config log data */
136 static void config_log_put(struct config_llog_data *cld)
137 {
138         ENTRY;
139
140         if (unlikely(!cld))
141                 RETURN_EXIT;
142
143         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
144                 atomic_read(&cld->cld_refcount));
145         LASSERT(atomic_read(&cld->cld_refcount) > 0);
146
147         /* spinlock to make sure no item with 0 refcount in the list */
148         if (atomic_dec_and_lock(&cld->cld_refcount, &config_list_lock)) {
149                 list_del(&cld->cld_list_chain);
150                 spin_unlock(&config_list_lock);
151
152                 CDEBUG(D_MGC, "dropping config log %s\n", cld->cld_logname);
153
154                 config_log_put(cld->cld_barrier);
155                 config_log_put(cld->cld_recover);
156                 config_log_put(cld->cld_params);
157                 config_log_put(cld->cld_nodemap);
158                 config_log_put(cld->cld_sptlrpc);
159                 if (cld_is_sptlrpc(cld))
160                         sptlrpc_conf_log_stop(cld->cld_logname);
161
162                 class_export_put(cld->cld_mgcexp);
163                 OBD_FREE(cld, sizeof(*cld) + strlen(cld->cld_logname) + 1);
164         }
165
166         EXIT;
167 }
168
169 /* Find a config log by name */
170 static
171 struct config_llog_data *config_log_find(char *logname,
172                                          struct config_llog_instance *cfg)
173 {
174         struct config_llog_data *cld;
175         struct config_llog_data *found = NULL;
176         unsigned long cfg_instance;
177
178         ENTRY;
179         LASSERT(logname != NULL);
180
181         cfg_instance = cfg ? cfg->cfg_instance : 0;
182         spin_lock(&config_list_lock);
183         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
184                 /* check if cfg_instance is the one we want */
185                 if (cfg_instance != cld->cld_cfg.cfg_instance)
186                         continue;
187
188                 /* instance may be NULL, should check name */
189                 if (strcmp(logname, cld->cld_logname) == 0) {
190                         found = cld;
191                         config_log_get(found);
192                         break;
193                 }
194         }
195         spin_unlock(&config_list_lock);
196         RETURN(found);
197 }
198
199 static
200 struct config_llog_data *do_config_log_add(struct obd_device *obd,
201                                            char *logname,
202                                            int type,
203                                            struct config_llog_instance *cfg,
204                                            struct super_block *sb)
205 {
206         struct config_llog_data *cld;
207         int rc;
208
209         ENTRY;
210
211         CDEBUG(D_MGC, "do adding config log %s-%016lx\n", logname,
212                cfg ? cfg->cfg_instance : 0);
213
214         OBD_ALLOC(cld, sizeof(*cld) + strlen(logname) + 1);
215         if (!cld)
216                 RETURN(ERR_PTR(-ENOMEM));
217
218         rc = mgc_logname2resid(logname, &cld->cld_resid, type);
219         if (rc) {
220                 OBD_FREE(cld, sizeof(*cld) + strlen(cld->cld_logname) + 1);
221                 RETURN(ERR_PTR(rc));
222         }
223
224         strcpy(cld->cld_logname, logname);
225         if (cfg)
226                 cld->cld_cfg = *cfg;
227         else
228                 cld->cld_cfg.cfg_callback = class_config_llog_handler;
229         mutex_init(&cld->cld_lock);
230         cld->cld_cfg.cfg_last_idx = 0;
231         cld->cld_cfg.cfg_flags = 0;
232         cld->cld_cfg.cfg_sb = sb;
233         cld->cld_type = type;
234         atomic_set(&cld->cld_refcount, 1);
235
236         /* Keep the mgc around until we are done */
237         cld->cld_mgcexp = class_export_get(obd->obd_self_export);
238
239         if (cld_is_sptlrpc(cld))
240                 sptlrpc_conf_log_start(logname);
241
242         spin_lock(&config_list_lock);
243         list_add(&cld->cld_list_chain, &config_llog_list);
244         spin_unlock(&config_list_lock);
245
246         if (cld_is_sptlrpc(cld) || cld_is_nodemap(cld) || cld_is_barrier(cld)) {
247                 rc = mgc_process_log(obd, cld);
248                 if (rc && rc != -ENOENT)
249                         CERROR("%s: failed processing log, type %d: rc = %d\n",
250                                obd->obd_name, type, rc);
251         }
252
253         RETURN(cld);
254 }
255
256 static struct config_llog_data *config_recover_log_add(struct obd_device *obd,
257                                         char *fsname,
258                                         struct config_llog_instance *cfg,
259                                         struct super_block *sb)
260 {
261         struct config_llog_instance lcfg = *cfg;
262         struct lustre_sb_info *lsi = s2lsi(sb);
263         struct config_llog_data *cld;
264         char logname[32];
265
266         if (IS_OST(lsi))
267                 return NULL;
268
269         /* for osp-on-ost, see lustre_start_osp() */
270         if (IS_MDT(lsi) && lcfg.cfg_instance)
271                 return NULL;
272
273         /* We have to use different llog for clients and MDTs for DNE,
274          * where only clients are notified if one of DNE server restarts.
275          */
276         LASSERT(strlen(fsname) < sizeof(logname) / 2);
277         strncpy(logname, fsname, sizeof(logname));
278         if (IS_SERVER(lsi)) { /* mdt */
279                 LASSERT(lcfg.cfg_instance == 0);
280                 lcfg.cfg_instance = ll_get_cfg_instance(sb);
281                 strncat(logname, "-mdtir", sizeof(logname));
282         } else {
283                 LASSERT(lcfg.cfg_instance != 0);
284                 strncat(logname, "-cliir", sizeof(logname));
285         }
286
287         cld = do_config_log_add(obd, logname, CONFIG_T_RECOVER, &lcfg, sb);
288         return cld;
289 }
290
291 static struct config_llog_data *config_log_find_or_add(struct obd_device *obd,
292                                 char *logname, struct super_block *sb, int type,
293                                 struct config_llog_instance *cfg)
294 {
295         struct config_llog_instance lcfg = *cfg;
296         struct config_llog_data *cld;
297
298         /* Note class_config_llog_handler() depends on getting "obd" back */
299         lcfg.cfg_instance = sb ? ll_get_cfg_instance(sb) : (unsigned long)obd;
300
301         cld = config_log_find(logname, &lcfg);
302         if (unlikely(cld != NULL))
303                 return cld;
304
305         return do_config_log_add(obd, logname, type, &lcfg, sb);
306 }
307
308 /** Add this log to the list of active logs watched by an MGC.
309  * Active means we're watching for updates.
310  * We have one active log per "mount" - client instance or servername.
311  * Each instance may be at a different point in the log.
312  */
313 static struct config_llog_data *
314 config_log_add(struct obd_device *obd, char *logname,
315                struct config_llog_instance *cfg, struct super_block *sb)
316 {
317         struct lustre_sb_info *lsi = s2lsi(sb);
318         struct config_llog_data *cld = NULL;
319         struct config_llog_data *sptlrpc_cld = NULL;
320         struct config_llog_data *params_cld = NULL;
321         struct config_llog_data *nodemap_cld = NULL;
322         struct config_llog_data *barrier_cld = NULL;
323         char seclogname[32];
324         char *ptr;
325         int rc;
326         bool locked = false;
327         ENTRY;
328
329         CDEBUG(D_MGC, "add config log %s-%016lx\n", logname,
330                cfg->cfg_instance);
331
332         /*
333          * for each regular log, the depended sptlrpc log name is
334          * <fsname>-sptlrpc. multiple regular logs may share one sptlrpc log.
335          */
336         ptr = strrchr(logname, '-');
337         if (ptr == NULL || ptr - logname > 8) {
338                 CERROR("logname %s is too long\n", logname);
339                 RETURN(ERR_PTR(-EINVAL));
340         }
341
342         memcpy(seclogname, logname, ptr - logname);
343         strcpy(seclogname + (ptr - logname), "-sptlrpc");
344
345         if (cfg->cfg_sub_clds & CONFIG_SUB_SPTLRPC) {
346                 sptlrpc_cld = config_log_find_or_add(obd, seclogname, NULL,
347                                                      CONFIG_T_SPTLRPC, cfg);
348                 if (IS_ERR(sptlrpc_cld)) {
349                         CERROR("%s: can't create sptlrpc log %s: rc = %ld\n",
350                                obd->obd_name, seclogname, PTR_ERR(sptlrpc_cld));
351                         RETURN(sptlrpc_cld);
352                 }
353         }
354
355         if (!IS_MGS(lsi) && cfg->cfg_sub_clds & CONFIG_SUB_NODEMAP) {
356                 nodemap_cld = config_log_find_or_add(obd, LUSTRE_NODEMAP_NAME,
357                                                      NULL, CONFIG_T_NODEMAP,
358                                                      cfg);
359                 if (IS_ERR(nodemap_cld)) {
360                         rc = PTR_ERR(nodemap_cld);
361                         CERROR("%s: cannot create nodemap log: rc = %d\n",
362                                obd->obd_name, rc);
363                         GOTO(out_sptlrpc, rc);
364                 }
365         }
366
367         if (cfg->cfg_sub_clds & CONFIG_SUB_PARAMS) {
368                 params_cld = config_log_find_or_add(obd, PARAMS_FILENAME, sb,
369                                                     CONFIG_T_PARAMS, cfg);
370                 if (IS_ERR(params_cld)) {
371                         rc = PTR_ERR(params_cld);
372                         CERROR("%s: can't create params log: rc = %d\n",
373                                obd->obd_name, rc);
374                         GOTO(out_nodemap, rc);
375                 }
376         }
377
378         if (IS_MDT(s2lsi(sb)) && cfg->cfg_sub_clds & CONFIG_SUB_BARRIER) {
379                 snprintf(seclogname + (ptr - logname), sizeof(seclogname) - 1,
380                          "-%s", BARRIER_FILENAME);
381                 barrier_cld = config_log_find_or_add(obd, seclogname, sb,
382                                                      CONFIG_T_BARRIER, cfg);
383                 if (IS_ERR(barrier_cld)) {
384                         rc = PTR_ERR(barrier_cld);
385                         CERROR("%s: can't create barrier log: rc = %d\n",
386                                obd->obd_name, rc);
387                         GOTO(out_params, rc);
388                 }
389         }
390
391         cld = do_config_log_add(obd, logname, CONFIG_T_CONFIG, cfg, sb);
392         if (IS_ERR(cld)) {
393                 rc = PTR_ERR(cld);
394                 CERROR("%s: can't create log: rc = %d\n",
395                        obd->obd_name, rc);
396                 GOTO(out_barrier, rc = PTR_ERR(cld));
397         }
398
399         LASSERT(lsi->lsi_lmd);
400         if (!(lsi->lsi_lmd->lmd_flags & LMD_FLG_NOIR) &&
401             cfg->cfg_sub_clds & CONFIG_SUB_RECOVER) {
402                 struct config_llog_data *recover_cld;
403
404                 ptr = strrchr(seclogname, '-');
405                 if (ptr != NULL) {
406                         *ptr = 0;
407                 } else {
408                         CERROR("%s: sptlrpc log name not correct, %s: "
409                                "rc = %d\n", obd->obd_name, seclogname, -EINVAL);
410                         GOTO(out_cld, rc = -EINVAL);
411                 }
412
413                 recover_cld = config_recover_log_add(obd, seclogname, cfg, sb);
414                 if (IS_ERR(recover_cld)) {
415                         rc = PTR_ERR(recover_cld);
416                         CERROR("%s: can't create recover log: rc = %d\n",
417                                obd->obd_name, rc);
418                         GOTO(out_cld, rc);
419                 }
420
421                 mutex_lock(&cld->cld_lock);
422                 locked = true;
423                 cld->cld_recover = recover_cld;
424         }
425
426         if (!locked)
427                 mutex_lock(&cld->cld_lock);
428         cld->cld_params = params_cld;
429         cld->cld_barrier = barrier_cld;
430         cld->cld_nodemap = nodemap_cld;
431         cld->cld_sptlrpc = sptlrpc_cld;
432         mutex_unlock(&cld->cld_lock);
433
434         RETURN(cld);
435
436 out_cld:
437         config_log_put(cld);
438 out_barrier:
439         config_log_put(barrier_cld);
440 out_params:
441         config_log_put(params_cld);
442 out_nodemap:
443         config_log_put(nodemap_cld);
444 out_sptlrpc:
445         config_log_put(sptlrpc_cld);
446
447         return ERR_PTR(rc);
448 }
449
450 DEFINE_MUTEX(llog_process_lock);
451
452 static inline void config_mark_cld_stop(struct config_llog_data *cld)
453 {
454         if (cld) {
455                 mutex_lock(&cld->cld_lock);
456                 spin_lock(&config_list_lock);
457                 cld->cld_stopping = 1;
458                 spin_unlock(&config_list_lock);
459                 mutex_unlock(&cld->cld_lock);
460         }
461 }
462
463 /** Stop watching for updates on this log.
464  */
465 static int config_log_end(char *logname, struct config_llog_instance *cfg)
466 {
467         struct config_llog_data *cld;
468         struct config_llog_data *cld_sptlrpc = NULL;
469         struct config_llog_data *cld_params = NULL;
470         struct config_llog_data *cld_recover = NULL;
471         struct config_llog_data *cld_nodemap = NULL;
472         struct config_llog_data *cld_barrier = NULL;
473         int rc = 0;
474
475         ENTRY;
476
477         cld = config_log_find(logname, cfg);
478         if (cld == NULL)
479                 RETURN(-ENOENT);
480
481         mutex_lock(&cld->cld_lock);
482         /*
483          * if cld_stopping is set, it means we didn't start the log thus
484          * not owning the start ref. this can happen after previous umount:
485          * the cld still hanging there waiting for lock cancel, and we
486          * remount again but failed in the middle and call log_end without
487          * calling start_log.
488          */
489         if (unlikely(cld->cld_stopping)) {
490                 mutex_unlock(&cld->cld_lock);
491                 /* drop the ref from the find */
492                 config_log_put(cld);
493                 RETURN(rc);
494         }
495
496         spin_lock(&config_list_lock);
497         cld->cld_stopping = 1;
498         spin_unlock(&config_list_lock);
499
500         cld_recover = cld->cld_recover;
501         cld->cld_recover = NULL;
502         cld_params = cld->cld_params;
503         cld->cld_params = NULL;
504         cld_nodemap = cld->cld_nodemap;
505         cld->cld_nodemap = NULL;
506         cld_barrier = cld->cld_barrier;
507         cld->cld_barrier = NULL;
508         cld_sptlrpc = cld->cld_sptlrpc;
509         cld->cld_sptlrpc = NULL;
510         mutex_unlock(&cld->cld_lock);
511
512         config_mark_cld_stop(cld_recover);
513         config_log_put(cld_recover);
514
515         config_mark_cld_stop(cld_params);
516         config_log_put(cld_params);
517
518         /* don't set cld_stopping on nm lock as other targets may be active */
519         config_log_put(cld_nodemap);
520
521         if (cld_barrier) {
522                 mutex_lock(&cld_barrier->cld_lock);
523                 cld_barrier->cld_stopping = 1;
524                 mutex_unlock(&cld_barrier->cld_lock);
525                 config_log_put(cld_barrier);
526         }
527
528         config_log_put(cld_sptlrpc);
529
530         /* drop the ref from the find */
531         config_log_put(cld);
532         /* drop the start ref */
533         config_log_put(cld);
534
535         CDEBUG(D_MGC, "end config log %s (%d)\n", logname ? logname : "client",
536                rc);
537         RETURN(rc);
538 }
539
540 int lprocfs_mgc_rd_ir_state(struct seq_file *m, void *data)
541 {
542         struct obd_device       *obd = data;
543         struct obd_import       *imp;
544         struct obd_connect_data *ocd;
545         struct config_llog_data *cld;
546
547         ENTRY;
548         LASSERT(obd);
549         LPROCFS_CLIMP_CHECK(obd);
550         imp = obd->u.cli.cl_import;
551         ocd = &imp->imp_connect_data;
552
553         seq_printf(m, "imperative_recovery: %s\n",
554                    OCD_HAS_FLAG(ocd, IMP_RECOV) ? "ENABLED" : "DISABLED");
555         seq_printf(m, "client_state:\n");
556
557         spin_lock(&config_list_lock);
558         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
559                 if (cld->cld_recover == NULL)
560                         continue;
561                 seq_printf(m,  "    - { client: %s, nidtbl_version: %u }\n",
562                            cld->cld_logname,
563                            cld->cld_recover->cld_cfg.cfg_last_idx);
564         }
565         spin_unlock(&config_list_lock);
566
567         LPROCFS_CLIMP_EXIT(obd);
568         RETURN(0);
569 }
570
571 /* reenqueue any lost locks */
572 #define RQ_RUNNING      0x1
573 #define RQ_NOW          0x2
574 #define RQ_LATER        0x4
575 #define RQ_STOP         0x8
576 #define RQ_PRECLEANUP   0x10
577 static int                    rq_state = 0;
578 static wait_queue_head_t      rq_waitq;
579 static DECLARE_COMPLETION(rq_exit);
580 static DECLARE_COMPLETION(rq_start);
581
582 static void do_requeue(struct config_llog_data *cld)
583 {
584         int rc = 0;
585         ENTRY;
586
587         LASSERT(atomic_read(&cld->cld_refcount) > 0);
588
589         /*
590          * Do not run mgc_process_log on a disconnected export or an
591          * export which is being disconnected. Take the client
592          * semaphore to make the check non-racy.
593          */
594         down_read_nested(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem,
595                          OBD_CLI_SEM_MGC);
596         if (cld->cld_mgcexp->exp_obd->u.cli.cl_conn_count != 0) {
597                 CDEBUG(D_MGC, "updating log %s\n", cld->cld_logname);
598                 rc = mgc_process_log(cld->cld_mgcexp->exp_obd, cld);
599                 if (rc && rc != -ENOENT)
600                         CERROR("failed processing log: %d\n", rc);
601         } else {
602                 CDEBUG(D_MGC, "disconnecting, won't update log %s\n",
603                        cld->cld_logname);
604         }
605         up_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
606
607         EXIT;
608 }
609
610 /* this timeout represents how many seconds MGC should wait before
611  * requeue config and recover lock to the MGS. We need to randomize this
612  * in order to not flood the MGS.
613  */
614 #define MGC_TIMEOUT_MIN_SECONDS   5
615 #define MGC_TIMEOUT_RAND_CENTISEC 500
616
617 static int mgc_requeue_thread(void *data)
618 {
619         int rc = 0;
620         bool first = true;
621         ENTRY;
622
623         CDEBUG(D_MGC, "Starting requeue thread\n");
624
625         /* Keep trying failed locks periodically */
626         spin_lock(&config_list_lock);
627         rq_state |= RQ_RUNNING;
628         while (!(rq_state & RQ_STOP)) {
629                 struct l_wait_info lwi;
630                 struct config_llog_data *cld, *cld_prev;
631                 int rand = prandom_u32_max(MGC_TIMEOUT_RAND_CENTISEC);
632                 int to;
633
634                 /* Any new or requeued lostlocks will change the state */
635                 rq_state &= ~(RQ_NOW | RQ_LATER);
636                 spin_unlock(&config_list_lock);
637
638                 if (first) {
639                         first = false;
640                         complete(&rq_start);
641                 }
642
643                 /* Always wait a few seconds to allow the server who
644                    caused the lock revocation to finish its setup, plus some
645                    random so everyone doesn't try to reconnect at once. */
646                 to = msecs_to_jiffies(MGC_TIMEOUT_MIN_SECONDS * MSEC_PER_SEC);
647                 /* rand is centi-seconds */
648                 to += msecs_to_jiffies(rand * MSEC_PER_SEC / 100);
649                 lwi = LWI_TIMEOUT(to, NULL, NULL);
650                 l_wait_event(rq_waitq, rq_state & (RQ_STOP | RQ_PRECLEANUP),
651                              &lwi);
652
653                 /*
654                  * iterate & processing through the list. for each cld, process
655                  * its depending sptlrpc cld firstly (if any) and then itself.
656                  *
657                  * it's guaranteed any item in the list must have
658                  * reference > 0; and if cld_lostlock is set, at
659                  * least one reference is taken by the previous enqueue.
660                  */
661                 cld_prev = NULL;
662
663                 spin_lock(&config_list_lock);
664                 rq_state &= ~RQ_PRECLEANUP;
665                 list_for_each_entry(cld, &config_llog_list,
666                                     cld_list_chain) {
667                         if (!cld->cld_lostlock || cld->cld_stopping)
668                                 continue;
669
670                         /* hold reference to avoid being freed during
671                          * subsequent processing. */
672                         config_log_get(cld);
673                         cld->cld_lostlock = 0;
674                         spin_unlock(&config_list_lock);
675
676                         config_log_put(cld_prev);
677                         cld_prev = cld;
678
679                         if (likely(!(rq_state & RQ_STOP))) {
680                                 do_requeue(cld);
681                                 spin_lock(&config_list_lock);
682                         } else {
683                                 spin_lock(&config_list_lock);
684                                 break;
685                         }
686                 }
687                 spin_unlock(&config_list_lock);
688                 config_log_put(cld_prev);
689
690                 /* Wait a bit to see if anyone else needs a requeue */
691                 lwi = (struct l_wait_info) { 0 };
692                 l_wait_event(rq_waitq, rq_state & (RQ_NOW | RQ_STOP),
693                              &lwi);
694                 spin_lock(&config_list_lock);
695         }
696
697         /* spinlock and while guarantee RQ_NOW and RQ_LATER are not set */
698         rq_state &= ~RQ_RUNNING;
699         spin_unlock(&config_list_lock);
700
701         complete(&rq_exit);
702
703         CDEBUG(D_MGC, "Ending requeue thread\n");
704         RETURN(rc);
705 }
706
707 /* Add a cld to the list to requeue.  Start the requeue thread if needed.
708    We are responsible for dropping the config log reference from here on out. */
709 static void mgc_requeue_add(struct config_llog_data *cld)
710 {
711         bool wakeup = false;
712         ENTRY;
713
714         CDEBUG(D_INFO, "log %s: requeue (r=%d sp=%d st=%x)\n",
715                 cld->cld_logname, atomic_read(&cld->cld_refcount),
716                 cld->cld_stopping, rq_state);
717         LASSERT(atomic_read(&cld->cld_refcount) > 0);
718
719         mutex_lock(&cld->cld_lock);
720         spin_lock(&config_list_lock);
721         if (!(rq_state & RQ_STOP) && !cld->cld_stopping && !cld->cld_lostlock) {
722                 cld->cld_lostlock = 1;
723                 rq_state |= RQ_NOW;
724                 wakeup = true;
725         }
726         spin_unlock(&config_list_lock);
727         mutex_unlock(&cld->cld_lock);
728         if (wakeup)
729                 wake_up(&rq_waitq);
730
731         EXIT;
732 }
733
734 /********************** class fns **********************/
735 static int mgc_local_llog_init(const struct lu_env *env,
736                                struct obd_device *obd,
737                                struct obd_device *disk)
738 {
739         struct llog_ctxt        *ctxt;
740         int                      rc;
741
742         ENTRY;
743
744         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CONFIG_ORIG_CTXT, disk,
745                         &llog_osd_ops);
746         if (rc)
747                 RETURN(rc);
748
749         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
750         LASSERT(ctxt);
751         ctxt->loc_dir = obd->u.cli.cl_mgc_configs_dir;
752         llog_ctxt_put(ctxt);
753
754         RETURN(0);
755 }
756
757 static int mgc_local_llog_fini(const struct lu_env *env,
758                                struct obd_device *obd)
759 {
760         struct llog_ctxt *ctxt;
761
762         ENTRY;
763
764         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
765         llog_cleanup(env, ctxt);
766
767         RETURN(0);
768 }
769
770 static int mgc_fs_setup(const struct lu_env *env, struct obd_device *obd,
771                         struct super_block *sb)
772 {
773         struct lustre_sb_info   *lsi = s2lsi(sb);
774         struct client_obd       *cli = &obd->u.cli;
775         struct lu_fid            rfid, fid;
776         struct dt_object        *root, *dto;
777         int                      rc = 0;
778
779         ENTRY;
780
781         LASSERT(lsi);
782         LASSERT(lsi->lsi_dt_dev);
783
784         /* The mgc fs exclusion mutex. Only one fs can be setup at a time. */
785         mutex_lock(&cli->cl_mgc_mutex);
786
787         /* Setup the configs dir */
788         fid.f_seq = FID_SEQ_LOCAL_NAME;
789         fid.f_oid = 1;
790         fid.f_ver = 0;
791         rc = local_oid_storage_init(env, lsi->lsi_dt_dev, &fid,
792                                     &cli->cl_mgc_los);
793         if (rc)
794                 RETURN(rc);
795
796         rc = dt_root_get(env, lsi->lsi_dt_dev, &rfid);
797         if (rc)
798                 GOTO(out_los, rc);
799
800         root = dt_locate_at(env, lsi->lsi_dt_dev, &rfid,
801                             &cli->cl_mgc_los->los_dev->dd_lu_dev, NULL);
802         if (unlikely(IS_ERR(root)))
803                 GOTO(out_los, rc = PTR_ERR(root));
804
805         dto = local_file_find_or_create(env, cli->cl_mgc_los, root,
806                                         MOUNT_CONFIGS_DIR,
807                                         S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO);
808         dt_object_put_nocache(env, root);
809         if (IS_ERR(dto))
810                 GOTO(out_los, rc = PTR_ERR(dto));
811
812         cli->cl_mgc_configs_dir = dto;
813
814         LASSERT(lsi->lsi_osd_exp->exp_obd->obd_lvfs_ctxt.dt);
815         rc = mgc_local_llog_init(env, obd, lsi->lsi_osd_exp->exp_obd);
816         if (rc)
817                 GOTO(out_llog, rc);
818
819         /* We take an obd ref to insure that we can't get to mgc_cleanup
820          * without calling mgc_fs_cleanup first. */
821         class_incref(obd, "mgc_fs", obd);
822
823         /* We keep the cl_mgc_sem until mgc_fs_cleanup */
824         EXIT;
825 out_llog:
826         if (rc) {
827                 dt_object_put(env, cli->cl_mgc_configs_dir);
828                 cli->cl_mgc_configs_dir = NULL;
829         }
830 out_los:
831         if (rc < 0) {
832                 local_oid_storage_fini(env, cli->cl_mgc_los);
833                 cli->cl_mgc_los = NULL;
834                 mutex_unlock(&cli->cl_mgc_mutex);
835         }
836         return rc;
837 }
838
839 static int mgc_fs_cleanup(const struct lu_env *env, struct obd_device *obd)
840 {
841         struct client_obd       *cli = &obd->u.cli;
842         ENTRY;
843
844         LASSERT(cli->cl_mgc_los != NULL);
845
846         mgc_local_llog_fini(env, obd);
847
848         dt_object_put_nocache(env, cli->cl_mgc_configs_dir);
849         cli->cl_mgc_configs_dir = NULL;
850
851         local_oid_storage_fini(env, cli->cl_mgc_los);
852         cli->cl_mgc_los = NULL;
853
854         class_decref(obd, "mgc_fs", obd);
855         mutex_unlock(&cli->cl_mgc_mutex);
856
857         RETURN(0);
858 }
859
860 static int mgc_llog_init(const struct lu_env *env, struct obd_device *obd)
861 {
862         struct llog_ctxt        *ctxt;
863         int                      rc;
864
865         ENTRY;
866
867         /* setup only remote ctxt, the local disk context is switched per each
868          * filesystem during mgc_fs_setup() */
869         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CONFIG_REPL_CTXT, obd,
870                         &llog_client_ops);
871         if (rc)
872                 RETURN(rc);
873
874         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
875         LASSERT(ctxt);
876
877         llog_initiator_connect(ctxt);
878         llog_ctxt_put(ctxt);
879
880         RETURN(0);
881 }
882
883 static int mgc_llog_fini(const struct lu_env *env, struct obd_device *obd)
884 {
885         struct llog_ctxt *ctxt;
886
887         ENTRY;
888
889         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
890         if (ctxt)
891                 llog_cleanup(env, ctxt);
892
893         RETURN(0);
894 }
895
896
897 static atomic_t mgc_count = ATOMIC_INIT(0);
898 static int mgc_precleanup(struct obd_device *obd)
899 {
900         int     rc = 0;
901         int     temp;
902         ENTRY;
903
904         if (atomic_dec_and_test(&mgc_count)) {
905                 LASSERT(rq_state & RQ_RUNNING);
906                 /* stop requeue thread */
907                 temp = RQ_STOP;
908         } else {
909                 /* wakeup requeue thread to clean our cld */
910                 temp = RQ_NOW | RQ_PRECLEANUP;
911         }
912
913         spin_lock(&config_list_lock);
914         rq_state |= temp;
915         spin_unlock(&config_list_lock);
916         wake_up(&rq_waitq);
917
918         if (temp & RQ_STOP)
919                 wait_for_completion(&rq_exit);
920         obd_cleanup_client_import(obd);
921
922         rc = mgc_llog_fini(NULL, obd);
923         if (rc != 0)
924                 CERROR("failed to cleanup llogging subsystems\n");
925
926         RETURN(rc);
927 }
928
929 static int mgc_cleanup(struct obd_device *obd)
930 {
931         int rc;
932         ENTRY;
933
934         /* COMPAT_146 - old config logs may have added profiles we don't
935            know about */
936         if (obd->obd_type->typ_refcnt <= 1)
937                 /* Only for the last mgc */
938                 class_del_profiles();
939
940         lprocfs_obd_cleanup(obd);
941         ptlrpcd_decref();
942
943         rc = client_obd_cleanup(obd);
944         RETURN(rc);
945 }
946
947 static int mgc_setup(struct obd_device *obd, struct lustre_cfg *lcfg)
948 {
949         struct task_struct      *task;
950         int                      rc;
951         ENTRY;
952
953         rc = ptlrpcd_addref();
954         if (rc < 0)
955                 RETURN(rc);
956
957         rc = client_obd_setup(obd, lcfg);
958         if (rc)
959                 GOTO(err_decref, rc);
960
961         rc = mgc_llog_init(NULL, obd);
962         if (rc) {
963                 CERROR("failed to setup llogging subsystems\n");
964                 GOTO(err_cleanup, rc);
965         }
966
967         rc = mgc_tunables_init(obd);
968         if (rc)
969                 GOTO(err_sysfs, rc);
970
971         if (atomic_inc_return(&mgc_count) == 1) {
972                 rq_state = 0;
973                 init_waitqueue_head(&rq_waitq);
974
975                 /* start requeue thread */
976                 task = kthread_run(mgc_requeue_thread, NULL, "ll_cfg_requeue");
977                 if (IS_ERR(task)) {
978                         rc = PTR_ERR(task);
979                         CERROR("%s: cannot start requeue thread: rc = %d; "
980                                "no more log updates\n",
981                                obd->obd_name, rc);
982                         GOTO(err_sysfs, rc);
983                 }
984                 /* rc is the task_struct pointer of mgc_requeue_thread. */
985                 rc = 0;
986                 wait_for_completion(&rq_start);
987         }
988
989         RETURN(rc);
990
991 err_sysfs:
992         lprocfs_obd_cleanup(obd);
993 err_cleanup:
994         client_obd_cleanup(obd);
995 err_decref:
996         ptlrpcd_decref();
997         RETURN(rc);
998 }
999
1000 /* based on ll_mdc_blocking_ast */
1001 static int mgc_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
1002                             void *data, int flag)
1003 {
1004         struct lustre_handle lockh;
1005         struct config_llog_data *cld = (struct config_llog_data *)data;
1006         int rc = 0;
1007         ENTRY;
1008
1009         switch (flag) {
1010         case LDLM_CB_BLOCKING:
1011                 /* mgs wants the lock, give it up... */
1012                 LDLM_DEBUG(lock, "MGC blocking CB");
1013                 ldlm_lock2handle(lock, &lockh);
1014                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
1015                 break;
1016         case LDLM_CB_CANCELING:
1017                 /* We've given up the lock, prepare ourselves to update. */
1018                 LDLM_DEBUG(lock, "MGC cancel CB");
1019
1020                 CDEBUG(D_MGC, "Lock res "DLDLMRES" (%.8s)\n",
1021                        PLDLMRES(lock->l_resource),
1022                        (char *)&lock->l_resource->lr_name.name[0]);
1023
1024                 if (!cld) {
1025                         CDEBUG(D_INFO, "missing data, won't requeue\n");
1026                         break;
1027                 }
1028
1029                 /* held at mgc_process_log(). */
1030                 LASSERT(atomic_read(&cld->cld_refcount) > 0);
1031
1032                 lock->l_ast_data = NULL;
1033                 /* Are we done with this log? */
1034                 if (cld->cld_stopping) {
1035                         CDEBUG(D_MGC, "log %s: stopping, won't requeue\n",
1036                                 cld->cld_logname);
1037                         config_log_put(cld);
1038                         break;
1039                 }
1040                 /* Make sure not to re-enqueue when the mgc is stopping
1041                    (we get called from client_disconnect_export) */
1042                 if (lock->l_conn_export == NULL ||
1043                     lock->l_conn_export->exp_obd->u.cli.cl_conn_count == 0) {
1044                         CDEBUG(D_MGC, "log %.8s: disconnecting, won't requeue\n",
1045                                 cld->cld_logname);
1046                         config_log_put(cld);
1047                         break;
1048                 }
1049
1050                 /* Re-enqueue now */
1051                 mgc_requeue_add(cld);
1052                 config_log_put(cld);
1053                 break;
1054         default:
1055                 LBUG();
1056         }
1057
1058         RETURN(rc);
1059 }
1060
1061 /* Not sure where this should go... */
1062 /* This is the timeout value for MGS_CONNECT request plus a ping interval, such
1063  * that we can have a chance to try the secondary MGS if any. */
1064 #define  MGC_ENQUEUE_LIMIT (INITIAL_CONNECT_TIMEOUT + (AT_OFF ? 0 : at_min) \
1065                                 + PING_INTERVAL)
1066 #define  MGC_TARGET_REG_LIMIT 10
1067 #define  MGC_TARGET_REG_LIMIT_MAX RECONNECT_DELAY_MAX
1068 #define  MGC_SEND_PARAM_LIMIT 10
1069
1070 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 13, 53, 0)
1071 /* Send parameter to MGS*/
1072 static int mgc_set_mgs_param(struct obd_export *exp,
1073                              struct mgs_send_param *msp)
1074 {
1075         struct ptlrpc_request *req;
1076         struct mgs_send_param *req_msp, *rep_msp;
1077         int rc;
1078         ENTRY;
1079
1080         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1081                                         &RQF_MGS_SET_INFO, LUSTRE_MGS_VERSION,
1082                                         MGS_SET_INFO);
1083         if (!req)
1084                 RETURN(-ENOMEM);
1085
1086         req_msp = req_capsule_client_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
1087         if (!req_msp) {
1088                 ptlrpc_req_finished(req);
1089                 RETURN(-ENOMEM);
1090         }
1091
1092         memcpy(req_msp, msp, sizeof(*req_msp));
1093         ptlrpc_request_set_replen(req);
1094
1095         /* Limit how long we will wait for the enqueue to complete */
1096         req->rq_delay_limit = MGC_SEND_PARAM_LIMIT;
1097         rc = ptlrpc_queue_wait(req);
1098         if (!rc) {
1099                 rep_msp = req_capsule_server_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
1100                 memcpy(msp, rep_msp, sizeof(*rep_msp));
1101         }
1102
1103         ptlrpc_req_finished(req);
1104
1105         RETURN(rc);
1106 }
1107 #endif
1108
1109 /* Take a config lock so we can get cancel notifications */
1110 static int mgc_enqueue(struct obd_export *exp, enum ldlm_type type,
1111                        union ldlm_policy_data *policy, enum ldlm_mode mode,
1112                        __u64 *flags, ldlm_glimpse_callback glimpse_callback,
1113                        void *data, __u32 lvb_len, void *lvb_swabber,
1114                        struct lustre_handle *lockh)
1115 {
1116         struct config_llog_data *cld = (struct config_llog_data *)data;
1117         struct ldlm_enqueue_info einfo = {
1118                 .ei_type        = type,
1119                 .ei_mode        = mode,
1120                 .ei_cb_bl       = mgc_blocking_ast,
1121                 .ei_cb_cp       = ldlm_completion_ast,
1122                 .ei_cb_gl       = glimpse_callback,
1123         };
1124         struct ptlrpc_request *req;
1125         int short_limit = cld_is_sptlrpc(cld);
1126         int rc;
1127         ENTRY;
1128
1129         CDEBUG(D_MGC, "Enqueue for %s (res %#llx)\n", cld->cld_logname,
1130                cld->cld_resid.name[0]);
1131
1132         /* We need a callback for every lockholder, so don't try to
1133            ldlm_lock_match (see rev 1.1.2.11.2.47) */
1134         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1135                                         &RQF_LDLM_ENQUEUE, LUSTRE_DLM_VERSION,
1136                                         LDLM_ENQUEUE);
1137         if (req == NULL)
1138                 RETURN(-ENOMEM);
1139
1140         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER, 0);
1141         ptlrpc_request_set_replen(req);
1142
1143         /* check if this is server or client */
1144         if (cld->cld_cfg.cfg_sb) {
1145                 struct lustre_sb_info *lsi = s2lsi(cld->cld_cfg.cfg_sb);
1146                 if (lsi && IS_SERVER(lsi))
1147                         short_limit = 1;
1148         }
1149         /* Limit how long we will wait for the enqueue to complete */
1150         req->rq_delay_limit = short_limit ? 5 : MGC_ENQUEUE_LIMIT;
1151         rc = ldlm_cli_enqueue(exp, &req, &einfo, &cld->cld_resid, NULL, flags,
1152                               NULL, 0, LVB_T_NONE, lockh, 0);
1153         /* A failed enqueue should still call the mgc_blocking_ast,
1154            where it will be requeued if needed ("grant failed"). */
1155         ptlrpc_req_finished(req);
1156         RETURN(rc);
1157 }
1158
1159 static int mgc_cancel(struct obd_export *exp, enum ldlm_mode mode,
1160                       struct lustre_handle *lockh)
1161 {
1162         ENTRY;
1163
1164         ldlm_lock_decref(lockh, mode);
1165
1166         RETURN(0);
1167 }
1168
1169 static void mgc_notify_active(struct obd_device *unused)
1170 {
1171         /* wakeup mgc_requeue_thread to requeue mgc lock */
1172         spin_lock(&config_list_lock);
1173         rq_state |= RQ_NOW;
1174         spin_unlock(&config_list_lock);
1175         wake_up(&rq_waitq);
1176
1177         /* TODO: Help the MGS rebuild nidtbl. -jay */
1178 }
1179
1180 /* Send target_reg message to MGS */
1181 static int mgc_target_register(struct obd_export *exp,
1182                                struct mgs_target_info *mti)
1183 {
1184         struct ptlrpc_request  *req;
1185         struct mgs_target_info *req_mti, *rep_mti;
1186         int                     rc;
1187         ENTRY;
1188
1189         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1190                                         &RQF_MGS_TARGET_REG, LUSTRE_MGS_VERSION,
1191                                         MGS_TARGET_REG);
1192         if (req == NULL)
1193                 RETURN(-ENOMEM);
1194
1195         req_mti = req_capsule_client_get(&req->rq_pill, &RMF_MGS_TARGET_INFO);
1196         if (!req_mti) {
1197                 ptlrpc_req_finished(req);
1198                 RETURN(-ENOMEM);
1199         }
1200
1201         memcpy(req_mti, mti, sizeof(*req_mti));
1202         ptlrpc_request_set_replen(req);
1203         CDEBUG(D_MGC, "register %s\n", mti->mti_svname);
1204         /* Limit how long we will wait for the enqueue to complete */
1205         req->rq_delay_limit = MGC_TARGET_REG_LIMIT;
1206
1207         /* if the target needs to regenerate the config log in MGS, it's better
1208          * to use some longer limit to let MGC have time to change connection to
1209          * another MGS (or try again with the same MGS) for the target (server)
1210          * will fail and exit if the request expired due to delay limit. */
1211         if (mti->mti_flags & (LDD_F_UPDATE | LDD_F_NEED_INDEX))
1212                 req->rq_delay_limit = MGC_TARGET_REG_LIMIT_MAX;
1213
1214         rc = ptlrpc_queue_wait(req);
1215         if (!rc) {
1216                 rep_mti = req_capsule_server_get(&req->rq_pill,
1217                                                  &RMF_MGS_TARGET_INFO);
1218                 memcpy(mti, rep_mti, sizeof(*rep_mti));
1219                 CDEBUG(D_MGC, "register %s got index = %d\n",
1220                        mti->mti_svname, mti->mti_stripe_index);
1221         }
1222         ptlrpc_req_finished(req);
1223
1224         RETURN(rc);
1225 }
1226
1227 static int mgc_set_info_async(const struct lu_env *env, struct obd_export *exp,
1228                               u32 keylen, void *key,
1229                               u32 vallen, void *val,
1230                               struct ptlrpc_request_set *set)
1231 {
1232         int rc = -EINVAL;
1233         ENTRY;
1234
1235         /* Turn off initial_recov after we try all backup servers once */
1236         if (KEY_IS(KEY_INIT_RECOV_BACKUP)) {
1237                 struct obd_import *imp = class_exp2cliimp(exp);
1238                 int value;
1239                 if (vallen != sizeof(int))
1240                         RETURN(-EINVAL);
1241                 value = *(int *)val;
1242                 CDEBUG(D_MGC, "InitRecov %s %d/d%d:i%d:r%d:or%d:%s\n",
1243                        imp->imp_obd->obd_name, value,
1244                        imp->imp_deactive, imp->imp_invalid,
1245                        imp->imp_replayable, imp->imp_obd->obd_replayable,
1246                        ptlrpc_import_state_name(imp->imp_state));
1247                 /* Resurrect the import immediately if
1248                  * 1. we previously got disconnected,
1249                  * 2. value > 1 (at the same node with MGS)
1250                  * */
1251                 if (imp->imp_state == LUSTRE_IMP_DISCON || value > 1)
1252                         ptlrpc_reconnect_import(imp);
1253
1254                 RETURN(0);
1255         }
1256
1257         /* FIXME move this to mgc_process_config */
1258         if (KEY_IS(KEY_REGISTER_TARGET)) {
1259                 struct mgs_target_info *mti;
1260                 if (vallen != sizeof(struct mgs_target_info))
1261                         RETURN(-EINVAL);
1262                 mti = (struct mgs_target_info *)val;
1263                 CDEBUG(D_MGC, "register_target %s %#x\n",
1264                        mti->mti_svname, mti->mti_flags);
1265                 rc =  mgc_target_register(exp, mti);
1266                 RETURN(rc);
1267         }
1268         if (KEY_IS(KEY_SET_FS)) {
1269                 struct super_block *sb = (struct super_block *)val;
1270
1271                 if (vallen != sizeof(struct super_block))
1272                         RETURN(-EINVAL);
1273
1274                 rc = mgc_fs_setup(env, exp->exp_obd, sb);
1275                 RETURN(rc);
1276         }
1277         if (KEY_IS(KEY_CLEAR_FS)) {
1278                 if (vallen != 0)
1279                         RETURN(-EINVAL);
1280                 rc = mgc_fs_cleanup(env, exp->exp_obd);
1281                 RETURN(rc);
1282         }
1283 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 13, 53, 0)
1284         if (KEY_IS(KEY_SET_INFO)) {
1285                 struct mgs_send_param *msp;
1286
1287                 msp = (struct mgs_send_param *)val;
1288                 rc =  mgc_set_mgs_param(exp, msp);
1289                 RETURN(rc);
1290         }
1291 #endif
1292         if (KEY_IS(KEY_MGSSEC)) {
1293                 struct client_obd     *cli = &exp->exp_obd->u.cli;
1294                 struct sptlrpc_flavor  flvr;
1295
1296                 /*
1297                  * empty string means using current flavor, if which haven't
1298                  * been set yet, set it as null.
1299                  *
1300                  * if flavor has been set previously, check the asking flavor
1301                  * must match the existing one.
1302                  */
1303                 if (vallen == 0) {
1304                         if (cli->cl_flvr_mgc.sf_rpc != SPTLRPC_FLVR_INVALID)
1305                                 RETURN(0);
1306                         val = "null";
1307                         vallen = 4;
1308                 }
1309
1310                 rc = sptlrpc_parse_flavor(val, &flvr);
1311                 if (rc) {
1312                         CERROR("invalid sptlrpc flavor %s to MGS\n",
1313                                (char *) val);
1314                         RETURN(rc);
1315                 }
1316
1317                 /*
1318                  * caller already hold a mutex
1319                  */
1320                 if (cli->cl_flvr_mgc.sf_rpc == SPTLRPC_FLVR_INVALID) {
1321                         cli->cl_flvr_mgc = flvr;
1322                 } else if (memcmp(&cli->cl_flvr_mgc, &flvr,
1323                                   sizeof(flvr)) != 0) {
1324                         char    str[20];
1325
1326                         sptlrpc_flavor2name(&cli->cl_flvr_mgc,
1327                                             str, sizeof(str));
1328                         LCONSOLE_ERROR("asking sptlrpc flavor %s to MGS but "
1329                                        "currently %s is in use\n",
1330                                        (char *) val, str);
1331                         rc = -EPERM;
1332                 }
1333                 RETURN(rc);
1334         }
1335
1336         RETURN(rc);
1337 }
1338
1339 static int mgc_get_info(const struct lu_env *env, struct obd_export *exp,
1340                         __u32 keylen, void *key, __u32 *vallen, void *val)
1341 {
1342         int rc = -EINVAL;
1343
1344         if (KEY_IS(KEY_CONN_DATA)) {
1345                 struct obd_import *imp = class_exp2cliimp(exp);
1346                 struct obd_connect_data *data = val;
1347
1348                 if (*vallen == sizeof(*data)) {
1349                         *data = imp->imp_connect_data;
1350                         rc = 0;
1351                 }
1352         }
1353
1354         return rc;
1355 }
1356
1357 static int mgc_import_event(struct obd_device *obd,
1358                             struct obd_import *imp,
1359                             enum obd_import_event event)
1360 {
1361         int rc = 0;
1362
1363         LASSERT(imp->imp_obd == obd);
1364         CDEBUG(D_MGC, "import event %#x\n", event);
1365
1366         switch (event) {
1367         case IMP_EVENT_DISCON:
1368                 /* MGC imports should not wait for recovery */
1369                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1370                         ptlrpc_pinger_ir_down();
1371                 break;
1372         case IMP_EVENT_INACTIVE:
1373                 break;
1374         case IMP_EVENT_INVALIDATE: {
1375                 struct ldlm_namespace *ns = obd->obd_namespace;
1376                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
1377                 break;
1378         }
1379         case IMP_EVENT_ACTIVE:
1380                 CDEBUG(D_INFO, "%s: Reactivating import\n", obd->obd_name);
1381                 /* Clearing obd_no_recov allows us to continue pinging */
1382                 obd->obd_no_recov = 0;
1383                 mgc_notify_active(obd);
1384                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1385                         ptlrpc_pinger_ir_up();
1386                 break;
1387         case IMP_EVENT_OCD:
1388                 break;
1389         case IMP_EVENT_DEACTIVATE:
1390         case IMP_EVENT_ACTIVATE:
1391                 break;
1392         default:
1393                 CERROR("Unknown import event %#x\n", event);
1394                 LBUG();
1395         }
1396         RETURN(rc);
1397 }
1398
1399 enum {
1400         CONFIG_READ_NRPAGES_INIT = 1 << (20 - PAGE_SHIFT),
1401         CONFIG_READ_NRPAGES      = 4
1402 };
1403
1404 static int mgc_apply_recover_logs(struct obd_device *mgc,
1405                                   struct config_llog_data *cld,
1406                                   __u64 max_version,
1407                                   void *data, int datalen, bool mne_swab)
1408 {
1409         struct config_llog_instance *cfg = &cld->cld_cfg;
1410         struct lustre_sb_info *lsi = s2lsi(cfg->cfg_sb);
1411         struct mgs_nidtbl_entry *entry;
1412         struct lustre_cfg *lcfg;
1413         struct lustre_cfg_bufs bufs;
1414         u64 prev_version = 0;
1415         char *inst;
1416         char *buf;
1417         int bufsz;
1418         int pos = 0;
1419         int rc  = 0;
1420         int off = 0;
1421
1422         ENTRY;
1423         LASSERT(cfg->cfg_instance != 0);
1424         LASSERT(ll_get_cfg_instance(cfg->cfg_sb) == cfg->cfg_instance);
1425
1426         OBD_ALLOC(inst, PAGE_SIZE);
1427         if (inst == NULL)
1428                 RETURN(-ENOMEM);
1429
1430         if (!IS_SERVER(lsi)) {
1431                 pos = snprintf(inst, PAGE_SIZE, "%016lx", cfg->cfg_instance);
1432                 if (pos >= PAGE_SIZE) {
1433                         OBD_FREE(inst, PAGE_SIZE);
1434                         return -E2BIG;
1435                 }
1436 #ifdef HAVE_SERVER_SUPPORT
1437         } else {
1438                 LASSERT(IS_MDT(lsi));
1439                 rc = server_name2svname(lsi->lsi_svname, inst, NULL,
1440                                         PAGE_SIZE);
1441                 if (rc) {
1442                         OBD_FREE(inst, PAGE_SIZE);
1443                         RETURN(-EINVAL);
1444                 }
1445                 pos = strlen(inst);
1446 #endif /* HAVE_SERVER_SUPPORT */
1447         }
1448
1449         ++pos;
1450         buf   = inst + pos;
1451         bufsz = PAGE_SIZE - pos;
1452
1453         while (datalen > 0) {
1454                 int   entry_len = sizeof(*entry);
1455                 int   is_ost, i;
1456                 struct obd_device *obd;
1457                 char *obdname;
1458                 char *cname;
1459                 char *params;
1460                 char *uuid;
1461
1462                 rc = -EINVAL;
1463                 if (datalen < sizeof(*entry))
1464                         break;
1465
1466                 entry = (typeof(entry))(data + off);
1467
1468                 /* sanity check */
1469                 if (entry->mne_nid_type != 0) /* only support type 0 for ipv4 */
1470                         break;
1471                 if (entry->mne_nid_count == 0) /* at least one nid entry */
1472                         break;
1473                 if (entry->mne_nid_size != sizeof(lnet_nid_t))
1474                         break;
1475
1476                 entry_len += entry->mne_nid_count * entry->mne_nid_size;
1477                 if (datalen < entry_len) /* must have entry_len at least */
1478                         break;
1479
1480                 /* Keep this swab for normal mixed endian handling. LU-1644 */
1481                 if (mne_swab)
1482                         lustre_swab_mgs_nidtbl_entry(entry);
1483                 if (entry->mne_length > PAGE_SIZE) {
1484                         CERROR("MNE too large (%u)\n", entry->mne_length);
1485                         break;
1486                 }
1487
1488                 if (entry->mne_length < entry_len)
1489                         break;
1490
1491                 off     += entry->mne_length;
1492                 datalen -= entry->mne_length;
1493                 if (datalen < 0)
1494                         break;
1495
1496                 if (entry->mne_version > max_version) {
1497                         CERROR("entry index(%lld) is over max_index(%lld)\n",
1498                                entry->mne_version, max_version);
1499                         break;
1500                 }
1501
1502                 if (prev_version >= entry->mne_version) {
1503                         CERROR("index unsorted, prev %lld, now %lld\n",
1504                                prev_version, entry->mne_version);
1505                         break;
1506                 }
1507                 prev_version = entry->mne_version;
1508
1509                 /*
1510                  * Write a string with format "nid::instance" to
1511                  * lustre/<osc|mdc>/<target>-<osc|mdc>-<instance>/import.
1512                  */
1513
1514                 is_ost = entry->mne_type == LDD_F_SV_TYPE_OST;
1515                 memset(buf, 0, bufsz);
1516                 obdname = buf;
1517                 pos = 0;
1518
1519                 /* lustre-OST0001-osc-<instance #> */
1520                 strcpy(obdname, cld->cld_logname);
1521                 cname = strrchr(obdname, '-');
1522                 if (cname == NULL) {
1523                         CERROR("mgc %s: invalid logname %s\n",
1524                                mgc->obd_name, obdname);
1525                         break;
1526                 }
1527
1528                 pos = cname - obdname;
1529                 obdname[pos] = 0;
1530                 pos += sprintf(obdname + pos, "-%s%04x",
1531                                   is_ost ? "OST" : "MDT", entry->mne_index);
1532
1533                 cname = is_ost ? "osc" : "mdc",
1534                 pos += sprintf(obdname + pos, "-%s-%s", cname, inst);
1535                 lustre_cfg_bufs_reset(&bufs, obdname);
1536
1537                 /* find the obd by obdname */
1538                 obd = class_name2obd(obdname);
1539                 if (obd == NULL) {
1540                         CDEBUG(D_INFO, "mgc %s: cannot find obdname %s\n",
1541                                mgc->obd_name, obdname);
1542                         rc = 0;
1543                         /* this is a safe race, when the ost is starting up...*/
1544                         continue;
1545                 }
1546
1547                 /* osc.import = "connection=<Conn UUID>::<target instance>" */
1548                 ++pos;
1549                 params = buf + pos;
1550                 pos += sprintf(params, "%s.import=%s", cname, "connection=");
1551                 uuid = buf + pos;
1552
1553                 down_read(&obd->u.cli.cl_sem);
1554                 if (obd->u.cli.cl_import == NULL) {
1555                         /* client does not connect to the OST yet */
1556                         up_read(&obd->u.cli.cl_sem);
1557                         rc = 0;
1558                         continue;
1559                 }
1560
1561                 /* iterate all nids to find one */
1562                 /* find uuid by nid */
1563                 rc = -ENOENT;
1564                 for (i = 0; i < entry->mne_nid_count; i++) {
1565                         rc = client_import_find_conn(obd->u.cli.cl_import,
1566                                                      entry->u.nids[i],
1567                                                      (struct obd_uuid *)uuid);
1568                         if (rc == 0)
1569                                 break;
1570                 }
1571
1572                 up_read(&obd->u.cli.cl_sem);
1573                 if (rc < 0) {
1574                         CERROR("mgc: cannot find uuid by nid %s\n",
1575                                libcfs_nid2str(entry->u.nids[0]));
1576                         break;
1577                 }
1578
1579                 CDEBUG(D_INFO, "Find uuid %s by nid %s\n",
1580                        uuid, libcfs_nid2str(entry->u.nids[0]));
1581
1582                 pos += strlen(uuid);
1583                 pos += sprintf(buf + pos, "::%u", entry->mne_instance);
1584                 LASSERT(pos < bufsz);
1585
1586                 lustre_cfg_bufs_set_string(&bufs, 1, params);
1587
1588                 OBD_ALLOC(lcfg, lustre_cfg_len(bufs.lcfg_bufcount,
1589                                                bufs.lcfg_buflen));
1590                 if (!lcfg) {
1591                         rc = -ENOMEM;
1592                         break;
1593                 }
1594                 lustre_cfg_init(lcfg, LCFG_PARAM, &bufs);
1595
1596                 CDEBUG(D_INFO, "ir apply logs %lld/%lld for %s -> %s\n",
1597                        prev_version, max_version, obdname, params);
1598
1599                 rc = class_process_config(lcfg);
1600                 OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount,
1601                                               lcfg->lcfg_buflens));
1602                 if (rc)
1603                         CDEBUG(D_INFO, "process config for %s error %d\n",
1604                                obdname, rc);
1605
1606                 /* continue, even one with error */
1607         }
1608
1609         OBD_FREE(inst, PAGE_SIZE);
1610         RETURN(rc);
1611 }
1612
1613 /**
1614  * This function is called if this client was notified for target restarting
1615  * by the MGS. A CONFIG_READ RPC is going to send to fetch recovery or
1616  * nodemap logs.
1617  */
1618 static int mgc_process_recover_nodemap_log(struct obd_device *obd,
1619                                            struct config_llog_data *cld)
1620 {
1621         struct ptlrpc_connection *mgc_conn;
1622         struct ptlrpc_request *req = NULL;
1623         struct config_llog_instance *cfg = &cld->cld_cfg;
1624         struct mgs_config_body *body;
1625         struct mgs_config_res *res;
1626         struct nodemap_config *new_config = NULL;
1627         struct lu_nodemap *recent_nodemap = NULL;
1628         struct ptlrpc_bulk_desc *desc;
1629         struct page **pages = NULL;
1630         __u64 config_read_offset = 0;
1631         __u8 nodemap_cur_pass = 0;
1632         int nrpages = 0;
1633         bool eof = true;
1634         bool mne_swab = false;
1635         int i;
1636         int ealen;
1637         int rc;
1638         ENTRY;
1639
1640         mgc_conn = class_exp2cliimp(cld->cld_mgcexp)->imp_connection;
1641
1642         /* don't need to get local config */
1643         if (cld_is_nodemap(cld) &&
1644             (LNET_NETTYP(LNET_NIDNET(mgc_conn->c_peer.nid)) == LOLND))
1645                 GOTO(out, rc = 0);
1646
1647         /* allocate buffer for bulk transfer.
1648          * if this is the first time for this mgs to read logs,
1649          * CONFIG_READ_NRPAGES_INIT will be used since it will read all logs
1650          * once; otherwise, it only reads increment of logs, this should be
1651          * small and CONFIG_READ_NRPAGES will be used.
1652          */
1653         nrpages = CONFIG_READ_NRPAGES;
1654         if (cfg->cfg_last_idx == 0 || cld_is_nodemap(cld))
1655                 nrpages = CONFIG_READ_NRPAGES_INIT;
1656
1657         OBD_ALLOC(pages, sizeof(*pages) * nrpages);
1658         if (pages == NULL)
1659                 GOTO(out, rc = -ENOMEM);
1660
1661         for (i = 0; i < nrpages; i++) {
1662                 pages[i] = alloc_page(GFP_KERNEL);
1663                 if (pages[i] == NULL)
1664                         GOTO(out, rc = -ENOMEM);
1665         }
1666
1667 again:
1668 #ifdef HAVE_SERVER_SUPPORT
1669         if (cld_is_nodemap(cld) && config_read_offset == 0) {
1670                 new_config = nodemap_config_alloc();
1671                 if (IS_ERR(new_config)) {
1672                         rc = PTR_ERR(new_config);
1673                         new_config = NULL;
1674                         GOTO(out, rc);
1675                 }
1676         }
1677 #endif
1678         LASSERT(cld_is_recover(cld) || cld_is_nodemap(cld));
1679         LASSERT(mutex_is_locked(&cld->cld_lock));
1680         req = ptlrpc_request_alloc(class_exp2cliimp(cld->cld_mgcexp),
1681                                    &RQF_MGS_CONFIG_READ);
1682         if (req == NULL)
1683                 GOTO(out, rc = -ENOMEM);
1684
1685         rc = ptlrpc_request_pack(req, LUSTRE_MGS_VERSION, MGS_CONFIG_READ);
1686         if (rc)
1687                 GOTO(out, rc);
1688
1689         /* pack request */
1690         body = req_capsule_client_get(&req->rq_pill, &RMF_MGS_CONFIG_BODY);
1691         LASSERT(body != NULL);
1692         LASSERT(sizeof(body->mcb_name) > strlen(cld->cld_logname));
1693         if (strlcpy(body->mcb_name, cld->cld_logname, sizeof(body->mcb_name))
1694             >= sizeof(body->mcb_name))
1695                 GOTO(out, rc = -E2BIG);
1696         if (cld_is_nodemap(cld))
1697                 body->mcb_offset = config_read_offset;
1698         else
1699                 body->mcb_offset = cfg->cfg_last_idx + 1;
1700         body->mcb_type   = cld->cld_type;
1701         body->mcb_bits   = PAGE_SHIFT;
1702         body->mcb_units  = nrpages;
1703         body->mcb_nm_cur_pass = nodemap_cur_pass;
1704
1705         /* allocate bulk transfer descriptor */
1706         desc = ptlrpc_prep_bulk_imp(req, nrpages, 1,
1707                                     PTLRPC_BULK_PUT_SINK | PTLRPC_BULK_BUF_KIOV,
1708                                     MGS_BULK_PORTAL,
1709                                     &ptlrpc_bulk_kiov_pin_ops);
1710         if (desc == NULL)
1711                 GOTO(out, rc = -ENOMEM);
1712
1713         for (i = 0; i < nrpages; i++)
1714                 desc->bd_frag_ops->add_kiov_frag(desc, pages[i], 0,
1715                                                  PAGE_SIZE);
1716
1717         ptlrpc_request_set_replen(req);
1718         rc = ptlrpc_queue_wait(req);
1719         if (rc)
1720                 GOTO(out, rc);
1721
1722         res = req_capsule_server_get(&req->rq_pill, &RMF_MGS_CONFIG_RES);
1723         if (!res)
1724                 GOTO(out, rc = -EPROTO);
1725
1726         if (cld_is_nodemap(cld)) {
1727                 config_read_offset = res->mcr_offset;
1728                 eof = config_read_offset == II_END_OFF;
1729                 nodemap_cur_pass = res->mcr_nm_cur_pass;
1730         } else {
1731                 if (res->mcr_size < res->mcr_offset)
1732                         GOTO(out, rc = -EINVAL);
1733
1734                 /* always update the index even though it might have errors with
1735                  * handling the recover logs
1736                  */
1737                 cfg->cfg_last_idx = res->mcr_offset;
1738                 eof = res->mcr_offset == res->mcr_size;
1739
1740                 CDEBUG(D_INFO, "Latest version %lld, more %d.\n",
1741                        res->mcr_offset, eof == false);
1742         }
1743
1744         ealen = sptlrpc_cli_unwrap_bulk_read(req, req->rq_bulk, 0);
1745         if (ealen < 0)
1746                 GOTO(out, rc = ealen);
1747
1748         if (ealen > nrpages << PAGE_SHIFT)
1749                 GOTO(out, rc = -EINVAL);
1750
1751         if (ealen == 0) { /* no logs transferred */
1752 #ifdef HAVE_SERVER_SUPPORT
1753                 /* config changed since first read RPC */
1754                 if (cld_is_nodemap(cld) && config_read_offset == 0) {
1755                         CDEBUG(D_INFO, "nodemap config changed in transit, retrying\n");
1756                         GOTO(out, rc = -EAGAIN);
1757                 }
1758 #endif
1759                 if (!eof)
1760                         rc = -EINVAL;
1761                 GOTO(out, rc);
1762         }
1763
1764         mne_swab = ptlrpc_rep_need_swab(req);
1765
1766         /* When a nodemap config is received, we build a new nodemap config,
1767          * with new nodemap structs. We keep track of the most recently added
1768          * nodemap since the config is read ordered by nodemap_id, and so it
1769          * is likely that the next record will be related. Because access to
1770          * the nodemaps is single threaded until the nodemap_config is active,
1771          * we don't need to reference count with recent_nodemap, though
1772          * recent_nodemap should be set to NULL when the nodemap_config
1773          * is either destroyed or set active.
1774          */
1775         for (i = 0; i < nrpages && ealen > 0; i++) {
1776                 int rc2;
1777                 union lu_page   *ptr;
1778
1779                 ptr = kmap(pages[i]);
1780                 if (cld_is_nodemap(cld))
1781                         rc2 = nodemap_process_idx_pages(new_config, ptr,
1782                                                        &recent_nodemap);
1783                 else
1784                         rc2 = mgc_apply_recover_logs(obd, cld, res->mcr_offset,
1785                                                      ptr,
1786                                                      min_t(int, ealen,
1787                                                            PAGE_SIZE),
1788                                                      mne_swab);
1789                 kunmap(pages[i]);
1790                 if (rc2 < 0) {
1791                         CWARN("%s: error processing %s log %s: rc = %d\n",
1792                               obd->obd_name,
1793                               cld_is_nodemap(cld) ? "nodemap" : "recovery",
1794                               cld->cld_logname,
1795                               rc2);
1796                         GOTO(out, rc = rc2);
1797                 }
1798
1799                 ealen -= PAGE_SIZE;
1800         }
1801
1802 out:
1803         if (req) {
1804                 ptlrpc_req_finished(req);
1805                 req = NULL;
1806         }
1807
1808         if (rc == 0 && !eof)
1809                 goto again;
1810
1811 #ifdef HAVE_SERVER_SUPPORT
1812         if (new_config != NULL) {
1813                 /* recent_nodemap cannot be used after set_active/dealloc */
1814                 if (rc == 0)
1815                         nodemap_config_set_active_mgc(new_config);
1816                 else
1817                         nodemap_config_dealloc(new_config);
1818         }
1819 #endif
1820
1821         if (pages) {
1822                 for (i = 0; i < nrpages; i++) {
1823                         if (pages[i] == NULL)
1824                                 break;
1825                         __free_page(pages[i]);
1826                 }
1827                 OBD_FREE(pages, sizeof(*pages) * nrpages);
1828         }
1829         return rc;
1830 }
1831
1832 static int mgc_barrier_glimpse_ast(struct ldlm_lock *lock, void *data)
1833 {
1834         struct config_llog_data *cld = lock->l_ast_data;
1835         int rc;
1836         ENTRY;
1837
1838         if (cld->cld_stopping)
1839                 RETURN(-ENODEV);
1840
1841         rc = barrier_handler(s2lsi(cld->cld_cfg.cfg_sb)->lsi_dt_dev,
1842                              (struct ptlrpc_request *)data);
1843
1844         RETURN(rc);
1845 }
1846
1847 /* Copy a remote log locally */
1848 static int mgc_llog_local_copy(const struct lu_env *env,
1849                                struct obd_device *obd,
1850                                struct llog_ctxt *rctxt,
1851                                struct llog_ctxt *lctxt, char *logname)
1852 {
1853         char    *temp_log;
1854         int      rc;
1855
1856         ENTRY;
1857
1858         /*
1859          * - copy it to backup using llog_backup()
1860          * - copy remote llog to logname using llog_backup()
1861          * - if failed then move bakup to logname again
1862          */
1863
1864         OBD_ALLOC(temp_log, strlen(logname) + 2);
1865         if (!temp_log)
1866                 RETURN(-ENOMEM);
1867         sprintf(temp_log, "%sT", logname);
1868
1869         /* make a copy of local llog at first */
1870         rc = llog_backup(env, obd, lctxt, lctxt, logname, temp_log);
1871         if (rc < 0 && rc != -ENOENT)
1872                 GOTO(out, rc);
1873         /* copy remote llog to the local copy */
1874         rc = llog_backup(env, obd, rctxt, lctxt, logname, logname);
1875         if (rc == -ENOENT) {
1876                 /* no remote llog, delete local one too */
1877                 llog_erase(env, lctxt, NULL, logname);
1878         } else if (rc < 0) {
1879                 /* error during backup, get local one back from the copy */
1880                 llog_backup(env, obd, lctxt, lctxt, temp_log, logname);
1881 out:
1882                 CERROR("%s: failed to copy remote log %s: rc = %d\n",
1883                        obd->obd_name, logname, rc);
1884         }
1885         llog_erase(env, lctxt, NULL, temp_log);
1886         OBD_FREE(temp_log, strlen(logname) + 2);
1887         return rc;
1888 }
1889
1890 /* local_only means it cannot get remote llogs */
1891 static int mgc_process_cfg_log(struct obd_device *mgc,
1892                                struct config_llog_data *cld, int local_only)
1893 {
1894         struct llog_ctxt        *ctxt, *lctxt = NULL;
1895         struct client_obd       *cli = &mgc->u.cli;
1896         struct lustre_sb_info   *lsi = NULL;
1897         int                      rc = 0;
1898         struct lu_env           *env;
1899
1900         ENTRY;
1901
1902         LASSERT(cld);
1903         LASSERT(mutex_is_locked(&cld->cld_lock));
1904
1905         if (cld->cld_cfg.cfg_sb)
1906                 lsi = s2lsi(cld->cld_cfg.cfg_sb);
1907
1908         OBD_ALLOC_PTR(env);
1909         if (env == NULL)
1910                 RETURN(-ENOMEM);
1911
1912         rc = lu_env_init(env, LCT_MG_THREAD);
1913         if (rc)
1914                 GOTO(out_free, rc);
1915
1916         ctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1917         LASSERT(ctxt);
1918
1919         lctxt = llog_get_context(mgc, LLOG_CONFIG_ORIG_CTXT);
1920
1921         /* Copy the setup log locally if we can. Don't mess around if we're
1922          * running an MGS though (logs are already local). */
1923         if (lctxt && lsi && IS_SERVER(lsi) && !IS_MGS(lsi) &&
1924             cli->cl_mgc_configs_dir != NULL &&
1925             lu2dt_dev(cli->cl_mgc_configs_dir->do_lu.lo_dev) ==
1926             lsi->lsi_dt_dev) {
1927                 if (!local_only && !lsi->lsi_dt_dev->dd_rdonly)
1928                         /* Only try to copy log if we have the lock. */
1929                         rc = mgc_llog_local_copy(env, mgc, ctxt, lctxt,
1930                                                  cld->cld_logname);
1931                 if (local_only || rc) {
1932                         if (strcmp(cld->cld_logname, PARAMS_FILENAME) != 0 &&
1933                             llog_is_empty(env, lctxt, cld->cld_logname)) {
1934                                 LCONSOLE_ERROR_MSG(0x13a, "Failed to get MGS "
1935                                                    "log %s and no local copy."
1936                                                    "\n", cld->cld_logname);
1937                                 GOTO(out_pop, rc = -ENOENT);
1938                         }
1939                         CDEBUG(D_MGC, "Failed to get MGS log %s, using local "
1940                                "copy for now, will try to update later.\n",
1941                                cld->cld_logname);
1942                         rc = 0;
1943                 }
1944                 /* Now, whether we copied or not, start using the local llog.
1945                  * If we failed to copy, we'll start using whatever the old
1946                  * log has. */
1947                 llog_ctxt_put(ctxt);
1948                 ctxt = lctxt;
1949                 lctxt = NULL;
1950         } else {
1951                 if (local_only) /* no local log at client side */
1952                         GOTO(out_pop, rc = -EIO);
1953         }
1954
1955         rc = -EAGAIN;
1956         if (lsi && IS_SERVER(lsi) && !IS_MGS(lsi) &&
1957             lsi->lsi_dt_dev->dd_rdonly) {
1958                 struct llog_ctxt *rctxt;
1959
1960                 /* Under readonly mode, we may have no local copy or local
1961                  * copy is incomplete, so try to use remote llog firstly. */
1962                 rctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1963                 LASSERT(rctxt);
1964
1965                 rc = class_config_parse_llog(env, rctxt, cld->cld_logname,
1966                                              &cld->cld_cfg);
1967                 llog_ctxt_put(rctxt);
1968         }
1969
1970         if (rc && rc != -ENOENT)
1971                 rc = class_config_parse_llog(env, ctxt, cld->cld_logname,
1972                                              &cld->cld_cfg);
1973
1974         /*
1975          * update settings on existing OBDs. doing it inside
1976          * of llog_process_lock so no device is attaching/detaching
1977          * in parallel.
1978          * the logname must be <fsname>-sptlrpc
1979          */
1980         if (rc == 0 && cld_is_sptlrpc(cld))
1981                 class_notify_sptlrpc_conf(cld->cld_logname,
1982                                           strlen(cld->cld_logname) -
1983                                           strlen("-sptlrpc"));
1984         EXIT;
1985
1986 out_pop:
1987         __llog_ctxt_put(env, ctxt);
1988         if (lctxt)
1989                 __llog_ctxt_put(env, lctxt);
1990
1991         lu_env_fini(env);
1992 out_free:
1993         OBD_FREE_PTR(env);
1994         return rc;
1995 }
1996
1997 static bool mgc_import_in_recovery(struct obd_import *imp)
1998 {
1999         bool in_recovery = true;
2000
2001         spin_lock(&imp->imp_lock);
2002         if (imp->imp_state == LUSTRE_IMP_FULL ||
2003             imp->imp_state == LUSTRE_IMP_CLOSED)
2004                 in_recovery = false;
2005         spin_unlock(&imp->imp_lock);
2006
2007         return in_recovery;
2008 }
2009
2010 /**
2011  * Get a configuration log from the MGS and process it.
2012  *
2013  * This function is called for both clients and servers to process the
2014  * configuration log from the MGS.  The MGC enqueues a DLM lock on the
2015  * log from the MGS, and if the lock gets revoked the MGC will be notified
2016  * by the lock cancellation callback that the config log has changed,
2017  * and will enqueue another MGS lock on it, and then continue processing
2018  * the new additions to the end of the log.
2019  *
2020  * Since the MGC import is not replayable, if the import is being evicted
2021  * (rcl == -ESHUTDOWN, \see ptlrpc_import_delay_req()), retry to process
2022  * the log until recovery is finished or the import is closed.
2023  *
2024  * Make a local copy of the log before parsing it if appropriate (non-MGS
2025  * server) so that the server can start even when the MGS is down.
2026  *
2027  * There shouldn't be multiple processes running process_log at once --
2028  * sounds like badness.  It actually might be fine, as long as they're not
2029  * trying to update from the same log simultaneously, in which case we
2030  * should use a per-log semaphore instead of cld_lock.
2031  *
2032  * \param[in] mgc       MGC device by which to fetch the configuration log
2033  * \param[in] cld       log processing state (stored in lock callback data)
2034  *
2035  * \retval              0 on success
2036  * \retval              negative errno on failure
2037  */
2038 int mgc_process_log(struct obd_device *mgc, struct config_llog_data *cld)
2039 {
2040         struct lustre_handle lockh = { 0 };
2041         __u64 flags = LDLM_FL_NO_LRU;
2042         int rc = 0, rcl;
2043         bool retry = false;
2044         ENTRY;
2045
2046         LASSERT(cld != NULL);
2047
2048         /* I don't want multiple processes running process_log at once --
2049            sounds like badness.  It actually might be fine, as long as
2050            we're not trying to update from the same log
2051            simultaneously (in which case we should use a per-log sem.) */
2052 restart:
2053         mutex_lock(&cld->cld_lock);
2054         if (cld->cld_stopping) {
2055                 mutex_unlock(&cld->cld_lock);
2056                 RETURN(0);
2057         }
2058
2059         OBD_FAIL_TIMEOUT(OBD_FAIL_MGC_PAUSE_PROCESS_LOG, 20);
2060
2061         CDEBUG(D_MGC, "Process log %s-%016lx from %d\n", cld->cld_logname,
2062                cld->cld_cfg.cfg_instance, cld->cld_cfg.cfg_last_idx + 1);
2063
2064         /* Get the cfg lock on the llog */
2065         rcl = mgc_enqueue(mgc->u.cli.cl_mgc_mgsexp, LDLM_PLAIN, NULL,
2066                           LCK_CR, &flags,
2067                           cld_is_barrier(cld) ? mgc_barrier_glimpse_ast : NULL,
2068                           cld, 0, NULL, &lockh);
2069         if (rcl == 0) {
2070                 /* Get the cld, it will be released in mgc_blocking_ast. */
2071                 config_log_get(cld);
2072                 rc = ldlm_lock_set_data(&lockh, (void *)cld);
2073                 LASSERT(rc == 0);
2074         } else {
2075                 CDEBUG(D_MGC, "Can't get cfg lock: %d\n", rcl);
2076
2077                 if (rcl == -ESHUTDOWN &&
2078                     atomic_read(&mgc->u.cli.cl_mgc_refcount) > 0 && !retry) {
2079                         struct obd_import *imp;
2080                         struct l_wait_info lwi;
2081                         int secs = cfs_time_seconds(obd_timeout);
2082
2083                         mutex_unlock(&cld->cld_lock);
2084                         imp = class_exp2cliimp(mgc->u.cli.cl_mgc_mgsexp);
2085
2086                         /* Let's force the pinger, and wait the import to be
2087                          * connected, note: since mgc import is non-replayable,
2088                          * and even the import state is disconnected, it does
2089                          * not mean the "recovery" is stopped, so we will keep
2090                          * waitting until timeout or the import state is
2091                          * FULL or closed */
2092                         ptlrpc_pinger_force(imp);
2093
2094                         lwi = LWI_TIMEOUT(secs, NULL, NULL);
2095                         l_wait_event(imp->imp_recovery_waitq,
2096                                      !mgc_import_in_recovery(imp), &lwi);
2097
2098                         if (imp->imp_state == LUSTRE_IMP_FULL) {
2099                                 retry = true;
2100                                 goto restart;
2101                         } else {
2102                                 mutex_lock(&cld->cld_lock);
2103                                 /* unlock/lock mutex, so check stopping again */
2104                                 if (cld->cld_stopping) {
2105                                         mutex_unlock(&cld->cld_lock);
2106                                         RETURN(0);
2107                                 }
2108                                 spin_lock(&config_list_lock);
2109                                 cld->cld_lostlock = 1;
2110                                 spin_unlock(&config_list_lock);
2111                         }
2112                 } else {
2113                         /* mark cld_lostlock so that it will requeue
2114                          * after MGC becomes available. */
2115                         spin_lock(&config_list_lock);
2116                         cld->cld_lostlock = 1;
2117                         spin_unlock(&config_list_lock);
2118                 }
2119         }
2120
2121         if (cld_is_recover(cld) || cld_is_nodemap(cld)) {
2122                 if (!rcl)
2123                         rc = mgc_process_recover_nodemap_log(mgc, cld);
2124                 else if (cld_is_nodemap(cld))
2125                         rc = rcl;
2126
2127                 if (cld_is_recover(cld) && rc) {
2128                         if (!rcl) {
2129                                 CERROR("%s: recover log %s failed, not fatal: rc = %d\n",
2130                                        mgc->obd_name, cld->cld_logname, rc);
2131                                 spin_lock(&config_list_lock);
2132                                 cld->cld_lostlock = 1;
2133                                 spin_unlock(&config_list_lock);
2134                         }
2135                         rc = 0; /* this is not a fatal error for recover log */
2136                 }
2137         } else if (!cld_is_barrier(cld)) {
2138                 rc = mgc_process_cfg_log(mgc, cld, rcl != 0);
2139         }
2140
2141         CDEBUG(D_MGC, "%s: configuration from log '%s' %sed (%d).\n",
2142                mgc->obd_name, cld->cld_logname, rc ? "fail" : "succeed", rc);
2143
2144         mutex_unlock(&cld->cld_lock);
2145
2146         /* Now drop the lock so MGS can revoke it */
2147         if (!rcl) {
2148                 rcl = mgc_cancel(mgc->u.cli.cl_mgc_mgsexp, LCK_CR, &lockh);
2149                 if (rcl)
2150                         CERROR("Can't drop cfg lock: %d\n", rcl);
2151         }
2152
2153         /* requeue nodemap lock immediately if transfer was interrupted */
2154         if (cld_is_nodemap(cld) && rc == -EAGAIN) {
2155                 mgc_requeue_add(cld);
2156                 rc = 0;
2157         }
2158
2159         RETURN(rc);
2160 }
2161
2162
2163 /** Called from lustre_process_log.
2164  * LCFG_LOG_START gets the config log from the MGS, processes it to start
2165  * any services, and adds it to the list logs to watch (follow).
2166  */
2167 static int mgc_process_config(struct obd_device *obd, size_t len, void *buf)
2168 {
2169         struct lustre_cfg *lcfg = buf;
2170         struct config_llog_instance *cfg = NULL;
2171         char *logname;
2172         int rc = 0;
2173         ENTRY;
2174
2175         switch(lcfg->lcfg_command) {
2176         case LCFG_LOV_ADD_OBD: {
2177                 /* Overloading this cfg command: register a new target */
2178                 struct mgs_target_info *mti;
2179
2180                 if (LUSTRE_CFG_BUFLEN(lcfg, 1) !=
2181                     sizeof(struct mgs_target_info))
2182                         GOTO(out, rc = -EINVAL);
2183
2184                 mti = (struct mgs_target_info *)lustre_cfg_buf(lcfg, 1);
2185                 CDEBUG(D_MGC, "add_target %s %#x\n",
2186                        mti->mti_svname, mti->mti_flags);
2187                 rc = mgc_target_register(obd->u.cli.cl_mgc_mgsexp, mti);
2188                 break;
2189         }
2190         case LCFG_LOV_DEL_OBD:
2191                 /* Unregister has no meaning at the moment. */
2192                 CERROR("lov_del_obd unimplemented\n");
2193                 rc = -ENOSYS;
2194                 break;
2195         case LCFG_SPTLRPC_CONF: {
2196                 rc = sptlrpc_process_config(lcfg);
2197                 break;
2198         }
2199         case LCFG_LOG_START: {
2200                 struct config_llog_data *cld;
2201                 struct super_block *sb;
2202
2203                 logname = lustre_cfg_string(lcfg, 1);
2204                 cfg = (struct config_llog_instance *)lustre_cfg_buf(lcfg, 2);
2205                 sb = *(struct super_block **)lustre_cfg_buf(lcfg, 3);
2206
2207                 CDEBUG(D_MGC, "parse_log %s from %d\n", logname,
2208                        cfg->cfg_last_idx);
2209
2210                 /* We're only called through here on the initial mount */
2211                 cld = config_log_add(obd, logname, cfg, sb);
2212                 if (IS_ERR(cld)) {
2213                         rc = PTR_ERR(cld);
2214                         break;
2215                 }
2216
2217                 rc = mgc_process_log(obd, cld);
2218                 if (rc == 0 && cld->cld_recover != NULL) {
2219                         if (OCD_HAS_FLAG(&obd->u.cli.cl_import->
2220                                          imp_connect_data, IMP_RECOV)) {
2221                                 rc = mgc_process_log(obd, cld->cld_recover);
2222                         } else {
2223                                 struct config_llog_data *cir;
2224
2225                                 mutex_lock(&cld->cld_lock);
2226                                 cir = cld->cld_recover;
2227                                 cld->cld_recover = NULL;
2228                                 mutex_unlock(&cld->cld_lock);
2229                                 config_log_put(cir);
2230                         }
2231
2232                         if (rc)
2233                                 CERROR("Cannot process recover llog %d\n", rc);
2234                 }
2235
2236                 if (rc == 0 && cld->cld_params != NULL) {
2237                         rc = mgc_process_log(obd, cld->cld_params);
2238                         if (rc == -ENOENT) {
2239                                 CDEBUG(D_MGC, "There is no params "
2240                                               "config file yet\n");
2241                                 rc = 0;
2242                         }
2243                         /* params log is optional */
2244                         if (rc)
2245                                 CERROR("%s: can't process params llog: rc = %d\n",
2246                                        obd->obd_name, rc);
2247                 }
2248
2249                 break;
2250         }
2251         case LCFG_LOG_END: {
2252                 logname = lustre_cfg_string(lcfg, 1);
2253
2254                 if (lcfg->lcfg_bufcount >= 2)
2255                         cfg = (struct config_llog_instance *)lustre_cfg_buf(
2256                                 lcfg, 2);
2257                 rc = config_log_end(logname, cfg);
2258                 break;
2259         }
2260         default: {
2261                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
2262                 GOTO(out, rc = -EINVAL);
2263
2264         }
2265         }
2266 out:
2267         RETURN(rc);
2268 }
2269
2270 static struct obd_ops mgc_obd_ops = {
2271         .o_owner        = THIS_MODULE,
2272         .o_setup        = mgc_setup,
2273         .o_precleanup   = mgc_precleanup,
2274         .o_cleanup      = mgc_cleanup,
2275         .o_add_conn     = client_import_add_conn,
2276         .o_del_conn     = client_import_del_conn,
2277         .o_connect      = client_connect_import,
2278         .o_disconnect   = client_disconnect_export,
2279         .o_set_info_async = mgc_set_info_async,
2280         .o_get_info       = mgc_get_info,
2281         .o_import_event = mgc_import_event,
2282         .o_process_config = mgc_process_config,
2283 };
2284
2285 static int __init mgc_init(void)
2286 {
2287         return class_register_type(&mgc_obd_ops, NULL, false, NULL,
2288                                    LUSTRE_MGC_NAME, NULL);
2289 }
2290
2291 static void __exit mgc_exit(void)
2292 {
2293         class_unregister_type(LUSTRE_MGC_NAME);
2294 }
2295
2296 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
2297 MODULE_DESCRIPTION("Lustre Management Client");
2298 MODULE_VERSION(LUSTRE_VERSION_STRING);
2299 MODULE_LICENSE("GPL");
2300
2301 module_init(mgc_init);
2302 module_exit(mgc_exit);