Whamcloud - gitweb
LU-8010 mdt: fix orphan layout_lock cases for restore
[fs/lustre-release.git] / lustre / mdt / mdt_coordinator.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2011, 2012 Commissariat a l'energie atomique et aux energies
24  *                          alternatives
25  *
26  * Copyright (c) 2013, 2014, Intel Corporation.
27  * Use is subject to license terms.
28  */
29 /*
30  * lustre/mdt/mdt_coordinator.c
31  *
32  * Lustre HSM Coordinator
33  *
34  * Author: Jacques-Charles Lafoucriere <jacques-charles.lafoucriere@cea.fr>
35  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
36  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <linux/kthread.h>
42 #include <obd_support.h>
43 #include <lustre_net.h>
44 #include <lustre_export.h>
45 #include <obd.h>
46 #include <lprocfs_status.h>
47 #include <lustre_log.h>
48 #include <lustre_kernelcomm.h>
49 #include "mdt_internal.h"
50
51 static struct lprocfs_vars lprocfs_mdt_hsm_vars[];
52
53 /**
54  * get obj and HSM attributes on a fid
55  * \param mti [IN] context
56  * \param fid [IN] object fid
57  * \param hsm [OUT] HSM meta data
58  * \retval obj or error (-ENOENT if not found)
59  */
60 struct mdt_object *mdt_hsm_get_md_hsm(struct mdt_thread_info *mti,
61                                       const struct lu_fid *fid,
62                                       struct md_hsm *hsm)
63 {
64         struct md_attr          *ma;
65         struct mdt_object       *obj;
66         int                      rc;
67         ENTRY;
68
69         ma = &mti->mti_attr;
70         ma->ma_need = MA_HSM;
71         ma->ma_valid = 0;
72
73         /* find object by FID */
74         obj = mdt_object_find(mti->mti_env, mti->mti_mdt, fid);
75         if (IS_ERR(obj))
76                 RETURN(obj);
77
78         if (!mdt_object_exists(obj)) {
79                 /* no more object */
80                 mdt_object_put(mti->mti_env, obj);
81                 RETURN(ERR_PTR(-ENOENT));
82         }
83
84         rc = mdt_attr_get_complex(mti, obj, ma);
85         if (rc) {
86                 mdt_object_put(mti->mti_env, obj);
87                 RETURN(ERR_PTR(rc));
88         }
89
90         if (ma->ma_valid & MA_HSM)
91                 *hsm = ma->ma_hsm;
92         else
93                 memset(hsm, 0, sizeof(*hsm));
94         ma->ma_valid = 0;
95         RETURN(obj);
96 }
97
98 void mdt_hsm_dump_hal(int level, const char *prefix,
99                       struct hsm_action_list *hal)
100 {
101         int                      i, sz;
102         struct hsm_action_item  *hai;
103         char                     buf[12];
104
105         CDEBUG(level, "%s: HAL header: version %X count %d compound "LPX64
106                       " archive_id %d flags "LPX64"\n",
107                prefix, hal->hal_version, hal->hal_count,
108                hal->hal_compound_id, hal->hal_archive_id, hal->hal_flags);
109
110         hai = hai_first(hal);
111         for (i = 0; i < hal->hal_count; i++) {
112                 sz = hai->hai_len - sizeof(*hai);
113                 CDEBUG(level, "%s %d: fid="DFID" dfid="DFID
114                        " compound/cookie="LPX64"/"LPX64
115                        " action=%s extent="LPX64"-"LPX64" gid="LPX64
116                        " datalen=%d data=[%s]\n",
117                        prefix, i,
118                        PFID(&hai->hai_fid), PFID(&hai->hai_dfid),
119                        hal->hal_compound_id, hai->hai_cookie,
120                        hsm_copytool_action2name(hai->hai_action),
121                        hai->hai_extent.offset,
122                        hai->hai_extent.length,
123                        hai->hai_gid, sz,
124                        hai_dump_data_field(hai, buf, sizeof(buf)));
125                 hai = hai_next(hai);
126         }
127 }
128
129 /**
130  * data passed to llog_cat_process() callback
131  * to scan requests and take actions
132  */
133 struct hsm_scan_data {
134         struct mdt_thread_info          *mti;
135         char                             fs_name[MTI_NAME_MAXLEN+1];
136         /* request to be send to agents */
137         int                              request_sz;    /** allocated size */
138         int                              max_requests;  /** vector size */
139         int                              request_cnt;   /** used count */
140         struct {
141                 int                      hal_sz;
142                 int                      hal_used_sz;
143                 struct hsm_action_list  *hal;
144         } *request;
145 };
146
147 /**
148  *  llog_cat_process() callback, used to:
149  *  - find waiting request and start action
150  *  - purge canceled and done requests
151  * \param env [IN] environment
152  * \param llh [IN] llog handle
153  * \param hdr [IN] llog record
154  * \param data [IN/OUT] cb data = struct hsm_scan_data
155  * \retval 0 success
156  * \retval -ve failure
157  */
158 static int mdt_coordinator_cb(const struct lu_env *env,
159                               struct llog_handle *llh,
160                               struct llog_rec_hdr *hdr,
161                               void *data)
162 {
163         struct llog_agent_req_rec       *larr;
164         struct hsm_scan_data            *hsd;
165         struct hsm_action_item          *hai;
166         struct mdt_device               *mdt;
167         struct coordinator              *cdt;
168         int                              rc;
169         ENTRY;
170
171         hsd = data;
172         mdt = hsd->mti->mti_mdt;
173         cdt = &mdt->mdt_coordinator;
174
175         larr = (struct llog_agent_req_rec *)hdr;
176         dump_llog_agent_req_rec("mdt_coordinator_cb(): ", larr);
177         switch (larr->arr_status) {
178         case ARS_WAITING: {
179                 int i, empty_slot, found;
180
181                 /* Are agents full? */
182                 if (atomic_read(&cdt->cdt_request_count) ==
183                     cdt->cdt_max_requests)
184                         break;
185
186                 /* first search whether the request is found in the list we
187                  * have built and if there is room in the request vector */
188                 empty_slot = -1;
189                 found = -1;
190                 for (i = 0; i < hsd->max_requests &&
191                             (empty_slot == -1 || found == -1); i++) {
192                         if (hsd->request[i].hal == NULL) {
193                                 empty_slot = i;
194                                 continue;
195                         }
196                         if (hsd->request[i].hal->hal_compound_id ==
197                                 larr->arr_compound_id) {
198                                 found = i;
199                                 continue;
200                         }
201                 }
202                 if (found == -1 && empty_slot == -1)
203                         /* unknown request and no more room for new request,
204                          * continue scan for to find other entries for
205                          * already found request
206                          */
207                         RETURN(0);
208
209                 if (found == -1) {
210                         struct hsm_action_list *hal;
211
212                         /* request is not already known */
213                         /* allocates hai vector size just needs to be large
214                          * enough */
215                         hsd->request[empty_slot].hal_sz =
216                                      sizeof(*hsd->request[empty_slot].hal) +
217                                      cfs_size_round(MTI_NAME_MAXLEN+1) +
218                                      2 * cfs_size_round(larr->arr_hai.hai_len);
219                         OBD_ALLOC(hal, hsd->request[empty_slot].hal_sz);
220                         if (!hal) {
221                                 CERROR("%s: Cannot allocate memory (%d o)"
222                                        "for compound "LPX64"\n",
223                                        mdt_obd_name(mdt),
224                                        hsd->request[i].hal_sz,
225                                        larr->arr_compound_id);
226                                 RETURN(-ENOMEM);
227                         }
228                         hal->hal_version = HAL_VERSION;
229                         strlcpy(hal->hal_fsname, hsd->fs_name,
230                                 MTI_NAME_MAXLEN + 1);
231                         hal->hal_compound_id = larr->arr_compound_id;
232                         hal->hal_archive_id = larr->arr_archive_id;
233                         hal->hal_flags = larr->arr_flags;
234                         hal->hal_count = 0;
235                         hsd->request[empty_slot].hal_used_sz = hal_size(hal);
236                         hsd->request[empty_slot].hal = hal;
237                         hsd->request_cnt++;
238                         found = empty_slot;
239                         hai = hai_first(hal);
240                 } else {
241                         /* request is known */
242                         /* we check if record archive num is the same as the
243                          * known request, if not we will serve it in multiple
244                          * time because we do not know if the agent can serve
245                          * multiple backend
246                          * a use case is a compound made of multiple restore
247                          * where the files are not archived in the same backend
248                          */
249                         if (larr->arr_archive_id !=
250                             hsd->request[found].hal->hal_archive_id)
251                                 RETURN(0);
252
253                         if (hsd->request[found].hal_sz <
254                             hsd->request[found].hal_used_sz +
255                              cfs_size_round(larr->arr_hai.hai_len)) {
256                                 /* Not enough room, need an extension */
257                                 void *hal_buffer;
258                                 int sz;
259
260                                 sz = 2 * hsd->request[found].hal_sz;
261                                 OBD_ALLOC(hal_buffer, sz);
262                                 if (!hal_buffer) {
263                                         CERROR("%s: Cannot allocate memory "
264                                                "(%d o) for compound "LPX64"\n",
265                                                mdt_obd_name(mdt), sz,
266                                                larr->arr_compound_id);
267                                         RETURN(-ENOMEM);
268                                 }
269                                 memcpy(hal_buffer, hsd->request[found].hal,
270                                        hsd->request[found].hal_used_sz);
271                                 OBD_FREE(hsd->request[found].hal,
272                                          hsd->request[found].hal_sz);
273                                 hsd->request[found].hal = hal_buffer;
274                                 hsd->request[found].hal_sz = sz;
275                         }
276                         hai = hai_first(hsd->request[found].hal);
277                         for (i = 0; i < hsd->request[found].hal->hal_count;
278                              i++)
279                                 hai = hai_next(hai);
280                 }
281                 memcpy(hai, &larr->arr_hai, larr->arr_hai.hai_len);
282                 hai->hai_cookie = larr->arr_hai.hai_cookie;
283                 hai->hai_gid = larr->arr_hai.hai_gid;
284
285                 hsd->request[found].hal_used_sz +=
286                                                    cfs_size_round(hai->hai_len);
287                 hsd->request[found].hal->hal_count++;
288                 break;
289         }
290         case ARS_STARTED: {
291                 struct hsm_progress_kernel pgs;
292                 struct cdt_agent_req *car;
293                 cfs_time_t now = cfs_time_current_sec();
294                 cfs_time_t last;
295
296                 /* we search for a running request
297                  * error may happen if coordinator crashes or stopped
298                  * with running request
299                  */
300                 car = mdt_cdt_find_request(cdt, larr->arr_hai.hai_cookie, NULL);
301                 if (car == NULL) {
302                         last = larr->arr_req_create;
303                 } else {
304                         last = car->car_req_update;
305                         mdt_cdt_put_request(car);
306                 }
307
308                 /* test if request too long, if yes cancel it
309                  * the same way the copy tool acknowledge a cancel request */
310                 if (now <= last + cdt->cdt_active_req_timeout)
311                         RETURN(0);
312
313                 dump_llog_agent_req_rec("request timed out, start cleaning",
314                                         larr);
315                 /* a too old cancel request just needs to be removed
316                  * this can happen, if copy tool does not support
317                  * cancel for other requests, we have to remove the
318                  * running request and notify the copytool */
319                 pgs.hpk_fid = larr->arr_hai.hai_fid;
320                 pgs.hpk_cookie = larr->arr_hai.hai_cookie;
321                 pgs.hpk_extent = larr->arr_hai.hai_extent;
322                 pgs.hpk_flags = HP_FLAG_COMPLETED;
323                 pgs.hpk_errval = ENOSYS;
324                 pgs.hpk_data_version = 0;
325
326                 /* update request state, but do not record in llog, to
327                  * avoid deadlock on cdt_llog_lock */
328                 rc = mdt_hsm_update_request_state(hsd->mti, &pgs, 0);
329                 if (rc)
330                         CERROR("%s: cannot cleanup timed out request: "
331                                DFID" for cookie "LPX64" action=%s\n",
332                                mdt_obd_name(mdt),
333                                PFID(&pgs.hpk_fid), pgs.hpk_cookie,
334                                hsm_copytool_action2name(
335                                        larr->arr_hai.hai_action));
336
337                 if (rc == -ENOENT) {
338                         /* The request no longer exists, forget
339                          * about it, and do not send a cancel request
340                          * to the client, for which an error will be
341                          * sent back, leading to an endless cycle of
342                          * cancellation. */
343                         RETURN(LLOG_DEL_RECORD);
344                 }
345
346                 /* XXX A cancel request cannot be cancelled. */
347                 if (larr->arr_hai.hai_action == HSMA_CANCEL)
348                         RETURN(0);
349
350                 larr->arr_status = ARS_CANCELED;
351                 larr->arr_req_change = now;
352                 rc = llog_write(hsd->mti->mti_env, llh, hdr, hdr->lrh_index);
353                 if (rc < 0)
354                         CERROR("%s: cannot update agent log: rc = %d\n",
355                                mdt_obd_name(mdt), rc);
356                 break;
357         }
358         case ARS_FAILED:
359         case ARS_CANCELED:
360         case ARS_SUCCEED:
361                 if ((larr->arr_req_change + cdt->cdt_grace_delay) <
362                     cfs_time_current_sec())
363                         RETURN(LLOG_DEL_RECORD);
364                 break;
365         }
366         RETURN(0);
367 }
368
369 /**
370  * create /proc entries for coordinator
371  * \param mdt [IN]
372  * \retval 0 success
373  * \retval -ve failure
374  */
375 int hsm_cdt_procfs_init(struct mdt_device *mdt)
376 {
377         struct coordinator      *cdt = &mdt->mdt_coordinator;
378         int                      rc = 0;
379         ENTRY;
380
381         /* init /proc entries, failure is not critical */
382         cdt->cdt_proc_dir = lprocfs_register("hsm",
383                                              mdt2obd_dev(mdt)->obd_proc_entry,
384                                              lprocfs_mdt_hsm_vars, mdt);
385         if (IS_ERR(cdt->cdt_proc_dir)) {
386                 rc = PTR_ERR(cdt->cdt_proc_dir);
387                 CERROR("%s: Cannot create 'hsm' directory in mdt proc dir,"
388                        " rc=%d\n", mdt_obd_name(mdt), rc);
389                 cdt->cdt_proc_dir = NULL;
390                 RETURN(rc);
391         }
392
393         RETURN(0);
394 }
395
396 /**
397  * remove /proc entries for coordinator
398  * \param mdt [IN]
399  */
400 void  hsm_cdt_procfs_fini(struct mdt_device *mdt)
401 {
402         struct coordinator      *cdt = &mdt->mdt_coordinator;
403
404         LASSERT(cdt->cdt_state == CDT_STOPPED);
405         if (cdt->cdt_proc_dir != NULL)
406                 lprocfs_remove(&cdt->cdt_proc_dir);
407 }
408
409 /**
410  * get vector of hsm cdt /proc vars
411  * \param none
412  * \retval var vector
413  */
414 struct lprocfs_vars *hsm_cdt_get_proc_vars(void)
415 {
416         return lprocfs_mdt_hsm_vars;
417 }
418
419 /**
420  * coordinator thread
421  * \param data [IN] obd device
422  * \retval 0 success
423  * \retval -ve failure
424  */
425 static int mdt_coordinator(void *data)
426 {
427         struct mdt_thread_info  *mti = data;
428         struct mdt_device       *mdt = mti->mti_mdt;
429         struct coordinator      *cdt = &mdt->mdt_coordinator;
430         struct hsm_scan_data     hsd = { NULL };
431         int                      rc = 0;
432         ENTRY;
433
434         cdt->cdt_thread.t_flags = SVC_RUNNING;
435         wake_up(&cdt->cdt_thread.t_ctl_waitq);
436
437         CDEBUG(D_HSM, "%s: coordinator thread starting, pid=%d\n",
438                mdt_obd_name(mdt), current_pid());
439
440         /* we use a copy of cdt_max_requests in the cb, so if cdt_max_requests
441          * increases due to a change from /proc we do not overflow the
442          * hsd.request[] vector
443          */
444         hsd.max_requests = cdt->cdt_max_requests;
445         hsd.request_sz = hsd.max_requests * sizeof(*hsd.request);
446         OBD_ALLOC(hsd.request, hsd.request_sz);
447         if (!hsd.request)
448                 GOTO(out, rc = -ENOMEM);
449
450         hsd.mti = mti;
451         obd_uuid2fsname(hsd.fs_name, mdt_obd_name(mdt), MTI_NAME_MAXLEN);
452
453         while (1) {
454                 struct l_wait_info lwi;
455                 int i;
456
457                 lwi = LWI_TIMEOUT(cfs_time_seconds(cdt->cdt_loop_period),
458                                   NULL, NULL);
459                 l_wait_event(cdt->cdt_thread.t_ctl_waitq,
460                              (cdt->cdt_thread.t_flags &
461                               (SVC_STOPPING|SVC_EVENT)),
462                              &lwi);
463
464                 CDEBUG(D_HSM, "coordinator resumes\n");
465
466                 if (cdt->cdt_thread.t_flags & SVC_STOPPING ||
467                     cdt->cdt_state == CDT_STOPPING) {
468                         cdt->cdt_thread.t_flags &= ~SVC_STOPPING;
469                         rc = 0;
470                         break;
471                 }
472
473                 /* wake up before timeout, new work arrives */
474                 if (cdt->cdt_thread.t_flags & SVC_EVENT)
475                         cdt->cdt_thread.t_flags &= ~SVC_EVENT;
476
477                 /* if coordinator is suspended continue to wait */
478                 if (cdt->cdt_state == CDT_DISABLE) {
479                         CDEBUG(D_HSM, "disable state, coordinator sleeps\n");
480                         continue;
481                 }
482
483                 CDEBUG(D_HSM, "coordinator starts reading llog\n");
484
485                 if (hsd.max_requests != cdt->cdt_max_requests) {
486                         /* cdt_max_requests has changed,
487                          * we need to allocate a new buffer
488                          */
489                         OBD_FREE(hsd.request, hsd.request_sz);
490                         hsd.max_requests = cdt->cdt_max_requests;
491                         hsd.request_sz =
492                                    hsd.max_requests * sizeof(*hsd.request);
493                         OBD_ALLOC(hsd.request, hsd.request_sz);
494                         if (!hsd.request) {
495                                 rc = -ENOMEM;
496                                 break;
497                         }
498                 }
499
500                 hsd.request_cnt = 0;
501
502                 rc = cdt_llog_process(mti->mti_env, mdt,
503                                       mdt_coordinator_cb, &hsd);
504                 if (rc < 0)
505                         goto clean_cb_alloc;
506
507                 CDEBUG(D_HSM, "found %d requests to send\n", hsd.request_cnt);
508
509                 if (list_empty(&cdt->cdt_agents)) {
510                         CDEBUG(D_HSM, "no agent available, "
511                                       "coordinator sleeps\n");
512                         goto clean_cb_alloc;
513                 }
514
515                 /* here hsd contains a list of requests to be started */
516                 for (i = 0; i < hsd.max_requests; i++) {
517                         struct hsm_action_list  *hal = hsd.request[i].hal;
518                         struct hsm_action_item  *hai;
519                         __u64                   *cookies;
520                         int                      sz, j;
521                         enum agent_req_status    status;
522
523                         /* still room for work ? */
524                         if (atomic_read(&cdt->cdt_request_count) ==
525                             cdt->cdt_max_requests)
526                                 break;
527
528                         if (hal == NULL)
529                                 continue;
530
531                         /* found a request, we start it */
532                         rc = mdt_hsm_agent_send(mti, hal, 0);
533                         /* if failure, we suppose it is temporary
534                          * if the copy tool failed to do the request
535                          * it has to use hsm_progress
536                          */
537                         status = (rc ? ARS_WAITING : ARS_STARTED);
538
539                         /* set up cookie vector to set records status
540                          * after copy tools start or failed
541                          */
542                         sz = hal->hal_count * sizeof(__u64);
543                         OBD_ALLOC(cookies, sz);
544                         if (cookies == NULL) {
545                                 CERROR("%s: Cannot allocate memory (%d o) "
546                                        "for cookies vector "LPX64"\n",
547                                        mdt_obd_name(mdt), sz,
548                                        hal->hal_compound_id);
549                                 kuc_free(hal, hsd.request[i].hal_used_sz);
550                                 continue;
551                         }
552                         hai = hai_first(hal);
553                         for (j = 0; j < hal->hal_count; j++) {
554                                 cookies[j] = hai->hai_cookie;
555                                 hai = hai_next(hai);
556                         }
557
558                         rc = mdt_agent_record_update(mti->mti_env, mdt, cookies,
559                                                      hal->hal_count, status);
560                         if (rc)
561                                 CERROR("%s: mdt_agent_record_update() failed, "
562                                        "rc=%d, cannot update status to %s "
563                                        "for %d cookies\n",
564                                        mdt_obd_name(mdt), rc,
565                                        agent_req_status2name(status),
566                                        hal->hal_count);
567
568                         OBD_FREE(cookies, sz);
569                 }
570 clean_cb_alloc:
571                 /* free hal allocated by callback */
572                 for (i = 0; i < hsd.max_requests; i++) {
573                         if (hsd.request[i].hal) {
574                                 OBD_FREE(hsd.request[i].hal,
575                                          hsd.request[i].hal_sz);
576                                 hsd.request[i].hal_sz = 0;
577                                 hsd.request[i].hal = NULL;
578                                 hsd.request_cnt--;
579                         }
580                 }
581                 LASSERT(hsd.request_cnt == 0);
582
583                 /* reset callback data */
584                 memset(hsd.request, 0, hsd.request_sz);
585         }
586         EXIT;
587 out:
588         if (hsd.request)
589                 OBD_FREE(hsd.request, hsd.request_sz);
590
591         if (cdt->cdt_state == CDT_STOPPING) {
592                 /* request comes from /proc path, so we need to clean cdt
593                  * struct */
594                  mdt_hsm_cdt_stop(mdt);
595                  mdt->mdt_opts.mo_coordinator = 0;
596         } else {
597                 /* request comes from a thread event, generated
598                  * by mdt_stop_coordinator(), we have to ack
599                  * and cdt cleaning will be done by event sender
600                  */
601                 cdt->cdt_thread.t_flags = SVC_STOPPED;
602                 wake_up(&cdt->cdt_thread.t_ctl_waitq);
603         }
604
605         if (rc != 0)
606                 CERROR("%s: coordinator thread exiting, process=%d, rc=%d\n",
607                        mdt_obd_name(mdt), current_pid(), rc);
608         else
609                 CDEBUG(D_HSM, "%s: coordinator thread exiting, process=%d,"
610                               " no error\n",
611                        mdt_obd_name(mdt), current_pid());
612
613         return rc;
614 }
615
616 /**
617  * lookup a restore handle by FID
618  * caller needs to hold cdt_restore_lock
619  * \param cdt [IN] coordinator
620  * \param fid [IN] FID
621  * \retval cdt_restore_handle found
622  * \retval NULL not found
623  */
624 struct cdt_restore_handle *mdt_hsm_restore_hdl_find(struct coordinator *cdt,
625                                                        const struct lu_fid *fid)
626 {
627         struct cdt_restore_handle       *crh;
628         ENTRY;
629
630         list_for_each_entry(crh, &cdt->cdt_restore_hdl, crh_list) {
631                 if (lu_fid_eq(&crh->crh_fid, fid))
632                         RETURN(crh);
633         }
634         RETURN(NULL);
635 }
636
637 /**
638  * data passed to llog_cat_process() callback
639  * to scan requests and take actions
640  */
641 struct hsm_restore_data {
642         struct mdt_thread_info  *hrd_mti;
643 };
644
645 /**
646  *  llog_cat_process() callback, used to:
647  *  - find restore request and allocate the restore handle
648  * \param env [IN] environment
649  * \param llh [IN] llog handle
650  * \param hdr [IN] llog record
651  * \param data [IN/OUT] cb data = struct hsm_restore_data
652  * \retval 0 success
653  * \retval -ve failure
654  */
655 static int hsm_restore_cb(const struct lu_env *env,
656                           struct llog_handle *llh,
657                           struct llog_rec_hdr *hdr, void *data)
658 {
659         struct llog_agent_req_rec       *larr;
660         struct hsm_restore_data         *hrd;
661         struct cdt_restore_handle       *crh;
662         struct hsm_action_item          *hai;
663         struct mdt_thread_info          *mti;
664         struct coordinator              *cdt;
665         struct mdt_object               *child;
666         int rc;
667         ENTRY;
668
669         hrd = data;
670         mti = hrd->hrd_mti;
671         cdt = &mti->mti_mdt->mdt_coordinator;
672
673         larr = (struct llog_agent_req_rec *)hdr;
674         hai = &larr->arr_hai;
675         if (hai->hai_cookie > cdt->cdt_last_cookie)
676                 /* update the cookie to avoid collision */
677                 cdt->cdt_last_cookie = hai->hai_cookie + 1;
678
679         if (hai->hai_action != HSMA_RESTORE ||
680             agent_req_in_final_state(larr->arr_status))
681                 RETURN(0);
682
683         /* restore request not in a final state */
684
685         /* force replay of restore requests left in started state from previous
686          * CDT context, to be canceled later if finally found to be incompatible
687          * when being re-started */
688         if (larr->arr_status == ARS_STARTED) {
689                 larr->arr_status = ARS_WAITING;
690                 larr->arr_req_change = cfs_time_current_sec();
691                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
692                 if (rc != 0)
693                         GOTO(out, rc);
694         }
695
696         OBD_SLAB_ALLOC_PTR(crh, mdt_hsm_cdt_kmem);
697         if (crh == NULL)
698                 RETURN(-ENOMEM);
699
700         crh->crh_fid = hai->hai_fid;
701         /* in V1 all file is restored
702         crh->extent.start = hai->hai_extent.offset;
703         crh->extent.end = hai->hai_extent.offset + hai->hai_extent.length;
704         */
705         crh->crh_extent.start = 0;
706         crh->crh_extent.end = hai->hai_extent.length;
707         /* get the layout lock */
708         mdt_lock_reg_init(&crh->crh_lh, LCK_EX);
709         child = mdt_object_find_lock(mti, &crh->crh_fid, &crh->crh_lh,
710                                      MDS_INODELOCK_LAYOUT);
711         if (IS_ERR(child))
712                 GOTO(out, rc = PTR_ERR(child));
713
714         rc = 0;
715         /* we choose to not keep a reference
716          * on the object during the restore time which can be very long */
717         mdt_object_put(mti->mti_env, child);
718
719         mutex_lock(&cdt->cdt_restore_lock);
720         list_add_tail(&crh->crh_list, &cdt->cdt_restore_hdl);
721         mutex_unlock(&cdt->cdt_restore_lock);
722
723 out:
724         RETURN(rc);
725 }
726
727 /**
728  * restore coordinator state at startup
729  * the goal is to take a layout lock for each registered restore request
730  * \param mti [IN] context
731  */
732 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti)
733 {
734         struct hsm_restore_data  hrd;
735         int                      rc;
736         ENTRY;
737
738         hrd.hrd_mti = mti;
739
740         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt,
741                               hsm_restore_cb, &hrd);
742
743         RETURN(rc);
744 }
745
746 static int hsm_init_ucred(struct lu_ucred *uc)
747 {
748         ENTRY;
749
750         uc->uc_valid = UCRED_OLD;
751         uc->uc_o_uid = 0;
752         uc->uc_o_gid = 0;
753         uc->uc_o_fsuid = 0;
754         uc->uc_o_fsgid = 0;
755         uc->uc_uid = 0;
756         uc->uc_gid = 0;
757         uc->uc_fsuid = 0;
758         uc->uc_fsgid = 0;
759         uc->uc_suppgids[0] = -1;
760         uc->uc_suppgids[1] = -1;
761         uc->uc_cap = CFS_CAP_FS_MASK;
762         uc->uc_umask = 0777;
763         uc->uc_ginfo = NULL;
764         uc->uc_identity = NULL;
765
766         RETURN(0);
767 }
768
769 /**
770  * wake up coordinator thread
771  * \param mdt [IN] device
772  * \retval 0 success
773  * \retval -ve failure
774  */
775 int mdt_hsm_cdt_wakeup(struct mdt_device *mdt)
776 {
777         struct coordinator      *cdt = &mdt->mdt_coordinator;
778         ENTRY;
779
780         if (cdt->cdt_state == CDT_STOPPED)
781                 RETURN(-ESRCH);
782
783         /* wake up coordinator */
784         cdt->cdt_thread.t_flags = SVC_EVENT;
785         wake_up(&cdt->cdt_thread.t_ctl_waitq);
786
787         RETURN(0);
788 }
789
790 /**
791  * initialize coordinator struct
792  * \param mdt [IN] device
793  * \retval 0 success
794  * \retval -ve failure
795  */
796 int mdt_hsm_cdt_init(struct mdt_device *mdt)
797 {
798         struct coordinator      *cdt = &mdt->mdt_coordinator;
799         struct mdt_thread_info  *cdt_mti = NULL;
800         int                      rc;
801         ENTRY;
802
803         cdt->cdt_state = CDT_STOPPED;
804
805         init_waitqueue_head(&cdt->cdt_thread.t_ctl_waitq);
806         mutex_init(&cdt->cdt_llog_lock);
807         init_rwsem(&cdt->cdt_agent_lock);
808         init_rwsem(&cdt->cdt_request_lock);
809         mutex_init(&cdt->cdt_restore_lock);
810
811         INIT_LIST_HEAD(&cdt->cdt_requests);
812         INIT_LIST_HEAD(&cdt->cdt_agents);
813         INIT_LIST_HEAD(&cdt->cdt_restore_hdl);
814
815         rc = lu_env_init(&cdt->cdt_env, LCT_MD_THREAD);
816         if (rc < 0)
817                 RETURN(rc);
818
819         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
820         rc = lu_context_init(&cdt->cdt_session, LCT_SERVER_SESSION);
821         if (rc == 0) {
822                 lu_context_enter(&cdt->cdt_session);
823                 cdt->cdt_env.le_ses = &cdt->cdt_session;
824         } else {
825                 lu_env_fini(&cdt->cdt_env);
826                 RETURN(rc);
827         }
828
829         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
830         LASSERT(cdt_mti != NULL);
831
832         cdt_mti->mti_env = &cdt->cdt_env;
833         cdt_mti->mti_mdt = mdt;
834
835         hsm_init_ucred(mdt_ucred(cdt_mti));
836
837         /* default values for /proc tunnables
838          * can be override by MGS conf */
839         cdt->cdt_default_archive_id = 1;
840         cdt->cdt_grace_delay = 60;
841         cdt->cdt_loop_period = 10;
842         cdt->cdt_max_requests = 3;
843         cdt->cdt_policy = CDT_DEFAULT_POLICY;
844         cdt->cdt_active_req_timeout = 3600;
845
846         RETURN(0);
847 }
848
849 /**
850  * free a coordinator thread
851  * \param mdt [IN] device
852  */
853 int  mdt_hsm_cdt_fini(struct mdt_device *mdt)
854 {
855         struct coordinator *cdt = &mdt->mdt_coordinator;
856         ENTRY;
857
858         lu_context_exit(cdt->cdt_env.le_ses);
859         lu_context_fini(cdt->cdt_env.le_ses);
860
861         lu_env_fini(&cdt->cdt_env);
862
863         RETURN(0);
864 }
865
866 /**
867  * start a coordinator thread
868  * \param mdt [IN] device
869  * \retval 0 success
870  * \retval -ve failure
871  */
872 int mdt_hsm_cdt_start(struct mdt_device *mdt)
873 {
874         struct coordinator      *cdt = &mdt->mdt_coordinator;
875         int                      rc;
876         void                    *ptr;
877         struct mdt_thread_info  *cdt_mti;
878         struct task_struct      *task;
879         ENTRY;
880
881         /* functions defined but not yet used
882          * this avoid compilation warning
883          */
884         ptr = dump_requests;
885
886         if (cdt->cdt_state != CDT_STOPPED) {
887                 CERROR("%s: Coordinator already started\n",
888                        mdt_obd_name(mdt));
889                 RETURN(-EALREADY);
890         }
891
892         CLASSERT(1 << (CDT_POLICY_SHIFT_COUNT - 1) == CDT_POLICY_LAST);
893         cdt->cdt_policy = CDT_DEFAULT_POLICY;
894
895         cdt->cdt_state = CDT_INIT;
896
897         atomic_set(&cdt->cdt_compound_id, cfs_time_current_sec());
898         /* just need to be larger than previous one */
899         /* cdt_last_cookie is protected by cdt_llog_lock */
900         cdt->cdt_last_cookie = cfs_time_current_sec();
901         atomic_set(&cdt->cdt_request_count, 0);
902         cdt->cdt_user_request_mask = (1UL << HSMA_RESTORE);
903         cdt->cdt_group_request_mask = (1UL << HSMA_RESTORE);
904         cdt->cdt_other_request_mask = (1UL << HSMA_RESTORE);
905
906         /* to avoid deadlock when start is made through /proc
907          * /proc entries are created by the coordinator thread */
908
909         /* set up list of started restore requests */
910         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
911         rc = mdt_hsm_pending_restore(cdt_mti);
912         if (rc)
913                 CERROR("%s: cannot take the layout locks needed"
914                        " for registered restore: %d\n",
915                        mdt_obd_name(mdt), rc);
916
917         task = kthread_run(mdt_coordinator, cdt_mti, "hsm_cdtr");
918         if (IS_ERR(task)) {
919                 rc = PTR_ERR(task);
920                 cdt->cdt_state = CDT_STOPPED;
921                 CERROR("%s: error starting coordinator thread: %d\n",
922                        mdt_obd_name(mdt), rc);
923                 RETURN(rc);
924         } else {
925                 CDEBUG(D_HSM, "%s: coordinator thread started\n",
926                        mdt_obd_name(mdt));
927                 rc = 0;
928         }
929
930         wait_event(cdt->cdt_thread.t_ctl_waitq,
931                        (cdt->cdt_thread.t_flags & SVC_RUNNING));
932
933         cdt->cdt_state = CDT_RUNNING;
934         mdt->mdt_opts.mo_coordinator = 1;
935         RETURN(0);
936 }
937
938 /**
939  * stop a coordinator thread
940  * \param mdt [IN] device
941  */
942 int mdt_hsm_cdt_stop(struct mdt_device *mdt)
943 {
944         struct coordinator              *cdt = &mdt->mdt_coordinator;
945         struct cdt_agent_req            *car, *tmp1;
946         struct hsm_agent                *ha, *tmp2;
947         struct cdt_restore_handle       *crh, *tmp3;
948         struct mdt_thread_info          *cdt_mti;
949         ENTRY;
950
951         if (cdt->cdt_state == CDT_STOPPED) {
952                 CERROR("%s: Coordinator already stopped\n",
953                        mdt_obd_name(mdt));
954                 RETURN(-EALREADY);
955         }
956
957         if (cdt->cdt_state != CDT_STOPPING) {
958                 /* stop coordinator thread before cleaning */
959                 cdt->cdt_thread.t_flags = SVC_STOPPING;
960                 wake_up(&cdt->cdt_thread.t_ctl_waitq);
961                 wait_event(cdt->cdt_thread.t_ctl_waitq,
962                            cdt->cdt_thread.t_flags & SVC_STOPPED);
963         }
964         cdt->cdt_state = CDT_STOPPED;
965
966         /* start cleaning */
967         down_write(&cdt->cdt_request_lock);
968         list_for_each_entry_safe(car, tmp1, &cdt->cdt_requests,
969                                  car_request_list) {
970                 list_del(&car->car_request_list);
971                 mdt_cdt_free_request(car);
972         }
973         up_write(&cdt->cdt_request_lock);
974
975         down_write(&cdt->cdt_agent_lock);
976         list_for_each_entry_safe(ha, tmp2, &cdt->cdt_agents, ha_list) {
977                 list_del(&ha->ha_list);
978                 OBD_FREE_PTR(ha);
979         }
980         up_write(&cdt->cdt_agent_lock);
981
982         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
983         mutex_lock(&cdt->cdt_restore_lock);
984         list_for_each_entry_safe(crh, tmp3, &cdt->cdt_restore_hdl, crh_list) {
985                 struct mdt_object       *child;
986
987                 /* give back layout lock */
988                 child = mdt_object_find(&cdt->cdt_env, mdt, &crh->crh_fid);
989                 if (!IS_ERR(child))
990                         mdt_object_unlock_put(cdt_mti, child, &crh->crh_lh, 1);
991
992                 list_del(&crh->crh_list);
993
994                 OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
995         }
996         mutex_unlock(&cdt->cdt_restore_lock);
997
998         mdt->mdt_opts.mo_coordinator = 0;
999
1000         RETURN(0);
1001 }
1002
1003 /**
1004  * register all requests from an hal in the memory list
1005  * \param mti [IN] context
1006  * \param hal [IN] request
1007  * \param uuid [OUT] in case of CANCEL, the uuid of the agent
1008  *  which is running the CT
1009  * \retval 0 success
1010  * \retval -ve failure
1011  */
1012 int mdt_hsm_add_hal(struct mdt_thread_info *mti,
1013                     struct hsm_action_list *hal, struct obd_uuid *uuid)
1014 {
1015         struct mdt_device       *mdt = mti->mti_mdt;
1016         struct coordinator      *cdt = &mdt->mdt_coordinator;
1017         struct hsm_action_item  *hai;
1018         int                      rc = 0, i;
1019         ENTRY;
1020
1021         /* register request in memory list */
1022         hai = hai_first(hal);
1023         for (i = 0; i < hal->hal_count; i++, hai = hai_next(hai)) {
1024                 struct cdt_agent_req *car;
1025
1026                 /* in case of a cancel request, we first mark the ondisk
1027                  * record of the request we want to stop as canceled
1028                  * this does not change the cancel record
1029                  * it will be done when updating the request status
1030                  */
1031                 if (hai->hai_action == HSMA_CANCEL) {
1032                         rc = mdt_agent_record_update(mti->mti_env, mti->mti_mdt,
1033                                                      &hai->hai_cookie,
1034                                                      1, ARS_CANCELED);
1035                         if (rc) {
1036                                 CERROR("%s: mdt_agent_record_update() failed, "
1037                                        "rc=%d, cannot update status to %s "
1038                                        "for cookie "LPX64"\n",
1039                                        mdt_obd_name(mdt), rc,
1040                                        agent_req_status2name(ARS_CANCELED),
1041                                        hai->hai_cookie);
1042                                 GOTO(out, rc);
1043                         }
1044
1045                         /* find the running request to set it canceled */
1046                         car = mdt_cdt_find_request(cdt, hai->hai_cookie, NULL);
1047                         if (car != NULL) {
1048                                 car->car_canceled = 1;
1049                                 /* uuid has to be changed to the one running the
1050                                 * request to cancel */
1051                                 *uuid = car->car_uuid;
1052                                 mdt_cdt_put_request(car);
1053                         }
1054                         /* no need to memorize cancel request
1055                          * this also avoid a deadlock when we receive
1056                          * a purge all requests command
1057                          */
1058                         continue;
1059                 }
1060
1061                 if (hai->hai_action == HSMA_ARCHIVE) {
1062                         struct mdt_object *obj;
1063                         struct md_hsm hsm;
1064
1065                         obj = mdt_hsm_get_md_hsm(mti, &hai->hai_fid, &hsm);
1066                         if (IS_ERR(obj) && (PTR_ERR(obj) == -ENOENT))
1067                                 continue;
1068                         if (IS_ERR(obj))
1069                                 GOTO(out, rc = PTR_ERR(obj));
1070
1071                         hsm.mh_flags |= HS_EXISTS;
1072                         hsm.mh_arch_id = hal->hal_archive_id;
1073                         rc = mdt_hsm_attr_set(mti, obj, &hsm);
1074                         mdt_object_put(mti->mti_env, obj);
1075                         if (rc)
1076                                 GOTO(out, rc);
1077                 }
1078
1079                 car = mdt_cdt_alloc_request(hal->hal_compound_id,
1080                                             hal->hal_archive_id, hal->hal_flags,
1081                                             uuid, hai);
1082                 if (IS_ERR(car))
1083                         GOTO(out, rc = PTR_ERR(car));
1084
1085                 rc = mdt_cdt_add_request(cdt, car);
1086                 if (rc != 0)
1087                         mdt_cdt_free_request(car);
1088         }
1089 out:
1090         RETURN(rc);
1091 }
1092
1093 /**
1094  * swap layouts between 2 fids
1095  * \param mti [IN] context
1096  * \param fid1 [IN]
1097  * \param fid2 [IN]
1098  * \param mh_common [IN] MD HSM
1099  */
1100 static int hsm_swap_layouts(struct mdt_thread_info *mti,
1101                             const lustre_fid *fid, const lustre_fid *dfid,
1102                             struct md_hsm *mh_common)
1103 {
1104         struct mdt_device       *mdt = mti->mti_mdt;
1105         struct mdt_object       *child1, *child2;
1106         struct mdt_lock_handle  *lh2;
1107         int                      rc;
1108         ENTRY;
1109
1110         child1 = mdt_object_find(mti->mti_env, mdt, fid);
1111         if (IS_ERR(child1))
1112                 GOTO(out, rc = PTR_ERR(child1));
1113
1114         /* we already have layout lock on FID so take only
1115          * on dfid */
1116         lh2 = &mti->mti_lh[MDT_LH_OLD];
1117         mdt_lock_reg_init(lh2, LCK_EX);
1118         child2 = mdt_object_find_lock(mti, dfid, lh2, MDS_INODELOCK_LAYOUT);
1119         if (IS_ERR(child2))
1120                 GOTO(out_child1, rc = PTR_ERR(child2));
1121
1122         /* if copy tool closes the volatile before sending the final
1123          * progress through llapi_hsm_copy_end(), all the objects
1124          * are removed and mdd_swap_layout LBUG */
1125         if (!mdt_object_exists(child2)) {
1126                 CERROR("%s: Copytool has closed volatile file "DFID"\n",
1127                        mdt_obd_name(mti->mti_mdt), PFID(dfid));
1128                 GOTO(out_child2, rc = -ENOENT);
1129         }
1130         /* Since we only handle restores here, unconditionally use
1131          * SWAP_LAYOUTS_MDS_HSM flag to ensure original layout will
1132          * be preserved in case of failure during swap_layout and not
1133          * leave a file in an intermediate but incoherent state.
1134          * But need to setup HSM xattr of data FID before, reuse
1135          * mti and mh presets for FID in hsm_cdt_request_completed(),
1136          * only need to clear RELEASED and DIRTY.
1137          */
1138         mh_common->mh_flags &= ~(HS_RELEASED | HS_DIRTY);
1139         rc = mdt_hsm_attr_set(mti, child2, mh_common);
1140         if (rc == 0)
1141                 rc = mo_swap_layouts(mti->mti_env,
1142                                      mdt_object_child(child1),
1143                                      mdt_object_child(child2),
1144                                      SWAP_LAYOUTS_MDS_HSM);
1145
1146 out_child2:
1147         mdt_object_unlock_put(mti, child2, lh2, 1);
1148 out_child1:
1149         mdt_object_put(mti->mti_env, child1);
1150 out:
1151         RETURN(rc);
1152 }
1153
1154 /**
1155  * update status of a completed request
1156  * \param mti [IN] context
1157  * \param pgs [IN] progress of the copy tool
1158  * \param update_record [IN] update llog record
1159  * \retval 0 success
1160  * \retval -ve failure
1161  */
1162 static int hsm_cdt_request_completed(struct mdt_thread_info *mti,
1163                                      struct hsm_progress_kernel *pgs,
1164                                      const struct cdt_agent_req *car,
1165                                      enum agent_req_status *status)
1166 {
1167         const struct lu_env     *env = mti->mti_env;
1168         struct mdt_device       *mdt = mti->mti_mdt;
1169         struct coordinator      *cdt = &mdt->mdt_coordinator;
1170         struct mdt_object       *obj = NULL;
1171         int                      cl_flags = 0, rc = 0;
1172         struct md_hsm            mh;
1173         bool                     is_mh_changed;
1174         ENTRY;
1175
1176         /* default is to retry */
1177         *status = ARS_WAITING;
1178
1179         /* find object by FID */
1180         obj = mdt_hsm_get_md_hsm(mti, &car->car_hai->hai_fid, &mh);
1181         /* we will update MD HSM only if needed */
1182         is_mh_changed = false;
1183         if (IS_ERR(obj)) {
1184                 /* object removed */
1185                 *status = ARS_SUCCEED;
1186                 goto unlock;
1187         }
1188
1189         /* no need to change mh->mh_arch_id
1190          * mdt_hsm_get_md_hsm() got it from disk and it is still valid
1191          */
1192         if (pgs->hpk_errval != 0) {
1193                 switch (pgs->hpk_errval) {
1194                 case ENOSYS:
1195                         /* the copy tool does not support cancel
1196                          * so the cancel request is failed
1197                          * As we cannot distinguish a cancel progress
1198                          * from another action progress (they have the
1199                          * same cookie), we suppose here the CT returns
1200                          * ENOSYS only if does not support cancel
1201                          */
1202                         /* this can also happen when cdt calls it to
1203                          * for a timed out request */
1204                         *status = ARS_FAILED;
1205                         /* to have a cancel event in changelog */
1206                         pgs->hpk_errval = ECANCELED;
1207                         break;
1208                 case ECANCELED:
1209                         /* the request record has already been set to
1210                          * ARS_CANCELED, this set the cancel request
1211                          * to ARS_SUCCEED */
1212                         *status = ARS_SUCCEED;
1213                         break;
1214                 default:
1215                         *status = (cdt->cdt_policy & CDT_NORETRY_ACTION ||
1216                                    !(pgs->hpk_flags & HP_FLAG_RETRY) ?
1217                                    ARS_FAILED : ARS_WAITING);
1218                         break;
1219                 }
1220
1221                 if (pgs->hpk_errval > CLF_HSM_MAXERROR) {
1222                         CERROR("%s: Request "LPX64" on "DFID
1223                                " failed, error code %d too large\n",
1224                                mdt_obd_name(mdt),
1225                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1226                                pgs->hpk_errval);
1227                         hsm_set_cl_error(&cl_flags,
1228                                          CLF_HSM_ERROVERFLOW);
1229                         rc = -EINVAL;
1230                 } else {
1231                         hsm_set_cl_error(&cl_flags, pgs->hpk_errval);
1232                 }
1233
1234                 switch (car->car_hai->hai_action) {
1235                 case HSMA_ARCHIVE:
1236                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1237                         break;
1238                 case HSMA_RESTORE:
1239                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1240                         break;
1241                 case HSMA_REMOVE:
1242                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1243                         break;
1244                 case HSMA_CANCEL:
1245                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1246                         CERROR("%s: Failed request "LPX64" on "DFID
1247                                " cannot be a CANCEL\n",
1248                                mdt_obd_name(mdt),
1249                                pgs->hpk_cookie,
1250                                PFID(&pgs->hpk_fid));
1251                         break;
1252                 default:
1253                         CERROR("%s: Failed request "LPX64" on "DFID
1254                                " %d is an unknown action\n",
1255                                mdt_obd_name(mdt),
1256                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1257                                car->car_hai->hai_action);
1258                         rc = -EINVAL;
1259                         break;
1260                 }
1261         } else {
1262                 *status = ARS_SUCCEED;
1263                 switch (car->car_hai->hai_action) {
1264                 case HSMA_ARCHIVE:
1265                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1266                         /* set ARCHIVE keep EXIST and clear LOST and
1267                          * DIRTY */
1268                         mh.mh_arch_ver = pgs->hpk_data_version;
1269                         mh.mh_flags |= HS_ARCHIVED;
1270                         mh.mh_flags &= ~(HS_LOST|HS_DIRTY);
1271                         is_mh_changed = true;
1272                         break;
1273                 case HSMA_RESTORE:
1274                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1275
1276                         /* do not clear RELEASED and DIRTY here
1277                          * this will occur in hsm_swap_layouts()
1278                          */
1279
1280                         /* Restoring has changed the file version on
1281                          * disk. */
1282                         mh.mh_arch_ver = pgs->hpk_data_version;
1283                         is_mh_changed = true;
1284                         break;
1285                 case HSMA_REMOVE:
1286                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1287                         /* clear ARCHIVED EXISTS and LOST */
1288                         mh.mh_flags &= ~(HS_ARCHIVED | HS_EXISTS | HS_LOST);
1289                         is_mh_changed = true;
1290                         break;
1291                 case HSMA_CANCEL:
1292                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1293                         CERROR("%s: Successful request "LPX64
1294                                " on "DFID
1295                                " cannot be a CANCEL\n",
1296                                mdt_obd_name(mdt),
1297                                pgs->hpk_cookie,
1298                                PFID(&pgs->hpk_fid));
1299                         break;
1300                 default:
1301                         CERROR("%s: Successful request "LPX64
1302                                " on "DFID
1303                                " %d is an unknown action\n",
1304                                mdt_obd_name(mdt),
1305                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1306                                car->car_hai->hai_action);
1307                         rc = -EINVAL;
1308                         break;
1309                 }
1310         }
1311
1312         /* rc != 0 means error when analysing action, it may come from
1313          * a crasy CT no need to manage DIRTY
1314          */
1315         if (rc == 0)
1316                 hsm_set_cl_flags(&cl_flags,
1317                                  mh.mh_flags & HS_DIRTY ? CLF_HSM_DIRTY : 0);
1318
1319         /* unlock is done later, after layout lock management */
1320         if (is_mh_changed)
1321                 rc = mdt_hsm_attr_set(mti, obj, &mh);
1322
1323 unlock:
1324         /* we give back layout lock only if restore was successful or
1325          * if restore was canceled or if policy is to not retry
1326          * in other cases we just unlock the object */
1327         if (car->car_hai->hai_action == HSMA_RESTORE &&
1328             (pgs->hpk_errval == 0 || pgs->hpk_errval == ECANCELED ||
1329              cdt->cdt_policy & CDT_NORETRY_ACTION)) {
1330                 struct cdt_restore_handle       *crh;
1331
1332                 /* restore in data FID done, we swap the layouts
1333                  * only if restore is successful */
1334                 if (pgs->hpk_errval == 0) {
1335                         rc = hsm_swap_layouts(mti, &car->car_hai->hai_fid,
1336                                               &car->car_hai->hai_dfid, &mh);
1337                         if (rc) {
1338                                 if (cdt->cdt_policy & CDT_NORETRY_ACTION)
1339                                         *status = ARS_FAILED;
1340                                 pgs->hpk_errval = -rc;
1341                         }
1342                 }
1343                 /* we have to retry, so keep layout lock */
1344                 if (*status == ARS_WAITING)
1345                         GOTO(out, rc);
1346
1347                 /* give back layout lock */
1348                 mutex_lock(&cdt->cdt_restore_lock);
1349                 crh = mdt_hsm_restore_hdl_find(cdt, &car->car_hai->hai_fid);
1350                 if (crh != NULL)
1351                         list_del(&crh->crh_list);
1352                 mutex_unlock(&cdt->cdt_restore_lock);
1353                 /* just give back layout lock, we keep
1354                  * the reference which is given back
1355                  * later with the lock for HSM flags */
1356                 if (!IS_ERR(obj) && crh != NULL)
1357                         mdt_object_unlock(mti, obj, &crh->crh_lh, 1);
1358
1359                 if (crh != NULL)
1360                         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
1361         }
1362
1363         GOTO(out, rc);
1364
1365 out:
1366         if (obj != NULL && !IS_ERR(obj)) {
1367                 mo_changelog(env, CL_HSM, cl_flags,
1368                              mdt_object_child(obj));
1369                 mdt_object_put(mti->mti_env, obj);
1370         }
1371
1372         RETURN(rc);
1373 }
1374
1375 /**
1376  * update status of a request
1377  * \param mti [IN] context
1378  * \param pgs [IN] progress of the copy tool
1379  * \param update_record [IN] update llog record
1380  * \retval 0 success
1381  * \retval -ve failure
1382  */
1383 int mdt_hsm_update_request_state(struct mdt_thread_info *mti,
1384                                  struct hsm_progress_kernel *pgs,
1385                                  const int update_record)
1386 {
1387         struct mdt_device       *mdt = mti->mti_mdt;
1388         struct coordinator      *cdt = &mdt->mdt_coordinator;
1389         struct cdt_agent_req    *car;
1390         int                      rc = 0;
1391         ENTRY;
1392
1393         /* no coordinator started, so we cannot serve requests */
1394         if (cdt->cdt_state == CDT_STOPPED)
1395                 RETURN(-EAGAIN);
1396
1397         /* first do sanity checks */
1398         car = mdt_cdt_update_request(cdt, pgs);
1399         if (IS_ERR(car)) {
1400                 CERROR("%s: Cannot find running request for cookie "LPX64
1401                        " on fid="DFID"\n",
1402                        mdt_obd_name(mdt),
1403                        pgs->hpk_cookie, PFID(&pgs->hpk_fid));
1404
1405                 RETURN(PTR_ERR(car));
1406         }
1407
1408         CDEBUG(D_HSM, "Progress received for fid="DFID" cookie="LPX64
1409                       " action=%s flags=%d err=%d fid="DFID" dfid="DFID"\n",
1410                       PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1411                       hsm_copytool_action2name(car->car_hai->hai_action),
1412                       pgs->hpk_flags, pgs->hpk_errval,
1413                       PFID(&car->car_hai->hai_fid),
1414                       PFID(&car->car_hai->hai_dfid));
1415
1416         /* progress is done on FID or data FID depending of the action and
1417          * of the copy progress */
1418         /* for restore progress is used to send back the data FID to cdt */
1419         if (car->car_hai->hai_action == HSMA_RESTORE &&
1420             lu_fid_eq(&car->car_hai->hai_fid, &car->car_hai->hai_dfid))
1421                 car->car_hai->hai_dfid = pgs->hpk_fid;
1422
1423         if ((car->car_hai->hai_action == HSMA_RESTORE ||
1424              car->car_hai->hai_action == HSMA_ARCHIVE) &&
1425             (!lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_dfid) &&
1426              !lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_fid))) {
1427                 CERROR("%s: Progress on "DFID" for cookie "LPX64
1428                        " does not match request FID "DFID" nor data FID "
1429                        DFID"\n",
1430                        mdt_obd_name(mdt),
1431                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1432                        PFID(&car->car_hai->hai_fid),
1433                        PFID(&car->car_hai->hai_dfid));
1434                 GOTO(out, rc = -EINVAL);
1435         }
1436
1437         if (pgs->hpk_errval != 0 && !(pgs->hpk_flags & HP_FLAG_COMPLETED)) {
1438                 CERROR("%s: Progress on "DFID" for cookie "LPX64" action=%s"
1439                        " is not coherent (err=%d and not completed"
1440                        " (flags=%d))\n",
1441                        mdt_obd_name(mdt),
1442                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1443                        hsm_copytool_action2name(car->car_hai->hai_action),
1444                        pgs->hpk_errval, pgs->hpk_flags);
1445                 GOTO(out, rc = -EINVAL);
1446         }
1447
1448         /* now progress is valid */
1449
1450         /* we use a root like ucred */
1451         hsm_init_ucred(mdt_ucred(mti));
1452
1453         if (pgs->hpk_flags & HP_FLAG_COMPLETED) {
1454                 enum agent_req_status    status;
1455
1456                 rc = hsm_cdt_request_completed(mti, pgs, car, &status);
1457
1458                 /* remove request from memory list */
1459                 mdt_cdt_remove_request(cdt, pgs->hpk_cookie);
1460
1461                 CDEBUG(D_HSM, "Updating record: fid="DFID" cookie="LPX64
1462                               " action=%s status=%s\n", PFID(&pgs->hpk_fid),
1463                        pgs->hpk_cookie,
1464                        hsm_copytool_action2name(car->car_hai->hai_action),
1465                        agent_req_status2name(status));
1466
1467                 if (update_record) {
1468                         int rc1;
1469
1470                         rc1 = mdt_agent_record_update(mti->mti_env, mdt,
1471                                                      &pgs->hpk_cookie, 1,
1472                                                      status);
1473                         if (rc1)
1474                                 CERROR("%s: mdt_agent_record_update() failed,"
1475                                        " rc=%d, cannot update status to %s"
1476                                        " for cookie "LPX64"\n",
1477                                        mdt_obd_name(mdt), rc1,
1478                                        agent_req_status2name(status),
1479                                        pgs->hpk_cookie);
1480                         rc = (rc != 0 ? rc : rc1);
1481                 }
1482                 /* ct has completed a request, so a slot is available, wakeup
1483                  * cdt to find new work */
1484                 mdt_hsm_cdt_wakeup(mdt);
1485         } else {
1486                 /* if copytool send a progress on a canceled request
1487                  * we inform copytool it should stop
1488                  */
1489                 if (car->car_canceled == 1)
1490                         rc = -ECANCELED;
1491         }
1492         GOTO(out, rc);
1493
1494 out:
1495         /* remove ref got from mdt_cdt_update_request() */
1496         mdt_cdt_put_request(car);
1497
1498         return rc;
1499 }
1500
1501
1502 /**
1503  * data passed to llog_cat_process() callback
1504  * to cancel requests
1505  */
1506 struct hsm_cancel_all_data {
1507         struct mdt_device       *mdt;
1508 };
1509
1510 /**
1511  *  llog_cat_process() callback, used to:
1512  *  - purge all requests
1513  * \param env [IN] environment
1514  * \param llh [IN] llog handle
1515  * \param hdr [IN] llog record
1516  * \param data [IN] cb data = struct hsm_cancel_all_data
1517  * \retval 0 success
1518  * \retval -ve failure
1519  */
1520 static int mdt_cancel_all_cb(const struct lu_env *env,
1521                              struct llog_handle *llh,
1522                              struct llog_rec_hdr *hdr, void *data)
1523 {
1524         struct llog_agent_req_rec       *larr;
1525         struct hsm_cancel_all_data      *hcad;
1526         int                              rc = 0;
1527         ENTRY;
1528
1529         larr = (struct llog_agent_req_rec *)hdr;
1530         hcad = data;
1531         if (larr->arr_status == ARS_WAITING ||
1532             larr->arr_status == ARS_STARTED) {
1533                 larr->arr_status = ARS_CANCELED;
1534                 larr->arr_req_change = cfs_time_current_sec();
1535                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
1536         }
1537
1538         RETURN(rc);
1539 }
1540
1541 /**
1542  * cancel all actions
1543  * \param obd [IN] MDT device
1544  */
1545 static int hsm_cancel_all_actions(struct mdt_device *mdt)
1546 {
1547         struct mdt_thread_info          *mti;
1548         struct coordinator              *cdt = &mdt->mdt_coordinator;
1549         struct cdt_agent_req            *car;
1550         struct hsm_action_list          *hal = NULL;
1551         struct hsm_action_item          *hai;
1552         struct hsm_cancel_all_data       hcad;
1553         int                              hal_sz = 0, hal_len, rc;
1554         enum cdt_states                  save_state;
1555         ENTRY;
1556
1557         /* retrieve coordinator context */
1558         mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1559
1560         /* disable coordinator */
1561         save_state = cdt->cdt_state;
1562         cdt->cdt_state = CDT_DISABLE;
1563
1564         /* send cancel to all running requests */
1565         down_read(&cdt->cdt_request_lock);
1566         list_for_each_entry(car, &cdt->cdt_requests, car_request_list) {
1567                 mdt_cdt_get_request(car);
1568                 /* request is not yet removed from list, it will be done
1569                  * when copytool will return progress
1570                  */
1571
1572                 if (car->car_hai->hai_action == HSMA_CANCEL) {
1573                         mdt_cdt_put_request(car);
1574                         continue;
1575                 }
1576
1577                 /* needed size */
1578                 hal_len = sizeof(*hal) + cfs_size_round(MTI_NAME_MAXLEN + 1) +
1579                           cfs_size_round(car->car_hai->hai_len);
1580
1581                 if (hal_len > hal_sz && hal_sz > 0) {
1582                         /* not enough room, free old buffer */
1583                         OBD_FREE(hal, hal_sz);
1584                         hal = NULL;
1585                 }
1586
1587                 /* empty buffer, allocate one */
1588                 if (hal == NULL) {
1589                         hal_sz = hal_len;
1590                         OBD_ALLOC(hal, hal_sz);
1591                         if (hal == NULL) {
1592                                 mdt_cdt_put_request(car);
1593                                 up_read(&cdt->cdt_request_lock);
1594                                 GOTO(out, rc = -ENOMEM);
1595                         }
1596                 }
1597
1598                 hal->hal_version = HAL_VERSION;
1599                 obd_uuid2fsname(hal->hal_fsname, mdt_obd_name(mdt),
1600                                 MTI_NAME_MAXLEN);
1601                 hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
1602                 hal->hal_compound_id = car->car_compound_id;
1603                 hal->hal_archive_id = car->car_archive_id;
1604                 hal->hal_flags = car->car_flags;
1605                 hal->hal_count = 0;
1606
1607                 hai = hai_first(hal);
1608                 memcpy(hai, car->car_hai, car->car_hai->hai_len);
1609                 hai->hai_action = HSMA_CANCEL;
1610                 hal->hal_count = 1;
1611
1612                 /* it is possible to safely call mdt_hsm_agent_send()
1613                  * (ie without a deadlock on cdt_request_lock), because the
1614                  * write lock is taken only if we are not in purge mode
1615                  * (mdt_hsm_agent_send() does not call mdt_cdt_add_request()
1616                  *   nor mdt_cdt_remove_request())
1617                  */
1618                 /* no conflict with cdt thread because cdt is disable and we
1619                  * have the request lock */
1620                 mdt_hsm_agent_send(mti, hal, 1);
1621
1622                 mdt_cdt_put_request(car);
1623         }
1624         up_read(&cdt->cdt_request_lock);
1625
1626         if (hal != NULL)
1627                 OBD_FREE(hal, hal_sz);
1628
1629         /* cancel all on-disk records */
1630         hcad.mdt = mdt;
1631
1632         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt,
1633                               mdt_cancel_all_cb, &hcad);
1634 out:
1635         /* enable coordinator */
1636         cdt->cdt_state = save_state;
1637
1638         RETURN(rc);
1639 }
1640
1641 /**
1642  * check if a request is compatible with file status
1643  * \param hai [IN] request description
1644  * \param hal_an [IN] request archive number (not used)
1645  * \param rq_flags [IN] request flags
1646  * \param hsm [IN] file HSM metadata
1647  * \retval boolean
1648  */
1649 bool mdt_hsm_is_action_compat(const struct hsm_action_item *hai,
1650                               const int hal_an, const __u64 rq_flags,
1651                               const struct md_hsm *hsm)
1652 {
1653         int      is_compat = false;
1654         int      hsm_flags;
1655         ENTRY;
1656
1657         hsm_flags = hsm->mh_flags;
1658         switch (hai->hai_action) {
1659         case HSMA_ARCHIVE:
1660                 if (!(hsm_flags & HS_NOARCHIVE) &&
1661                     (hsm_flags & HS_DIRTY || !(hsm_flags & HS_ARCHIVED)))
1662                         is_compat = true;
1663                 break;
1664         case HSMA_RESTORE:
1665                 if (!(hsm_flags & HS_DIRTY) && (hsm_flags & HS_RELEASED) &&
1666                     hsm_flags & HS_ARCHIVED && !(hsm_flags & HS_LOST))
1667                         is_compat = true;
1668                 break;
1669         case HSMA_REMOVE:
1670                 if (!(hsm_flags & HS_RELEASED) &&
1671                     (hsm_flags & (HS_ARCHIVED | HS_EXISTS)))
1672                         is_compat = true;
1673                 break;
1674         case HSMA_CANCEL:
1675                 is_compat = true;
1676                 break;
1677         }
1678         CDEBUG(D_HSM, "fid="DFID" action=%s flags="LPX64
1679                       " extent="LPX64"-"LPX64" hsm_flags=%.8X %s\n",
1680                       PFID(&hai->hai_fid),
1681                       hsm_copytool_action2name(hai->hai_action), rq_flags,
1682                       hai->hai_extent.offset, hai->hai_extent.length,
1683                       hsm->mh_flags,
1684                       (is_compat ? "compatible" : "uncompatible"));
1685
1686         RETURN(is_compat);
1687 }
1688
1689 /*
1690  * /proc interface used to get/set HSM behaviour (cdt->cdt_policy)
1691  */
1692 static const struct {
1693         __u64            bit;
1694         char            *name;
1695         char            *nickname;
1696 } hsm_policy_names[] = {
1697         { CDT_NONBLOCKING_RESTORE,      "NonBlockingRestore",   "NBR"},
1698         { CDT_NORETRY_ACTION,           "NoRetryAction",        "NRA"},
1699         { 0 },
1700 };
1701
1702 /**
1703  * convert a policy name to a bit
1704  * \param name [IN] policy name
1705  * \retval 0 unknown
1706  * \retval   policy bit
1707  */
1708 static __u64 hsm_policy_str2bit(const char *name)
1709 {
1710         int      i;
1711
1712         for (i = 0; hsm_policy_names[i].bit != 0; i++)
1713                 if (strcmp(hsm_policy_names[i].nickname, name) == 0 ||
1714                     strcmp(hsm_policy_names[i].name, name) == 0)
1715                         return hsm_policy_names[i].bit;
1716         return 0;
1717 }
1718
1719 /**
1720  * convert a policy bit field to a string
1721  * \param mask [IN] policy bit field
1722  * \param hexa [IN] print mask before bit names
1723  * \param buffer [OUT] string
1724  * \param count [IN] size of buffer
1725  */
1726 static void hsm_policy_bit2str(struct seq_file *m, const __u64 mask,
1727                                 const bool hexa)
1728 {
1729         int      i, j;
1730         __u64    bit;
1731         ENTRY;
1732
1733         if (hexa)
1734                 seq_printf(m, "("LPX64") ", mask);
1735
1736         for (i = 0; i < CDT_POLICY_SHIFT_COUNT; i++) {
1737                 bit = (1ULL << i);
1738
1739                 for (j = 0; hsm_policy_names[j].bit != 0; j++) {
1740                         if (hsm_policy_names[j].bit == bit)
1741                                 break;
1742                 }
1743                 if (bit & mask)
1744                         seq_printf(m, "[%s] ", hsm_policy_names[j].name);
1745                 else
1746                         seq_printf(m, "%s ", hsm_policy_names[j].name);
1747         }
1748         /* remove last ' ' */
1749         m->count--;
1750         seq_putc(m, '\0');
1751 }
1752
1753 /* methods to read/write HSM policy flags */
1754 static int mdt_hsm_policy_seq_show(struct seq_file *m, void *data)
1755 {
1756         struct mdt_device       *mdt = m->private;
1757         struct coordinator      *cdt = &mdt->mdt_coordinator;
1758         ENTRY;
1759
1760         hsm_policy_bit2str(m, cdt->cdt_policy, false);
1761         RETURN(0);
1762 }
1763
1764 static ssize_t
1765 mdt_hsm_policy_seq_write(struct file *file, const char __user *buffer,
1766                          size_t count, loff_t *off)
1767 {
1768         struct seq_file         *m = file->private_data;
1769         struct mdt_device       *mdt = m->private;
1770         struct coordinator      *cdt = &mdt->mdt_coordinator;
1771         char                    *start, *token, sign;
1772         char                    *buf;
1773         __u64                    policy;
1774         __u64                    add_mask, remove_mask, set_mask;
1775         int                      rc;
1776         ENTRY;
1777
1778         if (count + 1 > PAGE_SIZE)
1779                 RETURN(-EINVAL);
1780
1781         OBD_ALLOC(buf, count + 1);
1782         if (buf == NULL)
1783                 RETURN(-ENOMEM);
1784
1785         if (copy_from_user(buf, buffer, count))
1786                 GOTO(out, rc = -EFAULT);
1787
1788         buf[count] = '\0';
1789
1790         start = buf;
1791         CDEBUG(D_HSM, "%s: receive new policy: '%s'\n", mdt_obd_name(mdt),
1792                start);
1793
1794         add_mask = remove_mask = set_mask = 0;
1795         do {
1796                 token = strsep(&start, "\n ");
1797                 sign = *token;
1798
1799                 if (sign == '\0')
1800                         continue;
1801
1802                 if (sign == '-' || sign == '+')
1803                         token++;
1804
1805                 policy = hsm_policy_str2bit(token);
1806                 if (policy == 0) {
1807                         CWARN("%s: '%s' is unknown, "
1808                               "supported policies are:\n", mdt_obd_name(mdt),
1809                               token);
1810                         hsm_policy_bit2str(m, 0, false);
1811                         GOTO(out, rc = -EINVAL);
1812                 }
1813                 switch (sign) {
1814                 case '-':
1815                         remove_mask |= policy;
1816                         break;
1817                 case '+':
1818                         add_mask |= policy;
1819                         break;
1820                 default:
1821                         set_mask |= policy;
1822                         break;
1823                 }
1824
1825         } while (start != NULL);
1826
1827         CDEBUG(D_HSM, "%s: new policy: rm="LPX64" add="LPX64" set="LPX64"\n",
1828                mdt_obd_name(mdt), remove_mask, add_mask, set_mask);
1829
1830         /* if no sign in all string, it is a clear and set
1831          * if some sign found, all unsigned are converted
1832          * to add
1833          * P1 P2 = set to P1 and P2
1834          * P1 -P2 = add P1 clear P2 same as +P1 -P2
1835          */
1836         if (remove_mask == 0 && add_mask == 0) {
1837                 cdt->cdt_policy = set_mask;
1838         } else {
1839                 cdt->cdt_policy |= set_mask | add_mask;
1840                 cdt->cdt_policy &= ~remove_mask;
1841         }
1842
1843         GOTO(out, rc = count);
1844
1845 out:
1846         OBD_FREE(buf, count + 1);
1847         RETURN(rc);
1848 }
1849 LPROC_SEQ_FOPS(mdt_hsm_policy);
1850
1851 #define GENERATE_PROC_METHOD(VAR)                                       \
1852 static int mdt_hsm_##VAR##_seq_show(struct seq_file *m, void *data)     \
1853 {                                                                       \
1854         struct mdt_device       *mdt = m->private;                      \
1855         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
1856         ENTRY;                                                          \
1857                                                                         \
1858         seq_printf(m, LPU64"\n", (__u64)cdt->VAR);                      \
1859         RETURN(0);                                                      \
1860 }                                                                       \
1861 static ssize_t                                                          \
1862 mdt_hsm_##VAR##_seq_write(struct file *file, const char __user *buffer, \
1863                           size_t count, loff_t *off)                    \
1864                                                                         \
1865 {                                                                       \
1866         struct seq_file         *m = file->private_data;                \
1867         struct mdt_device       *mdt = m->private;                      \
1868         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
1869         __s64                    val;                                   \
1870         int                      rc;                                    \
1871         ENTRY;                                                          \
1872                                                                         \
1873         rc = lprocfs_str_to_s64(buffer, count, &val);                   \
1874         if (rc)                                                         \
1875                 RETURN(rc);                                             \
1876         if (val > 0 && val < INT_MAX) {                                 \
1877                 cdt->VAR = val;                                         \
1878                 RETURN(count);                                          \
1879         }                                                               \
1880         RETURN(-EINVAL);                                                \
1881 }                                                                       \
1882
1883 GENERATE_PROC_METHOD(cdt_loop_period)
1884 GENERATE_PROC_METHOD(cdt_grace_delay)
1885 GENERATE_PROC_METHOD(cdt_active_req_timeout)
1886 GENERATE_PROC_METHOD(cdt_max_requests)
1887 GENERATE_PROC_METHOD(cdt_default_archive_id)
1888
1889 /*
1890  * procfs write method for MDT/hsm_control
1891  * proc entry is in mdt directory so data is mdt obd_device pointer
1892  */
1893 #define CDT_ENABLE_CMD   "enabled"
1894 #define CDT_STOP_CMD     "shutdown"
1895 #define CDT_DISABLE_CMD  "disabled"
1896 #define CDT_PURGE_CMD    "purge"
1897 #define CDT_HELP_CMD     "help"
1898 #define CDT_MAX_CMD_LEN  10
1899
1900 ssize_t
1901 mdt_hsm_cdt_control_seq_write(struct file *file, const char __user *buffer,
1902                               size_t count, loff_t *off)
1903 {
1904         struct seq_file         *m = file->private_data;
1905         struct obd_device       *obd = m->private;
1906         struct mdt_device       *mdt = mdt_dev(obd->obd_lu_dev);
1907         struct coordinator      *cdt = &(mdt->mdt_coordinator);
1908         int                      rc, usage = 0;
1909         char                     kernbuf[CDT_MAX_CMD_LEN];
1910         ENTRY;
1911
1912         if (count == 0 || count >= sizeof(kernbuf))
1913                 RETURN(-EINVAL);
1914
1915         if (copy_from_user(kernbuf, buffer, count))
1916                 RETURN(-EFAULT);
1917         kernbuf[count] = 0;
1918
1919         if (kernbuf[count - 1] == '\n')
1920                 kernbuf[count - 1] = 0;
1921
1922         rc = 0;
1923         if (strcmp(kernbuf, CDT_ENABLE_CMD) == 0) {
1924                 if (cdt->cdt_state == CDT_DISABLE) {
1925                         cdt->cdt_state = CDT_RUNNING;
1926                         mdt_hsm_cdt_wakeup(mdt);
1927                 } else {
1928                         rc = mdt_hsm_cdt_start(mdt);
1929                 }
1930         } else if (strcmp(kernbuf, CDT_STOP_CMD) == 0) {
1931                 if ((cdt->cdt_state == CDT_STOPPING) ||
1932                     (cdt->cdt_state == CDT_STOPPED)) {
1933                         CERROR("%s: Coordinator already stopped\n",
1934                                mdt_obd_name(mdt));
1935                         rc = -EALREADY;
1936                 } else {
1937                         cdt->cdt_state = CDT_STOPPING;
1938                 }
1939         } else if (strcmp(kernbuf, CDT_DISABLE_CMD) == 0) {
1940                 if ((cdt->cdt_state == CDT_STOPPING) ||
1941                     (cdt->cdt_state == CDT_STOPPED)) {
1942                         CERROR("%s: Coordinator is stopped\n",
1943                                mdt_obd_name(mdt));
1944                         rc = -EINVAL;
1945                 } else {
1946                         cdt->cdt_state = CDT_DISABLE;
1947                 }
1948         } else if (strcmp(kernbuf, CDT_PURGE_CMD) == 0) {
1949                 rc = hsm_cancel_all_actions(mdt);
1950         } else if (strcmp(kernbuf, CDT_HELP_CMD) == 0) {
1951                 usage = 1;
1952         } else {
1953                 usage = 1;
1954                 rc = -EINVAL;
1955         }
1956
1957         if (usage == 1)
1958                 CERROR("%s: Valid coordinator control commands are: "
1959                        "%s %s %s %s %s\n", mdt_obd_name(mdt),
1960                        CDT_ENABLE_CMD, CDT_STOP_CMD, CDT_DISABLE_CMD,
1961                        CDT_PURGE_CMD, CDT_HELP_CMD);
1962
1963         if (rc)
1964                 RETURN(rc);
1965
1966         RETURN(count);
1967 }
1968
1969 int mdt_hsm_cdt_control_seq_show(struct seq_file *m, void *data)
1970 {
1971         struct obd_device       *obd = m->private;
1972         struct coordinator      *cdt;
1973         ENTRY;
1974
1975         cdt = &(mdt_dev(obd->obd_lu_dev)->mdt_coordinator);
1976
1977         if (cdt->cdt_state == CDT_INIT)
1978                 seq_printf(m, "init\n");
1979         else if (cdt->cdt_state == CDT_RUNNING)
1980                 seq_printf(m, "enabled\n");
1981         else if (cdt->cdt_state == CDT_STOPPING)
1982                 seq_printf(m, "stopping\n");
1983         else if (cdt->cdt_state == CDT_STOPPED)
1984                 seq_printf(m, "stopped\n");
1985         else if (cdt->cdt_state == CDT_DISABLE)
1986                 seq_printf(m, "disabled\n");
1987         else
1988                 seq_printf(m, "unknown\n");
1989
1990         RETURN(0);
1991 }
1992
1993 static int
1994 mdt_hsm_request_mask_show(struct seq_file *m, __u64 mask)
1995 {
1996         bool first = true;
1997         int i;
1998         ENTRY;
1999
2000         for (i = 0; i < 8 * sizeof(mask); i++) {
2001                 if (mask & (1UL << i)) {
2002                         seq_printf(m, "%s%s", first ? "" : " ",
2003                                    hsm_copytool_action2name(i));
2004                         first = false;
2005                 }
2006         }
2007         seq_putc(m, '\n');
2008
2009         RETURN(0);
2010 }
2011
2012 static int
2013 mdt_hsm_user_request_mask_seq_show(struct seq_file *m, void *data)
2014 {
2015         struct mdt_device *mdt = m->private;
2016         struct coordinator *cdt = &mdt->mdt_coordinator;
2017
2018         return mdt_hsm_request_mask_show(m, cdt->cdt_user_request_mask);
2019 }
2020
2021 static int
2022 mdt_hsm_group_request_mask_seq_show(struct seq_file *m, void *data)
2023 {
2024         struct mdt_device *mdt = m->private;
2025         struct coordinator *cdt = &mdt->mdt_coordinator;
2026
2027         return mdt_hsm_request_mask_show(m, cdt->cdt_group_request_mask);
2028 }
2029
2030 static int
2031 mdt_hsm_other_request_mask_seq_show(struct seq_file *m, void *data)
2032 {
2033         struct mdt_device *mdt = m->private;
2034         struct coordinator *cdt = &mdt->mdt_coordinator;
2035
2036         return mdt_hsm_request_mask_show(m, cdt->cdt_other_request_mask);
2037 }
2038
2039 static inline enum hsm_copytool_action
2040 hsm_copytool_name2action(const char *name)
2041 {
2042         if (strcasecmp(name, "NOOP") == 0)
2043                 return HSMA_NONE;
2044         else if (strcasecmp(name, "ARCHIVE") == 0)
2045                 return HSMA_ARCHIVE;
2046         else if (strcasecmp(name, "RESTORE") == 0)
2047                 return HSMA_RESTORE;
2048         else if (strcasecmp(name, "REMOVE") == 0)
2049                 return HSMA_REMOVE;
2050         else if (strcasecmp(name, "CANCEL") == 0)
2051                 return HSMA_CANCEL;
2052         else
2053                 return -1;
2054 }
2055
2056 static ssize_t
2057 mdt_write_hsm_request_mask(struct file *file, const char __user *user_buf,
2058                             size_t user_count, __u64 *mask)
2059 {
2060         char *buf, *pos, *name;
2061         size_t buf_size;
2062         __u64 new_mask = 0;
2063         int rc;
2064         ENTRY;
2065
2066         if (!(user_count < 4096))
2067                 RETURN(-ENOMEM);
2068
2069         buf_size = user_count + 1;
2070
2071         OBD_ALLOC(buf, buf_size);
2072         if (buf == NULL)
2073                 RETURN(-ENOMEM);
2074
2075         if (copy_from_user(buf, user_buf, buf_size - 1))
2076                 GOTO(out, rc = -EFAULT);
2077
2078         buf[buf_size - 1] = '\0';
2079
2080         pos = buf;
2081         while ((name = strsep(&pos, " \t\v\n")) != NULL) {
2082                 int action;
2083
2084                 if (*name == '\0')
2085                         continue;
2086
2087                 action = hsm_copytool_name2action(name);
2088                 if (action < 0)
2089                         GOTO(out, rc = -EINVAL);
2090
2091                 new_mask |= (1UL << action);
2092         }
2093
2094         *mask = new_mask;
2095         rc = user_count;
2096 out:
2097         OBD_FREE(buf, buf_size);
2098
2099         RETURN(rc);
2100 }
2101
2102 static ssize_t
2103 mdt_hsm_user_request_mask_seq_write(struct file *file, const char __user *buf,
2104                                         size_t count, loff_t *off)
2105 {
2106         struct seq_file         *m = file->private_data;
2107         struct mdt_device       *mdt = m->private;
2108         struct coordinator *cdt = &mdt->mdt_coordinator;
2109
2110         return mdt_write_hsm_request_mask(file, buf, count,
2111                                            &cdt->cdt_user_request_mask);
2112 }
2113
2114 static ssize_t
2115 mdt_hsm_group_request_mask_seq_write(struct file *file, const char __user *buf,
2116                                         size_t count, loff_t *off)
2117 {
2118         struct seq_file         *m = file->private_data;
2119         struct mdt_device       *mdt = m->private;
2120         struct coordinator      *cdt = &mdt->mdt_coordinator;
2121
2122         return mdt_write_hsm_request_mask(file, buf, count,
2123                                            &cdt->cdt_group_request_mask);
2124 }
2125
2126 static ssize_t
2127 mdt_hsm_other_request_mask_seq_write(struct file *file, const char __user *buf,
2128                                         size_t count, loff_t *off)
2129 {
2130         struct seq_file         *m = file->private_data;
2131         struct mdt_device       *mdt = m->private;
2132         struct coordinator      *cdt = &mdt->mdt_coordinator;
2133
2134         return mdt_write_hsm_request_mask(file, buf, count,
2135                                            &cdt->cdt_other_request_mask);
2136 }
2137
2138 LPROC_SEQ_FOPS(mdt_hsm_cdt_loop_period);
2139 LPROC_SEQ_FOPS(mdt_hsm_cdt_grace_delay);
2140 LPROC_SEQ_FOPS(mdt_hsm_cdt_active_req_timeout);
2141 LPROC_SEQ_FOPS(mdt_hsm_cdt_max_requests);
2142 LPROC_SEQ_FOPS(mdt_hsm_cdt_default_archive_id);
2143 LPROC_SEQ_FOPS(mdt_hsm_user_request_mask);
2144 LPROC_SEQ_FOPS(mdt_hsm_group_request_mask);
2145 LPROC_SEQ_FOPS(mdt_hsm_other_request_mask);
2146
2147 static struct lprocfs_vars lprocfs_mdt_hsm_vars[] = {
2148         { .name =       "agents",
2149           .fops =       &mdt_hsm_agent_fops                     },
2150         { .name =       "actions",
2151           .fops =       &mdt_hsm_actions_fops,
2152           .proc_mode =  0444                                    },
2153         { .name =       "default_archive_id",
2154           .fops =       &mdt_hsm_cdt_default_archive_id_fops    },
2155         { .name =       "grace_delay",
2156           .fops =       &mdt_hsm_cdt_grace_delay_fops           },
2157         { .name =       "loop_period",
2158           .fops =       &mdt_hsm_cdt_loop_period_fops           },
2159         { .name =       "max_requests",
2160           .fops =       &mdt_hsm_cdt_max_requests_fops          },
2161         { .name =       "policy",
2162           .fops =       &mdt_hsm_policy_fops                    },
2163         { .name =       "active_request_timeout",
2164           .fops =       &mdt_hsm_cdt_active_req_timeout_fops    },
2165         { .name =       "active_requests",
2166           .fops =       &mdt_hsm_active_requests_fops           },
2167         { .name =       "user_request_mask",
2168           .fops =       &mdt_hsm_user_request_mask_fops,        },
2169         { .name =       "group_request_mask",
2170           .fops =       &mdt_hsm_group_request_mask_fops,       },
2171         { .name =       "other_request_mask",
2172           .fops =       &mdt_hsm_other_request_mask_fops,       },
2173         { 0 }
2174 };