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