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