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